text:
<?php

namespace Platformsh\Cli\Service;

use Platformsh\Cli\SshCert\Certifier;
use Platformsh\Cli\Util\OsUtil;
use Platformsh\Cli\Util\Snippeter;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Process\Process;

class SshConfig {
    private $config;
    private $fs;
    private $stdErr;
    private $sshKey;
    private $certifier;
    private $openSshVersion;

    public function __construct(Config $config, Filesystem $fs, OutputInterface $output, SshKey $sshKey, Certifier $certifier)
    {
        $this->config = $config;
        $this->fs = $fs;
        $this->stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;
        $this->sshKey = $sshKey;
        $this->certifier = $certifier;
    }

    /**
     * Creates or updates session-specific SSH configuration.
     *
     * @return bool
     *   True if there is any session configuration, false otherwise.
     */
    public function configureSessionSsh()
    {
        if (!$this->supportsInclude()) {
            return false;
        }

        // Backwards compatibility: delete the old SSH configuration file.
        $legacy = $this->getCliSshDir() . DIRECTORY_SEPARATOR . 'sess-cli-default.config';
        if (\file_exists($legacy)) {
            $this->fs->remove($legacy);
        }

        $domainWildcards = $this->config->get('api.ssh_domain_wildcards');

        $lines = [];

        if ($certificate = $this->certifier->getExistingCertificate()) {
            $executable = $this->config->get('application.executable');
            $refreshCommand = sprintf('%s ssh-cert:load --refresh-only --yes --quiet', $executable);
            if (!OsUtil::isWindows()) {
                $refreshCommand .= ' 2>/dev/null';
            }
            // Use Match solely to run the refresh command.
            $lines[] = '# Auto-refresh the SSH certificate:';
            if ($domainWildcards) {
                $lines[] = sprintf('Match host "%s" exec "%s"', \implode(',', $domainWildcards), $refreshCommand);
            } else {
                $lines[] = sprintf('Match exec "%s"', $refreshCommand);
            }
            $lines[] = '';

            // Indentation in the SSH config is for readability (it has no other effect).
            $lines[] = '# Include the certificate and its key:';
            $lines[] = sprintf('CertificateFile %s', $this->formatFilePath($certificate->certificateFilename()));
            $lines[] = sprintf('IdentityFile %s', $this->formatFilePath($certificate->privateKeyFilename()));
            $lines[] = '';
        }

        if ($domainWildcards) {
            $lines[] = 'Host ' . implode(' ', $domainWildcards);
        }

        $sessionIdentityFile = $this->sshKey->selectIdentity();
        if ($sessionIdentityFile !== null) {
            $lines[] = '# This SSH key was detected as corresponding to the session:';
            $lines[] = sprintf('IdentityFile %s', $this->formatFilePath($sessionIdentityFile));
            $lines[] = '';
        }

        $sessionSpecificFilename = $this->getSessionSshDir() . DIRECTORY_SEPARATOR . 'config';
        $includerFilename = $this->getCliSshDir() . DIRECTORY_SEPARATOR . 'session.config';
        if (empty($lines)) {
            if (\file_exists($includerFilename) || \file_exists($sessionSpecificFilename)) {
                $this->fs->remove([$includerFilename, $sessionSpecificFilename]);
            }
            return false;
        }

        // Add default files if there is no preferred session identity file.
        if ($sessionIdentityFile === null && ($defaultFiles = $this->getUserDefaultSshIdentityFiles())) {
            $lines[] = '# Include SSH "default" identity files:';
            foreach ($defaultFiles as $identityFile) {
                $lines[] = sprintf('IdentityFile %s', $this->formatFilePath($identityFile));
            }
            $lines[] = '';
        }

        $this->writeSshIncludeFile($sessionSpecificFilename, $lines);

        $includerLines = [
            '# This file is included from your SSH config file (~/.ssh/config).',
            '# In turn, it includes the configuration for the currently active CLI session.',
            '# It is updated automatically when certain CLI commands are run.',
        ];

        $wildcards = $this->config->get('api.ssh_domain_wildcards');
        if (count($wildcards)) {
            $includerLines[] = 'Host ' . implode(' ', $wildcards);
            $includerLines[] = '  Include ' . $sessionSpecificFilename;
            $this->writeSshIncludeFile(
                $includerFilename,
                $includerLines
            );
        }

        return true;
    }

    /**
     * Formats a file path for an SSH config option.
     *
     * This should be applied to the IdentityFile and CertificateFile option
     * values. See the ssh_config(5) man page: https://www.freebsd.org/cgi/man.cgi?ssh_config%285%29
     *
     * Note: a previous version of this method replaced the home directory with
     * SSH's percent syntax (%d). However, this does not work on systems where
     * the HOME environment variable is set to a directory other than the
     * current user's (notably on GitHub Actions containers), because the
     * OpenSSH client does not support reading HOME.
     *
     * @param string $path
     *
     * @return string
     */
    public function formatFilePath($path)
    {
        // Escape paths containing a space.
        if (\strpos($path, ' ') !== false) {
            // The three quote marks in the middle mean: end quote, literal quote mark, start quote.
            return '"' . \str_replace('"', '"""', $path) . '"';
        }
        return $path;
    }

    /**
     * Creates or updates an SSH config include file.
     *
     * @param string $filename
     * @param array  $lines
     * @param bool   $allowDelete
     */
    private function writeSshIncludeFile($filename, array $lines, $allowDelete = true)
    {
        if (empty($lines) && $allowDelete && \file_exists($filename)) {
            $this->stdErr->writeln(sprintf('Deleting SSH configuration include file: <info>%s</info>', $filename), OutputInterface::VERBOSITY_VERBOSE);
            $this->fs->remove($filename);
            return;
        }
        $contents = implode(PHP_EOL, $lines) . PHP_EOL;
        if (!\file_exists($filename)) {
            $this->stdErr->writeln(sprintf('Creating SSH configuration include file: <info>%s</info>', $filename), OutputInterface::VERBOSITY_VERBOSE);
            $this->fs->writeFile($filename, $contents, false);
        } elseif (\file_get_contents($filename) !== $contents) {
            $this->stdErr->writeln(sprintf('Updating SSH configuration include file: <info>%s</info>', $filename), OutputInterface::VERBOSITY_VERBOSE);
            $this->fs->writeFile($filename, $contents, false);
        } else {
            $this->stdErr->writeln(sprintf('Validated SSH configuration include file: <info>%s</info>', $filename), OutputInterface::VERBOSITY_VERY_VERBOSE);
        }
        $this->chmod($filename, 0600);
    }

    /**
     * Returns the directory containing session-specific SSH configuration.
     *
     * @return string
     */
    public function getSessionSshDir()
    {
        return $this->config->getSessionDir(true) . DIRECTORY_SEPARATOR . 'ssh';
    }

    /**
     * Adds configuration to the user's global SSH config file (~/.ssh/config).
     *
     * @param QuestionHelper $questionHelper
     *
     * @return bool
     */
    public function addUserSshConfig(QuestionHelper $questionHelper)
    {
        if (!$this->supportsInclude()) {
            return false;
        }

        $filename = $this->getUserSshConfigFilename();

        $wildcards = $this->config->get('api.ssh_domain_wildcards');
        if (!$wildcards) {
            return true;
        }

        $suggestedConfig = \implode("\n", [
            'Host ' . \implode(' ', $wildcards),
            '  Include ' . $this->getCliSshDir() . DIRECTORY_SEPARATOR . '*.config',
            'Host *',
        ]);

        $manualMessage = 'To configure SSH, add the following lines to: <comment>' . $filename . '</comment>'
            . "\n" . $suggestedConfig;

        if (file_exists($filename)) {
            $currentContents = file_get_contents($filename);
            if ($currentContents === false) {
                $this->stdErr->writeln('Failed to read file: <comment>' . $filename . '</comment>');
                return false;
            }
            if (strpos($currentContents, $suggestedConfig) !== false) {
                $this->stdErr->writeln('Validated SSH configuration file: <info>' . $filename . '</info>', OutputInterface::VERBOSITY_VERBOSE);
                return true;
            }
            $this->stdErr->writeln('Checking SSH configuration file: <info>' . $filename . '</info>');
            if (!$questionHelper->confirm('Do you want to update the file automatically?')) {
                $this->stdErr->writeln($manualMessage);
                return false;
            }
            $creating = false;
        } elseif ($this->fs->canWrite($filename)) {
            if (!$questionHelper->confirm('Do you want to create an SSH configuration file automatically?')) {
                $this->stdErr->writeln($manualMessage);
                return false;
            }
            $currentContents = '';
            $creating = true;
        } else {
            $this->stdErr->writeln($manualMessage);
            return false;
        }

        $newContents = $this->getUserSshConfigChanges($currentContents, $suggestedConfig);
        $this->fs->writeFile($filename, $newContents);

        if ($creating) {
            $this->stdErr->writeln('Configuration file created successfully: <info>' . $filename . '</info>');
        } else {
            $this->stdErr->writeln('Configuration file updated successfully: <info>' . $filename . '</info>');
        }

        $this->chmod($filename, 0600);

        return true;
    }

    /**
     * Deletes session-specific SSH configuration files.
     *
     * Called from the logout command.
     */
    public function deleteSessionConfiguration()
    {
        $files = [
            $this->getSessionSshDir() . DIRECTORY_SEPARATOR . 'config',
            $this->getCliSshDir() . DIRECTORY_SEPARATOR . 'session.config',
        ];
        if (array_filter($files, '\\file_exists') !== []) {
            $this->stdErr->writeln('');
            $this->stdErr->writeln('Deleting all session SSH configuration');
            $this->fs->remove($files);
        }
    }

    /**
     * Change file permissions and emit a warning on failure.
     *
     * @param string $filename
     * @param int $mode
     *
     * @return bool
     */
    private function chmod($filename, $mode)
    {
        if (!@chmod($filename, $mode)) {
            $this->stdErr->writeln('Warning: failed to change permissions on file: <comment>' . $filename . '</comment>');
            return false;
        }
        return true;
    }

    /**
     * Returns the directory for CLI-specific SSH configuration files.
     *
     * @return string
     */
    private function getCliSshDir()
    {
        return $this->config->getWritableUserDir() . DIRECTORY_SEPARATOR . 'ssh';
    }

    /**
     * Calculates changes to a user's global SSH config file.
     *
     * @param string $currentConfig
     *   The current file contents.
     * @param string $newConfig
     *   The new config that should be inserted. Pass an empty string to delete
     *   the configuration.
     *
     * @return string The new file contents.
     */
    private function getUserSshConfigChanges($currentConfig, $newConfig)
    {
        $serviceName = (string)$this->config->get('service.name');
        $begin = '# BEGIN: ' . $serviceName . ' certificate configuration' . PHP_EOL;
        $end = PHP_EOL . '# END: ' . $serviceName . ' certificate configuration';

        return (new Snippeter())->updateSnippet($currentConfig, $newConfig, $begin, $end);
    }

    /**
     * Returns the path to the user's global SSH config file.
     *
     * @return string
     */
    private function getUserSshConfigFilename()
    {
        return $this->config->getHomeDirectory() . DIRECTORY_SEPARATOR . '.ssh' . DIRECTORY_SEPARATOR . 'config';
    }

    /**
     * Returns the user's default SSH identity files (if they exist).
     *
     * @todo prioritise account-specific identity files
     *
     * These are the filenames that are used by SSH when there is no
     * IdentityFile specified, and when there is no SSH agent.
     *
     * @see https://man.openbsd.org/ssh#i
     *
     * @return array
     */
    public function getUserDefaultSshIdentityFiles()
    {
        $dir = $this->config->getHomeDirectory() . DIRECTORY_SEPARATOR . '.ssh';
        if (!\is_dir($dir)) {
            return [];
        }
        $basenames = [
            'id_rsa',
            'id_ecdsa_sk',
            'id_ecdsa',
            'id_ed25519_sk',
            'id_ed25519',
            'id_dsa',
        ];
        $files = [];
        foreach ($basenames as $basename) {
            $filename = $dir . DIRECTORY_SEPARATOR . $basename;
            if (\file_exists($filename) && \file_exists($filename . '.pub')) {
                $files[] = $filename;
            }
        }

        return $files;
    }

