text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package managerdbeans;

import entities.Customer;
import entities.DiscountCode;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import session.CustomerManager;
import session.DiscountCodeManager;

/**
 *
 * @author marwen
 */
@Named
@ViewScoped
public class CustomerDetailsMBean implements Serializable {

    private int idCustomer;
    private Customer customer;

    @EJB
    private CustomerManager customerManager;

    public int getIdCustomer() {
        return idCustomer;
    }

    public void setIdCustomer(int idCustomer) {
        this.idCustomer = idCustomer;
    }

    public Customer getDetails() {
        return customer;
    }

    public String update() {
        System.out.println("###UPDATE###");
        customer = customerManager.update(customer);
        return "CustomerList";
    }

    public String list() {
        System.out.println("###LIST###");
        return "CustomerList";
    }

    public void loadCustomer() {
        this.customer = customerManager.getCustomer(idCustomer);
    }

    @EJB
    private DiscountCodeManager discountCodeManager;

    public Converter getDiscountCodeConverter() {
        return discountCodeConverter;
    }

    private final Converter discountCodeConverter = new Converter() {

        @Override
        public Object getAsObject(FacesContext context, UIComponent component, String value) {
            return new ConverterException("On verra la conversion String->Objet plus tard...");
        }

        @Override
        public String getAsString(FacesContext context, UIComponent component, Object value) {
            DiscountCode dc = (DiscountCode) value;
            return dc.getDiscountCode() + " : " + dc.getRate() + "%";
        }
    };

    /**
 * renvoie une liste de DiscountCode pour affichage dans le menu déroulant
 * de la page des détails d'un client
 * @return
 */
public List<DiscountCode> getAllDiscountCodes() {
    return discountCodeManager.getDiscountCodes();
}
}


text:
var webpack = require("webpack");

module.exports = {
    entry: ['./lib/djvi.js'],
    target: 'node',
    output: {
        library: 'djvi',
        libraryTarget: 'umd',
        filename: 'djvi.js',
        sourceMapFilename: '[file].map'
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin()
    ]
};

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace app\engine\models;

use R;
use Walrus\core\devises\Signup;
use Walrus\core\devises\Signin;
use Walrus\core\WalrusI18n;

class User extends WalrusUser
{

}


text:
'use strict';
var incomeCalculationsModule = angular.module('incomeCalculationsModule', []);

incomeCalculationsModule.factory('IncomeCalculationService', function(){

	/**
	 * A simple array to represent tax tables.
	 * Each object in the array only has 2 attributes, ceiling value for that bracket and the rate for that bracket.
	 * The final bracket has the ceiling of null.
	 *
	 * NOTE: Order matters!
	 */
	var DEFAULT_TAX_TABLE = [
		{
			ceiling: 18200,
			rate: 0,
		}, {
			ceiling: 37000,
			rate: 0.19,
		},
		{
			ceiling: 80000,
			rate: 0.325
		},
		{
			ceiling: 180000,
			rate: 0.37
		},
		{
			ceiling: null,
			rate: 0.45
		}
	];

	/**
	 * Recursively calculates that tax amount for the salary for the entire year.
	 */
	var calculateTax = function(salary, bracketIndex, prevBracketIndex, taxTable){

		var bracket = taxTable[bracketIndex];
		var prevCeiling = 0;
		if (angular.isDefined(prevBracketIndex) && prevBracketIndex !== null){
			prevCeiling = taxTable[prevBracketIndex].ceiling;
		}

		if (bracket.ceiling){
			if (salary > bracket.ceiling){
				 return (bracket.ceiling - prevCeiling) * bracket.rate + calculateTax(salary, bracketIndex+1, bracketIndex, taxTable);
			} else {
				return (salary - prevCeiling) * bracket.rate;
			}
		} else {
			return (salary - prevCeiling) * bracket.rate;
		}
	};

	return {

		// Calculates the income tax on the salary with the given tax table.
		// If no tax table is supplied, default is used.
		calculateMonthlyTax : function(salary, monthPortion, taxTable){
			taxTable = taxTable || DEFAULT_TAX_TABLE;
			var annualTaxAmount = calculateTax(salary, 0, null, taxTable);
			return Math.round((annualTaxAmount/12) * monthPortion);
		},

		calculateGrossIncome : function(salary, monthPortion){
			return Math.round(salary * monthPortion / 12);
		},

		calculateNetIncome : function(salary, monthPortion, monthlyTax) {
			var gross = this.calculateGrossIncome(salary, monthPortion);
			return gross - monthlyTax;
		},

		calculateSuper : function(salary, monthPortion, superRate) {
			var gross = this.calculateGrossIncome(salary, monthPortion);
			return Math.round(gross * superRate);
		}
	};

});


text:
package com.semmle.js.ast;

public class XMLFilterExpression extends Expression {
  final Expression left, right;

  public XMLFilterExpression(SourceLocation loc, Expression left, Expression right) {
    super("XMLFilterExpression", loc);
    this.left = left;
    this.right = right;
  }

  public Expression getLeft() {
    return left;
  }

  public Expression getRight() {
    return right;
  }

  @Override
  public <C, R> R accept(Visitor<C, R> v, C c) {
    return v.visit(this, c);
  }
}


text:
<?php

namespace Symfony\Component\HttpKernel\EventListener;

use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Injects a fatal error exceptions handler into the ErrorHandler.
 *
 * @author Nicolas Grekas <p@tchwork.com>
 */
class FatalErrorExceptionsListener implements EventSubscriberInterface
{
    private $handler = null;

    public function __construct($handler)
    {
        if (is_callable($handler)) {
            $this->handler = $handler;
        }
    }

    public function injectHandler()
    {
        if ($this->handler) {
            ErrorHandler::setFatalErrorExceptionHandler($this->handler);
            $this->handler = null;
        }
    }

    public static function getSubscribedEvents()
    {
        // Don't register early as e.g. the Router is generally required by the handler
        return array(KernelEvents::REQUEST => array('injectHandler', 8));
    }
}


text:
package org.apache.geode.management.internal.cli.commands;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;

import org.apache.geode.management.cli.CliMetaData;
import org.apache.geode.management.cli.GfshCommand;
import org.apache.geode.management.cli.Result;
import org.apache.geode.management.internal.cli.LogWrapper;
import org.apache.geode.management.internal.cli.result.model.InfoResultModel;
import org.apache.geode.management.internal.cli.result.model.ResultModel;
import org.apache.geode.management.internal.cli.util.DiskStoreUpgrader;
import org.apache.geode.management.internal.i18n.CliStrings;

public class UpgradeOfflineDiskStoreCommand extends GfshCommand {
  @CliCommand(value = CliStrings.UPGRADE_OFFLINE_DISK_STORE,
      help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__HELP)
  @CliMetaData(shellOnly = true, relatedTopic = CliStrings.TOPIC_GEODE_DISKSTORE)
  public ResultModel upgradeOfflineDiskStore(
      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME, mandatory = true,
          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME__HELP) String diskStoreName,
      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE,
          unspecifiedDefaultValue = "-1",
          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE__HELP) long maxOplogSize,
      @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J,
          help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J__HELP) String[] jvmProps) {

    String validatedDirectories = DiskStoreCommandsUtils.validatedDirectories(diskDirs);
    if (validatedDirectories != null) {
      throw new IllegalArgumentException(
          "Could not find " + CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS + ": \""
              + validatedDirectories + "\"");
    }

    ResultModel result = new ResultModel();
    InfoResultModel infoResult = result.addInfo();
    LogWrapper logWrapper = LogWrapper.getInstance(getCache());

    Process upgraderProcess = null;

    try {
      List<String> commandList = new ArrayList<>();
      commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
          + File.separatorChar + "java");

      DiskStoreCommandsUtils.configureLogging(commandList);

      if (jvmProps != null && jvmProps.length != 0) {
        commandList.addAll(Arrays.asList(jvmProps));
      }
      commandList.add("-classpath");
      commandList.add(System.getProperty("java.class.path", "."));
      commandList.add(DiskStoreUpgrader.class.getName());

      commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME + "=" + diskStoreName);

      if (diskDirs != null && diskDirs.length != 0) {
        StringBuilder builder = new StringBuilder();
        int arrayLength = diskDirs.length;
        for (int i = 0; i < arrayLength; i++) {
          if (File.separatorChar == '\\') {
            builder.append(diskDirs[i].replace("\\", "/")); // see 46120
          } else {
            builder.append(diskDirs[i]);
          }
          if (i + 1 != arrayLength) {
            builder.append(',');
          }
        }
        commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS + "=" + builder);
      }
      // -1 is ignore as maxOplogSize
      commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize);

      ProcessBuilder procBuilder = new ProcessBuilder(commandList);
      procBuilder.redirectErrorStream(true);
      upgraderProcess = procBuilder.start();

      String line;
      try (InputStream inputStream = upgraderProcess.getInputStream();
          InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
          BufferedReader inputReader = new BufferedReader(inputStreamReader)) {
        while ((line = inputReader.readLine()) != null) {
          infoResult.addLine(line);
        }
      }

      upgraderProcess.waitFor(2, TimeUnit.SECONDS);
      if (upgraderProcess.exitValue() != 0) {
        result.setStatus(Result.Status.ERROR);
      }
    } catch (Exception e) {
      infoResult.addLine(
          String.format("Error upgrading disk store %s: %s", diskStoreName, e.getMessage()));
      result.setStatus(Result.Status.ERROR);
      logWrapper.warning(e.getMessage(), e);
    } finally {
      if (upgraderProcess != null) {
        try {
          // just to check whether the process has exited
          // Process.exitValue() throws IllegalStateException if Process is alive
          upgraderProcess.exitValue();
        } catch (IllegalThreadStateException itse) {
          // not yet terminated, destroy the process
          upgraderProcess.destroy();
        }
      }
    }

    return result;
  }
}


text:
<!DOCTYPE HTML>

<title>text stagger</title>

<link href='https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:400,200' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="banner.css">

	Kwaliteit in leven

			Piet Klerkx groots in wonen voor de familie


text:
  <button ng-click="export()">Export</button>

Monthly Ticket Resolution

Tickets Total: {{ tickets.length }} | Tickets Resolved: {{ closedTickets.length }} | Tickets Still Opened: {{ openedTickets.length }}

      <highchart id="ticketChart" config="ticketReportConfig"></highchart>

  <button ng-click="back()" class="btn btn-default">
    ← Back
  </button>


text:
'use strict';

var broccoli = require('broccoli'),
    Watcher  = require('broccoli-sane-watcher'),
    fs       = require('fs'),
    rimraf   = require('rimraf');

var config = require('../config');

// -----------------------------------------------------------------------------

var tree    = broccoli.loadBrocfile(),
    builder = new broccoli.Builder(tree),
    watcher = new Watcher(builder);

function exit() {
    process.exit(1);
}

function cleanup() {
    rmBuildDir();
    builder.cleanup();
}

function rmBuildDir() {
    rimraf.sync(config.dirs.build);
}

function mkBuildDir(dir) {
    fs.symlinkSync(dir, config.dirs.build, 'dir');
}

function onBuildSuccess(results) {
    rmBuildDir();
    mkBuildDir(results.directory);
    console.log('BUILT - %d ms', Math.floor(results.totalTime / 1e6));
}

function onbuildError(err) {
    console.log('\x07BUILD ERROR:');
    console.log(err.stack);
    console.log('');
}

watcher.on('change', onBuildSuccess);
watcher.on('error', onbuildError);

process.on('SIGINT', exit);
process.on('SIGTERM', exit);
process.on('exit', cleanup);

module.exports = watcher;


text:
import { clickTarget, simulateTimeline, startTimeline } from "@jspsych/test-utils";

import fullscreen from ".";

jest.useFakeTimers();

describe("fullscreen plugin", () => {
  beforeEach(() => {
    document.documentElement.requestFullscreen = jest
      .fn<Promise<void>, any[]>()
      .mockResolvedValue();
  });

  test("launches fullscreen mode by default", async () => {
    await startTimeline([
      {
        type: fullscreen,
        delay_after: 0,
      },
    ]);

    expect(document.documentElement.requestFullscreen).not.toHaveBeenCalled();
    clickTarget(document.querySelector("#jspsych-fullscreen-btn"));
    expect(document.documentElement.requestFullscreen).toHaveBeenCalled();
  });
});

describe("fullscreen plugin simulation", () => {
  beforeEach(() => {
    document.documentElement.requestFullscreen = jest
      .fn<Promise<void>, any[]>()
      .mockResolvedValue();
  });

  test("data-only mode works", async () => {
    const { expectFinished, getData } = await simulateTimeline([
      {
        type: fullscreen,
        delay_after: 0,
      },
    ]);

    await expectFinished();

    expect(getData().values()[0].success).toBe(true);
  });

  test("visual mode works", async () => {
    const { expectRunning, expectFinished, getData } = await simulateTimeline(
      [
        {
          type: fullscreen,
          delay_after: 0,
        },
      ],
      "visual"
    );

    await expectRunning();

    jest.runAllTimers();

    await expectFinished();

    expect(getData().values()[0].success).toBe(true);
  });
});


text:
<?php
namespace UserAgentParser\Provider\Http;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use stdClass;
use UserAgentParser\Exception;
use UserAgentParser\Model;

/**
 * Abstraction of neutrinoapi.com
 *
 * @author Martin Keckeis <martin.keckeis1@gmail.com>
 * @license MIT
 * @see https://51degrees.com
 */
class FiftyOneDegreesCom extends AbstractHttpProvider
{
    /**
     * Name of the provider
     *
     * @var string
     */
    protected $name = 'FiftyOneDegreesCom';

    /**
     * Homepage of the provider
     *
     * @var string
     */
    protected $homepage = 'https://51degrees.com';

    protected $detectionCapabilities = [

        'browser' => [
            'name'    => true,
            'version' => true,
        ],

        'renderingEngine' => [
            'name'    => true,
            'version' => false,
        ],

        'operatingSystem' => [
            'name'    => true,
            'version' => true,
        ],

        'device' => [
            'model'    => true,
            'brand'    => true,
            'type'     => true,
            'isMobile' => true,
            'isTouch'  => false,
        ],

        'bot' => [
            'isBot' => true,
            'name'  => false,
            'type'  => false,
        ],
    ];

    protected $defaultValues = [
        'general' => [
            '/^Unknown$/i',
        ],
    ];

    private static $uri = 'https://cloud.51degrees.com/api/v1';

    private $apiKey;

    public function __construct(Client $client, $apiKey)
    {
        parent::__construct($client);

        $this->apiKey = $apiKey;
    }

    /**
     *
     * @param  string                     $userAgent
     * @param  array                      $headers
     * @return stdClass
     * @throws Exception\RequestException
     */
    protected function getResult($userAgent, array $headers)
    {
        /*
         * an empty UserAgent makes no sense
         */
        if ($userAgent == '') {
            throw new Exception\NoResultFoundException('No result found for user agent: ' . $userAgent);
        }

        $headers['User-Agent'] = $userAgent;

        $parameters = '/' . $this->apiKey;
        $parameters .= '/match?';

        $headerString = [];
        foreach ($headers as $key => $value) {
            $headerString[] = $key . '=' . rawurlencode($value);
        }

        $parameters .= implode('&', $headerString);

        $uri = self::$uri . $parameters;

        $request = new Request('GET', $uri);

        try {
            $response = $this->getResponse($request);
        } catch (Exception\RequestException $ex) {
            /* @var $prevEx \GuzzleHttp\Exception\ClientException */
            $prevEx = $ex->getPrevious();

            if ($prevEx->hasResponse() === true && $prevEx->getResponse()->getStatusCode() === 403) {
                throw new Exception\InvalidCredentialsException('Your API key "' . $this->apiKey . '" is not valid for ' . $this->getName(), null, $ex);
            }

            throw $ex;
        }

        /*
         * no json returned?
         */
        $contentType = $response->getHeader('Content-Type');
        if (! isset($contentType[0]) || $contentType[0] != 'application/json; charset=utf-8') {
            throw new Exception\RequestException('Could not get valid "application/json; charset=utf-8" response from "' . $request->getUri() . '". Response is "' . $response->getBody()->getContents() . '"');
        }

        $content = json_decode($response->getBody()->getContents());

        /*
         * No result
         */
        if (isset($content->MatchMethod) && $content->MatchMethod == 'None') {
            throw new Exception\NoResultFoundException('No result found for user agent: ' . $userAgent);
        }

        /*
         * Missing data?
         */
        if (! $content instanceof stdClass || ! isset($content->Values)) {
            throw new Exception\RequestException('Could not get valid response from "' . $request->getUri() . '". Data is missing "' . $response->getBody()->getContents() . '"');
        }

        /*
         * Convert the values, to something useable
         */
        $values              = new \stdClass();
        $values->MatchMethod = $content->MatchMethod;

        foreach ($content->Values as $key => $value) {
            if (is_array($value) && count($value) === 1 && isset($value[0])) {
                $values->{$key} = $value[0];
            }
        }

        foreach ($values as $key => $value) {
            if ($value === 'True') {
                $values->{$key} = true;
            } elseif ($value === 'False') {
                $values->{$key} = false;
            }
        }

        return $values;
    }

    /**
     *
     * @param Model\Bot $bot
     * @param stdClass  $resultRaw
     */
    private function hydrateBot(Model\Bot $bot, stdClass $resultRaw)
    {
        $bot->setIsBot(true);
    }

    /**
     *
     * @param Model\Browser $browser
     * @param stdClass      $resultRaw
     */
    private function hydrateBrowser(Model\Browser $browser, stdClass $resultRaw)
    {
        if (isset($resultRaw->BrowserName)) {
            $browser->setName($this->getRealResult($resultRaw->BrowserName));
        }

        if (isset($resultRaw->BrowserVersion)) {
            $browser->getVersion()->setComplete($this->getRealResult($resultRaw->BrowserVersion));
        }
    }

    /**
     *
     * @param Model\RenderingEngine $engine
     * @param stdClass              $resultRaw
     */
    private function hydrateRenderingEngine(Model\RenderingEngine $engine, stdClass $resultRaw)
    {
        if (isset($resultRaw->LayoutEngine)) {
            $engine->setName($this->getRealResult($resultRaw->LayoutEngine));
        }
    }

    /**
     *
     * @param Model\OperatingSystem $os
     * @param stdClass              $resultRaw
     */
    private function hydrateOperatingSystem(Model\OperatingSystem $os, stdClass $resultRaw)
    {
        if (isset($resultRaw->PlatformName)) {
            $os->setName($this->getRealResult($resultRaw->PlatformName));
        }

        if (isset($resultRaw->PlatformVersion)) {
            $os->getVersion()->setComplete($this->getRealResult($resultRaw->PlatformVersion));
        }
    }

    /**
     *
     * @param Model\Device $device
     * @param stdClass     $resultRaw
     */
    private function hydrateDevice(Model\Device $device, stdClass $resultRaw)
    {
        if (isset($resultRaw->HardwareVendor)) {
            $device->setBrand($this->getRealResult($resultRaw->HardwareVendor));
        }
        if (isset($resultRaw->HardwareFamily)) {
            $device->setModel($this->getRealResult($resultRaw->HardwareFamily));
        }
        if (isset($resultRaw->DeviceType)) {
            $device->setType($this->getRealResult($resultRaw->DeviceType));
        }
        if (isset($resultRaw->IsMobile)) {
            $device->setIsMobile($this->getRealResult($resultRaw->IsMobile));
        }
    }

    public function parse($userAgent, array $headers = [])
    {
        $resultRaw = $this->getResult($userAgent, $headers);

        /*
         * Hydrate the model
         */
        $result = new Model\UserAgent($this->getName(), $this->getVersion());
        $result->setProviderResultRaw($resultRaw);

        /*
         * Bot detection
         */
        if (isset($resultRaw->IsCrawler) && $resultRaw->IsCrawler === true) {
            $this->hydrateBot($result->getBot(), $resultRaw);

            return $result;
        }

        /*
         * hydrate the result
         */
        $this->hydrateBrowser($result->getBrowser(), $resultRaw);
        $this->hydrateRenderingEngine($result->getRenderingEngine(), $resultRaw);
        $this->hydrateOperatingSystem($result->getOperatingSystem(), $resultRaw);
        $this->hydrateDevice($result->getDevice(), $resultRaw);

        return $result;
    }
}


text:
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.ResourceManager;

namespace Azure.ResourceManager.ServiceFabricManagedClusters
{
    internal class ServiceFabricManagedServiceOperationSource : IOperationSource<ServiceFabricManagedServiceResource>
    {
        private readonly ArmClient _client;

        internal ServiceFabricManagedServiceOperationSource(ArmClient client)
        {
            _client = client;
        }

        ServiceFabricManagedServiceResource IOperationSource<ServiceFabricManagedServiceResource>.CreateResult(Response response, CancellationToken cancellationToken)
        {
            using var document = JsonDocument.Parse(response.ContentStream);
            var data = ServiceFabricManagedServiceData.DeserializeServiceFabricManagedServiceData(document.RootElement);
            return new ServiceFabricManagedServiceResource(_client, data);
        }

        async ValueTask<ServiceFabricManagedServiceResource> IOperationSource<ServiceFabricManagedServiceResource>.CreateResultAsync(Response response, CancellationToken cancellationToken)
        {
            using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false);
            var data = ServiceFabricManagedServiceData.DeserializeServiceFabricManagedServiceData(document.RootElement);
            return new ServiceFabricManagedServiceResource(_client, data);
        }
    }
}


text:
<?php

namespace Sake\BlockchainWalletApi\Service;

use Sake\BlockchainWalletApi\Exception;
use Sake\BlockchainWalletApi\Request\RequestInterface;
use Zend\ServiceManager\AbstractPluginManager;