    /**
     * Removes certificate configuration from the user's global SSH config file.
     *
     * @todo use this? maybe in an uninstall command
     */
    public function removeUserSshConfig()
    {
        $sshConfigFile = $this->getUserSshConfigFilename();
        if (!file_exists($sshConfigFile)) {
            return;
        }
        $currentSshConfig = file_get_contents($sshConfigFile);
        if ($currentSshConfig === false) {
            return;
        }
        $newConfig = $this->getUserSshConfigChanges($currentSshConfig, '');
        if ($newConfig === $currentSshConfig) {
            return;
        }
        $this->stdErr->writeln('Removing configuration from SSH configuration file: <info>' . $sshConfigFile . '</info>');

        try {
            $this->fs->writeFile($sshConfigFile, $newConfig);
            $this->stdErr->writeln('Configuration successfully removed');
        } catch (IOException $e) {
            $this->stdErr->writeln('The configuration could not be automatically removed: ' . $e->getMessage());
        }
    }

    /**
     * Finds the locally installed OpenSSH version.
     *
     * @param bool $reset
     *
     * @return string|false
     */
    private function findVersion($reset = false)
    {
        if (isset($this->openSshVersion) && !$reset) {
            return $this->openSshVersion;
        }
        $this->openSshVersion = false;
        $process = new Process('ssh -V');
        $process->run();
        $errorOutput = $process->getErrorOutput();
        if (!$process->isSuccessful()) {
            if ($this->stdErr->isVerbose()) {
                $this->stdErr->writeln('Unable to determine the installed OpenSSH version. The command output was:');
                $this->stdErr->writeln($errorOutput);
            }
            return false;
        }
        if (\preg_match('/OpenSSH_([0-9.]+[^ ,]*)/', $errorOutput, $matches)) {
            $this->openSshVersion = $matches[1];
        }
        return $this->openSshVersion;
    }

    /**
     * Checks if the installed OpenSSH version is below a given value.
     *
     * @param string $test
     *
     * @return bool
     *   True if the version is determined and it is lower than the $test value, false otherwise.
     */
    private function versionIsBelow($test)
    {
        $version = $this->findVersion();
        if (!$version) {
            return false;
        }
        return \version_compare($version, $test, '<');
    }

    /**
     * Checks if the installed OpenSSH version supports the 'Include' syntax.
     *
     * @return bool
     */
    public function supportsInclude() {
        return !$this->versionIsBelow('7.3');
    }

    /**
     * Checks if the installed OpenSSH version supports the 'CertificateFile' syntax.
     *
     * @return bool
     */
    public function supportsCertificateFile() {
        return !$this->versionIsBelow('7.2');
    }

    /**
     * Checks if the required version is supported, and prints a warning.
     *
     * @return bool
     *   False if an incorrect version is installed, true otherwise.
     */
    public function checkRequiredVersion()
    {
        $version = $this->findVersion();
        if (!$version) {
            return true;
        }
        if (\version_compare($version, '6.5', '<')) {
            $this->stdErr->writeln(\sprintf(
                'OpenSSH version <error>%s</error> is installed. Version 6.5 or above is required. Some features depend on version 7.3 or above.',
                $version
            ));
            return false;
        }
        if (\version_compare($version, '7.3', '<')) {
            $this->stdErr->writeln(\sprintf(
                'OpenSSH version <comment>%s</comment> is installed. Some features depend on version 7.3 or above.',
                $version
            ));
        }
        return true;
    }
}


text:
test_description='Test submodules config cache infrastructure

This test verifies that parsing .gitmodules configurations directly
from the database and from the worktree works.
'

TEST_NO_CREATE_REPO=1
. ./test-lib.sh

test_expect_success 'submodule config cache setup' '
	mkdir submodule &&
	(cd submodule &&
		git init &&
		echo a >a &&
		git add . &&
		git commit -ma
	) &&
	mkdir super &&
	(cd super &&
		git init &&
		git submodule add ../submodule &&
		git submodule add ../submodule a &&
		git commit -m "add as submodule and as a" &&
		git mv a b &&
		git commit -m "move a to b"
	)
'

cat >super/expect <<EOF
Submodule name: 'a' for path 'a'
Submodule name: 'a' for path 'b'
Submodule name: 'submodule' for path 'submodule'
Submodule name: 'submodule' for path 'submodule'
EOF

test_expect_success 'test parsing and lookup of submodule config by path' '
	(cd super &&
		test-submodule-config \
			HEAD^ a \
			HEAD b \
			HEAD^ submodule \
			HEAD submodule \
				>actual &&
		test_cmp expect actual
	)
'

test_expect_success 'test parsing and lookup of submodule config by name' '
	(cd super &&
		test-submodule-config --name \
			HEAD^ a \
			HEAD a \
			HEAD^ submodule \
			HEAD submodule \
				>actual &&
		test_cmp expect actual
	)
'

cat >super/expect_error <<EOF
Submodule name: 'a' for path 'b'
Submodule name: 'submodule' for path 'submodule'
EOF

test_expect_success 'error in one submodule config lets continue' '
	(cd super &&
		cp .gitmodules .gitmodules.bak &&
		echo "	value = \"" >>.gitmodules &&
		git add .gitmodules &&
		mv .gitmodules.bak .gitmodules &&
		git commit -m "add error" &&
		test-submodule-config \
			HEAD b \
			HEAD submodule \
				>actual &&
		test_cmp expect_error actual
	)
'

cat >super/expect_url <<EOF
Submodule url: 'git@somewhere.else.net:a.git' for path 'b'
Submodule url: 'git@somewhere.else.net:submodule.git' for path 'submodule'
EOF

cat >super/expect_local_path <<EOF
Submodule name: 'a' for path 'c'
Submodule name: 'submodule' for path 'submodule'
EOF

test_expect_success 'reading of local configuration' '
	(cd super &&
		old_a=$(git config submodule.a.url) &&
		old_submodule=$(git config submodule.submodule.url) &&
		git config submodule.a.url git@somewhere.else.net:a.git &&
		git config submodule.submodule.url git@somewhere.else.net:submodule.git &&
		test-submodule-config --url \
			"" b \
			"" submodule \
				>actual &&
		test_cmp expect_url actual &&
		git config submodule.a.path c &&
		test-submodule-config \
			"" c \
			"" submodule \
				>actual &&
		test_cmp expect_local_path actual &&
		git config submodule.a.url $old_a &&
		git config submodule.submodule.url $old_submodule &&
		git config --unset submodule.a.path c
	)
'

cat >super/expect_fetchrecurse_die.err <<EOF
fatal: bad submodule.submodule.fetchrecursesubmodules argument: blabla
EOF

test_expect_success 'local error in fetchrecursesubmodule dies early' '
	(cd super &&
		git config submodule.submodule.fetchrecursesubmodules blabla &&
		test_must_fail test-submodule-config \
			"" b \
			"" submodule \
				>actual.out 2>actual.err &&
		touch expect_fetchrecurse_die.out &&
		test_cmp expect_fetchrecurse_die.out actual.out  &&
		test_cmp expect_fetchrecurse_die.err actual.err  &&
		git config --unset submodule.submodule.fetchrecursesubmodules
	)
'

test_expect_success 'error in history in fetchrecursesubmodule lets continue' '
	(cd super &&
		git config -f .gitmodules \
			submodule.submodule.fetchrecursesubmodules blabla &&
		git add .gitmodules &&
		git config --unset -f .gitmodules \
			submodule.submodule.fetchrecursesubmodules &&
		git commit -m "add error in fetchrecursesubmodules" &&
		test-submodule-config \
			HEAD b \
			HEAD submodule \
				>actual &&
		test_cmp expect_error actual  &&
		git reset --hard HEAD^
	)
'

test_done

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace LD38.Gameplay
{
    public abstract class Building
    {
        public Player Owner { get; }
        public Building(Player owner) =>
            Owner = owner;
    }
}


text:
<% include header.html %>

<link href="/css/chatbox.css" rel="stylesheet">

<%=chatId%>
<%=chatFromId%>
<%=chatFromName%>
<%=chatToId%>

	<form id="uplfrm" method="post" action="/upload" enctype="multipart/form-data">

		<input type="file" style="display:none"/>
	</form>
	<form id="msgfrm">
		<input id="m" autocomplete="off"/><button>Send</button>
	</form>

<% include footer.html %>


text: Mozilla Foundation


text:
\documentclass[11pt, noincludeaddress, nopagination]{classes/cthit}
\usepackage{titlesec}
\usepackage{verbatimbox}
\usepackage{tabularx}
\usepackage{pgfkeys}

\newcommand{\sign}[4]{%
  \begin{tabular}[t]{@{}l@{}}
  \makebox[6.5cm]{\dotfill}\\
  \strut#1\strut \\
  \strut#2\strut \\
  \strut#3\strut \\
  \strut#4\strut \\
  \end{tabular}%
}
\newcommand{\Date}{%
  \begin{tabular}[t]{@{}p{1.5in}@{}}
  \\[-2ex]
  \strut Date: \dotfill\strut
  \end{tabular}%
}

\titleformat{\paragraph}[hang]{\normalfont\normalsize\bfseries}{\theparagraph}{1em}{}
\titlespacing*{\paragraph}{0pt}{3.25ex plus 1ex minus 0.2ex}{0.7em}

\graphicspath{ {images/} }

\begin{document}

\title{Hedersmedlemskapsdiplom}

\makeheadfoot%

\makesimpletitle
\begin{center}
\textbf{\Huge{NAMN PÅ PERSON}}
\end{center}
\vspace{1cm}
\subsection*{}
Intyg att NAMN PÅ PERSON har utnämnts till hedersmedlem hos Teknologsektionen Informationsteknik på Chalmers Tekniska Högskola datumet DATUM FÖR SEKTIONSMÖTET med motiveringen:
\\
\\
\textit{
``motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering motivering.''
}
\\

En hedersmedlem är en PERSON som synnerligen främjat teknologsektionens intressen och strävanden. Hos Teknologsektionen Informationsteknik har endast ANTAL tidigare personer utnämnts till hedersmedlem sedan sektionens uppstart 2001.

\vspace{4cm}

\noindent
  \begin{minipage}[t]{0.5\linewidth}
    \raggedright
    \sign{NAMN PÅ ORDFÖRANDE}{Ordförande}{Teknologsektionen Informationsteknik}{Chalmers Studentkår}
  \end{minipage}%
  \hfill
  \begin{minipage}[t]{0.5\linewidth}
  \sign{Ort \& datum}{}{}{}
  \end{minipage}

\end{document}