/**
 * Plugin manager implementation for requests.
 *
 * Enforces that requests retrieved are either callbacks or instances of RequestInterface. Additionally, it
 * registers a number of default requests which matches the blockchain wallet api service request method name.
 */
class RequestPluginManager extends AbstractPluginManager
{
    /**
     * Default set of requests, note the method name must be without underscore
     *
     * @var array
     */
    protected $invokableClasses = array(
        'addressbalance' => '\Sake\BlockchainWalletApi\Request\AddressBalance',
        'balance'        => '\Sake\BlockchainWalletApi\Request\WalletBalance',
        'list'           => '\Sake\BlockchainWalletApi\Request\ListAddresses',
        'newaddress'     => '\Sake\BlockchainWalletApi\Request\NewAddress',
        'payment'        => '\Sake\BlockchainWalletApi\Request\Send',
        'sendmany'       => '\Sake\BlockchainWalletApi\Request\SendMany',
        'archiveaddress' => '\Sake\BlockchainWalletApi\Request\AddressArchive',
        'unarchiveaddress' => '\Sake\BlockchainWalletApi\Request\AddressUnarchive',
        'autoconsolidate' => '\Sake\BlockchainWalletApi\Request\AutoConsolidateAddresses',
    );

    /**
     * Whether or not to share by default; default to false
     *
     * @var bool
     */
    protected $shareByDefault = false;

    /**
     * Validate the plugin
     *
     * Checks that the request loaded is either a valid callback or an instance of RequestInterface.
     *
     * @param  mixed $plugin
     * @return void
     * @throws Exception\RuntimeException if invalid
     */
    public function validatePlugin($plugin)
    {
        if ($plugin instanceof RequestInterface) {
            // we're okay
            return;
        }
        if (is_callable($plugin)) {
            // also okay
            return;
        }

        throw new Exception\RuntimeException(sprintf(
            'Plugin of type %s is invalid; must implement %s\RequestInterface or be callable',
            (is_object($plugin) ? get_class($plugin) : gettype($plugin)),
            __NAMESPACE__
        ));
    }
}


text:
package neophytesguide01

object ExtractorDemo3 {
  def main(args: Array[String]): Unit = {
    val user1: User = new FreeUser("Adam", 9, 0.6)
  	val user2: User = new FreeUser("Eva", 3, 0.9)
    val user3: User = new PremiumUser("Kain", 1)

    def greet(user: User): Unit = user match {
      case freeUser @ PremiumCandidate() => initiateSpamProgram(freeUser)
      case premiumUser: PremiumUser => sendRegularNewsletter(premiumUser)
      case _ =>
    }

    def initiateSpamProgram(user: FreeUser) = {
      for (i <- 1 to 3) {
        println("What can we do for you today, " + user.name + "?")
      }
    }

    def sendRegularNewsletter(user: User) = {
      println("Welcome back, dear " + user.name)
    }

    greet(user1)
    greet(user2)
    greet(user3)
  }

  trait User {
    def name: String
    def score: Int
  }

  class FreeUser(val name: String, val score: Int, val upgradeProbability: Double) extends User
  object FreeUser {
    def unapply(user: FreeUser): Option[(String, Int, Double)] = Some((user.name, user.score, user.upgradeProbability))
  }

  class PremiumUser(val name: String, val score: Int) extends User
  object PremiumUser {
    def unapply(user: PremiumUser): Option[(String, Int)] = Some((user.name, user.score))
  }

  object PremiumCandidate {
    def unapply(user: FreeUser): Boolean = user.upgradeProbability > 0.75
  }
}


text:
namespace ServicesInforCollector.UiControls
{
    partial class WmiSumInfo
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.gbDetail = new System.Windows.Forms.GroupBox();
            this.tbDesc = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.tbPath = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.tbDispName = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.tbName = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.gbDetail.SuspendLayout();
            this.SuspendLayout();
            //
            // gbDetail
            //
            this.gbDetail.Controls.Add(this.tbDesc);
            this.gbDetail.Controls.Add(this.label4);
            this.gbDetail.Controls.Add(this.tbPath);
            this.gbDetail.Controls.Add(this.label3);
            this.gbDetail.Controls.Add(this.tbDispName);
            this.gbDetail.Controls.Add(this.label2);
            this.gbDetail.Controls.Add(this.tbName);
            this.gbDetail.Controls.Add(this.label1);
            this.gbDetail.Dock = System.Windows.Forms.DockStyle.Fill;
            this.gbDetail.Location = new System.Drawing.Point(0, 0);
            this.gbDetail.Name = "gbDetail";
            this.gbDetail.Size = new System.Drawing.Size(158, 338);
            this.gbDetail.TabIndex = 0;
            this.gbDetail.TabStop = false;
            this.gbDetail.Text = "Service Info";
            //
            // tbDesc
            //
            this.tbDesc.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.tbDesc.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tbDesc.Location = new System.Drawing.Point(3, 177);
            this.tbDesc.Multiline = true;
            this.tbDesc.Name = "tbDesc";
            this.tbDesc.Size = new System.Drawing.Size(152, 158);
            this.tbDesc.TabIndex = 7;
            //
            // label4
            //
            this.label4.Dock = System.Windows.Forms.DockStyle.Top;
            this.label4.Location = new System.Drawing.Point(3, 157);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(152, 20);
            this.label4.TabIndex = 6;
            this.label4.Text = "Desc";
            //
            // tbPath
            //
            this.tbPath.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.tbPath.Dock = System.Windows.Forms.DockStyle.Top;
            this.tbPath.Location = new System.Drawing.Point(3, 119);
            this.tbPath.Multiline = true;
            this.tbPath.Name = "tbPath";
            this.tbPath.Size = new System.Drawing.Size(152, 38);
            this.tbPath.TabIndex = 5;
            //
            // label3
            //
            this.label3.Dock = System.Windows.Forms.DockStyle.Top;
            this.label3.Location = new System.Drawing.Point(3, 99);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(152, 20);
            this.label3.TabIndex = 4;
            this.label3.Text = "Path";
            //
            // tbDispName
            //
            this.tbDispName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.tbDispName.Dock = System.Windows.Forms.DockStyle.Top;
            this.tbDispName.Location = new System.Drawing.Point(3, 78);
            this.tbDispName.Name = "tbDispName";
            this.tbDispName.Size = new System.Drawing.Size(152, 21);
            this.tbDispName.TabIndex = 3;
            //
            // label2
            //
            this.label2.Dock = System.Windows.Forms.DockStyle.Top;
            this.label2.Location = new System.Drawing.Point(3, 58);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(152, 20);
            this.label2.TabIndex = 2;
            this.label2.Text = "Disp Name";
            //
            // tbName
            //
            this.tbName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.tbName.Dock = System.Windows.Forms.DockStyle.Top;
            this.tbName.Location = new System.Drawing.Point(3, 37);
            this.tbName.Name = "tbName";
            this.tbName.Size = new System.Drawing.Size(152, 21);
            this.tbName.TabIndex = 1;
            //
            // label1
            //
            this.label1.Dock = System.Windows.Forms.DockStyle.Top;
            this.label1.Location = new System.Drawing.Point(3, 17);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(152, 20);
            this.label1.TabIndex = 0;
            this.label1.Text = "Name";
            //
            // WmiSumInfo
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.gbDetail);
            this.Name = "WmiSumInfo";
            this.Size = new System.Drawing.Size(158, 338);
            this.gbDetail.ResumeLayout(false);
            this.gbDetail.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.GroupBox gbDetail;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox tbDesc;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox tbPath;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox tbDispName;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox tbName;

    }
}


text:
namespace SpacedTextPlugin.Data
{
    using System.Drawing;

    class Settings
    {
        public string Text { get; set; }
        public FontFamily FontFamily { get; set; }
        public int FontSize { get; set; }
        public double LetterSpacing { get; set; }
        public double LineSpacing { get; set; }
        public int AntiAliasLevel { get; set; }
        public FontStyle FontStyle { get; set; }
        public Constants.TextAlignmentOptions TextAlign { get; set; }

        public Font GetFont()
        {
            return new Font(FontFamily, FontSize, FontStyle, GraphicsUnit.Pixel);
        }

        public Font GetAntiAliasSizeFont()
        {
            return new Font(FontFamily, FontSize * AntiAliasLevel, FontStyle, GraphicsUnit.Pixel);
        }
    }
}


text:
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);

function drawChart() {

    $.get('data.csv', function(csvString) {

        var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});

        var data = new google.visualization.arrayToDataTable(arrayData);

        // this view can select a subset of the data at a time
        var view = new google.visualization.DataView(data);
        view.setColumns([0,1]);

        var options = {
            legend: { position: 'top', maxLines: 3 },
            bar: { groupWidth: '90%' },
            height: 550,
            isStacked: true,
            colors: ['#993300', '#b50000', '#FF0000', '#FF6600', '#a2d93c', '#0099C6', '#3366CC'],
            chartArea: {
                'width': '80%',
                'height': '75%' },
                hAxis: {
                    showTextEvery: 'automatic' }
                };

        var chart = new google.visualization.ColumnChart(document.getElementById('chart_div')); // ColumnChart / PieChart / BarChart ect...
        chart.draw(data, options);
    });
}

// Redraw chart on window resize

jQuery(window).resize(function () { // Resize charts in case of window resize

    drawChart();
});