text:
describe("Package Detail Tab", () => {
  beforeEach(() => {
    cy.configureCluster({
      mesos: "1-task-healthy",
      universePackages: true,
    }).visitUrl({ url: "/catalog/packages/marathon?version=1.4.6" });
  });

  context("Package Details", () => {
    it("displays package information on package page", () => {
      cy.get(".page-body-content h1").should("contain", "marathon");
    });

    // Stalls tests in CI. TODO: Talk with Brian about this test.
    it("displays marathon package details", () => {
      cy.get(".page-body-content .pod p").as("information");

      cy.get("@information")
        .eq(0)
        .should(
          "contain",
          "A container orchestration platform for Mesos and DCOS"
        )
        .get("@information")
        .eq(1)
        .should(
          "contain",
          "We recommend a minimum of one node with at least 2 CPU shares and 1GB of RAM available for the Marathon DCOS Service."
        )
        .get("@information")
        .eq(2)
        .should("contain", "SCM: https://github.com/mesosphere/marathon.git")
        .get("@information")
        .eq(3)
        .should("contain", "Maintainer: support@mesosphere.io")
        .get("@information")
        .eq(4)
        .should(
          "contain",
          "Apache License Version 2.0: https://github.com/mesosphere/marathon/blob/master/LICENSE"
        );
    });

    it("contains _blank target for links in description", () => {
      cy.get("h2")
        .contains("Description")
        .parent()
        .find("a")
        .should("have.attr", "target", "_blank");
    });

    it("contains _blank target for links in preinstall notes", () => {
      cy.get(".pre-install-notes")
        .find("a")
        .should("have.attr", "target", "_blank");
    });

    it("displays image in the image viewer", () => {
      cy.get(".media-object-item-fill-image.image-rounded-corners.clickable")
        .eq(4)
        .click();

      cy.get(".modal.modal-image-viewer img").should(
        "have.attr",
        "src",
        "http://www.clker.com/cliparts/0/f/d/b/12917289761851255679earth-map-huge.jpg"
      );
    });

    it("changes image in the image viewer by clicking left arrow", () => {
      cy.get(".media-object-item-fill-image.image-rounded-corners.clickable")
        .eq(4)
        .click();

      cy.get(".modal-image-viewer-arrow-container.clickable.backward").click();

      cy.get(".modal.modal-image-viewer img").should(
        "have.attr",
        "src",
        "https://mesosphere.com/wp-content/themes/mesosphere/library/images/assets/marathon-0.6.0/mesosphere-marathon-app-list.png"
      );
    });

    it("changes image in the image viewer by clicking right arrow", () => {
      cy.get(".media-object-item-fill-image.image-rounded-corners.clickable")
        .eq(4)
        .click();

      cy.get(".modal-image-viewer-arrow-container.clickable.forward").click();

      cy.get(".modal.modal-image-viewer img").should(
        "have.attr",
        "src",
        "https://mesosphere.com/wp-content/themes/mesosphere/library/images/assets/marathon-0.6.0/mesosphere-marathon-app-list.png"
      );
    });

    it("dropdown display all versions available", () => {
      cy.get(".dropdown-toggle").click();
      cy.get(".is-selectable").should("have.length", 4);
    });

    it("select available version on dropdown", () => {
      cy.get(".dropdown-toggle").click();
      cy.get(".is-selectable").eq(3).click();
      cy.window().then((window) => {
        const result = window.location.hash.includes("0.2.1");
        expect(result).to.equal(true);
      });
    });

    it("Does not ask for confirmation for certified packages", () => {
      cy.get(".page-body-content .package-action-buttons button")
        .contains("Review & Run")
        .click();
      cy.get(".modal-body")
        .contains("Install Community Package")
        .should("not.exist");
      cy.get(".modal-full-screen-header-title").contains("Edit Configuration");
    });

    it("Does not shows a knownIssues-warning ", () => {
      cy.get("h1").contains("marathon");
      cy.get("[aria-describedby=has-known-issues]").should("not.exist");
    });

    context("Unmet dependency", () => {
      beforeEach(() => {
        cy.configureCluster({
          mesos: "1-task-healthy",
          universePackages: "dependencyPackage",
        }).visitUrl({ url: "/catalog/packages/marathon?version=1.4.6" });
      });

      it("Displays a warning", () => {
        cy.get(".infoBoxWrapper").contains(
          "This service cannot run without the marathon-cluster package. Please run marathon-cluster package to enable this service."
        );
      });

      it("Disables the review and run button", () => {
        cy.get(".disabled").contains("Review & Run");
      });
    });

    context("Community Packages", () => {
      beforeEach(() => {
        cy.configureCluster({
          mesos: "1-task-healthy",
          universePackages: "communityPackage",
        }).visitUrl({ url: "/catalog/packages/marathon?version=1.4.6" });
        cy.get(".page-body-content .package-action-buttons button")
          .contains("Review & Run")
          .click();
      });

      it("Asks for confirmation for community packages", () => {
        cy.get(".modal-body").contains("Install Community Package");
        cy.get(".modal-body").contains(
          "This package is not tested for production environments and technical support is not provided."
        );
      });

      it("Goes back when Cancel is clicked", () => {
        cy.get(".button-primary-link").contains("Cancel").click();
        cy.get(".breadcrumb__content--text").contains("marathon");
      });

      it("Goes to package configuration when Continue is clicked", () => {
        cy.get(".button-primary").contains("Continue").click();
        cy.get(".modal-full-screen-header-title").contains(
          "Edit Configuration"
        );
      });
      it("Shows a warning in case the package is known to have issues", () => {
        cy.get("[aria-describedby=has-known-issues]");
      });
    });

    context("Last updated", () => {
      it("Shows no label for packages with no last updated information", () => {
        cy.get("[data-cy=outdated-warning]").should("not.exist");
        cy.get("[data-cy=last-updated]").should("not.exist");
        cy.get(".page-body-content .package-action-buttons button")
          .contains("Review & Run")
          .click();
        cy.get("[data-cy=outdated-warning]").should("not.exist");
      });

      it("Shows a label if the package has information about when it was last updated", () => {
        cy.configureCluster({
          mesos: "1-task-healthy",
          universePackages: "old",
        }).visitUrl({
          url: "/catalog/packages/marathon?version=1.4.6",
        });

        cy.get("[data-cy=last-updated]");
        cy.get(".page-body-content .package-action-buttons button")
          .contains("Review & Run")
          .click();
        cy.get("[data-cy=outdated-warning]").should("not.exist");
      });

      it("Shows a yellow warning if the package has not been updated for over a year", () => {
        cy.configureCluster({
          mesos: "1-task-healthy",
          universePackages: "older",
        }).visitUrl({ url: "/catalog/packages/marathon?version=1.4.6" });

        cy.get("[data-cy=outdated-warning]");
        cy.get(".tooltip").contains(
          "This service has not been updated for at least 1 year. We recommend you update if possible."
        );

        cy.get(".page-body-content .package-action-buttons button")
          .contains("Review & Run")
          .click();
        cy.get("[data-cy=outdated-warning]");
        cy.get(".tooltip").contains(
          "This service has not been updated for at least 1 year. We recommend you update if possible."
        );
      });
    });
  });

  context("Package Configuration", () => {
    beforeEach(() => {
      cy.get(".page-body-content .package-action-buttons button")
        .contains("Review & Run")
        .click();

      cy.get(".modal .modal-header button").contains("Review & Run").click();
    });

    it("opens framework configuration when Review & Run clicked", () => {
      cy.get(".modal .configuration-map-label")
        .contains("Name")
        .should("have.length", 1);
    });

    it("shows preinstall notes on review screen", () => {
      cy.get(".modal .infoBoxWrapper")
        .contains(
          "We recommend a minimum of one node with at least 2 CPU shares and 1GB of RAM available for the Marathon DCOS Service."
        )
        .should("have.length", 1);
    });

    it("goes to form when back button is clicked", () => {
      cy.get(".modal .modal-header button").contains("Back").click();
      cy.get('.modal .menu-tabbed-container input[name="group"]').retype(
        "group-1"
      );
    });

    it("changes cancel button to back when on review screen", () => {
      cy.get(".modal button").contains("Edit Config").click();

      cy.get('.modal .menu-tabbed-container input[name="group"]').type(
        "group-1"
      );

      cy.get(".modal .modal-header button").contains("Review & Run").click();

      cy.get(".modal .modal-header button")
        .contains("Back")
        .should("have.length", 1);
    });

    it("shows success dialog on successfully package install", () => {
      cy.get(".modal .modal-header button.button-primary")
        .contains("Run Service")
        .click();

      cy.get(".modal.modal-small .modal-body")
        .contains("Success")
        .should("have.length", 1);
    });

    context("Framework: Placement", () => {
      beforeEach(() => {
        cy.get(".modal button").contains("Edit Config").click();
      });

      context("Add Placement Constraint", () => {
        beforeEach(() => {
          cy.get(".menu-tabbed-view-container").as("tabView");
          cy.get(".button-primary-link")
            .contains("Add Placement Constraint")
            .click();
        });

        it('Should add rows when "Add Placement Constraint" link clicked', () => {
          // Field
          cy.get("@tabView").find(
            '.form-control[name="constraints.0.fieldName"]'
          );

          // operator
          cy.get("@tabView").find('[name="constraints.0.operator"]');

          // value
          cy.get("@tabView").find('.form-control[name="constraints.0.value"]');
        });

        it("Should remove rows when remove button clicked", () => {
          cy.contains(".form-row", "Operator").within(() => {
            // Click delete button
            cy.get("a.button").click();
          });

          // Field
          cy.get("@tabView")
            .find('.form-control[name="constraints.0.fieldName"]')
            .should("not.exist");

          // operator
          cy.get("@tabView")
            .find('[name="constraints.0.operator"]')
            .should("not.exist");

          // value
          cy.get("@tabView")
            .find('.form-control[name="constraints.0.value"]')
            .should("not.exist");
        });

        it("Should disable the field value when Unique is selected in operator dropdown", () => {
          cy.get("@tabView").find(".button.dropdown-toggle").click();

          cy.contains(".dropdown-select-item-title", "Unique").click();

          // value
          cy.get("@tabView")
            .find('[name="constraints.0.value"]')
            .should("be.disabled");
        });
      });
    });
  });
});