text:
```
go get github.com/javidgon/historian
```
In case of errors, please have a look at the `git2go` documentation [here](https://github.com/libgit2/git2go).
You might need to follow the instuctions as described in the `install_requirements.sh` file

### Getting started

```
# The first argument is the path to the git repository
# The second argument is the last commit we want to include in the "release notes"

historian /path/to/the/repo 4481c5c8b3b548490e0cc55a18fb599a61d98131

Processing...
err %v <nil>
err %v <nil>
err %v <nil>
err %v <nil>
err %v <nil>
err %v <nil>
err %v <nil>
err %v <nil>
err %v <nil>
err %v <nil>
err %v <nil>
ret %v 0
********************************************
release_notes.txt file successfully created!
********************************************
```

Having a look at the `release_notes.txt` file:

```
==========================================================
** Release Notes (Sunday, 26-Jul-15 09:21:29 UTC):
0) <you@example.com> (2015-07-25 19:10:03 +0000 +0000) This is my first commit
1) <you@example.com> (2015-07-25 19:20:16 +0000 +0000) This my second commit
2) <you@example.com> (2015-07-26 08:14:10 +0000 +0000) This is my third commit

This commit has body with points as well:

* Point 1
* Point 2

3) <you@example.com> (2015-07-26 08:20:14 +0000 +0000) This is my forth commit
4) <you@example.com> (2015-07-26 08:24:10 +0000 +0000) This is my fifth comment

This one has a smaller body
==========================================================
```


text:
//  Color.cpp
// Sketchup C++ Wrapper for C API
// MIT License
//
// Copyright (c) 2017 Tom Kaneko
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

#include "SUAPI-CppWrapper/Color.hpp"

namespace CW {

Color::Color():
  m_color(SUColor{}),
  red(m_color.red),
  green(m_color.green),
  blue(m_color.blue),
  alpha(m_color.alpha)
{}

Color::Color(SUColor color_input):
  m_color(color_input),
  red(m_color.red),
  green(m_color.green),
  blue(m_color.blue),
  alpha(m_color.alpha)
{}

SUColor Color::ref() const {
  return m_color;
}

Color::operator SUColor() const {
  return ref();
}

bool operator ==(const Color &lhs, const Color &rhs) {
  if (lhs.m_color.alpha == rhs.m_color.alpha &&
      lhs.m_color.red == rhs.m_color.red &&
      lhs.m_color.blue == rhs.m_color.blue &&
      lhs.m_color.green == rhs.m_color.green)  {
    return true;
  }
  return false;
}

} /* namespace CW */


text:
require "spec_helper"

RSpec.describe ResultDisplayer::TimeResult do
  let(:subject) { described_class.new(competition) }

  context "points competition" do
    let(:competition) { FactoryBot.build(:high_points_competition) }
    let(:result) { FactoryBot.build(:import_result, points: 3.45) }

    it "summary_headings" do
      expect(subject.summary_headings).to eq(["Points"])
    end

    it "summary_result_data" do
      expect(subject.summary_result_data(result)).to eq(["3.45"])
    end
  end

  context "times competition" do
    let(:competition) { FactoryBot.build(:timed_competition) }
    let(:result) { FactoryBot.build(:import_result, minutes: 1, seconds: 2, thousands: 345) }

    it "summary_headings" do
      expect(subject.summary_headings).to eq(["Time"])
    end

    it "summary_result_data" do
      expect(subject.summary_result_data(result)).to eq(["01:02.345"])
    end

    it "headings" do
      expect(subject.headings).to eq(["Minutes", "Seconds", "Thousands"])
    end

    it "result_data" do
      expect(subject.result_data(result)).to eq([1, 2, 345])
    end

    it "form_label_symbols" do
      expect(subject.form_label_symbols).to eq(%i[minutes seconds thousands])
    end

    it "form_inputs" do
      expect(subject.form_inputs).to eq([
                                          [:minutes, { min: 0 }],
                                          [:seconds, { min: 0 }],
                                          [:thousands, { min: 0 }]
                                        ])
    end
  end

  context "times with laps competition" do
    let(:competition) { FactoryBot.build(:timed_laps_competition) }
    let(:result) { FactoryBot.build(:import_result, minutes: 1, seconds: 2, thousands: 345, number_of_laps: 3) }

    it "summary_headings" do
      expect(subject.summary_headings).to eq(["Time", "# Laps"])
    end

    it "summary_result_data" do
      expect(subject.summary_result_data(result)).to eq(["01:02.345", 3])
    end

    it "headings" do
      expect(subject.headings).to eq(["Minutes", "Seconds", "Thousands", "# Laps"])
    end

    it "result_data" do
      expect(subject.result_data(result)).to eq([1, 2, 345, 3])
    end

    it "form_label_symbols" do
      expect(subject.form_label_symbols).to eq(%i[minutes seconds thousands number_of_laps])
    end

    it "form_inputs" do
      expect(subject.form_inputs).to eq([
                                          [:minutes, { min: 0 }],
                                          [:seconds, { min: 0 }],
                                          [:thousands, { min: 0 }],
                                          [:number_of_laps, { min: 1 }]
                                        ])
    end
  end
end


text:
'use strict';

var io = require('socket.io-client/dist/socket.io');

var injectParams = ['socketFactory'];

var SocketService = function(socketFactory)
{
    return socketFactory(
    {
        ioSocket: io()
    });
};

SocketService.$inject = injectParams;

module.exports = SocketService;


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;

namespace LibRJ.Cities.Models
{
    public class City : GeoNameResource
    {
        public int ID { get; set; }

        [StringLength(200)]
        public string Name { get; set; }

        [StringLength(200)]
        public string DisplayName { get; set; }

        public decimal Latitude { get; set; }
        public decimal Longitude { get; set; }

        public UInt32 Population { get; set; }

        public int RegionID { get; set; }
	}

}


text:
package org.cogroo.analyzer;

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

import org.cogroo.text.Document;
import org.cogroo.text.Sentence;
import org.cogroo.text.impl.SentenceImpl;

import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.util.Span;

/**
 *  The <code> SentenceDetector</code> class gets all the sentences in the document text and store them in a list of sentences.
 *
 */
public class SentenceDetector implements Analyzer {

  private SentenceDetectorME sentenceDetector;

  public SentenceDetector(SentenceDetectorME sentenceDetector) {
    this.sentenceDetector = sentenceDetector;
  }

  /**
   * @throws IllegalArgumentException
   *           if document text is null.
   */
  public void analyze(Document document) {

    if (document.getText() == null)
      throw new IllegalArgumentException("Document text is null.");

    Span[] spans;
    synchronized (sentenceDetector) {
      spans = sentenceDetector.sentPosDetect(document.getText());
    }

    List<Sentence> sentences = new ArrayList<Sentence>(spans.length);

    for (int i = 0; i < spans.length; i++) {
      Sentence sentence = new SentenceImpl(spans[i].getStart(), spans[i].getEnd(), document);
      sentences.add(sentence);
    }

    document.setSentences(sentences);
  }
}


text:
using Latrunculi.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Latrunculi
{
    /// <summary>
    /// Obecná hrací deska
    /// </summary>
    public abstract class Board
    {
        private Pieces[,] _data = null;
        /// <summary>
        /// interní reprezentace desky
        /// </summary>
        private Pieces[,] Data
        {
            get
            {
                return _data;
            }
        }

        /// <summary>
        /// Přístup k hodnotám polí desky.
        /// </summary>
        /// <param name="coord"></param>
        /// <returns></returns>
        public Pieces this[Coord coord]
        {
            get
            {
                if (!IsInitiaized || (Data == null))
                    throw new InvalidOperationException("Pole hrací desky nelze přečíst, protože deska ještě nebyla inicializována.");

                if (!IsCoordValid(coord))
                    throw new IndexOutOfRangeException("Zadaná souřadnice je mimo rozsah hrací desky !");

                return Data[coord.x - 'A', coord.y - 1];
            }
            set
            {
                if (!IsInitiaized || (Data == null))
                    throw new InvalidOperationException("Pole hrací desky nelze nastavit, protože deska ještě nebyla inicializována.");

                if (!IsCoordValid(coord))
                    throw new IndexOutOfRangeException("Zadaná souřadnice je mimo rozsah hrací desky !");

                Data[coord.x - 'A', coord.y - 1] = value;
            }
        }

        /// <summary>
        /// zjisti pocet kamenu dane barvy
        /// </summary>
        /// <param name="color"></param>
        /// <returns></returns>
        public int GetNumberOfPieces(GameColorsEnum color)
        {
            Coord c = new Coord();
            int result = 0;

            for (char x = 'A'; x <= MaxX; x++)
            {
                for (byte y = 1; y <= MaxY; y++)
                {
                    c.Set(x, y);

                    switch(color)
                    {
                        case GameColorsEnum.plrBlack:
                            if (this[c] == Pieces.pcBlack || this[c] == Pieces.pcBlackKing)
                                result++;
                            break;
                        case GameColorsEnum.plrWhite:
                            if (this[c] == Pieces.pcWhite || this[c] == Pieces.pcWhiteKing)
                                result++;
                            break;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Přetížit pro nastavení max. hodnoty první souřadnice
        /// </summary>
        public virtual char MaxX
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// Přetížit pro nastavení max. hodnoty druhé souřadnice
        /// </summary>
        public virtual byte MaxY
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// Indikuje zda byla zavolána metoda init.
        /// </summary>
        public bool IsInitiaized
        {
            get;
            private set;
        }

        /// <summary>
        /// Alokovat nebo vynulovat pole.
        /// </summary>
        private void AllocOrResetData()
        {
            int n_x, n_y;
            n_x = MaxX - 'A' + 1;
            n_y = MaxY;

            if (_data == null)
                _data = new Pieces[n_x, n_y];
            else
                Array.Clear(_data, 0, n_x * n_y);
        }

        /// <summary>
        /// inicializace desky = výchozí rozestavění figurek podle pravidel
        /// </summary>
        public void Init()
        {
            IsInitiaized = false;
            AllocOrResetData();
            IsInitiaized = true;

            try
            {
                OnInit();
            }
            catch (Exception exc)
            {
                IsInitiaized = false;
                throw exc;
            }
        }

        /// <summary>
        /// Místo pro implementaci inicializační metody.
        /// </summary>
        protected virtual void OnInit()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Provedeni tahu bez odebrani kamenu.
        /// </summary>
        /// <param name="move"></param>
        private void ApplyMoveNoRemove(Move move)
        {
            if (move == null)
                throw new ArgumentNullException("move");

            Coord src = move.Source;
            Coord tar = move.Target;

            this[src] = move.SourcePiece;
            this[tar] = move.TargetPiece;
        }

        /// <summary>
        /// Proved tah
        /// </summary>
        public void ApplyMove(Move move)
        {
            ApplyMoveNoRemove(move);

            foreach(RemovedPiece c in move.RemovedPieces)
            {
                this[c.Coord] = Pieces.pcNone;
            }
        }

        /// <summary>
        /// Proved inverzni tah
        /// </summary>
        /// <param name="move"></param>
        public void ApplyInvMove(Move move)
        {
            Move inv = new Move(move.Target, move.Source, move.SourcePiece, move.TargetPiece);
            ApplyMoveNoRemove(inv);

            foreach(RemovedPiece c in move.RemovedPieces)
            {
                this[c.Coord] = c.Piece;
            }
        }

        /// <summary>
        /// Pro ověření souřadnice zadané uživatelem.
        /// </summary>
        /// <param name="coord"></param>
        /// <returns></returns>
        public bool IsCoordValid(Coord coord)
        {
            return (coord.x >= 'A' && coord.x <= MaxX) &&
                   (coord.y >= 1 && coord.y <= MaxY);
        }

        /// <summary>
        /// Ziska posunutou souradnici. Za okraj desky nedovoli jit a vraci null.
        /// Podporuje zatim pouze ortogonalni smery.
        /// </summary>
        /// <param name="current"></param>
        /// <returns></returns>
        public Coord? GetRelativeCoord(Coord current, CoordDirectionEnum direction)
        {
            int deltaX = 0;
            int deltaY = 0;

            switch (direction)
            {
                case CoordDirectionEnum.deForward:
                    deltaY = 1;
                    break;
                case CoordDirectionEnum.deAft:
                    deltaY = -1;
                    break;
                case CoordDirectionEnum.deLeft:
                    deltaX = -1;
                    break;
                case CoordDirectionEnum.deRight:
                    deltaX = 1;
                    break;
            }

            if ((current.x + deltaX) > MaxX || (current.x + deltaX) < 'A')
                return null;
            else if ((current.y + deltaY) > MaxY || (current.y + deltaY) < 1)
                return null;
            else
                return Coord.Create((char)(current.x + deltaX), (byte)(current.y + deltaY));
        }

        /// <summary>
        /// Vytvorit kopii desky (napr. pro ucely Mozku)
        /// </summary>
        public Board GetBoardCopy()
        {
            if (!(this is ICloneable))
                throw new NotSupportedException();
            else
            {
                Board board = ((ICloneable)this).Clone() as Board;
                board.AllocOrResetData();
                board.IsInitiaized = true;

                Coord c = new Coord();
                for (char x = 'A'; x <= MaxX; x++)
                {
                    for (byte y = 1; y <= MaxY; y++)
                    {
                        c.Set(x, y);
                        board[c] = this[c];
                    }
                }

                return board;
            }
        }
    }
}


text:
describe('helper', function()
  local Helper = require 'resty.web_shield.helper'

  describe('correct_time', function()
    after_each(function()
      Helper.cache:set('last_correct_time_at', 0)
      Helper.time_offset = 0
    end)

    it('should update time_offset', function()
      local s = spy.new(function() return os.time() - 1 end)
      assert.is_equal(Helper.time_offset, 0)
      Helper.correct_time(s)
      assert.is_equal(Helper.time_offset, -1)
      assert.is_truthy((os.time() - Helper.cache:get('last_correct_time_at')) <= 1)
      assert.spy(s).was_called()
      s:revert()
    end)

    it('should not call if last called in the last 30 seconds', function()
      local s = spy.new(function() return os.time() - 1 end)
      Helper.correct_time(os.time)
      Helper.correct_time(s)
      assert.is_equal(Helper.time_offset, 0)
      assert.spy(s).was_not_called()
      Helper.cache:set('last_correct_time_at', 0)
      Helper.correct_time(s)
      assert.spy(s).was_called()
      s:revert()
    end)

    it('should not raise error', function()
      -- exception
      Helper.correct_time(function() asdf() end)

      Helper.cache:set('last_correct_time_at', 0)
      -- invalid value
      Helper.correct_time(function() return 'asdf' end)
    end)
  end)

  describe('time', function()
    it('should return current timestamp', function()
      assert.is_equal(Helper.time(), ngx.time())
    end)
  end)

  describe('md5', function()
    it('should return md5 hex', function()
      assert.is_equal(Helper.md5('hello'), '5d41402abc4b2a76b9719d911017c592')
    end)
  end)

  describe('new_redis', function()
    local Redis = require 'resty.redis'
    local redis_new_fn = Redis.new

    after_each(function()
      Redis.new = redis_new_fn
    end)

    it('should connect local redis if not give config', function()
      local r = Redis.new()
      local s1 = spy.on(Redis, 'new')
      local s2 = spy.on(r, 'connect')
      s1.callback = function() return r end

      assert.is_equal(Helper.new_redis(), r)
      assert.spy(s1).was_called()
      assert.spy(s2).was_called_with(match.is_table(), '127.0.0.1', 6379)
      s1:revert()
      s2:revert()
    end)

    it('should connect specify redis if give config', function()
      local r = Redis.new()
      local s1 = spy.on(Redis, 'new')
      local s2 = spy.on(r, 'connect')
      s1.callback = function() return r end

      assert.is_equal(Helper.new_redis{host = '1.2.3.4', port = 1234}, nil)
      assert.spy(s1).was_called()
      assert.spy(s2).was_called_with(match.is_table(), '1.2.3.4', 1234)
      s1:revert()
      s2:revert()
    end)
  end)

  describe('new_redis_with', function()
    it('should use conn_config', function()
      local r = {set_keepalive = function() end}
      local new_redis = Helper.new_redis
      local s1 = spy.on(Helper, 'new_redis')
      s1.callback = function() return r end
      local s2 = spy.on(r, 'set_keepalive')

      assert.is_equal(Helper.new_redis_with(
        {host = '1.2.3.4', port = 1234},
        {pool_size = 12, pool_timeout = 211},
        function(conn) return 123 end
      ), 123)

      assert.spy(s1).was_called_with({host = '1.2.3.4', port = 1234})
      assert.spy(s2).was_called_with(r, 211, 12)
      s1:revert()
      s2:revert()
      Helper.new_redis = new_redis
    end)
  end)

  describe('new_mysql', function()
    local Mysql = require 'resty.mysql'
    local mysql_new_fn = Mysql.new
    local config = {
      host = '127.0.0.1',
      port = '3306',
      user = 'root',
      password = '',
      database = 'ngx_test'
    }

    after_each(function()
      Mysql.new = mysql_new_fn
    end)

    it('should connect specify db', function()
      local db = Mysql.new()
      local s1 = spy.on(Mysql, 'new')
      local s2 = spy.on(db, 'connect')
      s1.callback = function() return db end

      assert.is_equal(Helper.new_mysql(config), db)
      assert.spy(s1).was_called()
      assert.spy(s2).was_called_with(match.is_table(), config)
      s1:revert()
      s2:revert()
    end)
  end)

  describe('new_mysql_with', function()
    it('should use conn_config', function()
      local db = {set_keepalive = function() end}
      local new_mysql = Helper.new_mysql
      local s1 = spy.on(Helper, 'new_mysql')
      s1.callback = function() return db end
      local s2 = spy.on(db, 'set_keepalive')

      assert.is_equal(Helper.new_mysql_with(
        {foo = 'bar'},
        {pool_size = 33, pool_timeout = 222},
        function(conn) return 123 end
      ), 123)

      assert.spy(s1).was_called_with({foo = 'bar'})
      assert.spy(s2).was_called_with(db, 222, 33)
      s1:revert()
      s2:revert()
      Helper.new_mysql = new_mysql
    end)
  end)

end)


text:
This package includes the global command for [Create React App](https://github.com/facebook/create-react-app).<br>
Please refer to its documentation:

- [Getting Started](https://github.com/facebook/create-react-app/blob/master/README.md#getting-started) – How to create a new app.
- [User Guide](https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md) – How to develop apps bootstrapped with Create React App.


text:
import React from 'react';
import renderer from 'react-test-renderer';

import { BLOCK_TYPE_TEXT } from '../../common/api/pages';
import BlockText from '../../common/components/BlockText';

const FAKE_BLOCK_TEXT = {
  type: BLOCK_TYPE_TEXT,
  body: 'Universal JavaScript applications',
};

describe('Block Text Component', () => {
  it('renders a text block', () => {
    const tree = renderer.create(<BlockText {...FAKE_BLOCK_TEXT} />).toJSON();
    expect(tree).toMatchSnapshot();
  });
});


text:
import {entity, stain, vector} from "../entities.js";
import {random, tau, torus, modulo} from "../math.js";
import {board} from "../board.js";
import {draw} from "../draw.js";

export class ant extends entity {
	constructor(position, nest) {
		super(position);
		this.direction = random(tau);
		Object.assign(this, {
			drawn: draw.addPolygon(this, 'entities'),
			nest,
			strength: 1,
			manoeuvrability: .5,
			velocity: [.6, 1],
			carry: 1,
			talkative: .1,	//0-> no msg, 1-> a msg each turn
			loaded: false,
			spoken: {}
		});
		this.redraw();
	}
	get radius() { return 5; }
	roundDir(add) {
		if(add) this.direction += add;
		this.direction = modulo(this.direction);
	}
	/**
	 * Turns toward angle {{angle}} turning maximum {{vel}} radians
	 */
	turnTo(angle, vel) {
		angle = torus(angle, this.direction);
		vel = Math.min(vel || this.manoeuvrability, Math.abs(angle));
		if(angle < 0) vel = -vel;
		this.roundDir(vel);
		return this;
	}
	advance(steps) {
		return board.clip(this.add((new vector((steps||1)*this.velocity[this.loaded?0:1])).rotate(this.direction)));
	}
	wound(objects) {
		var o, p;
		for(o of objects.stains) {
			p = o.intensity(this);
			if(p) {
				p = p.strength*o.strength;
				p = Math.min(o.strength, Math.max(p, .001));	//don't take less than .001 or the remaining strength if it is smaller
				this.strength -= p;
				if(0< (o.strength -= p))
					o.redraw();
				else
					o.remove()
			}
		}
		this.strength -= Math.random()/500;
		if(0>= this.strength) this.remove();
	}
	eat(qtt) {
		this.strength = Math.min(1, this.strength+qtt);
	}
	remove() {
		super.remove();
		this.nest.ants.delete(this);
	}
	redraw() {
		var angle = Math.atan(this.strength);
		this.points = [
			(new vector(1)).rotate(this.direction+Math.PI).add(this),
			(new vector(1)).rotate(this.direction+angle).add(this),
			(new vector(1)).rotate(this.direction).add(this),
			(new vector(1)).rotate(this.direction-angle).add(this)
		];
		super.redraw();
	}
	get fill() {
		return {
			h: this.nest.hue,
			s: .5,
			b: this.loaded?.25+this.loaded.grass:.25,
			o: .7
		};
	}
}

export class nest extends stain {
	constructor(hue, position, radius) {
		super(position, radius, 1);

		Object.assign(this, {
			hue,
			strength: 1,
			ants: new Set(),
			resource: 0
		});
		this.redraw();
	}
	get fill() {
		return {
			h: this.hue,
			s: this.strength,
			b: .5,
			o: .3
		};
	}
	/**
	 * Spawn ants to this nest
	 */
	spawn(number) {
		var i;
		for(i=0; i<(number||1); ++i)
			this.ants.add(new ant(vector.around(this.radius, this), this));
	}
	eat(qtt) {
		var r = Math.floor(this.resource += 2*qtt);
		if(r) {
			this.spawn(r);
			this.resource -= r;
		}
	}
	clear() {
		for(let ant of this.ants) ant.remove();
		Object.assign(this, {
			strength: 1,
			ants: new Set(),
			resource: 0
		});
	}
}


text:
"""
A minimal front end to the Docutils Publisher, producing LaTeX.
"""

try:
    import locale
    locale.setlocale(locale.LC_ALL, '')
except:
    pass

from docutils.parsers.rst.roles import register_canonical_role
from docutils import nodes
from docutils.writers.latex2e import LaTeXTranslator
from docutils.parsers.rst.directives import _directives
from docutils.core import publish_cmdline, default_description

# Define LaTeX math node:
class latex_math(nodes.Element):
    tagname = '#latex-math'
    def __init__(self, rawsource, latex):
        nodes.Element.__init__(self, rawsource)
        self.latex = latex

# Register role:
def latex_math_role(role, rawtext, text, lineno, inliner,
                    options={}, content=[]):
    i = rawtext.find('`')
    latex = rawtext[i+1:-1]
    node = latex_math(rawtext, latex)
    return [node], []
register_canonical_role('latex-math', latex_math_role)

# Register directive:
def latex_math_directive(name, arguments, options, content, lineno,
                         content_offset, block_text, state, state_machine):
    latex = ''.join(content)
    node = latex_math(block_text, latex)
    return [node]
latex_math_directive.arguments = None
latex_math_directive.options = {}
latex_math_directive.content = 1
_directives['latex-math'] = latex_math_directive

# Add visit/depart methods to HTML-Translator:
def visit_latex_math(self, node):
    inline = isinstance(node.parent, nodes.TextElement)
    if inline:
        self.body.append('$%s$' % node.latex)
    else:
        self.body.extend(['\\begin{equation*}\\begin{split}',
                          node.latex,
                          '\\end{split}\\end{equation*}'])
def depart_latex_math(self, node):
    pass
LaTeXTranslator.visit_latex_math = visit_latex_math
LaTeXTranslator.depart_latex_math = depart_latex_math

description = ('Generates LaTeX documents from standalone reStructuredText '
               'sources.  ' + default_description)

publish_cmdline(writer_name='latex', description=description)


text:
import lombok.Data;

@Data
public record DataOnRecord(String a, String b) {
}


text:
// English - root strings
/*jslint indent: 4 */
/*global define */
define({
    // Brackets Menus
    'SHOW_PANEL': 'Show brackets-tailf',
    // Templates HTML Content
    'TITLE_PANEL': 'brackets-tailf'
});


text:
<?php

namespace Yutta\Routing;
use Yutta\Support\Controller;

/**
 * Class Router
 * @package Yutta\Routing
 * @author Tobias Maxham <git2016@maxham.de>
 */
class Router
{

    public $routes = [];

    public function get($path, $action)
    {
        return $this->addRoute('GET', $path, $action);
    }

    public function addRoute($method, $path, $action)
    {
        if ($path == '') {
            $path = '/';
        }

        // never override route
        if (isset($this->routes[$method][$path])) {
            return $this;
        }
        $this->routes[$method][$path] = with(new Route($action, $method, $path));

        return $this;
    }

    private function checkMatches($method)
    {
        if (!isset($this->routes[$method])) {
            return false;
        }

        /** @var Route $route **/
        foreach ($this->routes[$method] as $uri => $route) {
            if (preg_match($route->getCompiled()->getRegex(), $uri)) {
                return $route;
            }
        }
        return false;
    }

    /**
     * @return mixed
     * @throws \Exception
     */
    public function invoke()
    {
        $path = app()['request']->getPathinfo();
        $method = app()['request']->getMethod();

        if (!isset($this->routes[$method][$path])) {
            if (!($route = $this->checkMatches($method))) {
                throw new \Exception('not a route');
            }
        } else {
            $route = $this->routes[$method][$path];
        }

        $routeAction = $route->getAction();

        if (is_callable($routeAction)) {
            return $routeAction->__invoke();
        }

        if (is_string($routeAction)) {
            return $this->callControllerAction($route);
        }

        throw new \Exception('not a program');
    }

    /**
     * @param Route $_route
     * @return mixed
     * @throws \Exception
     */
    private function callControllerAction($_route)
    {
        $routeAction = $_route->getAction();

        $route = explode('@', $routeAction);
        $ctr = $route[0];

        if (count($route) == 1) {
            $method = 'run';
        } else {
            $method = $route[1];
        }

        if (!class_exists($ctr)) {
            throw new \Exception('class does not exists ' . $ctr);
        }

        $ctr = new $ctr;
        if (!$ctr instanceof Controller) {
            throw new \Exception('not a controller');
        }

        if (!method_exists($ctr, $method)) {
            throw new \Exception('Invalid method ' . $method);
        }

        return $ctr->{$method}($_route->getMethod());
    }

}


text:
import inspect
import json
import sys
import time
import os

import ggps

# python ggps-examples.py > data/ggps-examples.txt

if __name__ == "__main__":

    print('version {}'.format(ggps.VERSION))
    print(str(inspect.ismodule(ggps)))

    if True:
        infile = 'data/twin_cities_marathon.tcx'
        handler = ggps.PathHandler()
        handler.parse(infile)
        print(str(handler))
        obj = json.loads(str(handler))

    if True:
        infile = 'data/twin_cities_marathon.tcx'
        handler = ggps.TcxHandler()
        handler.parse(infile)
        trackpoints = handler.trackpoints
        count = len(trackpoints)
        print('{} trackpoints loaded from file {}'.format(count, infile))
        for t in trackpoints:
            print(repr(t))
        print('---')
        print(repr(trackpoints[-1]))
        print('{} trackpoints loaded from file {}'.format(count, infile))

    if True:
        infile = 'data/twin_cities_marathon.gpx'
        handler = ggps.GpxHandler()
        handler.parse(infile)
        trackpoints = handler.trackpoints
        count = len(trackpoints)
        print('{} trackpoints loaded from file {}'.format(count, infile))
        for t in trackpoints:
            print(repr(t))
        print('---')
        print(repr(trackpoints[-1]))
        print('{} trackpoints loaded from file {}'.format(count, infile))

    if True:
        infile = 'data/activity_4564516081.tcx'
        handler = ggps.TcxHandler()
        handler.parse(infile)
        trackpoints = handler.trackpoints
        count = len(trackpoints)
        print('{} trackpoints loaded from file {}'.format(count, infile))
        for t in trackpoints:
            print(repr(t))
        print('trackpoint count: {}'.format(len(trackpoints)))

    if False:
        infile = 'data/activity_4564516081.gpx'
        handler = ggps.GpxHandler()
        handler.parse(infile)
        trackpoints = handler.trackpoints
        count = len(trackpoints)
        print('{} trackpoints loaded from file {}'.format(count, infile))
        for t in trackpoints:
            print(repr(t))

    print('version {}'.format(ggps.VERSION))
    print(str(inspect.ismodule(ggps)))


text:
def check_nxlog(cfg = false)
  # => Config Test
  describe command('nxlog -v') do
    its(:exit_status) { should eq 0 }
    its(:stdout) { should match(/configuration OK/) }
    its(:stderr) { should match(/WARNING no routes defined!/) } unless cfg
    its(:stderr) { should match(/^$/) } if cfg
  end

  # => Verify Service
  if os[:family] == 'debian' && os[:release] == '12.04'
    # => 12.04 Hackjob
    describe command('service nxlog status') do
      its(:exit_status) { should eq 0 }
      its(:stdout) { should match(/[0-9]/) }
      its(:stderr) { should match(/^$/) }
    end
  else
    describe service('nxlog') do
      it { should be_installed }
      it { should be_enabled }
      it { should be_running }
    end
  end
end


text:
"use strict";

/* exported Validation */

var Matcher = require("./Matcher");
var Properties = require("./Properties");
var ValidationTypes = require("./ValidationTypes");
var ValidationError = require("./ValidationError");
var PropertyValueIterator = require("./PropertyValueIterator");

var Validation = module.exports = {

    validate: function(property, value) {

        //normalize name
        var name        = property.toString().toLowerCase(),
            expression  = new PropertyValueIterator(value),
            spec        = Properties[name],
            part;

        if (!spec) {
            if (name.indexOf("-") !== 0) {    //vendor prefixed are ok
                throw new ValidationError("Unknown property '" + property + "'.", property.line, property.col);
            }
        } else if (typeof spec !== "number") {

            // All properties accept some CSS-wide values.
            // https://drafts.csswg.org/css-values-3/#common-keywords
            if (ValidationTypes.isAny(expression, "inherit | initial | unset")) {
                if (expression.hasNext()) {
                    part = expression.next();
                    throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
                }
                return;
            }

            // Property-specific validation.
            this.singleProperty(spec, expression);

        }

    },

    singleProperty: function(types, expression) {

        var result      = false,
            value       = expression.value,
            part;

        result = Matcher.parse(types).match(expression);

        if (!result) {
            if (expression.hasNext() && !expression.isFirst()) {
                part = expression.peek();
                throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
            } else {
                throw new ValidationError("Expected (" + ValidationTypes.describe(types) + ") but found '" + value + "'.", value.line, value.col);
            }
        } else if (expression.hasNext()) {
            part = expression.next();
            throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
        }

    }

};


text:
require 'test_helper'

class Admin::AlipayNotifiesControllerTest < ActionController::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
if [ "${TESTSRC}" = "" ]
then
  echo "TESTSRC not set.  Test cannot execute.  Failed."
  exit 1
fi
echo "TESTSRC=${TESTSRC}"
if [ "${TESTJAVA}" = "" ]
then
  echo "TESTJAVA not set.  Test cannot execute.  Failed."
  exit 1
fi
echo "TESTJAVA=${TESTJAVA}"
if [ "${TESTCLASSES}" = "" ]
then
  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
  exit 1
fi
echo "TESTCLASSES=${TESTCLASSES}"
echo "CLASSPATH=${CLASSPATH}"

# set platform-dependent variables
OS=`uname -s`
case "$OS" in
  SunOS | Linux )
    NULL=/dev/null
    PS=":"
    FS="/"
    ;;
  Windows* )
    NULL=NUL
    PS=";"
    FS="\\"
    ;;
  * )
    echo "Unrecognized system!"
    exit 1;
    ;;
esac

mkdir -p classes
cp ${TESTSRC}${FS}*.java .
${TESTJAVA}${FS}bin${FS}javac -d classes A.java B.java C.java
${TESTJAVA}${FS}bin${FS}javac Main.java
${TESTJAVA}${FS}bin${FS}java Main
result=$?
if [ $result -eq 0 ]
then
  echo "Passed 1 of 2"
else
  echo "Failed 1 of 2"
  exit $result
fi
${TESTJAVA}${FS}bin${FS}java Main foo
result=$?
if [ $result -eq 0 ]
then
  echo "Passed 2 of 2"
else
  echo "Failed 2 of 2"
fi
exit $result


text:
Background
----------
CommandoJS is a study on HTML5 canvas and audio capabilities implemented using CoffeeScript.
It is also a nostalgic glimpse in the past in a form of Commodore 64 game "Commando".

Used libraries
--------------
The game uses MelonJS library for low level functionality (e.g. input handling, sprite drawing
and camera handling).

Unit tests are implemented with QUnit.

Inspiration
-----------
Inspiration to create this game was gotten from couple of similar projects:

* Blitz Basic Commando Remake: http://www.blitzbasic.com/Community/posts.php?topic=90079
* HTML5 Command and Conquer: http://www.adityaravishankar.com/projects/games/command-and-conquer/
* Infinite Mario Bros. in HTML5: http://www.rawrbitrary.com/arcade/infinite-mario-bros-in-html5/

Notes
-----
* Game has only rough implementation for level 1 of the game
* At the stage of the initial exposure, code is not optimized neither for performance nor beauty
* Unit tests are far from complete

Contact
-------
* **The Game**: http://commandojs.org
* **E-mail**: admin@commandojs.org
* **Twitter**: @commandojs


text:
$(document).ready(function () {
    // Replace this and use the mako?
    get_branches()
    // Activates the tooltips
    $('.settingstooltip').tooltip({placement: 'right'})

    // Only look for tvs if its enabled.
    if ($("#samsungtv_enable").is(':checked')) {
        samsung_tvs();
    }
    $('#other button.save').on('click', function (event) {
        event.preventDefault();

        data = [];
        $('#other table tbody tr').each(function (index) {
            tr = $(this);
            data.push({
                name: tr.find("input[name='name']").val(),
                url: tr.find("input[name='url']").val()
            });
        });

        // Save data
        $.ajax({
            method: 'POST',
            url: WEBDIR + 'settings/urls',
            data: JSON.stringify(data),
            success: function () {
                notify('Settings', 'Save successful', 'info');
            },
            error: function () {
                notify('Settings', 'Save failed', 'error');
            }
        });
    });

    $(document.body).off('click', '#other button.delete');
    $(document.body).on('click', '#other button.delete', function (event) {
        event.preventDefault();
        $(this).closest('tr').remove();
    });

    $('#other button.add').on('click', function (event) {
        event.preventDefault();
        $('#other table tbody').append(
        $('<tr>').append(
        $('<td>').html('<input type="text" value=""name="name">'),
        $('<td>').html('<input type="text" value=""name="url">'),
        $('<td>').html('<button class="btn btn-mini delete">Delete</button>')));
    });

    $(window).trigger('hashchange');
    $('.btn-test').click(function (e) {
        e.preventDefault();
        var btn = $(this).button('loading');
        var action = btn.attr('data-target');
        var data = btn.parents('form:first').serialize();
        $.post(action, data, function (data) {
            btn.button('reset');
            if ($('#couchpotato_name').is(":visible")) {
                if (data === null || !data.success) {
                    notify('Settings', 'Failed to get couchpotato apikey', 'error');
                } else {
                    $('#couchpotato_apikey').val(data.api_key);
                }
            }
            if (data !== null) {
                btn.addClass('btn-success').append(' ').append($('<i>').addClass('fa fa-check fa-inverse'));
                if (data['Network.MacAddress'] && data['Network.MacAddress'] != 'Busy') {
                    $('#kodi_server_mac:visible').val(data['Network.MacAddress']);
                }
            } else {
                btn.addClass('btn-danger').append(' ').append($('<i>').addClass('fa fa-exclamation-circle fa-inverse'));
            }
        }).error(function () {
            btn.button('reset');
            btn.addClass('btn-danger').append(' ').append($('<i>').addClass('fa fa-exclamation-circle fa-inverse'));
        });
    });

    $('input, radio, select, button').bind('change input', function (e) {
        $('.btn-test').button('reset').removeClass('btn-success btn-danger');
    });

    $('form').submit(function (e) {
        e.preventDefault();
        var action = $(this).attr('action');
        if (action === undefined) action = '';
        var data = $(this).serialize();
        $(this).find("input:checkbox:not(:checked)").each(function (e) {
            data += '&' + $(this).attr('name') + '=0';
        });
        $.post(action, data, function (data) {
            msg = data ? 'Save successful' : 'Save failed';
            if ($('#kodi_server_id').is(":visible")) {
                kodi_update_servers(0);
            }
            if ($('#users_user_id').is(":visible")) {
                users_update_user(0);
            }
            if ($('#plex_name').is(":visible")) {
                $.post(WEBDIR + 'plex/myPlexSignin', '', function (data) {
                    if (data === null) return;
                    notify('myPlex', data, 'info');
                });
            }
            if ($('#newznab_indexer_id').is(":visible")) {
                newznab_update_indexer(0);
            }

        }).done(function () {
                notify('Settings', msg, 'info');
                // Force reload without cache
                setTimeout(function () {
                    window.location.reload(true);
                }, 1000);

            });
    });

    $(":reset").click(function (e) {
        e.preventDefault();
        $(':input').not(':button, :submit, :reset, :hidden').removeAttr('checked').removeAttr('selected').not(':checkbox, :radio, select').val('');
    });

    $('input.enable-module').change(function () {
        var disabled = !$(this).is(':checked');
        $(this).parents('fieldset:first').find('input, radio, select').not(this)
            .attr('readonly', disabled).attr('disabled', disabled);
    });

    $('input.enable-module').trigger('change');
    $('#kodi_server_id').change(function () {
        $('button:reset:visible').html('Clear').removeClass('btn-danger').unbind();
        var item = $(this);
        var id = item.val();
        if (id == 0) $('button:reset:visible').trigger('click');
        $.get(WEBDIR + 'kodi/getserver?id=' + id, function (data) {
            if (data === null) return;
            $('#kodi_server_name').val(data.name);
            $('#kodi_server_host').val(data.host);
            $('#kodi_server_port').val(data.port);
            $('#kodi_server_username').val(data.username);
            $('#kodi_server_password').val(data.password);
            $('#kodi_server_mac').val(data.mac);
			$('#kodi_server_starterport').val(data.starterport);
            $("button:reset:visible").html('Delete').addClass('btn-danger').click(function (e) {
                var name = item.find('option:selected').text();
                if (!confirm('Delete ' + name)) return;
                $.get(WEBDIR + 'kodi/delserver?id=' + id, function (data) {
                    notify('Settings', 'Server deleted', 'info');
                    $(this).val(0);
                    item.find('option[value=' + id + ']').remove();
                    $('button:reset:visible').html('Clear').removeClass('btn-danger').unbind();
                });
            });
        });
    });
    kodi_update_servers(0);

    $('input.enable-module').trigger('change');
    $('#users_user_id').change(function () {
        $('button:reset:visible').html('Clear').removeClass('btn-danger').unbind();
        var item = $(this);
        var id = item.val();
        if (id == 0) $('button:reset:visible').trigger('click');
        $.get(WEBDIR + 'users/getuser?id=' + id, function (data) {
            if (data === null) return;
            $('#users_user_username').val(data.username);
            $('#users_user_password').val(data.password);
            $('#users_user_role').val(data.role);
            $("button:reset:visible").html('Delete').addClass('btn-danger').click(function (e) {
                var name = item.find('option:selected').text();
                if (!confirm('Delete ' + name)) return;
                $.get(WEBDIR + 'users/deluser?id=' + id, function (data) {
                    notify('Settings', name + ' deleted', 'info');
                    $(this).val(0);
                    item.find('option[value=' + id + ']').remove();
                    $('button:reset:visible').html('Clear').removeClass('btn-danger').unbind();
                });
            });
        });
    });
    users_update_user(0);

    $('input.enable-module').trigger('change');
    $('#newznab_indexer_id').change(function () {
        $('button:reset:visible').html('Clear').removeClass('btn-danger').unbind();
        var item = $(this);
        var id = item.val();
        if (id == 0) $('button:reset:visible').trigger('click');
        $.get(WEBDIR + 'newznab/getindexer?id=' + id, function (data) {
            if (data === null) return;
            $('#newznab_indexer_name').val(data['name']);
            $('#newznab_indexer_host').val(data['host']);
            $('#newznab_indexer_apikey').val(data.apikey);
            if (data.use_ssl == 'on') {
                $('#newznab_indexer_ssl').attr('checked', true);
            } else {
                $('#newznab_indexer_ssl').attr('checked', false);
            }

            $("button:reset:visible").html('Delete').addClass('btn-danger').click(function (e) {
                var name = item.find('option:selected').text();
                if (!confirm('Delete ' + name)) return;
                $.get(WEBDIR + 'newznab/delindexer?id=' + id, function (data) {
                    notify('Settings', name + ' deleted', 'info');
                    $(this).val(0);
                    item.find('option[value=' + id + ']').remove();
                    $('button:reset:visible').html('Clear').removeClass('btn-danger').unbind();
                });
            });
        });
    });
    newznab_update_indexer(0)

    $('#gdm_plex_servers').change(function () {
        var item = $(this);
        var id = item.val();
        $.get(WEBDIR + 'plex/GetServers?id=' + id, function (data) {
            if (data === null) return;
            $('#plex_name').val(data.servers.serverName);
            $('#plex_host').val(data.servers.ip);
            $('#plex_port').val(data.servers.port);
        });
    });
    gdm_plex_servers(0);

    $('input.enable-module').trigger('change');
    $('#tvs').change(function () {
        var item = $(this);
        var id = item.val();
        $.get(WEBDIR + 'samsungtv/findtv?id=' + id, function (data) {
            if (data === null) return;
            $('#samsungtv_name').val(data.tv_model);
            $('#samsungtv_host').val(data.host);
            $('#samsungtv_model').val(data.tv_model);
            $('#samsung_htpcmac').val(data.mac);
            $('#samsung_htpchost').val(data.local_ip);
        });
    });

});

function kodi_update_servers(id) {
    $.get(WEBDIR + 'kodi/getserver', function (data) {
        if (data === null) return;
        var servers = $('#kodi_server_id').empty().append($('<option>').text('New').val(0));
        $.each(data.servers, function (i, item) {
            var option = $('<option>').text(item.name).val(item.id);
            if (id == item.id) option.attr('selected', 'selected');
            servers.append(option);
        });
    }, 'json');
}

function gdm_plex_servers(id) {
    $.get(WEBDIR + 'plex/GetServers', function (data) {
        if (data === null) return;
        var servers = $('#gdm_plex_servers').empty().append($('<option>').text('Select').val(0));
        $.each(data.servers, function (i, item) {
            var option = $('<option>').text(item.serverName).val(item.uuid);
            if (id == item.id) option.attr('selected', 'selected');
            servers.append(option);
        });
    }, 'json');
}

function users_update_user(id) {
    $.get(WEBDIR + 'users/getuser', function (data) {
        if (data === null) return;
        var users = $('#users_user_id').empty().append($('<option>').text('New').val(0));
        $.each(data.users, function (i, item) {
            var option = $('<option>').text(item.name).val(item.id);
            if (id == item.id) option.attr('selected', 'selected');
            users.append(option);
        });
    }, 'json');
}

function newznab_update_indexer(id) {
    $.get(WEBDIR + 'newznab/getindexer', function (data) {
        if (data === null) return;
        var indexers = $('#newznab_indexer_id').empty().append($('<option>').text('New').val(0));
        $.each(data.indexers, function (i, item) {
            var option = $('<option>').text(item.name).val(item.id);
            if (id == item.id) option.attr('selected', 'selected');
            indexers.append(option);
        });
    }, 'json');
}

function get_branches() {
    $.get(WEBDIR + 'update/branches', function (data) {
        var branches = $('#branch').empty();
        $.each(data.branches, function (i, item) {
            var option = $('<option>').text(item).val(item);
            //if (data.branch == item) option.attr('selected', 'selected');
            branches.append(option);
        });
        branches.append($('<option>').text(data.branch).val(data.branch).attr('selected', 'selected'));
        //if (!data.verified) {
            //notify('Warning', 'Couldnt determine branch, select correct and save', 'warning');
        //}

    }, 'json');
}

$(document).on('click', '.delete_cache', function(e){
    $.ajax({
        'url': WEBDIR + 'settings/delete_cache',
        'dataType': 'json',
        'success': function(response) {
            if (response.success) {
                $('.delete_cache').addClass('btn-success').removeClass('btn-danger');
                notify('Info', 'Cache folder was deleted', 'success', 5);

            } else {
                $('.delete_cache').addClass('btn-danger').removeClass('btn-success');
                notify('Error', 'Failed to delete cache folder', 'error', 5);
            }
        }
    });
});

$(document).on('click', '.force_update', function(e){
    $.ajax({
        'url': WEBDIR + 'update/?force=True',
        'dataType': 'json',
        'type': "POST"
    });
    notify("Updating", "Forced update started", "info");
});

function samsung_tvs(id) {
    $.get(WEBDIR + 'samsungtv/findtv', function (data) {
        if (data === null) return;
        var tv = $('#tvs').empty().append($('<option>').text('Select').val(0));
        $.each(data, function (i, item) {
            var option = $('<option>').text(item.name).val(item.id);
            if (id == item.id) option.attr('selected', 'selected');
            tv.append(option);
        });
    }, 'json');
}

if ($('#reorder').length){
    $('#reorder').sortable();
}


text:
div#logo a {
  display: block;
  width: 100%;
  height: 100%;
}
#footer_text a {
  font-family: Arial,sans-serif;
  font-style: normal;
  font-size: 10px;
  font-weight: normal;
  color: #00F;
  text-decoration: underline; white-space: nowrap;
}

#logo {
   background: url(resources/_wsb_logo.jpg) no-repeat;
}
#key_visual {
   background: url(images/dynamic/key_visual1.jpg) no-repeat;
}
#slogan {
  font-family: Arial,sans-serif;
  font-style: normal;
  font-size: 11px;
  font-weight: normal;
  text-decoration: none;
  color: #ffffff;
}
a.main_nav_active_item {
  background: url(images/dynamic/buttonset7/n1active.gif) no-repeat;
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 11px;
  font-weight: bold;
  text-decoration: none;
  color: #cb6a06;
}
a.main_nav_item {
  background: url(images/dynamic/buttonset7/n1.gif) no-repeat;
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 11px;
  font-weight: bold;
  text-decoration: none;
  color: #ffffff;
}
a.main_nav_item:hover {
  background: url(images/dynamic/buttonset7/n1active.gif) no-repeat;
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 11px;
  font-weight: bold;
  text-decoration: none;
  color: #cb6a06;
}
a.sub_nav_active_item {
  background: url(images/dynamic/buttonset7/sn1active.gif) no-repeat;
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 11px;
  font-weight: normal;
  text-decoration: none;
  color: #dd783f;
}
a.sub_nav_item {
  background: url(images/dynamic/buttonset7/sn1.gif) no-repeat;
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 11px;
  font-weight: normal;
  text-decoration: none;
  color: #7d7d7d;
}
a.sub_nav_item:hover {
  background: url(images/dynamic/buttonset7/sn1active.gif) no-repeat;
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 11px;
  font-weight: normal;
  text-decoration: none;
  color: #dd783f;
}
.content h1 {
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 30px;
  font-weight: bold;
  text-decoration: none;
  color: #a34e25;
}
.content h2 {
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 24px;
  font-weight: bold;
  text-decoration: none;
  color: #ffb122;
}
.content h3 {
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 18px;
  font-weight: bold;
  text-decoration: none;
  color: #4e4e4e;
}
.content, .content p {
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 12px;
  font-weight: normal;
  text-decoration: none;
  color: #7d7d7d;
}
.content a:link {
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 100%;
  font-weight: normal;
  text-decoration: underline;
  color: #eb9973;
}
.content a:visited {
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 100%;
  font-weight: normal;
  text-decoration: underline;
  color: #eb9973;
}
.content a:hover {
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 100%;
  font-weight: normal;
  text-decoration: none;
  color: #7d7d7d;
}
.content a:active {
  font-family: Arial, Verdana, sans-serif;
  font-style: normal;
  font-size: 100%;
  font-weight: normal;
  text-decoration: underline;
  color: #7d7d7d;
}
#footer_text {
  font-family: Arial,sans-serif;
  font-style: normal;
  font-size: 10px;
  font-weight: normal;
  text-decoration: none;
  color: #00F;
}