text:
module S3FTP
  class Driver

    USER  = 0
    PASS  = 1
    ADMIN = 2

    def initialize(config, passwd)
      @config = config
      @users  = {}
      CSV.parse(passwd).map { |row|
        @users[row[USER]] = {
          :pass  => passwordfile_uses_bcrypt ? BCrypt::Password.new(row[PASS]) : row[PASS],
          :admin => row[ADMIN].to_s.upcase == "Y"
        }
      }
    end

    def change_dir(path, &block)
      prefix = scoped_path(path)

      item = Happening::S3::Bucket.new(aws_bucket, :aws_access_key_id => aws_key, :aws_secret_access_key => aws_secret, :prefix => prefix, :delimiter => "/")
      item.get do |response|
        yield contains_directory?(response.response, prefix)
      end
    end

    def dir_contents(path, &block)
      puts path
      puts "Interesting"
      prefix = scoped_path_with_trailing_slash(path)

      on_error   = Proc.new {|response| yield false }
      on_success = Proc.new {|response| yield response.response_header["CONTENT_LENGTH"].to_i }

      item = Happening::S3::Bucket.new(aws_bucket, :aws_access_key_id => aws_key, :aws_secret_access_key => aws_secret, :prefix => prefix, :delimiter => "/")
      item.get do |response|
        puts parse_bucket_list(response.response)
        yield parse_bucket_list(response.response)
      end
    end

    def authenticate(user, pass, &block)
      if @users[user] && @users[user][:pass] == pass
        @user = user
        yield true
      else
        yield false
      end
    end

    def bytes(path, &block)
      key = scoped_path(path)

      on_error   = Proc.new {|response| yield false }
      on_success = Proc.new {|response| yield response.response_header["CONTENT_LENGTH"].to_i }

      item = Happening::S3::Item.new(aws_bucket, key, :aws_access_key_id => aws_key, :aws_secret_access_key => aws_secret)
      item.head(:retry_count => 0, :on_success => on_success, :on_error => on_error)
    end

    def get_file(path, &block)
      key = scoped_path(path)

      on_error   = Proc.new {|response| yield false }
      on_success = Proc.new {|response| yield response.response }

      item = Happening::S3::Item.new(aws_bucket, key, :aws_access_key_id => aws_key, :aws_secret_access_key => aws_secret)
      item.get(:retry_count => 1, :on_success => on_success, :on_error => on_error)
    end

    def put_file(path, tmp_path, &block)
      key = scoped_path(path)

      bytes      = File.size(tmp_path)
      on_error   = Proc.new {|response| yield false }
      on_success = Proc.new {|response| yield bytes  }

      item = Happening::S3::Item.new(aws_bucket, key, :aws_access_key_id => aws_key, :aws_secret_access_key => aws_secret)
      item.put(File.binread(tmp_path), :retry_count => 0, :on_success => on_success, :on_error => on_error)
    end

    def delete_file(path, &block)
      key = scoped_path(path)

      on_error   = Proc.new {|response| yield false }
      on_success = Proc.new {|response| yield true  }

      item = Happening::S3::Item.new(aws_bucket, key, :aws_access_key_id => aws_key, :aws_secret_access_key => aws_secret)
      item.delete(:retry_count => 1, :on_success => on_success, :on_error => on_error)
    end

    def delete_dir(path, &block)
      prefix = scoped_path(path)

      on_error   = Proc.new {|response| yield false }

      item = Happening::S3::Bucket.new(aws_bucket, :aws_access_key_id => aws_key, :aws_secret_access_key => aws_secret, :prefix => prefix)
      item.get(:on_error => on_error) do |response|
        keys = bucket_list_to_full_keys(response.response)
        delete_object = Proc.new { |key, iter|
          item = Happening::S3::Item.new(aws_bucket, key, :aws_access_key_id => aws_key, :aws_secret_access_key => aws_secret)
          item.delete(:retry_count => 1, :on_error => on_error) do |response|
            iter.next
          end
        }
        on_complete = Proc.new { yield true }

        EM::Iterator.new(keys, 5).each(delete_object, on_complete)
      end
    end

    def rename(from, to, &block)
      source_key = scoped_path(from)
      source_obj = aws_bucket + "/" + source_key
      dest_key   = scoped_path(to)

      on_error   = Proc.new {|response| yield false }
      on_success = Proc.new {|response| yield true  }

      item = Happening::S3::Item.new(aws_bucket, dest_key, :aws_access_key_id => aws_key, :aws_secret_access_key => aws_secret)
      item.put(nil, :retry_count => 1, :on_error => on_error, :headers => {"x-amz-copy-source" => source_obj}) do |response|
        item = Happening::S3::Item.new(aws_bucket, source_key, :aws_access_key_id => aws_key, :aws_secret_access_key => aws_secret)
        item.delete(:retry_count => 1, :on_success => on_success, :on_error => on_error)
      end
    end

    def make_dir(path, &block)
      key = scoped_path(path) + "/.dir"

      on_error   = Proc.new {|response| yield false }
      on_success = Proc.new {|response| yield true  }

      item = Happening::S3::Item.new(aws_bucket, key, :aws_access_key_id => aws_key, :aws_secret_access_key => aws_secret)
      item.put("", :retry_count => 0, :on_success => on_success, :on_error => on_error)
    end

    private

    def admin?
      @users[@user] && @users[@user][:admin]
    end

    def scoped_path_with_trailing_slash(path)
      path  = File.join("/", path)
      path += "/" if path[-1,1] != "/"
      path == "/" ? nil : path[1..-1]
    end

    def scoped_path(path)
      path = "" if path == "/"
      if admin?
      	 File.join("/", path)[1,1024]
      else
        File.join("/", @user, path)[1,1024]
      end
    end

    def aws_bucket
      @config[:bucket]
    end

    def aws_key
      @config[:aws_key]
    end

    def aws_secret
      @config[:aws_secret]
    end

    def passwordfile_uses_bcrypt
      @config[:remote_passwd_use_bcrypt]
    end

    def bucket_list_to_full_keys(xml)
      doc = Nokogiri::XML(xml)
      doc.remove_namespaces!
      doc.xpath('//Contents').map { |node|
        node.xpath('./Key').first.content
      }
    end

    def contains_directory?(xml, path)
      doc = Nokogiri::XML(xml)
      doc.remove_namespaces!
      prefix = doc.xpath('/ListBucketResult/Prefix').first.content

      doc.xpath('//CommonPrefixes').any? { |node|
        name  = node.xpath('./Prefix').first.content

        name.to_s.start_with?(prefix)
      }
    end

    def parse_bucket_list(xml)
      doc = Nokogiri::XML(xml)
      doc.remove_namespaces!
      prefix = doc.xpath('/ListBucketResult/Prefix').first.content
      files = doc.xpath('//Contents').select { |node|
        name  = node.xpath('./Key').first.content
        bytes = node.xpath('./Size').first.content.to_i
        name != prefix && bytes > 0
      }.map { |node|
        name  = node.xpath('./Key').first.content
        bytes = node.xpath('./Size').first.content
        file_item(name[prefix.size, 1024], bytes)
      }
      dirs = doc.xpath('//CommonPrefixes').select { |node|
        node.xpath('./Prefix').first.content != prefix + "/"
      }.map { |node|
        name  = node.xpath('./Prefix').first.content
        dir_item(name[prefix.size, 1024].tr("/",""))
      }
      default_dirs + dirs + files
    end

    def default_dirs
      [dir_item("."), dir_item("..")]
    end

    def dir_item(name)
      EM::FTPD::DirectoryItem.new(:name => name, :directory => true, :size => 0)
    end

    def file_item(name, bytes)
      EM::FTPD::DirectoryItem.new(:name => name, :directory => false, :size => bytes)
    end

  end
end


text:
#include "pch.h"
#include "MainPage.xaml.h"

using namespace SimpleAnimation;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Media::Animation;
using namespace Windows::UI::Xaml::Navigation;

MainPage::MainPage()
{
    InitializeComponent();
}

void MainPage::OnButtonClick(Object^ sender, RoutedEventArgs^ args)
{
    dynamic_cast<Storyboard^>(this->Resources->Lookup("storyboard"))->Begin();
}


text:
name: Hacking on Gogs
sort: 3
---

# Hacking on Gogs

If you want to contribute to Gogs you should fork the project and work on the dev branch.
There is a catch though; some internal packages are referenced by their Github url. So
you have to trick the Go tool to think that you work on a clone of the official repository.

Start by downloading the source code as you normally would:

    $ go get github.com/gogits/gogs

Now fork the project on Github and then go to gogs' source parent directory:

    $ cd $GOPATH/src/github.com/gogits

Remove the gogs repository and clone your fork in its place:

    $ rm -rf gogs
    $ git clone git@github.com:<USERNAME>/gogs.git gogs

Go inside the gogs directory, checkout the dev branch and use `go get` again to fetch any new dependencies:

    $ cd gogs
    $ git checkout develop
    $ go get

That's it! You are ready to hack on Gogs. Test your changes, push them to your repository and open a pull request.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `Executor` trait in crate `futures`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, Executor">

    <title>futures::executor::Executor - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../main.css">

futures::<wbr>executor

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

Trait futures::<wbr>executor::<wbr>Executor

                       [−]

               [src]

pub trait Executor: Send + Sync + 'static {
    fn execute(&self, r: Run);
}

A trait representing requests to poll futures.

This trait is an argument to the Spawn::execute which is used to run a
future to completion. An executor will receive requests to run a future and
an executor is responsible for ensuring that happens in a timely fashion.

Note that this trait is likely to be deprecated and/or renamed to avoid
clashing with the future::Executor trait. If you've got a use case for
this or would like to comment on the name please let us know!

Required Methods

fn execute(&self, r: Run)

Requests that Run is executed soon on the given executor.

Implementors

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
using System;