text:
/*
55. Jump Game  QuestionEditorial Solution  My Submissions
Total Accepted: 85328
Total Submissions: 297281
Difficulty: Medium
Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

Hide Company Tags Microsoft
Hide Tags Array Greedy
*/
public class Solution {
    public boolean canJump(int[] nums) {
        int reachable = 0;
        for(int i=0;i<nums.length;i++){
            if(i>reachable)return false;
            reachable=Math.max(reachable,i+nums[i]);
        }
        return true;
    }
}


text:
{% extends "base.html" %}
{% import "_macros.html" as macros %}

{% block title %}建筑节能 - {{ user.username }}{% endblock %}

{% block page_content %}

{{ user.username }}

        {% if user.name or user.location %}

            {% if user.name %}{{ user.name }}
{% endif %}
            {% if user.location %}
                From {{ user.location }}

            {% endif %}

        {% endif %}
        {% if current_user.is_administrator() %}

{{ user.email }}

        {% endif %}
        {% if user.about_me %}
{{ user.about_me }}
{% endif %}

注册时间 {{ moment(user.member_since).format('L') }}. 上次登陆时间 {{ moment(user.last_seen).fromNow() }}.

{{ user.posts.count() }} 篇文章. {{ user.comments.count() }} 条评论.

            {% if current_user.can(Permission.FOLLOW) and user != current_user %}
                {% if not current_user.is_following(user) %}
                Follow
                {% else %}
                Unfollow
                {% endif %}
            {% endif %}
            关注: {{ user.followers.count() - 1 }}
            粉丝: {{ user.followed.count() - 1 }}
            {% if current_user.is_authenticated and user != current_user and user.is_following(current_user) %}
            | 关注Ta
            {% endif %}

            {% if user == current_user %}
            编辑资料
            {% endif %}
            {% if current_user.is_administrator() %}
            编辑资料 [Admin]
            {% endif %}

{{ user.username }}的文章

{% include '_posts.html' %}
{% if pagination %}

    {{ macros.pagination_widget(pagination, '.user', username=user.username) }}

{% endif %}
{% endblock %}


text:
from dash import html
import dash

dash.register_page(__name__, path="/404", id="not_found_404")

layout = html.Div("text for not_found_404", id="text_not_found_404")


text:
<?php
/**
 * Created by PhpStorm.
 * User: Fahmy
 * Date: 8/25/15
 * Time: 10:24 AM
 */

/* @var $this \yii\web\View */
/* @var $content string */

use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
//use frontend\assets\AppAsset;
use common\widgets\Alert;
use common\assets\inspinia\InspiniaAsset;

InspiniaAsset::register($this);

?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
</head>
<?php
$options = ['class'=>''];
if(isset($this->params['bodyClass'])){
    Html::addCssClass($options,$this->params['bodyClass']);
}
echo Html::beginTag('body',$options);
?>
<?php $this->beginBody() ?>
    <?=$content?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>


text:
/* eslint-disable */

'use strict';

// @dataDrivenDependency DataCheckerTest5Fragment.nameRenderer {"branches":{"MarkdownUserNameRenderer":{"component":"MarkdownUserNameRenderer.react","fragment":"DataCheckerTest5MarkdownUserNameRenderer_name$normalization.graphql"},"PlainUserNameRenderer":{"component":"PlainUserNameRenderer.react","fragment":"DataCheckerTest5PlainUserNameRenderer_name$normalization.graphql"}},"plural":false}