namespace NServiceKit.Common.Tests.Models
{
    /// A model with fields of different types factory.
	public class ModelWithFieldsOfDifferentTypesFactory
		: ModelFactoryBase<ModelWithFieldsOfDifferentTypes>
	{
        /// The instance.
		public static ModelWithFieldsOfDifferentTypesFactory Instance
			= new ModelWithFieldsOfDifferentTypesFactory();

        /// Assert is equal.
        ///
        /// <param name="actual">  The actual.</param>
        /// <param name="expected">The expected.</param>
		public override void AssertIsEqual(
			ModelWithFieldsOfDifferentTypes actual, ModelWithFieldsOfDifferentTypes expected)
		{
			ModelWithFieldsOfDifferentTypes.AssertIsEqual(actual, expected);
		}

        /// Creates an instance.
        ///
        /// <param name="i">Zero-based index of the.</param>
        ///
        /// <returns>The new instance.</returns>
		public override ModelWithFieldsOfDifferentTypes CreateInstance(int i)
		{
			return ModelWithFieldsOfDifferentTypes.CreateConstant(i);
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="ESBJAVA3676"
       transports="https,http"
       statistics="disable"
       trace="disable"
       startOnLoad="true">
    <target>
        <inSequence>
            <property name="PAYLOAD" expression="//payload/content" type="OM"/>
            <enrich>
                <source type="property" clone="false" property="PAYLOAD"/>
                <target type="body"/>
            </enrich>
            <respond/>
        </inSequence>
    </target>
    <description/>
</proxy>


text:
package com.gemstone.gemfire.admin;

import com.gemstone.gemfire.SystemFailure;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.internal.cache.DistributedCacheTestCase;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;

import java.util.*;

import dunit.*;

/**
 * Tests that admin distributed systems properly recuse when
 * their JVM crashes.
 *
 * @author jpenney
 */
public class SystemFailureAdminDUnitTest extends DistributedCacheTestCase {

  /**
   * Creates a new AdminAndCacheDUnitTest with the given
   * name.
   */
  public SystemFailureAdminDUnitTest(String name) {
    super(name);
  }

  ////////  Test Methods

  protected static void connectAdminSystem() throws Exception {
    assertTrue(!system.getConfig().getLocators().equals(""));

    DistributedSystemConfig config =
      AdminDistributedSystemFactory.defineDistributedSystem(system, null);
    assertEquals(system.getConfig().getLocators(),
                 config.getLocators());
    assertEquals(system.getConfig().getMcastPort(),
                 config.getMcastPort());

    getLogWriter().info("Locators are: " + config.getLocators() +
                        ", mcast port is: " + config.getMcastPort());

    AdminDistributedSystem admin =
      AdminDistributedSystemFactory.getDistributedSystem(config);
    admin.connect();
    assertTrue(admin.waitToBeConnected(5 * 1000));
  }

  protected static ArrayList pesky;
  protected static void crashMe() {
    pesky = new ArrayList();

    SystemFailure.setFailureMemoryThreshold(0); // Disable watchcat
//  SystemFailure.setExitOK(true); // This VM gets _really_ sick, screws up RMI
    Runnable r = new Runnable() {
      public void run() {
        try {
          for (;;) {
            pesky.add(new int[1000]);
          }
        }
        catch (OutOfMemoryError e) {
          SystemFailure.setFailure(e); // don't throw here :-)

          // Wait and let watchdog notice
          try {
            Thread.sleep(15 * 1000);
          }
          catch (InterruptedException e2) {
            // eeeuw, probably won't do anything useful...
            throw new util.TestException("interrupted");
          }
        } // oome
      }
    };
    new Thread(r, "crashMe").start();
  }

  private void waitForDeath(GemFireCacheImpl c, int numBefore) {
    InternalDistributedSystem ids = (InternalDistributedSystem)
        c.getDistributedSystem();
    long start = System.currentTimeMillis();
    for (;;) {
      if (System.currentTimeMillis() - start > 90 * 1000) {
        fail("Peer did not recuse");
        break; // for lint
      }
      Set membersAfter = ids.getDistributionManager().getNormalDistributionManagerIds();
      int numAfter = membersAfter.size();
      if (numAfter == numBefore - 1) {
        break; // success
      }
      pause(5 * 1000);
    }
    c.getLogger().info("Passed recusal test");
  }

  /**
   * Tests that the admin API launched in an application VM can see
   * caches and regions in other members of the distributed system.
   */
  public void _testAdminRecuses() throws Exception {
    Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);

    // Connect ourselves to the DS
    GemFireCacheImpl c = (GemFireCacheImpl)cache;
    InternalDistributedSystem ids = (InternalDistributedSystem)
        c.getDistributedSystem();

    // Create the admin system
    vm0.invoke(this.getClass(), "connectAdminSystem");

    // How many of us are there?  Use this healthy DS member
    // to examine...
    int numBefore = ids.getDistributionManager().getNormalDistributionManagerIds().size();

    vm0.invokeAsync(this.getClass(), "crashMe");
    waitForDeath(c, numBefore);
    resetVm(vm0);
  }

  public void testNull() {
    // TODO remove once other test is in place
    getLogWriter().info("TODO: this test needs to use VM#bounce");
  }

  private void resetVm(VM vm) {
    // TODO needs to be implemented
    throw new util.TestException("not implemented");
  }
}


text:
{% extends "base.html" %}
{% load i18n %}
{% block content %}

  <form method="post" action="{% url "molo.profiles:edit_my_profile" %}" class="profiles__form">
  {% csrf_token %}

  {% if settings.profiles.UserProfilesSettings.activate_display_name %}
  <fieldset>
		{% trans "Type new display name:" %}
    {{ form.alias.errors}}
    {{ form.alias }}

{% trans "We value your online security, therefore we hide your username and allow you to comment and interact with the site anonymously." %}

{% trans "If you would like to interact with other people, like your friends, to be able to see you as a username and not anonymous, update your username here or select to keep your username as your display name." %}

  </fieldset>
  {% endif %}

  {% if settings.profiles.UserProfilesSettings.activate_dob %}
  <fieldset>
    {% trans "Update your date of birth:" %}

    {{ form.date_of_birth.errors}}
    {{ form.date_of_birth }}
  </fieldset>
  {% endif %}

  {% if settings.profiles.UserProfilesSettings.activate_gender %}
  <fieldset>
    {% trans "Update your gender:" %}

    {{ form.gender.errors}}
    {{ form.gender }}

{% trans "Only you will see this" %}
  </fieldset>
  {% endif %}

  {% if settings.profiles.UserProfilesSettings.activate_location %}
    <fieldset>
      {% trans "Update where you live:" %}

      {{ form.location.errors}}
      {{ form.location }}

{% trans "Only you will see this" %}
    </fieldset>
  {% endif %}

  {% if settings.profiles.UserProfilesSettings.activate_education_level %}
  <fieldset>
    {% trans "Update your Education Level:" %}

    {{ form.education_level.errors}}
    {{ form.education_level }}

{% trans "Only you will see this" %}
  </fieldset>
  {% endif %}

  {% if settings.profiles.UserProfilesSettings.show_mobile_number_field and settings.profiles.UserProfilesSettings.country_code %}
	<fieldset>
		{% trans "Update your mobile number:" %}
		{{ form.mobile_number.errors }}
		{{ form.mobile_number }}

{% trans "(e.g. 0914556789)" %}
	</fieldset>
	{% endif %}

  {% if settings.profiles.UserProfilesSettings.show_email_field %}
  <fieldset>
    {% trans "Update your email address:" %}
    {{ form.email.errors }}
		{{ form.email}}

{% trans "(e.g. example@foo.com)" %}
  </fieldset>
  {% endif %}
  <input type="submit" value='{% trans "Update profile" %}'>
  </form>

  {% trans "Back" %}
  {% trans "Home Page" %}

{% endblock %}


text:
svt_repo_location=/root
controller_namespace=controller
properties_path=/root/properties
counter_time=5
wait_time=25

# Cleanup
function cleanup() {
	oc delete -f $svt_repo_location/svt/openshift_templates/performance_monitoring/scale-ci-controller/controller-job.yml -n $controller_namespace
	oc delete cm tooling-config -n $controller_namespace
	oc delete project --wait=true $controller_namespace
	sleep $wait_time
}

# Create a service account and add it to the privileged scc
function create_service_account() {
        oc create serviceaccount useroot -n $controller_namespace
        oc adm policy add-scc-to-user privileged -z useroot -n $controller_namespace
}

# Ensure that the host has svt repo cloned
if [[ ! -d $svt_repo_location/svt ]]; then
	 git clone https://github.com/openshift/svt.git
fi

# Check if the controller job and configmap exists
oc get jobs -n $controller_namespace | grep -w "controller" &>/dev/null
if [[ $? == 0 ]]; then
	cleanup
fi
oc get cm -n $controller_namespace | grep -w "tooling-config" &>/dev/null
if [[ $? == 0 ]]; then
	cleanup
fi

oc project $controller_namespace &>/dev/null
if [[ $? == 0 ]]; then
        echo "Looks like the $controller_namespace already exists, deleting it"
        oc delete project --wait=true $controller_namespace
	sleep $wait_time
fi

# Create controller ns, configmap and run the job
oc create -f $svt_repo_location/svt/openshift_templates/performance_monitoring/scale-ci-controller/controller-ns.yml
create_service_account
oc create configmap tooling-config --from-env-file=$properties_path -n $controller_namespace
oc create -f $svt_repo_location/svt/openshift_templates/performance_monitoring/scale-ci-controller/controller-job.yml -n $controller_namespace
sleep $wait_time
controller_pod=$(oc get pods -n $controller_namespace | grep "controller" | awk '{print $1}')
counter=0
while [[ $(oc --namespace=default get pods $controller_pod -n $controller_namespace -o json | jq -r ".status.phase") != "Running" ]]; do
	sleep $counter_time
	counter=$((counter+1))
	if [[ $counter -ge 120 ]]; then
		echo "Looks like the $controller_pod is not up after 120 sec, please check"
		exit 1
	fi
done

# logging
logs_counter=0
logs_counter_limit=500
oc logs -f $controller_pod -n $controller_namespace
while true; do
        logs_counter=$((logs_counter+1))
        if [[ $(oc --namespace=default get pods $controller_pod -n $controller_namespace -o json | jq -r ".status.phase") == "Running" ]]; then
                if [[ $logs_counter -le $logs_counter_limit ]]; then
			echo "=================================================================================================================================================================="
			echo "Attempt $logs_counter to reconnect and fetch the controller pod logs"
			echo "=================================================================================================================================================================="
			echo "------------------------------------------------------------------------------------------------------------------------------------------------------------------"
			echo "------------------------------------------------------------------------------------------------------------------------------------------------------------------"
                        oc logs -f $controller_pod -n $controller_namespace
                else
                        echo "Exceeded the retry limit trying to get the controller logs: $logs_counter_limit, exiting."
                        exit 1
                fi
        else
                echo "Job completed"
                break
        fi
done

# check the status of the controller pod
while [[ $(oc --namespace=default get pods $controller_pod -n $controller_namespace -o json | jq -r ".status.phase") != "Succeeded" ]]; do
	if [[ $(oc --namespace=default get pods $controller_pod -n $controller_namespace -o json | jq -r ".status.phase") == "Failed" ]]; then
   		echo "JOB FAILED"
		echo "CLEANING UP"
   		cleanup
   		exit 1
   	else
    		sleep $wait_time
        fi
done
echo "JOB SUCCEEDED"

# cleanup
echo "CLEANING UP"
cleanup


text:
<?php

declare(strict_types=1);

namespace EngineWorks\DBAL\Iterators;

use EngineWorks\DBAL\Result;
use Iterator;

/**
 * @implements Iterator<int, array<string, scalar|null>>
 */
class ResultIterator implements Iterator
{
    /** @var Result */
    private $result;

    /** @var int autonumeric index */
    private $index;

    /** @var array<string, scalar|null>|false Store of current values */
    private $currentValues;

    /**
     * ResultIterator constructor.
     * @param Result $result
     */
    public function __construct(Result $result)
    {
        $this->result = $result;
    }

    /** @return array<string, scalar|null>|false */
    #[\ReturnTypeWillChange]
    public function current()
    {
        return $this->currentValues;
    }

    #[\ReturnTypeWillChange]
    public function key(): int
    {
        return $this->index;
    }

    public function valid(): bool
    {
        return is_array($this->currentValues);
    }

    public function next(): void
    {
        $this->currentValues = $this->result->fetchRow();
        $this->index = $this->index + 1;
    }

    public function rewind(): void
    {
        $this->result->moveFirst();
        $this->currentValues = $this->result->fetchRow();
        $this->index = 0;
    }
}


text:
package main

import (
	"flag"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"os"
	"regexp"
	"strconv"
	"time"
)

const (
	DefaultNumOfResultToShow = 3
)

type Time struct {
	hour, minute int
}

func (time *Time) toString() string {
	if time.minute < 10 {
		return fmt.Sprintf("%d:0%d ", time.hour, time.minute)
	} else {
		return fmt.Sprintf("%d:%d ", time.hour, time.minute)
	}
}

func departureTime(departure string) (int, int) {
	ret, _ := regexp.MatchString("^[0-9]{1,2}:[0-9]{1,2}$", departure)
	var hour int
	var minute int
	if ret {
		re := regexp.MustCompile("^([0-9]{1,2}):([0-9]{1,2})$")
		bs := []byte(departure)
		group := re.FindSubmatch(bs)
		h, _ := strconv.Atoi(string(group[1]))
		m, _ := strconv.Atoi(string(group[2]))
		if h >= 0 && h < 24 && m >= 0 && m < 60 {
			hour = h
			minute = m
		} else {
			now := time.Now()
			hour = now.Hour()
			minute = now.Minute()
		}
	} else {
		now := time.Now()
		hour = now.Hour()
		minute = now.Minute()
	}
	return hour, minute
}

func getTimeTableUrl() string {
	weekday := time.Now().Weekday().String()
	if weekday == "Saturday" || weekday == "Sunday" {
		return "http://www.jreast-timetable.jp/1509/timetable/tt0413/0413021.html"
	} else {
		return "http://www.jreast-timetable.jp/1509/timetable/tt0413/0413020.html"
	}
}

func createTimetable() []Time {
	var timetable = make([]Time, 0)
	url := getTimeTableUrl()
	doc, _ := goquery.NewDocument(url)
	doc.Find(".timetable .result_03").Each(func(_ int, s *goquery.Selection) {
		s.Find("tbody tr").Each(func(_ int, s *goquery.Selection) {
			key, err := strconv.Atoi(s.Find("td:nth-child(1)").Text())
			if err == nil {
				s.Find("td:nth-child(2) div.timetable_time[data-dest='府']").Each(func(_ int, s *goquery.Selection) {
					value, _ := strconv.Atoi(s.Find(".minute").Text())
					timetable = append(timetable, Time{key, value})
				})
			}
		})
	})
	return timetable
}

func printTimes(times []string) {
	for _, v := range times {
		fmt.Println(v)
	}
}

func main() {
	var (
		departure   string
		numOfResult int
		isLast      bool
	)
	flag.StringVar(&departure, "t", "", "specify departure time.")
	flag.BoolVar(&isLast, "l", false, "show last bus of the day.")
	flag.IntVar(&numOfResult, "n", DefaultNumOfResultToShow, "specify amount of result.")
	flag.Parse()

	if numOfResult < 0 {
		fmt.Fprintf(os.Stderr, "parameter for -n must be greater than 0.\n")
		os.Exit(2)
	}

	hour, minute := departureTime(departure)
	timetable := createTimetable()

	if isLast {
		result := []string{timetable[len(timetable)-1].toString()}
		printTimes(result)
		return
	}

	result := make([]string, 0, numOfResult)
	for i := 0; i < len(timetable); i++ {
		v := timetable[i]
		if v.minute > minute && v.hour >= hour {
			timeStr := v.toString()
			result = append(result, timeStr)
			if len(result) >= numOfResult {
				break
			}
		}
	}
	printTimes(result)
}


text:
package org.kiji.mapreduce.kvstore.lib;

import java.io.IOException;
import java.util.Map;

import com.google.common.collect.ImmutableMap;
import org.apache.avro.Schema;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;

import org.kiji.annotations.ApiAudience;
import org.kiji.annotations.ApiStability;
import org.kiji.mapreduce.kvstore.KeyValueStore;
import org.kiji.mapreduce.kvstore.KeyValueStoreReader;
import org.kiji.mapreduce.kvstore.framework.KeyValueStoreConfiguration;
import org.kiji.mapreduce.util.LruCache;
import org.kiji.schema.EntityId;
import org.kiji.schema.Kiji;
import org.kiji.schema.KijiColumnName;
import org.kiji.schema.KijiDataRequest;
import org.kiji.schema.KijiDataRequestBuilder;
import org.kiji.schema.KijiRowData;
import org.kiji.schema.KijiRowKeyComponents;
import org.kiji.schema.KijiTable;
import org.kiji.schema.KijiTableReader;
import org.kiji.schema.KijiTableReaderPool;
import org.kiji.schema.KijiTableReaderPool.Builder.WhenExhaustedAction;
import org.kiji.schema.KijiURI;
import org.kiji.schema.KijiURIException;
import org.kiji.schema.layout.ColumnReaderSpec;
import org.kiji.schema.util.ResourceUtils;

/**
 * KeyValueStore lookup implementation based on a Kiji table.
 *
 *
Allows you to use a single fully-qualified column of a Kiji table as a
 * key-value store (using a KijiRowKeyComponents that corresponds to the
 * entity id associated with each row as the key).

 *
 *
This operates over the most recent timestamped value (within the optionally-configured
 * timestamp range associated with the Store).

 *
 *
This implementation assumes that the column is immutable while being used in this
 * fashion. It may cache values to improve repeated read performance. You can set the
 * cache size with {@link KijiTableKeyValueStore.Builder#withCacheLimit(int)}.

 *
 *
XML Configuration

 *
 *
When configuring a KijiTableKeyValueStore from a kvstores XML file, the following
 * properties may be used to specify the behavior of this class:

 *

 *
<tt>table.uri</tt> - The Kiji URI for the table backing this store.

 *
<tt>column</tt> - The family and qualifier of the column representing the values
 *       in this store. e.g., <tt>info:name</tt>

 *
<tt>min.ts</tt> - A <tt>long</tt> value representing the minimum timestamp to
 *       include in the results for this KeyValueStore.

 *
<tt>max.ts</tt> - A <tt>long</tt> value representing the maximum timestamp to
 *       include in the results for this KeyValueStore.

 *
<tt>cache.size</tt> - An <tt>int</tt> value representing the number of results
 *       to cache locally. (Default is 100; set to 0 to disable caching.)

 *
<tt>avro.reader.schema</tt> - The common Avro reader schema used to
 *       deserialize values from
 *       the value column to return them to the client.

 *

 *
 *
Default Values

 *

 *
You must specify the {@link KijiURI} of the table to read; it is an error to
 *   leave this unconfigured.

 *
You must specify the column to read as the value; it is an error to leave
 *   this unconfigured.

 *
HBase tables will be accessed through a new <tt>Configuration</tt> object
 *   if none is explicitly specified.

 *
The minimum timestamp to read defaults to <tt>0</tt>.

 *
The maximum timestamp to read is "infinity" (no maximum). This can be specified
 *   as <tt>HConstants.FOREVER</tt>.

 *
The number of rowkey-to-value mappings to cache locally defaults to 100. You
 *   can disable caching by setting the cache size to 0.

 *
The Avro reader schema field is currently ignored. The reader schema from the
 *   table layout for that column will always be used as the reader schema. Support for
 *   custom reader schemas will be added after SCHEMA-295 is committed to KijiSchema.

 *

 *
 * @param <V> the value type returned by this key-value store.
 */
@ApiAudience.Public
@ApiStability.Evolving
public final class KijiTableKeyValueStore<V>
    implements Configurable, KeyValueStore<KijiRowKeyComponents, V> {

  /** Cache the most recent 100 lookups in memory. */
  private static final int DEFAULT_MAX_OBJECTS_TO_CACHE = 100;

  // See javadoc for this class to understand the definitions of these configuration keys.

  private static final String CONF_TABLE_URI = "table.uri";
  private static final String CONF_COLUMN = "column";
  private static final String CONF_MIN_TS = "min.ts";
  private static final String CONF_MAX_TS = "max.ts";
  private static final String CONF_CACHE_SIZE = "cache.size";
  private static final String CONF_READER_SCHEMA = "avro.reader.schema";

  private KijiURI mTableUri;
  private KijiColumnName mColumn;
  private long mMinTs;
  private long mMaxTs;
  private int mMaxObjectsToCache = DEFAULT_MAX_OBJECTS_TO_CACHE;
  private Schema mReaderSchema;
  private Configuration mConf;

  /** true if the user has called open() on this object. */
  private boolean mOpened;

  /**
   * A Builder-pattern class that configures and creates new KijiTableKeyValueStore
   * instances. You should use this to specify the input to this KeyValueStore.
   * Call the build() method to return a new KijiTableKeyValueStore instance.
   */
  @ApiAudience.Public
  @ApiStability.Evolving
  public static final class Builder {
    private KijiURI mTableUri;
    private KijiColumnName mColumn;
    private long mMinTs;
    private long mMaxTs;
    private int mMaxObjectsToCache = DEFAULT_MAX_OBJECTS_TO_CACHE;
    private Schema mReaderSchema;
    private Configuration mConf;

    /**
     * Private, default constructor. Call the builder() method of this KeyValueStore
     * to get a new builder instance.
     */
    private Builder() {
      mMaxObjectsToCache = DEFAULT_MAX_OBJECTS_TO_CACHE;
      mMinTs = 0;
      mMaxTs = HConstants.LATEST_TIMESTAMP;
      mConf = HBaseConfiguration.create(); //new Configuration();
    }

    /**
     * Sets the Configuration to use to connect to Kiji.
     *
     * @param conf the Configuration to use.
     * @return this builder instance.
     */
    public Builder withConfiguration(Configuration conf) {
      mConf = conf;
      return this;
    }

    /**
     * Sets the table to use as the backing store.
     *
     * @param tableUri the Kiji table URI to use.
     * @return this builder instance.
     */
    public Builder withTable(KijiURI tableUri) {
      checkTableUri(tableUri);
      mTableUri = tableUri;
      return this;
    }

    /**
     * Sets the column to retrieve values from.
     *
     * @param colName the column to use.
     * @return this builder instance.
     */
    public Builder withColumn(KijiColumnName colName) {
      if (!colName.isFullyQualified()) {
        throw new IllegalArgumentException("Must specify a fully-qualified column, not a map.");
      }
      mColumn = colName;
      return this;
    }

    /**
     * Sets the column to retrieve values from.
     *
     * @param family the column family to use.
     * @param qualifier the column qualifier to use.
     * @return this builder instance.
     */
    public Builder withColumn(String family, String qualifier) {
      return withColumn(new KijiColumnName(family, qualifier));
    }

    /**
     * Sets the oldest timestamp to retrieve values from in the column.
     *
     * @param timestamp the oldest timestamp to consider.
     * @return this builder instance.
     */
    public Builder withMinTimestamp(long timestamp) {
      mMinTs = timestamp;
      return this;
    }

    /**
     * Sets the newest timestamp to retrieve values from in the column.
     *
     * @param timestamp the newest timestamp to consider.
     * @return this builder instance.
     */
    public Builder withMaxTimestamp(long timestamp) {
      mMaxTs = timestamp;
      return this;
    }

    /**
     * Sets the maximum number of lookups to cache in memory.
     *
     *
Defaults to 100.

     *
     * @param numValues the maximum number of values to keep in the cache.
     * @return this builder instance.
     */
    public Builder withCacheLimit(int numValues) {
      mMaxObjectsToCache = numValues;
      return this;
    }

    /**
     * Sets the reader schema to use when deserializing values from the value column.
     * If set to null, will use the common reader schema associated with the column.
     *
     * @param schema the reader schema to use.
     * @return this builder instance.
     */
    public Builder withReaderSchema(Schema schema) {
      mReaderSchema = schema;
      return this;
    }

    /**
     * Throws an IllegalArgumentException if tableUri is invalid. The URI
     * is valid iff it is not null, specifies a Kiji instance, and specifies
     * a Kiji table within that instance to read.
     *
     * @param tableUri a Kiji URI that must specify an instance and table.
     * @throws IllegalArgumentException if the uri is invalid.
     */
    private void checkTableUri(KijiURI tableUri) {
      if (null == tableUri) {
        throw new IllegalArgumentException("Must specify non-null table URI");
      }

      String tableName = tableUri.getTable();
      if (null == tableName || tableName.isEmpty()) {
        throw new IllegalArgumentException("Must specify a non-empty table name");
      }
    }

    /**
     * Build a new KijiTableKeyValueStore instance.
     *
     * @param <V> The value type for the KeyValueStore.
     * @return the initialized KeyValueStore.
     */
    public <V> KijiTableKeyValueStore<V> build() {
      checkTableUri(mTableUri);
      if (null == mColumn || !mColumn.isFullyQualified()) {
        throw new IllegalArgumentException("Must specify a fully-qualified column");
      }
      if (mMinTs > mMaxTs) {
        throw new IllegalArgumentException("Minimum timestamp must be less than max timestamp");
      }

      // Check that the table exists, so users can fail fast before finding this
      // IO error after the MapReduce job has started.
      Kiji kiji = null;
      KijiTable kijiTable = null;
      try {
        kiji = Kiji.Factory.open(mTableUri, mConf);
        kijiTable = kiji.openTable(mTableUri.getTable());
      } catch (IOException ioe) {
        throw new IllegalArgumentException("Could not open table: " + mTableUri, ioe);
      } finally {
        ResourceUtils.releaseOrLog(kijiTable);
        ResourceUtils.releaseOrLog(kiji);
      }

      return new KijiTableKeyValueStore<V>(this);
    }
  }

  /**
   * Creates a new KijiTableKeyValueStore.Builder instance that can be used
   * to configure and create a new KeyValueStore.
   *
   * @return a new Builder instance.
   */
  public static Builder builder() {
    return new Builder();
  }

  /**
   * Reflection-only constructor. Used only for reflection. You should create and configure
   * KijiTableKeyValueStore instances by using a builder;
   * call KijiTableKeyValueStore.builder() to get a new builder instance.
   */
  public KijiTableKeyValueStore() {
    this(builder());
  }

  /**
   * Constructor that up this KeyValueStore using a builder.
   *
   * @param builder the builder instance to read configuration from.
   */
  private KijiTableKeyValueStore(Builder builder) {
    mTableUri = builder.mTableUri;
    mColumn = builder.mColumn;
    mMinTs = builder.mMinTs;
    mMaxTs = builder.mMaxTs;
    mMaxObjectsToCache = builder.mMaxObjectsToCache;
    mReaderSchema = builder.mReaderSchema;
    mConf = builder.mConf;
  }

  /**
   * Set the configuration object to refer to.
   *
   * @param conf the Configuration object to use.
   */
  @Override
  public void setConf(Configuration conf) {
    if (mOpened) {
      // Don't allow mutation after we start using this store for reads.
      throw new IllegalStateException(
          "Cannot set the configuration after a reader has been opened");
    }
    mConf = conf;
  }

  /** @return a copy of the Configuration object we are using. */
  @Override
  public Configuration getConf() {
    return new Configuration(mConf);
  }

  /** {@inheritDoc} */
  @Override
  public void storeToConf(KeyValueStoreConfiguration conf) throws IOException {
    if (null == mTableUri) {
      throw new IOException("Required attribute not set: table URI");
    }
    if (null == mColumn) {
      throw new IOException("Required attribute not set: column");
    }
    if (!mColumn.isFullyQualified()) {
      throw new IOException("Column must be fully qualified");
    }

    conf.set(CONF_TABLE_URI, mTableUri.toString());
    conf.set(CONF_COLUMN, mColumn.toString());
    conf.setLong(CONF_MIN_TS, mMinTs);
    conf.setLong(CONF_MAX_TS, mMaxTs);
    conf.setInt(CONF_CACHE_SIZE, mMaxObjectsToCache);

    if (null != mReaderSchema) {
      conf.set(CONF_READER_SCHEMA, mReaderSchema.toString());
    }
  }

  /** {@inheritDoc} */
  @Override
  public void initFromConf(KeyValueStoreConfiguration conf) throws IOException {
    if (mOpened) {
      // Don't allow mutation after we start using this store for reads.
      throw new IllegalStateException(
          "Cannot set the configuration after a reader has been opened");
    }

    try {
      mTableUri = KijiURI.newBuilder(conf.get(CONF_TABLE_URI)).build();
    } catch (KijiURIException kue) {
      throw new IOException("Error parsing input URI: " + kue.getMessage(), kue);
    }

    mColumn = new KijiColumnName(conf.get(CONF_COLUMN));
    mMinTs = conf.getLong(CONF_MIN_TS, 0);
    mMaxTs = conf.getLong(CONF_MAX_TS, Long.MAX_VALUE);
    mMaxObjectsToCache = conf.getInt(CONF_CACHE_SIZE, DEFAULT_MAX_OBJECTS_TO_CACHE);

    String schemaStr = conf.get(CONF_READER_SCHEMA);
    if (null != schemaStr) {
      mReaderSchema = new Schema.Parser().parse(schemaStr);
    } else {
      mReaderSchema = null; // Just use whatever's in the cell directly.
    }

    // Set the job Configuration so that we get connection parameters to the Kiji table.
    setConf(conf.getDelegate());
  }

  /** {@inheritDoc} */
  @Override
  public KeyValueStoreReader<KijiRowKeyComponents, V> open() throws IOException {
    mOpened = true;
    return new TableKVReader();
  }

  /** {@inheritDoc} */
  @Override
  public boolean equals(Object otherObj) {
    if (otherObj == this) {
      return true;
    } else if (null == otherObj) {
      return false;
    } else if (!otherObj.getClass().equals(getClass())) {
      return false;
    }

    @SuppressWarnings("unchecked")
    KijiTableKeyValueStore<V> other = (KijiTableKeyValueStore<V>) otherObj;

    if (null == mTableUri) {
      if (other.mTableUri != null) {
        return false;
      }
    } else if (!mTableUri.equals(other.mTableUri)) {
      return false;
    }

    if (null == mColumn) {
      if (other.mColumn != null) {
        return false;
      }
    } else if (!mColumn.equals(other.mColumn)) {
      return false;
    }

    if (mMinTs != other.mMinTs) {
      return false;
    } else if (mMaxTs != other.mMaxTs) {
      return false;
    } else if (mMaxObjectsToCache != other.mMaxObjectsToCache) {
      return false;
    }

    if (null == mReaderSchema) {
      if (other.mReaderSchema != null) {
        return false;
      }
    } else if (!mReaderSchema.equals(other.mReaderSchema)) {
      return false;
    }

    // We don't care about mConf.

    return true;
  }

  /** {@inheritDoc} */
  @Override
  public int hashCode() {
    int hash = 17;
    hash = hash + (null == mTableUri ? 0 : mTableUri.hashCode()) * 31;
    hash = hash + (null == mColumn ? 0 : mColumn.hashCode()) * 31;
    return hash;
  }

  /** KeyValueStoreReader implementation that reads from a Kiji table. */
  @ApiAudience.Private
  private final class TableKVReader implements KeyValueStoreReader<KijiRowKeyComponents, V> {
    /** Kiji Table instance to open. */
    private KijiTable mKijiTable;
    /** KijiTableReader to read the table. */
    private KijiTableReaderPool mTableReaderPool;
    /** Data request to use for all lookups. */
    private final KijiDataRequest mDataReq;
    /** If the user has requested result caching, do this here. */
    private final Map<KijiRowKeyComponents, V> mResultCache;

    /**
     * Creates a new TableKVReader.
     *
     * @throws IOException if there's an error opening the Kiji table.
     */
    private TableKVReader() throws IOException {
      Configuration conf = getConf();
      final Kiji kiji = Kiji.Factory.open(mTableUri, conf);
      try {
        mKijiTable = kiji.openTable(mTableUri.getTable());
      } finally {
        kiji.release();
      }

      final KijiTableReaderPool.Builder poolBuilder = KijiTableReaderPool.Builder.create()
          .withReaderFactory(mKijiTable.getReaderFactory())
          .withExhaustedAction(WhenExhaustedAction.GROW);

      if (null != mReaderSchema) {
        poolBuilder.withColumnReaderSpecOverrides(ImmutableMap.of(
            mColumn, ColumnReaderSpec.avroReaderSchemaGeneric(mReaderSchema)));
      }

      mTableReaderPool = poolBuilder.build();

      KijiDataRequestBuilder dataReqBuilder = KijiDataRequest.builder()
          .withTimeRange(mMinTs, mMaxTs);
      dataReqBuilder
          .newColumnsDef().withMaxVersions(1).add(mColumn.getFamily(), mColumn.getQualifier());
      mDataReq = dataReqBuilder.build();

      if (mMaxObjectsToCache > 1) {
        mResultCache = LruCache.create(mMaxObjectsToCache);
      } else {
        mResultCache = null;
      }
    }

    /**
     * Get the row for the given EntityId.
     *
     * @param eid Entity for which to get the row.
     * @return the row for the given Entity.
     * @throws IOException in case of an error reading from the table.
     */
    private KijiRowData getRow(
        final EntityId eid
    ) throws IOException {
      try {
        final KijiTableReader reader = mTableReaderPool.borrowObject();
        try {
          return reader.get(eid, mDataReq);
        } finally {
          reader.close();
        }
      } catch (IOException ioe) {
        throw ioe;
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }

    /** {@inheritDoc} */
    @Override
    public boolean isOpen() {
      return null != mKijiTable;
    }

    /** {@inheritDoc} */
    @Override
    public V get(KijiRowKeyComponents rowKey) throws IOException {
      if (!isOpen()) {
        throw new IOException("Closed");
      }

      // Check the cache first.
      if (null != mResultCache && mResultCache.containsKey(rowKey)) {
        return mResultCache.get(rowKey);
      }

      // Now do a full lookup.
      final EntityId eid = rowKey.getEntityIdForTable(mKijiTable);
      final KijiRowData rowData = getRow(eid);

      if (null == rowData) {
        return null;
      }

      if (rowData.containsColumn(mColumn.getFamily(), mColumn.getQualifier())) {
        // If mReaderSchema is null, that's ok; it uses the cell writer schema.
        // TODO: But we must actually use it if it's not null!
        V val = rowData.<V>getMostRecentValue(mColumn.getFamily(), mColumn.getQualifier());
        if (null != mResultCache) {
          mResultCache.put(rowKey, val);
        }

        return val;
      } else {
        if (null != mResultCache) {
          mResultCache.put(rowKey, null);
        }
        return null;
      }
    }

    /** {@inheritDoc} */
    @Override
    public boolean containsKey(KijiRowKeyComponents rowKey) throws IOException {
      if (!isOpen()) {
        throw new IOException("Closed");
      }

      if (null != mResultCache && mResultCache.containsKey(rowKey)) {
        return true; // Cache hit.
      }

      final EntityId eid = rowKey.getEntityIdForTable(mKijiTable);
      final KijiRowData rowData = getRow(eid);

      if (null == rowData) {
        return false;
      }

      return rowData.containsColumn(mColumn.getFamily(), mColumn.getQualifier());
    }

    /** {@inheritDoc} */
    @Override
    public void close() throws IOException {
      try {
        mTableReaderPool.close();
      } catch (IOException ioe) {
        throw ioe;
      } catch (Exception e) {
        throw new RuntimeException(e);
      } finally {
        mKijiTable.release();
      }
    }
  }
}


text:
/* WorldSynthesizer.cpp from libstand http://github.com/qtau-devgroup/libstand by Hal@ShurabaP, BSD license */
#include "synthesis/FrameRenderer.h"
#include "WorldFrameSynthesizer.h"

#include "WorldSynthesizer.h"

using namespace stand;

Signal WorldSynthesizer::synthesize(const QSharedPointer<FrameProvider<WorldFrame> > &data)
{
    return renderer->render(data, synthesizer);
}

QSharedPointer<WorldSynthesizer> DefaultWorldSynthesizerFactory::apply(int samplingFrequency) const
{
    QSharedPointer<FrameSynthesizer<WorldFrame> > synthesizer = QSharedPointer<FrameSynthesizer<WorldFrame> >(new WorldFrameSynthesizer(samplingFrequency));
    QSharedPointer<FrameRenderer<WorldFrame> > renderer = QSharedPointer<FrameRenderer<WorldFrame> >(new SimpleRenderer<WorldFrame>());
    WorldSynthesizer *result = new WorldSynthesizer(synthesizer, renderer, samplingFrequency);
    return QSharedPointer<WorldSynthesizer>(result);
}


text:
/*global CompletenessTest, sinon */
/*jshint evil: true */
( function ( $, mw, QUnit ) {
	'use strict';

	var mwTestIgnore, mwTester,
		addons,
		ELEMENT_NODE = 1,
		TEXT_NODE = 3;

	/**
	 * Add bogus to url to prevent IE crazy caching
	 *
	 * @param value {String} a relative path (eg. 'data/foo.js'
	 * or 'data/test.php?foo=bar').
	 * @return {String} Such as 'data/foo.js?131031765087663960'
	 */
	QUnit.fixurl = function ( value ) {
		return value + (/\?/.test( value ) ? '&' : '?')
			+ String( new Date().getTime() )
			+ String( parseInt( Math.random() * 100000, 10 ) );
	};

	/**
	 * Configuration
	 */

	// When a test() indicates asynchronicity with stop(),
	// allow 30 seconds to pass before killing the test(),
	// and assuming failure.
	QUnit.config.testTimeout = 30 * 1000;

	QUnit.config.requireExpects = true;

	// Add a checkbox to QUnit header to toggle MediaWiki ResourceLoader debug mode.
	QUnit.config.urlConfig.push( {
		id: 'debug',
		label: 'Enable ResourceLoaderDebug',
		tooltip: 'Enable debug mode in ResourceLoader',
		value: 'true'
	} );

	/**
	 * CompletenessTest
	 *
	 * Adds toggle checkbox to header
	 */
	QUnit.config.urlConfig.push( {
		id: 'completenesstest',
		label: 'Run CompletenessTest',
		tooltip: 'Run the completeness test'
	} );

	/**
	 * SinonJS
	 *
	 * Glue code for nicer integration with QUnit setup/teardown
	 * Inspired by http://sinonjs.org/releases/sinon-qunit-1.0.0.js
	 * Fixes:
	 * - Work properly with asynchronous QUnit by using module setup/teardown
	 *   instead of synchronously wrapping QUnit.test.
	 */
	sinon.assert.fail = function ( msg ) {
		QUnit.assert.ok( false, msg );
	};
	sinon.assert.pass = function ( msg ) {
		QUnit.assert.ok( true, msg );
	};
	sinon.config = {
		injectIntoThis: true,
		injectInto: null,
		properties: ['spy', 'stub', 'mock', 'sandbox'],
		// Don't fake timers by default
		useFakeTimers: false,
		useFakeServer: false
	};
	( function () {
		var orgModule = QUnit.module;

		QUnit.module = function ( name, localEnv ) {
			localEnv = localEnv || {};
			orgModule( name, {
				setup: function () {
					var config = sinon.getConfig( sinon.config );
					config.injectInto = this;
					sinon.sandbox.create( config );

					if ( localEnv.setup ) {
						localEnv.setup.call( this );
					}
				},
				teardown: function () {
					this.sandbox.verifyAndRestore();

					if ( localEnv.teardown ) {
						localEnv.teardown.call( this );
					}
				}
			} );
		};
	}() );

	// Extend QUnit.module to provide a fixture element.
	( function () {
		var orgModule = QUnit.module;

		QUnit.module = function ( name, localEnv ) {
			var fixture;
			localEnv = localEnv || {};
			orgModule( name, {
				setup: function () {
					fixture = document.createElement( 'div' );
					fixture.id = 'qunit-fixture';
					document.body.appendChild( fixture );

					if ( localEnv.setup ) {
						localEnv.setup.call( this );
					}
				},
				teardown: function () {
					if ( localEnv.teardown ) {
						localEnv.teardown.call( this );
					}

					fixture.parentNode.removeChild( fixture );
				}
			} );
		};
	}() );

	// Initiate when enabled
	if ( QUnit.urlParams.completenesstest ) {

		// Return true to ignore
		mwTestIgnore = function ( val, tester ) {

			// Don't record methods of the properties of constructors,
			// to avoid getting into a loop (prototype.constructor.prototype..).
			// Since we're therefor skipping any injection for
			// "new mw.Foo()", manually set it to true here.
			if ( val instanceof mw.Map ) {
				tester.methodCallTracker.Map = true;
				return true;
			}
			if ( val instanceof mw.Title ) {
				tester.methodCallTracker.Title = true;
				return true;
			}

			// Don't record methods of the properties of a jQuery object
			if ( val instanceof $ ) {
				return true;
			}

			// Don't iterate over the module registry (the 'script' references would
			// be listed as untested methods otherwise)
			if ( val === mw.loader.moduleRegistry ) {
				return true;
			}

			return false;
		};

		mwTester = new CompletenessTest( mw, mwTestIgnore );
	}

	/**
	 * Test environment recommended for all QUnit test modules
	 *
	 * Whether to log environment changes to the console
	 */
	QUnit.config.urlConfig.push( 'mwlogenv' );

	/**
	 * Reset mw.config and others to a fresh copy of the live config for each test(),
	 * and restore it back to the live one afterwards.
	 * @param localEnv {Object} [optional]
	 * @example (see test suite at the bottom of this file)
	 *
	 */
	QUnit.newMwEnvironment = ( function () {
		var warn, log, liveConfig, liveMessages;

		liveConfig = mw.config.values;
		liveMessages = mw.messages.values;

		function suppressWarnings() {
			warn = mw.log.warn;
			mw.log.warn = $.noop;
		}

		function restoreWarnings() {
			if ( warn !== undefined ) {
				mw.log.warn = warn;
				warn = undefined;
			}
		}

		function freshConfigCopy( custom ) {
			var copy;
			// Tests should mock all factors that directly influence the tested code.
			// For backwards compatibility though we set mw.config to a fresh copy of the live
			// config. This way any modifications made to mw.config during the test will not
			// affect other tests, nor the global scope outside the test runner.
			// This is a shallow copy, since overriding an array or object value via "custom"
			// should replace it. Setting a config property means you override it, not extend it.
			// NOTE: It is important that we suppress warnings because extend() will also access
			// deprecated properties and trigger deprecation warnings from mw.log#deprecate.
			suppressWarnings();
			copy = $.extend( {}, liveConfig, custom );
			restoreWarnings();

			return copy;
		}

		function freshMessagesCopy( custom ) {
			return $.extend( /*deep=*/true, {}, liveMessages, custom );
		}

		log = QUnit.urlParams.mwlogenv ? mw.log : function () {};

		return function ( localEnv ) {
			localEnv = $.extend( {
				// QUnit
				setup: $.noop,
				teardown: $.noop,
				// MediaWiki
				config: {},
				messages: {}
			}, localEnv );

			return {
				setup: function () {
					log( 'MwEnvironment> SETUP    for "' + QUnit.config.current.module
						+ ': ' + QUnit.config.current.testName + '"' );

					// Greetings, mock environment!
					mw.config.values = freshConfigCopy( localEnv.config );
					mw.messages.values = freshMessagesCopy( localEnv.messages );
					this.suppressWarnings = suppressWarnings;
					this.restoreWarnings = restoreWarnings;

					localEnv.setup.call( this );
				},

				teardown: function () {
					var timers;
					log( 'MwEnvironment> TEARDOWN for "' + QUnit.config.current.module
						+ ': ' + QUnit.config.current.testName + '"' );

					localEnv.teardown.call( this );

					// Farewell, mock environment!
					mw.config.values = liveConfig;
					mw.messages.values = liveMessages;

					// As a convenience feature, automatically restore warnings if they're
					// still suppressed by the end of the test.
					restoreWarnings();

					// Check for incomplete animations/requests/etc and throw
					// error if there are any.
					if ( $.timers && $.timers.length !== 0 ) {
						timers = $.timers.length;
						// Tests shoulld use fake timers or wait for animations to complete
						$.each( $.timers, function ( i, timer ) {
							var node = timer.elem;
							mw.log.warn( 'Unfinished animation #' + i + ' in ' + timer.queue + ' queue on ' +
								mw.html.element( node.nodeName.toLowerCase(), $(node).getAttrs() )
							);
						} );
						// Force animations to stop to give the next test a clean start
						$.fx.stop();

						throw new Error( 'Unfinished animations: ' + timers );
					}
					if ( $.active !== undefined && $.active !== 0 ) {
						// Test may need to use fake XHR, wait for requests or
						// call abort().
						throw new Error( 'Unfinished AJAX requests: ' + $.active );
					}
				}
			};
		};
	}() );

	// $.when stops as soon as one fails, which makes sense in most
	// practical scenarios, but not in a unit test where we really do
	// need to wait until all of them are finished.
	QUnit.whenPromisesComplete = function () {
		var altPromises = [];

		$.each( arguments, function ( i, arg ) {
			var alt = $.Deferred();
			altPromises.push( alt );

			// Whether this one fails or not, forwards it to
			// the 'done' (resolve) callback of the alternative promise.
			arg.always( alt.resolve );
		} );

		return $.when.apply( $, altPromises );
	};

	/**
	 * Recursively convert a node to a plain object representing its structure.
	 * Only considers attributes and contents (elements and text nodes).
	 * Attribute values are compared strictly and not normalised.
	 *
	 * @param {Node} node
	 * @return {Object|string} Plain JavaScript value representing the node.
	 */
	function getDomStructure( node ) {
		var $node, children, processedChildren, i, len, el;
		$node = $( node );
		if ( node.nodeType === ELEMENT_NODE ) {
			children = $node.contents();
			processedChildren = [];
			for ( i = 0, len = children.length; i < len; i++ ) {
				el = children[i];
				if ( el.nodeType === ELEMENT_NODE || el.nodeType === TEXT_NODE ) {
					processedChildren.push( getDomStructure( el ) );
				}
			}

			return {
				tagName: node.tagName,
				attributes: $node.getAttrs(),
				contents: processedChildren
			};
		} else {
			// Should be text node
			return $node.text();
		}
	}

	/**
	 * Gets structure of node for this HTML.
	 *
	 * @param {string} html HTML markup for one or more nodes.
	 */
	function getHtmlStructure( html ) {
		var el = $( '
' ).append( html )[0];
		return getDomStructure( el );
	}

	/**
	 * Add-on assertion helpers
	 */
	// Define the add-ons
	addons = {

		// Expect boolean true
		assertTrue: function ( actual, message ) {
			QUnit.push( actual === true, actual, true, message );
		},

		// Expect boolean false
		assertFalse: function ( actual, message ) {
			QUnit.push( actual === false, actual, false, message );
		},

		// Expect numerical value less than X
		lt: function ( actual, expected, message ) {
			QUnit.push( actual < expected, actual, 'less than ' + expected, message );
		},

		// Expect numerical value less than or equal to X
		ltOrEq: function ( actual, expected, message ) {
			QUnit.push( actual <= expected, actual, 'less than or equal to ' + expected, message );
		},

		// Expect numerical value greater than X
		gt: function ( actual, expected, message ) {
			QUnit.push( actual > expected, actual, 'greater than ' + expected, message );
		},

		// Expect numerical value greater than or equal to X
		gtOrEq: function ( actual, expected, message ) {
			QUnit.push( actual >= expected, actual, 'greater than or equal to ' + expected, message );
		},

		/**
		 * Asserts that two HTML strings are structurally equivalent.
		 *
		 * @param {string} actualHtml Actual HTML markup.
		 * @param {string} expectedHtml Expected HTML markup
		 * @param {string} message Assertion message.
		 */
		htmlEqual: function ( actualHtml, expectedHtml, message ) {
			var actual = getHtmlStructure( actualHtml ),
				expected = getHtmlStructure( expectedHtml );

			QUnit.push(
				QUnit.equiv(
					actual,
					expected
				),
				actual,
				expected,
				message
			);
		},

		/**
		 * Asserts that two HTML strings are not structurally equivalent.
		 *
		 * @param {string} actualHtml Actual HTML markup.
		 * @param {string} expectedHtml Expected HTML markup.
		 * @param {string} message Assertion message.
		 */
		notHtmlEqual: function ( actualHtml, expectedHtml, message ) {
			var actual = getHtmlStructure( actualHtml ),
				expected = getHtmlStructure( expectedHtml );

			QUnit.push(
				!QUnit.equiv(
					actual,
					expected
				),
				actual,
				expected,
				message
			);
		}
	};

	$.extend( QUnit.assert, addons );

	/**
	 * Small test suite to confirm proper functionality of the utilities and
	 * initializations defined above in this file.
	 */
	QUnit.module( 'test.mediawiki.qunit.testrunner', QUnit.newMwEnvironment( {
		setup: function () {
			this.mwHtmlLive = mw.html;
			mw.html = {
				escape: function () {
					return 'mocked';
				}
			};
		},
		teardown: function () {
			mw.html = this.mwHtmlLive;
		},
		config: {
			testVar: 'foo'
		},
		messages: {
			testMsg: 'Foo.'
		}
	} ) );

	QUnit.test( 'Setup', 3, function ( assert ) {
		assert.equal( mw.html.escape( 'foo' ), 'mocked', 'setup() callback was ran.' );
		assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object applied' );
		assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object applied' );

		mw.config.set( 'testVar', 'bar' );
		mw.messages.set( 'testMsg', 'Bar.' );
	} );

	QUnit.test( 'Teardown', 2, function ( assert ) {
		assert.equal( mw.config.get( 'testVar' ), 'foo', 'config object restored and re-applied after test()' );
		assert.equal( mw.messages.get( 'testMsg' ), 'Foo.', 'messages object restored and re-applied after test()' );
	} );

	QUnit.test( 'Loader status', 2, function ( assert ) {
		var i, len, state,
			modules = mw.loader.getModuleNames(),
			error = [],
			missing = [];

		for ( i = 0, len = modules.length; i < len; i++ ) {
			state = mw.loader.getState( modules[i] );
			if ( state === 'error' ) {
				error.push( modules[i] );
			} else if ( state === 'missing' ) {
				missing.push( modules[i] );
			}
		}

		assert.deepEqual( error, [], 'Modules in error state' );
		assert.deepEqual( missing, [], 'Modules in missing state' );
	} );

	QUnit.test( 'htmlEqual', 8, function ( assert ) {
		assert.htmlEqual(
			'

Child paragraph with A link
Regular textA span
',
			'

Child paragraph with A link
Regular textA span
',
			'Attribute order, spacing and quotation marks (equal)'
		);

		assert.notHtmlEqual(
			'

Child paragraph with A link
Regular textA span
',
			'

Child paragraph with A link
Regular textA span
',
			'Attribute order, spacing and quotation marks (not equal)'
		);

		assert.htmlEqual(
			'First<input id="firstname" />Last<input id="lastname" />',
			'First<input id="firstname" />Last<input id="lastname" />',
			'Multiple root nodes (equal)'
		);

		assert.notHtmlEqual(
			'First<input id="firstname" />Last<input id="lastname" />',
			'First<input id="firstname" />Last<input id="lastname" />',
			'Multiple root nodes (not equal, last label node is different)'
		);

		assert.htmlEqual(
			'fo"o
b>ar',
			'fo"o
b>ar',
			'Extra escaping is equal'
		);
		assert.notHtmlEqual(
			'foo<br/>bar',
			'foo
bar',
			'Text escaping (not equal)'
		);

		assert.htmlEqual(
			'fooexamplebar',
			'fooexamplebar',
			'Outer text nodes are compared (equal)'
		);

		assert.notHtmlEqual(
			'fooexamplebar',
			'fooexamplequux',
			'Outer text nodes are compared (last text node different)'
		);

	} );

	QUnit.module( 'test.mediawiki.qunit.testrunner-after', QUnit.newMwEnvironment() );

	QUnit.test( 'Teardown', 3, function ( assert ) {
		assert.equal( mw.html.escape( '<' ), '<', 'teardown() callback was ran.' );
		assert.equal( mw.config.get( 'testVar' ), null, 'config object restored to live in next module()' );
		assert.equal( mw.messages.get( 'testMsg' ), null, 'messages object restored to live in next module()' );
	} );

}( jQuery, mediaWiki, QUnit ) );