/*::
import type { Fragment, ReaderFragment } from 'relay-runtime';
type DataCheckerTest5MarkdownUserNameRenderer_name$fragmentType = any;
type DataCheckerTest5PlainUserNameRenderer_name$fragmentType = any;
import type { FragmentType } from "relay-runtime";
declare export opaque type DataCheckerTest5Fragment$fragmentType: FragmentType;
export type DataCheckerTest5Fragment$data = {|
  +id: string,
  +nameRenderer: ?{|
    +__fragmentPropName?: ?string,
    +__module_component?: ?string,
    +$fragmentSpreads: DataCheckerTest5MarkdownUserNameRenderer_name$fragmentType & DataCheckerTest5PlainUserNameRenderer_name$fragmentType,
  |},
  +$fragmentType: DataCheckerTest5Fragment$fragmentType,
|};
export type DataCheckerTest5Fragment$key = {
  +$data?: DataCheckerTest5Fragment$data,
  +$fragmentSpreads: DataCheckerTest5Fragment$fragmentType,
  ...
};
*/

var node/*: ReaderFragment*/ = {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": null,
  "name": "DataCheckerTest5Fragment",
  "selections": [
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "id",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "concreteType": null,
      "kind": "LinkedField",
      "name": "nameRenderer",
      "plural": false,
      "selections": [
        {
          "kind": "InlineFragment",
          "selections": [
            {
              "args": null,
              "documentName": "DataCheckerTest5Fragment",
              "fragmentName": "DataCheckerTest5PlainUserNameRenderer_name",
              "fragmentPropName": "name",
              "kind": "ModuleImport"
            }
          ],
          "type": "PlainUserNameRenderer",
          "abstractKey": null
        },
        {
          "kind": "InlineFragment",
          "selections": [
            {
              "args": null,
              "documentName": "DataCheckerTest5Fragment",
              "fragmentName": "DataCheckerTest5MarkdownUserNameRenderer_name",
              "fragmentPropName": "name",
              "kind": "ModuleImport"
            }
          ],
          "type": "MarkdownUserNameRenderer",
          "abstractKey": null
        }
      ],
      "storageKey": null
    }
  ],
  "type": "User",
  "abstractKey": null
};

if (__DEV__) {
  (node/*: any*/).hash = "8a7920a2a8ae8065ddf4b46a76f2199c";
}

module.exports = ((node/*: any*/)/*: Fragment<
  DataCheckerTest5Fragment$fragmentType,
  DataCheckerTest5Fragment$data,
>*/);


text:
<?php

namespace Doctrine\Tests\Mocks;

use Doctrine\DBAL\Driver\Statement;

/**
 * This class is a mock of the Statement interface.
 *
 * @author Alexander <iam.asm89@gmail.com>
 */
class StatementMock implements \IteratorAggregate, Statement
{
    /**
     * {@inheritdoc}
     */
    public function bindValue($param, $value, $type = null)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function bindParam($column, &$variable, $type = null, $length = null)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function errorCode()
    {
    }

    /**
     * {@inheritdoc}
     */
    public function errorInfo(){}

    /**
     * {@inheritdoc}
     */
    public function execute($params = null)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function rowCount()
    {
    }

    /**
     * {@inheritdoc}
     */
    public function closeCursor()
    {
    }

    /**
     * {@inheritdoc}
     */
    public function columnCount()
    {
    }

    /**
     * {@inheritdoc}
     */
    public function setFetchMode($fetchStyle, $arg2 = null, $arg3 = null)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function fetch($fetchMode = null, $cursorOrientation = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function fetchColumn($columnIndex = 0)
    {
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
    }
}