text:
using System.Collections.Generic;

namespace SharePointPnP.PowerShell.CmdletHelpGenerator
{
    public class CmdletInfo
    {
        public string Verb { get; set; }
        public string Noun { get; set; }

        public string Description { get; set; }

        public string DetailedDescription { get; set; }

        public List<CmdletParameterInfo> Parameters { get; set; }

        public string Version { get; set; }

        public string Copyright { get; set; }

        public List<CmdletSyntax> Syntaxes { get; set; }

        public string FullCommand
        {
            get
            {
                return string.Format("{0}-{1}", Verb, Noun);
            }
        }

        public string Category { get; set; }

        public CmdletInfo(string verb, string noun)
        {
            Verb = verb;
            Noun = noun;
            Parameters = new List<CmdletParameterInfo>();
            Syntaxes = new List<CmdletSyntax>();
        }
    }
}


text:
gem 'minitest', '>= 5.0.0'
require 'minitest/autorun'
require_relative 'run_length_encoding'

# Test data version:
# deb225e Implement canonical dataset for scrabble-score problem (#255)

class RunLengthEncodingTest < Minitest::Test
  def test_encode_simple
    input = 'AABBBCCCC'
    output = '2A3B4C'
    assert_equal output, RunLengthEncoding.encode(input)
  end

  def test_decode_simple
    input = '2A3B4C'
    output = 'AABBBCCCC'
    assert_equal output, RunLengthEncoding.decode(input)
  end

  def test_encode_with_single_values
    input = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB'
    output = '12WB12W3B24WB'
    assert_equal output, RunLengthEncoding.encode(input)
  end

  def test_decode_with_single_values
    input = '12WB12W3B24WB'
    output = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB'
    assert_equal output, RunLengthEncoding.decode(input)
  end

  def test_decode_encode_combination
    input = 'zzz ZZ  zZ'
    output = 'zzz ZZ  zZ'
    assert_equal output,
                 RunLengthEncoding.decode(RunLengthEncoding.encode(input))
  end

  def test_encode_unicode
    input = '⏰⚽⚽⚽⭐⭐⏰'
    output = '⏰3⚽2⭐⏰'
    assert_equal output, RunLengthEncoding.encode(input)
  end

  def test_decode_unicode
    input = '⏰3⚽2⭐⏰'
    output = '⏰⚽⚽⚽⭐⭐⏰'
    assert_equal output, RunLengthEncoding.decode(input)
  end

  # Problems in exercism evolve over time, as we find better ways to ask
  # questions.
  # The version number refers to the version of the problem you solved,
  # not your solution.
  #
  # Define a constant named VERSION inside of the top level BookKeeping
  # module.
  #  In your file, it will look like this:
  #
  # module BookKeeping
  #   VERSION = 1 # Where the version number matches the one in the test.
  # end
  #
  # If you are curious, read more about constants on RubyDoc:
  # http://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html

  def test_bookkeeping
    assert_equal 2, BookKeeping::VERSION
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

return [
    'add_bread'              => 'Add BREAD to this table',
    'bread_crud_actions'     => 'BREAD/CRUD Actions',
    'bread_info'             => 'BREAD info',
    'controller_name_hint'   => 'ex. PageController, if left empty will use the BREAD Controller',
    'create_bread_for_table' => 'Create BREAD for :table table',
    'delete_bread'           => 'Delete BREAD',
    'delete_bread_conf'      => 'Yes, remove the BREAD',
    'delete_bread_quest'     => 'Are you sure you want to delete the BREAD for the :table table?',
    'edit_bread'             => 'Edit BREAD',
    'edit_bread_for_table'   => 'Edit BREAD for :table table',
    'error_creating_bread'   => 'Sorry it appears there may have been a problem creating this BREAD',
    'error_removing_bread'   => 'Sorry it appears there was a problem removing this BREAD',
    'error_updating_bread'   => 'Sorry it appears there may have been a problem updating this BREAD',
    'error_tagging'          => 'Sorry it appears there may have been a problem creating the record. Please make sure your table has defaults for other fields.',
    'success_created_bread'  => 'Successfully created new BREAD',
    'success_remove_bread'   => 'Successfully removed BREAD from :datatype',
    'success_update_bread'   => 'Successfully updated the :datatype BREAD',
    'controller_name'        => 'Controller Name',
    'create_migration'       => 'Create migration for this table?',
    'description'            => 'Description',
    'display_name'           => 'Display Name',
    'display_name_plural'    => 'Display Name (Plural)',
    'display_name_singular'  => 'Display Name (Singular)',
    'edit_rows'              => 'Edit the rows for the :table table below',
    'generate_permissions'   => 'Generate Permissions',
    'icon_class'             => 'Icon to use for this Table',
    'icon_hint'              => 'Icon (optional) Use a',
    'icon_hint2'             => 'Voyager Font Class',
    'model_class'            => 'Model Class Name',
    'model_name'             => 'Model Name',
    'model_name_ph'          => 'ex. \App\User, if left empty will try and use the table name',
    'order'                  => 'Order',
    'order_column'           => 'Order column',
    'order_column_ph'        => 'The column where the order is stored',
    'order_ident_column'     => 'Order display column',
    'order_ident_column_ph'  => 'The column which is displayed in the order page',
    'ordering_not_set'       => 'You have to define ordering first',
    'policy_class'           => 'Policy Class Name',
    'policy_name'            => 'Policy Name',
    'policy_name_ph'         => 'ex. \App\Policies\UserPolicy, if left empty will try and use the default',
    'server_pagination'      => 'Server-side Pagination',
    'url_slug'               => 'URL Slug (must be unique)',
    'url_slug_ph'            => 'URL slug (ex. posts)',
];


text:
export ISTP_PATH="/data/istp"

export SD_HDWPATH="${RSTPATH}/tables/superdarn/hdw/"
export SD_RADAR="${RSTPATH}/tables/superdarn/radar.dat"

export AACGM_DAT_PREFIX=${RSTPATH}"/tables/analysis/aacgm/aacgm_coeffs"
export IGRF_PATH=${RSTPATH}"/tables/analysis/mag/"
export SD_MODEL_TABLE=${RSTPATH}"/tables/superdarn/model"

#####################################################################
#                                                                   #
# SuperDARN ROS Environment                                         #
#                                                                   #
#####################################################################

export SD_RAW_PATH="/data/ros/rawacf"
export SD_FIT_PATH="/data/ros/fitacf"
export SD_IQ_PATH="/data/ros/iqdat"
export SD_ERRLOG_PATH="/data/ros/errlog";


text:
using UnityEngine;
using System.Collections;

public class a_pit_trap : trap_base {

	//Quality or some portion of it appears (first 4 bits?) to define the texture of the tile to create at the base.
	//Owner does the same for the top??
	//ZPos is likely the height of the floor.

	public override void ExecuteTrap (object_base src, int triggerX, int triggerY, int State)
	{
		int tileXToChange=triggerX;
		int tileYToChange=triggerY;
		GameObject tile = GameWorldController.FindTile(tileXToChange,tileYToChange,TileMap.SURFACE_FLOOR);
		if (tile!=null)
		{
			TileInfo tileToChange = CurrentTileMap().Tiles[tileXToChange,tileYToChange];
			if (tileToChange.floorHeight==0)
			{//create a tile at the floor height
				tileToChange.floorHeight=(short)(zpos>>2);
				tileToChange.floorTexture =(short)(owner & 0xf);
			}
			else
			{
				tileToChange.floorHeight=0;
				tileToChange.floorTexture =(short)(quality & 0xf);
			}
			tileToChange.TileNeedsUpdate();
			Destroy (tile);
		}

	}

	//	//Do not destroy
	//public override void PostActivate (object_base src)
	//{
 //       Debug.Log("Overridden PostActivate to test " + this.name);
 //       base.PostActivate(src);
 //   }
}


text:
import { getAllNodes } from './util';
import FlowsenseUpdateTracker from './tracker';

/**
 * Applies auto layout on all the diagram nodes.
 */
export const autoLayout = (tracker: FlowsenseUpdateTracker) => {
  tracker.toAutoLayout(getAllNodes());
};


text:
class LoadedCssInclusion < Netzke::Base
  action :load do |c|
    c.text = "Load CssInclusion"
  end

  component :css_inclusion

  js_configure do |c|
    c.layout = :fit
    c.title = "LoadedCssInclusion component"
    c.on_load = <<-JS
      function(){
        this.netzkeLoadComponent('css_inclusion');
      }
    JS
  end

  def configure(c)
    super
    c.bbar = [:load]
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Captcha</title>

	<form action="process.php" method="post" enctype="application/x-www-form-urlencoded" id="myForm" onsubmit="return verifyForm('myForm');">
<input type="hidden" name="Form_Name" value="Contact" />

 *Indicates required fields

*Name<input type="text" name="Name" dir="ltr" class="formField" />

Company<input type="text" name="Company" class="formField" />

*Email<input type="text" name="Email" class="formField" />

Comments/Questions<textarea name="Comments" class="formField" ></textarea>

*Verification Code:

<input type="text" name="Verification" class="formField1" dir="ltr"/>

 <button type="submit">Submit</button><button type="reset">Reset</button>

</form>


text:
layout: article
title: "Optimiser vos annonces"
description: "L'optimisation de votre site et des annonces y figurant peut améliorer la qualité des annonces diffusées et accroître votre potentiel de revenus."
introduction: "L'optimisation de vos annonces et de votre site est cruciale pour la réussite de vos objectifs. Grâce à l'optimisation, vous pouvez augmenter les revenus générés par vos annonces, améliorer la qualité de votre site, obtenir davantage de trafic ou atteindre un autre de vos objectifs."
article:
  written_on: 2014-08-12
  updated_on: 2014-08-12
  order: 4
id: optimize-ads
collection: ads
authors:
  - megginkearney
  - petelepage
key-takeaways:
  tldr:
  - Consultez régulièrement votre tableau de bord et appliquez toutes les recommandations.
  - Étudiez les rapports de performance pour déterminer quelles annonces apportent le plus de valeur ajoutée, pour vous et vos utilisateurs.
  - Sélectionnez les annonces qui ont les meilleures performances sur votre site.
  - Ne bloquez pas le robot d'exploration Google AdSense dans le code robots.txt.

---

{% wrap content %}

Vous souhaitez obtenir de meilleurs résultats avec les annonces AdSense et faire en sorte de donner à vos visiteurs ce qu'ils veulent tout en atteignant vos propres objectifs ? Vous manquez d'inspiration ?
Consultez les conseils de nos spécialistes Google AdSense ayant travaillé avec des éditeurs de sites Web de toute taille.

Remarque : Cet article concerne Google AdSense, cependant les concepts exposés sont applicables à tous les fournisseurs d'annonces.

{% include modules/toc.liquid %}

{% include modules/takeaway.liquid list=page.key-takeaways.tldr %}

## Consulter les tableaux de bord et les recommandations

Utilisez le tableau de bord de l'onglet [Accueil](https://www.google.com/adsense/app#home) de votre compte pour connaître les performances de vos paramètres d'annonces, de vos pages Web et de votre contenu, par rapport à ceux des autres annonceurs Google AdSense.

Le tableau de bord est organisé en plusieurs catégories (optimisation des revenus, état de santé du site, etc.). Il indique un score allant de un à cinq points bleus. Chaque score indique le classement par rapport aux autres annonceurs dans la catégorie en question. Un score plus faible dans une catégorie signifie qu'il reste une marge potentielle d'amélioration. Accordez cependant une attention particulière aux éléments signalés par un pont d'exclamation rouge ou orange.

Tableau de bord de l'optimisation des revenus

Tableau de bord multi-écrans

Tableau de bord de l'état de santé du site

La colonne Recommandations de l'onglet [Accueil](https://www.google.com/adsense/app#home) contient des recommandations de modifications pour que votre site génère davantage de revenus.
Ces recommandations sont basées sur l'analyse de performance des recommandations récemment mises en œuvre par d'autres annonceurs Google AdSense. Nous ne les envoyons que lorsque leur fiabilité en matière d'amélioration de la performance est élevée.

{% include modules/remember.liquid title="Learn more" text="consultez les pages relatives au tableau de bord et à la colonne de recommandations dans le centre d'aide Google AdSense." %}

## Utiliser les rapports de performance

Utilisez l'onglet [Rapports de performance](https://www.google.com/adsense/app#viewreports) de Google AdSense pour connaître vos revenus et ce qui ce qui les influence, et pour consulter des graphiques illustrant les tendances sur une période donnée.

Pour démarrer, utilisez les rapports suivants :

  <colgroup>
    <col span="1">
    <col span="1">
  </colgroup>

      Rapport
      Description

        Taille des créations

        Indique la taille d'affichage des annonces qui sont diffusées sur votre site. Ce rapport vous permet de déterminer les tendances en matière de taille d'annonces lorsque vous utilisez les annonces adaptatives.

        Blocs d'annonces

        Affiche la performance individuelle des bloc d'annonces que vous avez personnalisés. Permet de déterminer quels blocs sont les plus performants et de décider si ce type de blocs peut être placé ailleurs. Permet également de mieux analyser les facteurs qui les rendent plus performants et d'appliquer ceux-ci à d'autres blocs.

       Sites

        Si vous possédez plusieurs sites, ce rapport vous permet de savoir si un site est plus performant et comment appliquer ce comportement à d'autres sites..

### Se connecter pour obtenir une aide et des suggestions personnalisées

En plus des rapports de performance, vous pouvez occasionnellement recevoir par e-mail de l'aide et des suggestions relatives aux rapports de performance personnalisées. Pour vous connecter, validez votre adresse e-mail dans la section [Paramètres personnels](https://www.google.com/adsense/app#personalSettings), puis cochez la case *Aide personnalisée et suggestions de performance* située dans la section *Préférences relatives aux e-mails*.

Activation des e-mails d'aide et de suggestions de performance personnalisées

{% include modules/remember.liquid title="Learn more" text="Pour en savoir plus, consultez la page relative aux rapports de performance dans le centre d'aide Google AdSense." %}

## Optimiser le potentiel d'enchères

Plus il y a de concurrence (ou 'pression des enchères'), plus l'annonceur sera enclin à payer pour obtenir des vues et des clics sur votre site. Pour optimiser votre potentiel d'enchères :

* Assurez-vous d'autoriser les annonces [textuelles](https://support.google.com/adsense/answer/185665) et [graphiques](https://support.google.com/adsense/answer/185666). Si vous excluez un type d'annonces, cela limite le nombre des annonceurs disponibles pour votre site.
* Pour utiliser les tailles d'annonces populaires chez les annonceurs, consultez le [Guide des tailles d'annonces](https://support.google.com/adsense/answer/6002621).
* Parfois, certaines annonces risquent de ne pas s'intégrer à votre contenu. Veillez à ne pas bloquer trop de catégories, car cela peut diminuer vos revenus potentiels.

Remarque : Ces informations figurent également dans le tableau de bord de l'éditeur, mais elles sont essentielles pour que la performance des annonces soit efficace.

## Autoriser le robot d'exploration de Google AdSense

Vérifiez que le fichier [robots.txt](https://support.google.com/webmasters/answer/6062608) de votre site [ne bloque pas le robot d'exploration de Google AdSense](https://support.google.com/adsense/answer/10532).
Comme nous devons traiter et d'indexer le contenu des pages Web dans Google AdSense, le robot d'exploration Google AdSense visite votre site et en détermine le contenu.  Cela permet au système de fournir des annonces pertinentes.

Pour mettre à jour le fichier `robots.txt`, afin qu'il autorise notre robot d'exploration à accéder à vos pages, vous devez *supprimer* les deux lignes de texte suivantes de votre fichier `robots.txt` :

    User-agent: Mediapartners-Google
    Disallow: /

{% endwrap %}


text:
/*
 */

#ifndef INCshandlerh
#define INCshandlerh

/* ------------- Make C header file C++ compliant ------------------- */
#ifdef __cplusplus
extern "C" {
#endif

/* Table Header Structure */
/* The entry element the first in a list. There are four for 	*/
/* longword alignment.						*/

typedef struct {
	int	SWItrId;
	int	acode;
} SHDLR_MSG;

/* --------- ANSI/C++ compliant function prototypes --------------- */

#if defined(__STDC__) || defined(__cplusplus)

#else
/* --------- NON-ANSI/C++ prototypes ------------  */

#endif

#ifdef __cplusplus
}
#endif

#endif


text:
<?php

/**
 * Spiral Framework, SpiralScout LLC.
 *
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Tests\Console;

use Spiral\Console\StaticLocator;
use Spiral\Tests\Console\Fixtures\TestCommand;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;

class CoreTest extends BaseTest
{
    public function testWelcome(): void
    {
        $core = $this->getCore(new StaticLocator([
            TestCommand::class
        ]));

        $this->assertSame(
            'Hello World - 0',
            $core->run('test')->getOutput()->fetch()
        );

        $this->assertSame(
            'Hello World - 1',
            $core->run('test')->getOutput()->fetch()
        );
    }

    public function testStart(): void
    {
        $core = $this->getCore(new StaticLocator([
            TestCommand::class
        ]));

        $output = new BufferedOutput();

        $core->start(new ArrayInput([]), $output);
        $output = $output->fetch();

        $this->assertStringContainsString('Spiral Framework', $output);
        $this->assertStringContainsString('Test Command', $output);
        $this->assertStringContainsString('test:user', $output);
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>test</groupId>
	<artifactId>test</artifactId>
	<version>0.1.0</version>
	<packaging>jar</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
    <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
      <version>1.1.1</version>
    </dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<encoding>utf-8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<version>2.4.1</version>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.14.1</version>
				<configuration>
					<testFailureIgnore>true</testFailureIgnore>
					<junitArtifactName>junit:junit</junitArtifactName>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.2.1</version>
				<configuration>
					<descriptors>
						<descriptor>assembly-hadoop-job.xml</descriptor>
					</descriptors>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<reporting>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.5</version>
				<configuration>
					<aggregate>true</aggregate>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-report-plugin</artifactId>
				<version>2.12</version>
				<configuration>
					<aggregate>true</aggregate>
				</configuration>
			</plugin>
		</plugins>
	</reporting>

	<repositories>
		<repository>
			<id>conjars.org</id>
			<url>http://conjars.org/repo</url>
		</repository>

    <repository>
      <id>clojars.org</id>
      <url>http://clojars.org/repo</url>
		</repository>
	</repositories>
</project>


text:
"use strict";

const clientServiceFactory = require('./lib/clientService'),
    userServiceFactory = require('./lib/userService'),
    authorizationCodeServiceFactory = require('./lib/authorizationCodeService'),
    userConsentServiceFactory = require('./lib/userConsentService'),
    idTokenService = require('./lib/idTokenService'),
    accessTokenService = require('./lib/accessTokenService'),
    refreshTokenService = require('./lib/refreshTokenService'),
    AuthenticationRequest = require('./lib/model/authentication'),
    AuthorizationCode = require('./lib/model/authorizationCode'),
    RefreshToken = require('./lib/model/refreshToken'),
    AccessToken = require('./lib/model/accessToken'),
    Client = require('./lib/model/client'),
    User = require('./lib/model/user'),
    dbFactory = require('./lib/dbFactory'),
    levelup = require('levelup'),
    memdown = require('memdown'),
    fs = require('fs'),
    path = require('path'),
    moment = require('moment'),
    env = process.env.NODE_ENV || 'development',
    settings = require('../settings.' + env);

console.log("Settings: " + JSON.stringify(settings));

// TODO: file location
let db;
/*
if (process.env.NODE_ENV !== 'production') {
    db = levelup({ db: memdown, valueEncoding: 'json' });
} else {
    const dbDir = process.env.OPENSHIFT_DATA_DIR || '/var/tmp';
    db = levelup(dbDir + '/db', { valueEncoding: 'json' });
}
*/

if (settings.dbDir === 'mem') {
    db = levelup({ db: memdown, valueEncoding: 'json' });
} else {
    db = levelup(settings.dbDir + '/db', { valueEncoding: 'json' });
}

const clientDb = dbFactory(db, 'client');
const userDb = dbFactory(db, 'user');
const authorizationCodeDb = dbFactory(db, 'authorizationCode');
const userConsentDb = dbFactory(db,'userConsent');
const accessTokenDb = dbFactory(db, 'accessToken');
const refreshTokenDb = dbFactory(db, 'refreshToken');

if (process.env.NODE_ENV !== 'production') {
    clientDb.put('111', new Client({
        clientId: '111',
        clientSecret: '$2a$10$DH8B5ZMp/gYV0FPNmpdj6e9LivlBBjUgVIacxstN/Ob/s8oYaL7xu',
        clientName: 'test',
        redirectUri: 'http://localhost/client'
    }));
    clientDb.put('112', new Client({
        clientId: '112',
        clientSecret: '$2a$10$DH8B5ZMp/gYV0FPNmpdj6e9LivlBBjUgVIacxstN/Ob/s8oYaL7xu',
        clientName: 'test2',
        redirectUri: 'http://localhost/client2'
    }));
    clientDb.put('s6BhdRkqt3', new Client({
        clientId: 's6BhdRkqt3',
        clientSecret: '$2a$10$DH8B5ZMp/gYV0FPNmpdj6e9LivlBBjUgVIacxstN/Ob/s8oYaL7xu',
        clientName: 's6BhdRkqt3',
        redirectUri: 'https://noidcjc-tgwagner.rhcloud.com/oauth2callback'
    }));
    clientDb.put('local', new Client({
        clientId: 'local',
        clientSecret: '$2a$10$DH8B5ZMp/gYV0FPNmpdj6e9LivlBBjUgVIacxstN/Ob/s8oYaL7xu',
        clientName: 'local',
        redirectUri: 'http://localhost:9090/oauth2callback'
    }));
    userDb.put('test', new User({
        sub: 'test',
        givenName: 'Thomas',
        familyName: 'Wagner',
        password: '$2a$10$DH8B5ZMp/gYV0FPNmpdj6e9LivlBBjUgVIacxstN/Ob/s8oYaL7xu',
        email: 'test@mail.de'
    }));
    userDb.put('user1', new User({
        sub: 'user1',
        givenName: 'User',
        familyName: '1',
        password: '$2a$10$DH8B5ZMp/gYV0FPNmpdj6e9LivlBBjUgVIacxstN/Ob/s8oYaL7xu',
        email: 'dummy@mail.de'
    }));
    userDb.put('Birgit.Feldmann@fernuni-hagen.de', new User({
        sub: 'Birgit.Feldmann@fernuni-hagen.de',
        givenName: 'Birgit',
        familyName: 'Feldmann',
        password: '$2a$10$DH8B5ZMp/gYV0FPNmpdj6e9LivlBBjUgVIacxstN/Ob/s8oYaL7xu',
        email: 'Birgit.Feldmann@fernuni-hagen.de'
    }));
    // adding some authorization codes:
    authorizationCodeDb.put('11100000001', new AuthorizationCode({
        code: '11100000001',
        sub: 'user1',
        clientId: '111',
        redirectUri: 'http://localhost/client',
        scope: 'test'
    }));
    authorizationCodeDb.put('11200000001', new AuthorizationCode({
        code: '11200000001',
        clientId: '112',
        redirectUri: 'http://localhost/client2',
        scope: 'test'
    }));
    authorizationCodeDb.put('11100000002', new AuthorizationCode({
        code: '11100000002',
        sub: 'user1',
        clientId: '111',
        redirectUri: 'http://localhost/client',
        scope: 'test'
    }));
    authorizationCodeDb.put('11100000003', new AuthorizationCode({
        code: '11100000003',
        sub: 'user1',
        clientId: '111',
        redirectUri: 'http://localhost/client',
        scope: 'openid test'
    }));
    // revoked refresh token
    refreshTokenDb.put('BKfaW6wjLL0yAp9XdQaO', new RefreshToken({
        token: 'BKfaW6wjLL0yAp9XdQaO',
        clientId: '111',
        revoked: true,
        scope: 'test'
    }));
    // refresh token with different client id.
    refreshTokenDb.put('mZzOhOuFj6yIMXYc7M57', new RefreshToken({
        token: 'mZzOhOuFj6yIMXYc7M57',
        clientId: '112',
        scope: 'test'
    }));
    // expired refresh token.
    refreshTokenDb.put('5PbaQQJtns36mFs1AAZs', new RefreshToken({
        token: '5PbaQQJtns36mFs1AAZs',
        clientId: '111',
        expiration: moment().add(-7, 'd').toDate(),
        scope: 'test'
    }));
    refreshTokenDb.put('WX0X7Kew7f7z7UvGmgQC', new RefreshToken({
        token: 'WX0X7Kew7f7z7UvGmgQC',
        clientId: '111',
        expiration: moment().add(5, 'd').toDate(),
        scope: 'test'
    }));
    refreshTokenDb.put('axBtCHW1FaD0rQLROhv4', new RefreshToken({
        token: 'axBtCHW1FaD0rQLROhv4',
        clientId: '111',
        expiration: moment().add(5, 'd').toDate(),
        scope: 'openid test',
        sub: 'user1'
    }));
    accessTokenDb.put('123456789', new AccessToken({
        sub : 'test',
        clientId : '111',
        token: '123456789',
        expiresIn : 60*60*10,
        scope : 'sub name'
    }));
}

// system user for administration
userDb.put('root', new User({
    sub: 'root',
    password: '$2a$10$DH8B5ZMp/gYV0FPNmpdj6e9LivlBBjUgVIacxstN/Ob/s8oYaL7xu',
    email: 'root@localhost'
}));

// jwt keys
const privkey = fs.readFileSync(path.resolve(__dirname, '../privkey.pem'));
const pubkey = fs.readFileSync(path.resolve(__dirname, '../pubkey.pem'));
const iss = settings.iss; //'https://noidcp-tgwagner.rhcloud.com';
const userService = userServiceFactory(userDb);
const config = {
    clientDb: clientDb,
    userDb: userDb,
    authorizationCodeDb: authorizationCodeDb,
    userConsentDb: userConsentDb,
    accessTokenDb: accessTokenDb,
    refreshTokenDb: refreshTokenDb,
    baseUrl: settings.baseUrl, //'https://noidcp-tgwagner.rhcloud.com',
    /** Issuer Identifier */
    iss: iss,
    privkey: privkey,
    pubkey: pubkey,
    clientService: clientServiceFactory(clientDb),
    userService: userService,
    authorizationCodeService: authorizationCodeServiceFactory(authorizationCodeDb),
    userConsentService: userConsentServiceFactory(userConsentDb),
    idTokenService: idTokenService(iss, privkey, pubkey, userService),
    accessTokenService: accessTokenService(accessTokenDb),
    refreshTokenService: refreshTokenService(refreshTokenDb)

};

module.exports = config;


text:
#region

using System;
using System.Reflection;
using System.Web.Mvc;

#endregion

namespace Snooze
{
    public class IEPngFixController : ResourceController
    {
        public ActionResult Get(IEPngFixUrl url)
        {
            SetFarFutureExpires();
            return
                new FileStreamResult(
                    Assembly.GetExecutingAssembly().GetManifestResourceStream("Snooze.Resources.iepngfix.htc"),
                    "text/x-component");
        }

        public ActionResult Get(BlankGifUrl url)
        {
            SetFarFutureExpires();
            return
                new FileStreamResult(
                    Assembly.GetExecutingAssembly().GetManifestResourceStream("Snooze.Resources.blank.gif"), "image/gif");
        }

        void SetFarFutureExpires()
        {
            Response.Cache.SetExpires(DateTime.Now.AddYears(10));
        }
    }
}


text:
from rest_framework.parsers import JSONParser
from drf_hal_json import HAL_JSON_MEDIA_TYPE

from drf_hal_json.renderers import JsonHalRenderer

class JsonHalParser(JSONParser):
    media_type = HAL_JSON_MEDIA_TYPE
    renderer_class = JsonHalRenderer


text:
import Component from './ImageViewer';
import createRenderer from './ImageViewer.relay';
export default createRenderer(Component);


text:
<?php
/**
 * Created by PhpStorm.
 * User: PC Dell
 * Date: 10/05/2017
 * Time: 10:11
 */

namespace AppBundle\Repository;
use AppBundle\Entity\User;
use AppBundle\Entity\Cours;

use Doctrine\ORM\EntityRepository;

class InscriptionCoursRepository extends EntityRepository
{
    public function findByCours(Cours $cours)
    {
        $qb = $this->createQueryBuilder('i');

        return $qb
            ->where($qb->expr()->eq('i.cours', ':cours'))
            ->getQuery()
            ->setParameter('cours', $cours)
            ->getResult();
    }

}


text:
#ifndef VRPTW_RELOCATE_H
#define VRPTW_RELOCATE_H

#include "problems/cvrp/operators/relocate.h"

namespace vroom {
namespace vrptw {

class Relocate : public cvrp::Relocate {
private:
  TWRoute& _tw_s_route;
  TWRoute& _tw_t_route;

public:
  Relocate(const Input& input,
           const utils::SolutionState& sol_state,
           TWRoute& tw_s_route,
           Index s_vehicle,
           Index s_rank,
           TWRoute& tw_t_route,
           Index t_vehicle,
           Index t_rank);

  virtual bool is_valid() override;

  virtual void apply() override;
};

} // namespace vrptw
} // namespace vroom

#endif


text:
package io.twasyl.jstackfx.beans;

import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableSet;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.input.Clipboard;
import javafx.scene.input.DataFormat;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;

import java.util.*;

/**
 * A thread element is a part in the thread dump that gives information about a thread. It typically has a number,
 * various IDs and priorities, a name, a state among others.
 *
 * @author Thierry Wasylczenko
 * @since JStackFX 1.0
 */
public class ThreadElement {
    final static Font bold = Font.font("Helvetica", FontWeight.BOLD, 12);
    final static Font normal = Font.font("Helvetica", FontWeight.NORMAL, 12);
    final static Font code = Font.font("Courier New", FontWeight.NORMAL, 12);

    protected final ObjectProperty<Dump> dump = new SimpleObjectProperty<>();
    protected final StringProperty name = new SimpleStringProperty();
    protected final LongProperty number = new SimpleLongProperty();
    protected final ObjectProperty<Thread.State> state = new SimpleObjectProperty<>();
    protected final StringProperty callingStack = new SimpleStringProperty();
    protected final IntegerProperty priority = new SimpleIntegerProperty();
    protected final IntegerProperty osPriority = new SimpleIntegerProperty();
    protected final StringProperty threadId = new SimpleStringProperty();
    protected final SetProperty<ThreadReference> lockedSynchronizers = new SimpleSetProperty<>(FXCollections.observableSet());
    protected final SetProperty<ThreadReference> holdingLocks = new SimpleSetProperty<>(FXCollections.observableSet());
    protected final SetProperty<ThreadReference> waitingToLock = new SimpleSetProperty<>(FXCollections.observableSet());
    protected final SetProperty<ThreadReference> parkingReasons = new SimpleSetProperty<>(FXCollections.observableSet());
    protected final StringProperty source = new SimpleStringProperty();

    public ObjectProperty<Dump> dumpProperty() {
        return dump;
    }

    public Dump getDump() {
        return dump.get();
    }

    public void setDump(Dump dump) {
        this.dump.set(dump);
    }

    public StringProperty nameProperty() {
        return name;
    }

    public String getName() {
        return name.get();
    }

    public void setName(String name) {
        this.name.set(name);
    }

    public LongProperty numberProperty() {
        return number;
    }

    public long getNumber() {
        return number.get();
    }

    public void setNumber(long number) {
        this.number.set(number);
    }

    public ObjectProperty<Thread.State> stateProperty() {
        return state;
    }

    public Thread.State getState() {
        return state.get();
    }

    public void setState(Thread.State state) {
        this.state.set(state);
    }

    public StringProperty callingStackProperty() {
        return callingStack;
    }

    public String getCallingStack() {
        return callingStack.get();
    }

    public void setCallingStack(String callingStack) {
        this.callingStack.set(callingStack);
    }

    public IntegerProperty priorityProperty() {
        return priority;
    }

    public int getPriority() {
        return priority.get();
    }

    public void setPriority(int priority) {
        this.priority.set(priority);
    }

    public IntegerProperty osPriorityProperty() {
        return osPriority;
    }

    public int getOsPriority() {
        return osPriority.get();
    }

    public void setOsPriority(int osPriority) {
        this.osPriority.set(osPriority);
    }

    public StringProperty threadIdProperty() {
        return threadId;
    }

    public String getThreadId() {
        return threadId.get();
    }

    public void setThreadId(String threadId) {
        this.threadId.set(threadId);
    }

    public SetProperty<ThreadReference> lockedSynchronizersProperty() {
        return lockedSynchronizers;
    }

    public ObservableSet<ThreadReference> getLockedSynchronizers() {
        return lockedSynchronizers.get();
    }

    public void setLockedSynchronizers(ObservableSet<ThreadReference> lockedSynchronizers) {
        this.lockedSynchronizers.set(lockedSynchronizers);
    }

    public SetProperty<ThreadReference> holdingLocksProperty() {
        return holdingLocks;
    }

    public ObservableSet<ThreadReference> getHoldingLocks() {
        return holdingLocks.get();
    }

    public void setHoldingLocks(ObservableSet<ThreadReference> holdingLocks) {
        this.holdingLocks.set(holdingLocks);
    }

    public SetProperty<ThreadReference> waitingToLockProperty() {
        return waitingToLock;
    }

    public ObservableSet<ThreadReference> getWaitingToLock() {
        return waitingToLock.get();
    }

    public void setWaitingToLock(ObservableSet<ThreadReference> waitingToLock) {
        this.waitingToLock.set(waitingToLock);
    }

    public SetProperty<ThreadReference> parkingReasonsProperty() {
        return parkingReasons;
    }

    public ObservableSet<ThreadReference> getParkingReasons() {
        return parkingReasons.get();
    }

    public void setParkingReasons(ObservableSet<ThreadReference> parkingReasons) {
        this.parkingReasons.set(parkingReasons);
    }

    public String getSource() {
        return source.get();
    }

    public StringProperty sourceProperty() {
        return source;
    }

    public void setSource(String source) {
        this.source.set(source);
    }

    /**
     * Get threads in the given {@link Dump dump} that are blocking this thread.
     *
     * @return A never {@code null} collection of threads blocking this instance.
     */
    public Set<ThreadElement> getBlockingThreads() {
        final Set<ThreadElement> blockingThreads = new HashSet<>();

        if (!getDump().getElements().isEmpty()) {
            for (final ThreadElement thread : getDump().getElements()) {
                if (!Objects.equals(thread, this)) {
                    final long numberOfLocks = thread.getHoldingLocks()
                            .stream()
                            .filter(this.getWaitingToLock()::contains)
                            .count();

                    if (numberOfLocks > 0) {
                        blockingThreads.add(thread);
                    }
                }
            }
        }

        return blockingThreads;
    }

    /**
     * Get threads in the given {@link Dump dump} that are blocked by this thread.
     *
     * @return A never {@code null} collection of threads blocked by this instance.
     */
    public Set<ThreadElement> getBlockedThreads() {
        final Set<ThreadElement> blockedThreads = new HashSet<>();

        if (!getDump().getElements().isEmpty()) {
            for (final ThreadElement thread : getDump().getElements()) {
                if (!Objects.equals(thread, this)) {
                    final long numberOfLocks = thread.getWaitingToLock()
                            .stream()
                            .filter(this.getHoldingLocks()::contains)
                            .count();

                    if (numberOfLocks > 0) {
                        blockedThreads.add(thread);
                    }
                }
            }
        }

        return blockedThreads;
    }

    public List<Text> asText() {
        final List<Text> texts = new ArrayList<>();

        appendThreadNumberText(texts);
        appendThreadName(texts);
        appendThreadId(texts);

        Text text;

        text = new Text("Priority:");
        text.setFont(bold);
        texts.add(text);

        text = new Text(" " + this.getPriority() + " ");
        text.setFont(normal);
        texts.add(text);

        text = new Text("OS priority:");
        text.setFont(bold);
        texts.add(text);

        text = new Text(" " + this.getOsPriority() + "\n\n");
        text.setFont(normal);
        texts.add(text);

        this.appendThreadReferences(texts, "Parking to wait for:", this.parkingReasons);
        this.appendThreadReferences(texts, "Locked synchronizers:", this.lockedSynchronizers);
        this.appendThreadReferences(texts, "Wait to acquire locks:", this.waitingToLock);
        this.appendThreadReferences(texts, "Holding locks on:", this.holdingLocks);

        if (this.callingStack.isNotNull().and(this.callingStack.isNotEmpty()).get()) {
            text = new Text("Calling stack:\n\n");
            text.setFont(bold);
            texts.add(text);

            text = new Text(this.getCallingStack());
            text.setFont(code);
            defineContextMenu(text);
            texts.add(text);
        }
        return texts;
    }

    protected void appendThreadNumberText(List<Text> texts) {
        Text text = new Text("#");
        text.setFont(bold);
        texts.add(text);

        text = new Text("" + this.getNumber());
        text.setFont(bold);
        defineContextMenu(text);
        texts.add(text);
    }

    protected void appendThreadName(List<Text> texts) {
        Text text = new Text(" ");
        text.setFont(normal);
        texts.add(text);

        text = new Text(this.getName());
        text.setFont(normal);
        defineContextMenu(text);
        texts.add(text);

        text = new Text(" ");
        text.setFont(normal);
        texts.add(text);
    }

    protected void appendThreadId(List<Text> texts) {
        Text text = new Text("(");
        text.setFont(normal);
        texts.add(text);

        text = new Text(this.getThreadId());
        text.setFont(normal);
        defineContextMenu(text);
        texts.add(text);

        text = new Text(")\n\n");
        text.setFont(normal);
        texts.add(text);
    }

    protected void appendThreadReferences(final List<Text> texts, final String label, final Collection<ThreadReference> references) {
        if (!references.isEmpty()) {
            Text text = new Text(label + "\n\n");
            text.setFont(bold);
            texts.add(text);

            for (final ThreadReference reference : references) {
                text = new Text(reference.getThreadId());
                text.setFont(normal);
                defineContextMenu(text);
                texts.add(text);

                text = new Text(" (");
                text.setFont(normal);
                texts.add(text);

                text = new Text(reference.getClassName());
                text.setFont(code);
                defineContextMenu(text);
                texts.add(text);

                text = new Text(")\n");
                text.setFont(normal);
                texts.add(text);
            }

            text = new Text("\n");
            text.setFont(normal);
            texts.add(text);
        }
    }

    protected void defineContextMenu(final Text text) {
        final MenuItem copy = new MenuItem("Copy");
        copy.setOnAction(event -> {
            Clipboard.getSystemClipboard().setContent(Collections.singletonMap(DataFormat.PLAIN_TEXT, text.getText()));
        });
        final ContextMenu menu = new ContextMenu(copy);

        text.setOnContextMenuRequested(event -> {
            menu.show(text, event.getScreenX(), event.getScreenY());
        });
    }
}


text:
package decorate

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
	"time"

	coreapi "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/equality"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/diff"
	utilpointer "k8s.io/utils/pointer"
	"sigs.k8s.io/yaml"

	prowapi "k8s.io/test-infra/prow/apis/prowjobs/v1"
	"k8s.io/test-infra/prow/clonerefs"
	"k8s.io/test-infra/prow/entrypoint"
	"k8s.io/test-infra/prow/initupload"
	"k8s.io/test-infra/prow/sidecar"
)

func cookieVolumeOnly(secret string) coreapi.Volume {
	v, _, _ := cookiefileVolume(secret)
	return v
}

func cookieMountOnly(secret string) coreapi.VolumeMount {
	_, vm, _ := cookiefileVolume(secret)
	return vm
}
func cookiePathOnly(secret string) string {
	_, _, vp := cookiefileVolume(secret)
	return vp
}

func TestCloneRefs(t *testing.T) {
	truth := true
	logMount := coreapi.VolumeMount{
		Name:      "log",
		MountPath: "/log-mount",
	}
	codeMount := coreapi.VolumeMount{
		Name:      "code",
		MountPath: "/code-mount",
	}
	tmpMount := coreapi.VolumeMount{
		Name:      "clonerefs-tmp",
		MountPath: "/tmp",
	}
	tmpVolume := coreapi.Volume{
		Name: "clonerefs-tmp",
		VolumeSource: coreapi.VolumeSource{
			EmptyDir: &coreapi.EmptyDirVolumeSource{},
		},
	}
	envOrDie := func(opt clonerefs.Options) []coreapi.EnvVar {
		e, err := cloneEnv(opt)
		if err != nil {
			t.Fatal(err)
		}
		return e
	}
	sshVolumeOnly := func(secret string) coreapi.Volume {
		v, _ := sshVolume(secret)
		return v
	}

	sshMountOnly := func(secret string) coreapi.VolumeMount {
		_, vm := sshVolume(secret)
		return vm
	}

	cases := []struct {
		name              string
		pj                prowapi.ProwJob
		codeMountOverride *coreapi.VolumeMount
		logMountOverride  *coreapi.VolumeMount
		expected          *coreapi.Container
		volumes           []coreapi.Volume
		err               bool
	}{
		{
			name: "empty returns nil",
		},
		{
			name: "nil refs and extrarefs returns nil",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					DecorationConfig: &prowapi.DecorationConfig{},
				},
			},
		},
		{
			name: "nil DecorationConfig returns nil",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					Refs: &prowapi.Refs{},
				},
			},
		},
		{
			name: "SkipCloning returns nil",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					Refs: &prowapi.Refs{},
					DecorationConfig: &prowapi.DecorationConfig{
						SkipCloning: &truth,
					},
				},
			},
		},
		{
			name: "reject empty code mount name",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					DecorationConfig: &prowapi.DecorationConfig{},
					Refs:             &prowapi.Refs{},
				},
			},
			codeMountOverride: &coreapi.VolumeMount{
				MountPath: "/whatever",
			},
			err: true,
		},
		{
			name: "reject empty code mountpath",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					DecorationConfig: &prowapi.DecorationConfig{},
					Refs:             &prowapi.Refs{},
				},
			},
			codeMountOverride: &coreapi.VolumeMount{
				Name: "wee",
			},
			err: true,
		},
		{
			name: "reject empty log mount name",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					DecorationConfig: &prowapi.DecorationConfig{},
					Refs:             &prowapi.Refs{},
				},
			},
			logMountOverride: &coreapi.VolumeMount{
				MountPath: "/whatever",
			},
			err: true,
		},
		{
			name: "reject empty log mountpath",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					DecorationConfig: &prowapi.DecorationConfig{},
					Refs:             &prowapi.Refs{},
				},
			},
			logMountOverride: &coreapi.VolumeMount{
				Name: "wee",
			},
			err: true,
		},
		{
			name: "create clonerefs container when refs are set",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					Refs: &prowapi.Refs{},
					DecorationConfig: &prowapi.DecorationConfig{
						UtilityImages: &prowapi.UtilityImages{},
					},
				},
			},
			expected: &coreapi.Container{
				Name:    cloneRefsName,
				Command: []string{cloneRefsCommand},
				Env: envOrDie(clonerefs.Options{
					GitRefs:      []prowapi.Refs{{}},
					GitUserEmail: clonerefs.DefaultGitUserEmail,
					GitUserName:  clonerefs.DefaultGitUserName,
					SrcRoot:      codeMount.MountPath,
					Log:          CloneLogPath(logMount),
				}),
				VolumeMounts: []coreapi.VolumeMount{logMount, codeMount, tmpMount},
			},
			volumes: []coreapi.Volume{tmpVolume},
		},
		{
			name: "create clonerefs containers when extrarefs are set",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					ExtraRefs: []prowapi.Refs{{}},
					DecorationConfig: &prowapi.DecorationConfig{
						UtilityImages: &prowapi.UtilityImages{},
					},
				},
			},
			expected: &coreapi.Container{
				Name:    cloneRefsName,
				Command: []string{cloneRefsCommand},
				Env: envOrDie(clonerefs.Options{
					GitRefs:      []prowapi.Refs{{}},
					GitUserEmail: clonerefs.DefaultGitUserEmail,
					GitUserName:  clonerefs.DefaultGitUserName,
					SrcRoot:      codeMount.MountPath,
					Log:          CloneLogPath(logMount),
				}),
				VolumeMounts: []coreapi.VolumeMount{logMount, codeMount, tmpMount},
			},
			volumes: []coreapi.Volume{tmpVolume},
		},
		{
			name: "append extrarefs after refs",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					Refs:      &prowapi.Refs{Org: "first"},
					ExtraRefs: []prowapi.Refs{{Org: "second"}, {Org: "third"}},
					DecorationConfig: &prowapi.DecorationConfig{
						UtilityImages: &prowapi.UtilityImages{},
					},
				},
			},
			expected: &coreapi.Container{
				Name:    cloneRefsName,
				Command: []string{cloneRefsCommand},
				Env: envOrDie(clonerefs.Options{
					GitRefs:      []prowapi.Refs{{Org: "first"}, {Org: "second"}, {Org: "third"}},
					GitUserEmail: clonerefs.DefaultGitUserEmail,
					GitUserName:  clonerefs.DefaultGitUserName,
					SrcRoot:      codeMount.MountPath,
					Log:          CloneLogPath(logMount),
				}),
				VolumeMounts: []coreapi.VolumeMount{logMount, codeMount, tmpMount},
			},
			volumes: []coreapi.Volume{tmpVolume},
		},
		{
			name: "append ssh secrets when set",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					Refs: &prowapi.Refs{},
					DecorationConfig: &prowapi.DecorationConfig{
						UtilityImages: &prowapi.UtilityImages{},
						SSHKeySecrets: []string{"super", "secret"},
					},
				},
			},
			expected: &coreapi.Container{
				Name:    cloneRefsName,
				Command: []string{cloneRefsCommand},
				Env: envOrDie(clonerefs.Options{
					GitRefs:      []prowapi.Refs{{}},
					GitUserEmail: clonerefs.DefaultGitUserEmail,
					GitUserName:  clonerefs.DefaultGitUserName,
					KeyFiles:     []string{sshMountOnly("super").MountPath, sshMountOnly("secret").MountPath},
					SrcRoot:      codeMount.MountPath,
					Log:          CloneLogPath(logMount),
				}),
				VolumeMounts: []coreapi.VolumeMount{
					logMount,
					codeMount,
					sshMountOnly("super"),
					sshMountOnly("secret"),
					tmpMount,
				},
			},
			volumes: []coreapi.Volume{sshVolumeOnly("super"), sshVolumeOnly("secret"), tmpVolume},
		},
		{
			name: "include ssh host fingerprints when set",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					ExtraRefs: []prowapi.Refs{{}},
					DecorationConfig: &prowapi.DecorationConfig{
						UtilityImages:       &prowapi.UtilityImages{},
						SSHHostFingerprints: []string{"thumb", "pinky"},
					},
				},
			},
			expected: &coreapi.Container{
				Name:    cloneRefsName,
				Command: []string{cloneRefsCommand},
				Env: envOrDie(clonerefs.Options{
					GitRefs:          []prowapi.Refs{{}},
					GitUserEmail:     clonerefs.DefaultGitUserEmail,
					GitUserName:      clonerefs.DefaultGitUserName,
					SrcRoot:          codeMount.MountPath,
					HostFingerprints: []string{"thumb", "pinky"},
					Log:              CloneLogPath(logMount),
				}),
				VolumeMounts: []coreapi.VolumeMount{logMount, codeMount, tmpMount},
			},
			volumes: []coreapi.Volume{tmpVolume},
		},
		{
			name: "include cookiefile secrets when set",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					ExtraRefs: []prowapi.Refs{{}},
					DecorationConfig: &prowapi.DecorationConfig{
						UtilityImages:    &prowapi.UtilityImages{},
						CookiefileSecret: "oatmeal",
					},
				},
			},
			expected: &coreapi.Container{
				Name:    cloneRefsName,
				Command: []string{cloneRefsCommand},
				Args:    []string{"--cookiefile=" + cookiePathOnly("oatmeal")},
				Env: envOrDie(clonerefs.Options{
					CookiePath:   cookiePathOnly("oatmeal"),
					GitRefs:      []prowapi.Refs{{}},
					GitUserEmail: clonerefs.DefaultGitUserEmail,
					GitUserName:  clonerefs.DefaultGitUserName,
					SrcRoot:      codeMount.MountPath,
					Log:          CloneLogPath(logMount),
				}),
				VolumeMounts: []coreapi.VolumeMount{logMount, codeMount, tmpMount, cookieMountOnly("oatmeal")},
			},
			volumes: []coreapi.Volume{tmpVolume, cookieVolumeOnly("oatmeal")},
		},
		{
			name: "include oauth token secret when set",
			pj: prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					ExtraRefs: []prowapi.Refs{{}},
					DecorationConfig: &prowapi.DecorationConfig{
						UtilityImages: &prowapi.UtilityImages{},
						OauthTokenSecret: &prowapi.OauthTokenSecret{
							Name: "oauth-secret",
							Key:  "oauth-file",
						},
					},
				},
			},
			expected: &coreapi.Container{
				Name:    cloneRefsName,
				Command: []string{cloneRefsCommand},
				Env: envOrDie(clonerefs.Options{
					GitRefs:        []prowapi.Refs{{}},
					GitUserEmail:   clonerefs.DefaultGitUserEmail,
					GitUserName:    clonerefs.DefaultGitUserName,
					SrcRoot:        codeMount.MountPath,
					Log:            CloneLogPath(logMount),
					OauthTokenFile: "/secrets/oauth/oauth-token",
				}),
				VolumeMounts: []coreapi.VolumeMount{logMount, codeMount,
					{Name: "oauth-secret", ReadOnly: true, MountPath: "/secrets/oauth"}, tmpMount,
				},
			},
			volumes: []coreapi.Volume{
				{
					Name: "oauth-secret",
					VolumeSource: coreapi.VolumeSource{
						Secret: &coreapi.SecretVolumeSource{
							SecretName: "oauth-secret",
							Items: []coreapi.KeyToPath{{
								Key:  "oauth-file",
								Path: "./oauth-token"}},
						},
					},
				},
				tmpVolume,
			},
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			lm := logMount
			if tc.logMountOverride != nil {
				lm = *tc.logMountOverride
			}
			cm := codeMount
			if tc.codeMountOverride != nil {
				cm = *tc.codeMountOverride
			}
			actual, refs, volumes, err := CloneRefs(tc.pj, cm, lm)
			switch {
			case err != nil:
				if !tc.err {
					t.Errorf("unexpected error: %v", err)
				}
			case tc.err:
				t.Error("failed to receive expected exception")
			case !equality.Semantic.DeepEqual(tc.expected, actual):
				t.Errorf("unexpected container:\n%s", diff.ObjectReflectDiff(tc.expected, actual))
			case !equality.Semantic.DeepEqual(tc.volumes, volumes):
				t.Errorf("unexpected volume:\n%s", diff.ObjectReflectDiff(tc.volumes, volumes))
			case actual != nil:
				var er []prowapi.Refs
				if tc.pj.Spec.Refs != nil {
					er = append(er, *tc.pj.Spec.Refs)
				}
				for _, r := range tc.pj.Spec.ExtraRefs {
					er = append(er, r)
				}
				if !equality.Semantic.DeepEqual(refs, er) {
					t.Errorf("unexpected refs:\n%s", diff.ObjectReflectDiff(er, refs))
				}
			}
		})
	}
}

func TestProwJobToPod(t *testing.T) {
	truth := true
	tests := []struct {
		podName  string
		buildID  string
		labels   map[string]string
		pjSpec   prowapi.ProwJobSpec
		pjStatus prowapi.ProwJobStatus
	}{
		{
			podName: "pod",
			buildID: "blabla",
			labels:  map[string]string{"needstobe": "inherited"},
			pjSpec: prowapi.ProwJobSpec{
				Type:  prowapi.PresubmitJob,
				Job:   "job-name",
				Agent: prowapi.KubernetesAgent,
				Refs: &prowapi.Refs{
					Org:     "org-name",
					Repo:    "repo-name",
					BaseRef: "base-ref",
					BaseSHA: "base-sha",
					Pulls: []prowapi.Pull{{
						Number: 1,
						Author: "author-name",
						SHA:    "pull-sha",
					}},
				},
				PodSpec: &coreapi.PodSpec{
					Containers: []coreapi.Container{
						{
							Image: "tester",
							Env: []coreapi.EnvVar{
								{Name: "MY_ENV", Value: "rocks"},
							},
						},
					},
				},
			},
			pjStatus: prowapi.ProwJobStatus{
				BuildID: "blabla",
			},
		},
		{
			podName: "pod",
			buildID: "blabla",
			labels:  map[string]string{"needstobe": "inherited"},
			pjSpec: prowapi.ProwJobSpec{
				Type: prowapi.PresubmitJob,
				Job:  "job-name",
				DecorationConfig: &prowapi.DecorationConfig{
					Timeout:     &prowapi.Duration{Duration: 120 * time.Minute},
					GracePeriod: &prowapi.Duration{Duration: 10 * time.Second},
					UtilityImages: &prowapi.UtilityImages{
						CloneRefs:  "clonerefs:tag",
						InitUpload: "initupload:tag",
						Entrypoint: "entrypoint:tag",
						Sidecar:    "sidecar:tag",
					},
					GCSConfiguration: &prowapi.GCSConfiguration{
						Bucket:       "my-bucket",
						PathStrategy: "legacy",
						DefaultOrg:   "kubernetes",
						DefaultRepo:  "kubernetes",
						MediaTypes:   map[string]string{"log": "text/plain"},
					},
					GCSCredentialsSecret: "secret-name",
					CookiefileSecret:     "yummy/.gitcookies",
				},
				Agent: prowapi.KubernetesAgent,
				Refs: &prowapi.Refs{
					Org:     "org-name",
					Repo:    "repo-name",
					BaseRef: "base-ref",
					BaseSHA: "base-sha",
					Pulls: []prowapi.Pull{{
						Number: 1,
						Author: "author-name",
						SHA:    "pull-sha",
					}},
					PathAlias: "somewhere/else",
				},
				ExtraRefs: []prowapi.Refs{},
				PodSpec: &coreapi.PodSpec{
					Containers: []coreapi.Container{
						{
							Image:   "tester",
							Command: []string{"/bin/thing"},
							Args:    []string{"some", "args"},
							Env: []coreapi.EnvVar{
								{Name: "MY_ENV", Value: "rocks"},
							},
						},
					},
				},
			},
		},
		{
			podName: "pod",
			buildID: "blabla",
			labels:  map[string]string{"needstobe": "inherited"},
			pjSpec: prowapi.ProwJobSpec{
				Type: prowapi.PresubmitJob,
				Job:  "job-name",
				DecorationConfig: &prowapi.DecorationConfig{
					Timeout:     &prowapi.Duration{Duration: 120 * time.Minute},
					GracePeriod: &prowapi.Duration{Duration: 10 * time.Second},
					UtilityImages: &prowapi.UtilityImages{
						CloneRefs:  "clonerefs:tag",
						InitUpload: "initupload:tag",
						Entrypoint: "entrypoint:tag",
						Sidecar:    "sidecar:tag",
					},
					GCSConfiguration: &prowapi.GCSConfiguration{
						Bucket:       "my-bucket",
						PathStrategy: "legacy",
						DefaultOrg:   "kubernetes",
						DefaultRepo:  "kubernetes",
					},
					GCSCredentialsSecret: "secret-name",
					CookiefileSecret:     "yummy",
				},
				Agent: prowapi.KubernetesAgent,
				Refs: &prowapi.Refs{
					Org:     "org-name",
					Repo:    "repo-name",
					BaseRef: "base-ref",
					BaseSHA: "base-sha",
					Pulls: []prowapi.Pull{{
						Number: 1,
						Author: "author-name",
						SHA:    "pull-sha",
					}},
					PathAlias: "somewhere/else",
				},
				ExtraRefs: []prowapi.Refs{},
				PodSpec: &coreapi.PodSpec{
					Containers: []coreapi.Container{
						{
							Image:   "tester",
							Command: []string{"/bin/thing"},
							Args:    []string{"some", "args"},
							Env: []coreapi.EnvVar{
								{Name: "MY_ENV", Value: "rocks"},
							},
						},
					},
				},
			},
		},
		{
			podName: "pod",
			buildID: "blabla",
			labels:  map[string]string{"needstobe": "inherited"},
			pjSpec: prowapi.ProwJobSpec{
				Type: prowapi.PresubmitJob,
				Job:  "job-name",
				DecorationConfig: &prowapi.DecorationConfig{
					Timeout:     &prowapi.Duration{Duration: 120 * time.Minute},
					GracePeriod: &prowapi.Duration{Duration: 10 * time.Second},
					UtilityImages: &prowapi.UtilityImages{
						CloneRefs:  "clonerefs:tag",
						InitUpload: "initupload:tag",
						Entrypoint: "entrypoint:tag",
						Sidecar:    "sidecar:tag",
					},
					GCSConfiguration: &prowapi.GCSConfiguration{
						Bucket:       "my-bucket",
						PathStrategy: "legacy",
						DefaultOrg:   "kubernetes",
						DefaultRepo:  "kubernetes",
					},
					GCSCredentialsSecret: "secret-name",
					SSHKeySecrets:        []string{"ssh-1", "ssh-2"},
					SSHHostFingerprints:  []string{"hello", "world"},
				},
				Agent: prowapi.KubernetesAgent,
				Refs: &prowapi.Refs{
					Org:     "org-name",
					Repo:    "repo-name",
					BaseRef: "base-ref",
					BaseSHA: "base-sha",
					Pulls: []prowapi.Pull{{
						Number: 1,
						Author: "author-name",
						SHA:    "pull-sha",
					}},
					PathAlias: "somewhere/else",
				},
				ExtraRefs: []prowapi.Refs{},
				PodSpec: &coreapi.PodSpec{
					Containers: []coreapi.Container{
						{
							Image:   "tester",
							Command: []string{"/bin/thing"},
							Args:    []string{"some", "args"},
							Env: []coreapi.EnvVar{
								{Name: "MY_ENV", Value: "rocks"},
							},
							TerminationMessagePolicy: coreapi.TerminationMessageReadFile,
						},
					},
				},
			},
		},
		{
			podName: "pod",
			buildID: "blabla",
			labels:  map[string]string{"needstobe": "inherited"},
			pjSpec: prowapi.ProwJobSpec{
				Type: prowapi.PresubmitJob,
				Job:  "job-name",
				DecorationConfig: &prowapi.DecorationConfig{
					Timeout:     &prowapi.Duration{Duration: 120 * time.Minute},
					GracePeriod: &prowapi.Duration{Duration: 10 * time.Second},
					UtilityImages: &prowapi.UtilityImages{
						CloneRefs:  "clonerefs:tag",
						InitUpload: "initupload:tag",
						Entrypoint: "entrypoint:tag",
						Sidecar:    "sidecar:tag",
					},
					GCSConfiguration: &prowapi.GCSConfiguration{
						Bucket:       "my-bucket",
						PathStrategy: "legacy",
						DefaultOrg:   "kubernetes",
						DefaultRepo:  "kubernetes",
					},
					GCSCredentialsSecret: "secret-name",
					SSHKeySecrets:        []string{"ssh-1", "ssh-2"},
				},
				Agent: prowapi.KubernetesAgent,
				Refs: &prowapi.Refs{
					Org:     "org-name",
					Repo:    "repo-name",
					BaseRef: "base-ref",
					BaseSHA: "base-sha",
					Pulls: []prowapi.Pull{{
						Number: 1,
						Author: "author-name",
						SHA:    "pull-sha",
					}},
					PathAlias: "somewhere/else",
				},
				ExtraRefs: []prowapi.Refs{},
				PodSpec: &coreapi.PodSpec{
					Containers: []coreapi.Container{
						{
							Image:   "tester",
							Command: []string{"/bin/thing"},
							Args:    []string{"some", "args"},
							Env: []coreapi.EnvVar{
								{Name: "MY_ENV", Value: "rocks"},
							},
						},
					},
				},
			},
		},
		{
			podName: "pod",
			buildID: "blabla",
			labels:  map[string]string{"needstobe": "inherited"},
			pjSpec: prowapi.ProwJobSpec{
				Type: prowapi.PeriodicJob,
				Job:  "job-name",
				DecorationConfig: &prowapi.DecorationConfig{
					Timeout:     &prowapi.Duration{Duration: 120 * time.Minute},
					GracePeriod: &prowapi.Duration{Duration: 10 * time.Second},
					UtilityImages: &prowapi.UtilityImages{
						CloneRefs:  "clonerefs:tag",
						InitUpload: "initupload:tag",
						Entrypoint: "entrypoint:tag",
						Sidecar:    "sidecar:tag",
					},
					GCSConfiguration: &prowapi.GCSConfiguration{
						Bucket:       "my-bucket",
						PathStrategy: "legacy",
						DefaultOrg:   "kubernetes",
						DefaultRepo:  "kubernetes",
					},
					GCSCredentialsSecret: "secret-name",
					SSHKeySecrets:        []string{"ssh-1", "ssh-2"},
				},
				Agent: prowapi.KubernetesAgent,
				PodSpec: &coreapi.PodSpec{
					Containers: []coreapi.Container{
						{
							Image:   "tester",
							Command: []string{"/bin/thing"},
							Args:    []string{"some", "args"},
							Env: []coreapi.EnvVar{
								{Name: "MY_ENV", Value: "rocks"},
							},
						},
					},
				},
			},
		},
		{
			podName: "pod",
			buildID: "blabla",
			labels:  map[string]string{"needstobe": "inherited"},
			pjSpec: prowapi.ProwJobSpec{
				Type: prowapi.PresubmitJob,
				Job:  "job-name",
				DecorationConfig: &prowapi.DecorationConfig{
					Timeout:     &prowapi.Duration{Duration: 120 * time.Minute},
					GracePeriod: &prowapi.Duration{Duration: 10 * time.Second},
					UtilityImages: &prowapi.UtilityImages{
						CloneRefs:  "clonerefs:tag",
						InitUpload: "initupload:tag",
						Entrypoint: "entrypoint:tag",
						Sidecar:    "sidecar:tag",
					},
					GCSConfiguration: &prowapi.GCSConfiguration{
						Bucket:       "my-bucket",
						PathStrategy: "legacy",
						DefaultOrg:   "kubernetes",
						DefaultRepo:  "kubernetes",
					},
					GCSCredentialsSecret: "secret-name",
					SSHKeySecrets:        []string{"ssh-1", "ssh-2"},
					SkipCloning:          &truth,
				},
				Agent: prowapi.KubernetesAgent,
				Refs: &prowapi.Refs{
					Org:     "org-name",
					Repo:    "repo-name",
					BaseRef: "base-ref",
					BaseSHA: "base-sha",
					Pulls: []prowapi.Pull{{
						Number: 1,
						Author: "author-name",
						SHA:    "pull-sha",
					}},
					PathAlias: "somewhere/else",
				},
				ExtraRefs: []prowapi.Refs{
					{
						Org:  "extra-org",
						Repo: "extra-repo",
					},
				},
				PodSpec: &coreapi.PodSpec{
					Containers: []coreapi.Container{
						{
							Image:   "tester",
							Command: []string{"/bin/thing"},
							Args:    []string{"some", "args"},
							Env: []coreapi.EnvVar{
								{Name: "MY_ENV", Value: "rocks"},
							},
						},
					},
				},
			},
		},
		{
			podName: "pod",
			buildID: "blabla",
			labels:  map[string]string{"needstobe": "inherited"},
			pjSpec: prowapi.ProwJobSpec{
				Type: prowapi.PresubmitJob,
				Job:  "job-name",
				DecorationConfig: &prowapi.DecorationConfig{
					Timeout:     &prowapi.Duration{Duration: 120 * time.Minute},
					GracePeriod: &prowapi.Duration{Duration: 10 * time.Second},
					UtilityImages: &prowapi.UtilityImages{
						CloneRefs:  "clonerefs:tag",
						InitUpload: "initupload:tag",
						Entrypoint: "entrypoint:tag",
						Sidecar:    "sidecar:tag",
					},
					GCSConfiguration: &prowapi.GCSConfiguration{
						Bucket:       "my-bucket",
						PathStrategy: "legacy",
						DefaultOrg:   "kubernetes",
						DefaultRepo:  "kubernetes",
					},
					GCSCredentialsSecret: "secret-name",
					SSHKeySecrets:        []string{"ssh-1", "ssh-2"},
					CookiefileSecret:     "yummy",
				},
				Agent: prowapi.KubernetesAgent,
				Refs: &prowapi.Refs{
					Org:     "org-name",
					Repo:    "repo-name",
					BaseRef: "base-ref",
					BaseSHA: "base-sha",
					Pulls: []prowapi.Pull{{
						Number: 1,
						Author: "author-name",
						SHA:    "pull-sha",
					}},
					PathAlias: "somewhere/else",
				},
				ExtraRefs: []prowapi.Refs{
					{
						Org:  "extra-org",
						Repo: "extra-repo",
					},
				},
				PodSpec: &coreapi.PodSpec{
					Containers: []coreapi.Container{
						{
							Name:    "test-0",
							Image:   "tester",
							Command: []string{"/bin/thing"},
							Args:    []string{"some", "args"},
							Env: []coreapi.EnvVar{
								{Name: "MY_ENV", Value: "rocks"},
							},
						},
						{
							Name:    "test-1",
							Image:   "othertester",
							Command: []string{"/bin/otherthing"},
							Args:    []string{"other", "args"},
							Env: []coreapi.EnvVar{
								{Name: "MY_ENV", Value: "stones"},
							},
						},
					},
				},
			},
		},
	}

	findContainer := func(name string, pod coreapi.Pod) *coreapi.Container {
		for _, c := range pod.Spec.Containers {
			if c.Name == name {
				return &c
			}
		}
		return nil
	}
	findEnv := func(key string, container coreapi.Container) *string {
		for _, env := range container.Env {
			if env.Name == key {
				v := env.Value
				return &v
			}

		}
		return nil
	}

	type checker interface {
		ConfigVar() string
		LoadConfig(string) error
		Validate() error
	}

	checkEnv := func(pod coreapi.Pod, name string, opt checker) error {
		c := findContainer(name, pod)
		if c == nil {
			return nil
		}
		env := opt.ConfigVar()
		val := findEnv(env, *c)
		if val == nil {
			return fmt.Errorf("missing %s env var", env)
		}
		if err := opt.LoadConfig(*val); err != nil {
			return fmt.Errorf("load: %v", err)
		}
		if err := opt.Validate(); err != nil {
			return fmt.Errorf("validate: %v", err)
		}
		return nil
	}

	for i, test := range tests {
		t.Run(strconv.Itoa(i), func(t *testing.T) {
			pj := prowapi.ProwJob{ObjectMeta: metav1.ObjectMeta{Name: test.podName, Labels: test.labels}, Spec: test.pjSpec, Status: test.pjStatus}
			pj.Status.BuildID = test.buildID
			got, err := ProwJobToPod(pj)
			if err != nil {
				t.Errorf("unexpected error: %v", err)
			}
			fixtureName := filepath.Join("testdata", fmt.Sprintf("%s.yaml", strings.ReplaceAll(t.Name(), "/", "_")))
			if os.Getenv("UPDATE") != "" {
				marshalled, err := yaml.Marshal(got)
				if err != nil {
					t.Fatalf("failed to marhsal pod: %v", err)
				}
				if err := ioutil.WriteFile(fixtureName, marshalled, 0644); err != nil {
					t.Errorf("failed to update fixture: %v", err)
				}
			}
			expectedRaw, err := ioutil.ReadFile(fixtureName)
			if err != nil {
				t.Fatalf("failed to read fixture: %v", err)
			}
			expected := &coreapi.Pod{}
			if err := yaml.Unmarshal(expectedRaw, expected); err != nil {
				t.Fatalf("failed to unmarshal fixture: %v", err)
			}
			if !equality.Semantic.DeepEqual(got, expected) {
				t.Errorf("unexpected pod diff:\n%s. You can update the fixtures by running this test with UPDATE=true if this is expected.", diff.ObjectReflectDiff(expected, got))
			}
			if err := checkEnv(*got, "sidecar", sidecar.NewOptions()); err != nil {
				t.Errorf("bad sidecar env: %v", err)
			}
			if err := checkEnv(*got, "initupload", initupload.NewOptions()); err != nil {
				t.Errorf("bad clonerefs env: %v", err)
			}
			if err := checkEnv(*got, "clonerefs", &clonerefs.Options{}); err != nil {
				t.Errorf("bad clonerefs env: %v", err)
			}
			if test.pjSpec.DecorationConfig != nil { // all jobs get a test container
				// But only decorated jobs need valid entrypoint options
				if err := checkEnv(*got, "test", entrypoint.NewOptions()); err != nil {
					t.Errorf("bad test entrypoint: %v", err)
				}
			}
		})
	}
}

func TestProwJobToPod_setsTerminationGracePeriodSeconds(t *testing.T) {
	testCases := []struct {
		name                                  string
		prowjob                               *prowapi.ProwJob
		expectedTerminationGracePeriodSeconds int64
	}{
		{
			name: "GracePeriodSeconds from decoration config",
			prowjob: &prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					PodSpec: &coreapi.PodSpec{Containers: []coreapi.Container{{}}},
					DecorationConfig: &prowapi.DecorationConfig{
						UtilityImages: &prowapi.UtilityImages{},
						GracePeriod:   &prowapi.Duration{Duration: 10 * time.Second},
					},
				},
			},
			expectedTerminationGracePeriodSeconds: 10,
		},
		{
			name: "Existing GracePeriodSeconds is not overwritten",
			prowjob: &prowapi.ProwJob{
				Spec: prowapi.ProwJobSpec{
					PodSpec: &coreapi.PodSpec{TerminationGracePeriodSeconds: utilpointer.Int64Ptr(60), Containers: []coreapi.Container{{}}},
					DecorationConfig: &prowapi.DecorationConfig{
						UtilityImages: &prowapi.UtilityImages{},
						Timeout:       &prowapi.Duration{Duration: 10 * time.Second},
					},
				},
			},
			expectedTerminationGracePeriodSeconds: 60,
		},
	}

	for idx := range testCases {
		tc := testCases[idx]
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()
			if err := decorate(tc.prowjob.Spec.PodSpec, tc.prowjob, map[string]string{}, ""); err != nil {
				t.Fatalf("decoration failed: %v", err)
			}
			if tc.prowjob.Spec.PodSpec.TerminationGracePeriodSeconds == nil || *tc.prowjob.Spec.PodSpec.TerminationGracePeriodSeconds != tc.expectedTerminationGracePeriodSeconds {
				t.Errorf("expected pods TerminationGracePeriodSeconds to be %d was %v", tc.expectedTerminationGracePeriodSeconds, tc.prowjob.Spec.PodSpec.TerminationGracePeriodSeconds)
			}
		})
	}
}


text:
package org.apache.streams.osgi.components;

/**
 * Public API representing an example OSGi service
 */
public interface ActivityStreamsSubscriberRegistration {

    public Object register(Object obj);

}


text:
'use strict';

exports.__esModule = true;

var _utils = require('flux/utils');

var _ActorAppDispatcher = require('../dispatcher/ActorAppDispatcher');

var _ActorAppDispatcher2 = _interopRequireDefault(_ActorAppDispatcher);

var _ActorAppConstants = require('../constants/ActorAppConstants');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ActivityStore = function (_ReduceStore) {
  _inherits(ActivityStore, _ReduceStore);

  function ActivityStore() {
    _classCallCheck(this, ActivityStore);

    return _possibleConstructorReturn(this, _ReduceStore.apply(this, arguments));
  }

  ActivityStore.prototype.getInitialState = function getInitialState() {
    return {
      isOpen: false
    };
  };

  ActivityStore.prototype.reduce = function reduce(state, action) {
    switch (action.type) {
      case _ActorAppConstants.ActionTypes.CALL_MODAL_OPEN:
      case _ActorAppConstants.ActionTypes.ACTIVITY_HIDE:
        return this.getInitialState();
      case _ActorAppConstants.ActionTypes.ACTIVITY_SHOW:
        return {
          isOpen: true
        };
      default:
        return state;
    }
  };

  ActivityStore.prototype.isOpen = function isOpen() {
    return this.getState().isOpen;
  };

  return ActivityStore;
}(_utils.ReduceStore);

exports.default = new ActivityStore(_ActorAppDispatcher2.default);
//# sourceMappingURL=ActivityStore.js.map


text:
require 'truenames'
require 'truenames/rspec'


text:
module.exports = promooseify;

function promooseify() {
  var config = Array.prototype.slice.call(arguments);
  var func = config.shift();
  var scope = config.shift();
  return function() {
    var args = Array.prototype.slice.call(arguments);
    return new Promise(function callbackPromise(resolve, reject) {
      function finalCallback(err, result) {
        if (err) return reject(err);
        resolve(result);
      }
      args.push(finalCallback);
      return func.apply(scope || this, args);
    });
  };
}

promooseify.applyStatic = applyStatic = function applyStatic(object) {
  return function(funcName) {
    Object.getPrototypeOf(object)[funcName + 'P'] = repromiseCallback(funcName);
  };
};

promooseify.applyMethod = applyMethod = function applyMethod(object) {
  return function(funcName) {
    object.prototype[funcName + 'P'] = repromiseCallback(funcName);
  };
};

promooseify.repromiseCallback = repromiseCallback = function repromiseCallback(funcName) {
  return function callbackPromise() {
    var args = Array.prototype.slice.call(arguments);
    var _this = this;
    var scopedFunc = curryFunctionScope(_this, funcName);
    return callbackShimToPromise(scopedFunc, args);
  };
};

promooseify.curryFunctionScope = curryFunctionScope = function curryFunctionScope(scope, funcName) {
  var func = scope[funcName];
  return function scopedFunction(args) {
    return func.apply(scope, args);
  };
};

promooseify.callbackShimToPromise = callbackShimToPromise = function callbackShimToPromise(func, args) {
  return new Promise(function callbackPromise(resolve, reject) {
    args.push(function finalCallback(err, result) {
      if (err) return reject(err);
      return resolve(result);
    });
    return func(args);
  });
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright (C) 2014 Kaya Software, LLC

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<project name="${project.name}" xmlns="http://maven.apache.org/DECORATION/1.4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/DECORATION/1.4.0 http://maven.apache.org/xsd/decoration-1.4.0.xsd">

    <!-- http://maven.apache.org/plugins/maven-site-plugin/examples/sitedescriptor.html -->

    <!-- banner logo on the masthead of the site to the left -->
    <!--<bannerLeft></bannerLeft>-->

    <!-- banner logo on the masthead of the site to the right -->
    <!--<bannerRight></bannerRight>-->

    <publishDate position="left" format=" yyyy-MM-dd"/>

    <version position="left"/>

    <!-- artifact containing the skin for the site -->
    <skin>
        <groupId>org.apache.maven.skins</groupId>
        <artifactId>maven-fluido-skin</artifactId>
        <version>1.6</version>
    </skin>

    <custom>
        <fluidoSkin>
            <breadcrumbDivider>»</breadcrumbDivider>
            <copyrightClass>pull-right</copyrightClass>
            <leftColumnClass>span2</leftColumnClass>
            <bodyColumnClass>span10</bodyColumnClass>
            <topBarEnabled>false</topBarEnabled>
            <sideBarEnabled>true</sideBarEnabled>
            <sourceLineNumbersEnabled>true</sourceLineNumbersEnabled>
            <gitHub>
                <projectId>${config.scm.owner}/${config.scm.repoName}</projectId>
                <ribbonOrientation>right</ribbonOrientation>
                <ribbonColor>green</ribbonColor>
            </gitHub>
        </fluidoSkin>
    </custom>

    <body>
        <!-- menu with links to all the generated reports for your project -->
        <menu ref="reports" />
        <!-- menu containing the links to the sites of the submodules of this project -->
        <menu ref="modules" />
        <!-- menu with a link to the parent project's site -->
        <menu ref="parent" />
    </body>
</project>


text:
package rx.operators;

import rx.Observable;
import rx.Observable.OnSubscribeFunc;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.observables.ConnectableObservable;
import rx.subjects.Subject;
import rx.subscriptions.CompositeSubscription;
import rx.subscriptions.Subscriptions;

public class OperationMulticast {
    public static <T, R> ConnectableObservable<R> multicast(Observable<? extends T> source, final Subject<? super T, ? extends R> subject) {
        return new MulticastConnectableObservable<T, R>(source, subject);
    }

    private static class MulticastConnectableObservable<T, R> extends ConnectableObservable<R> {
        private final Object lock = new Object();

        private final Observable<? extends T> source;
        private final Subject<? super T, ? extends R> subject;

        private Subscription subscription;

        public MulticastConnectableObservable(Observable<? extends T> source, final Subject<? super T, ? extends R> subject) {
            super(new OnSubscribe<R>() {
                @Override
                public void call(Subscriber<? super R> observer) {
                    subject.subscribe(observer);
                }
            });
            this.source = source;
            this.subject = subject;
        }

        public Subscription connect() {
            synchronized (lock) {
                if (subscription == null) {
                    subscription = source.subscribe(new Observer<T>() {
                        @Override
                        public void onCompleted() {
                            subject.onCompleted();
                        }

                        @Override
                        public void onError(Throwable e) {
                            subject.onError(e);
                        }

                        @Override
                        public void onNext(T args) {
                            subject.onNext(args);
                        }
                    });
                }
            }

            return Subscriptions.create(new Action0() {
                @Override
                public void call() {
                    synchronized (lock) {
                        if (subscription != null) {
                            subscription.unsubscribe();
                            subscription = null;
                        }
                    }
                }
            });
        }

    }

    /**
     * Returns an observable sequence that contains the elements of a sequence
     * produced by multicasting the source sequence within a selector function.
     *
     * @param source
     * @param subjectFactory
     * @param selector
     * @return
     *
     * @see MSDN: Observable.Multicast
     */
    public static <TInput, TIntermediate, TResult> Observable<TResult> multicast(
            final Observable<? extends TInput> source,
            final Func0<? extends Subject<? super TInput, ? extends TIntermediate>> subjectFactory,
            final Func1<? super Observable<TIntermediate>, ? extends Observable<TResult>> selector) {
        return Observable.create(new MulticastSubscribeFunc<TInput, TIntermediate, TResult>(source, subjectFactory, selector));
    }

    /** The multicast subscription function. */
    private static final class MulticastSubscribeFunc<TInput, TIntermediate, TResult> implements OnSubscribeFunc<TResult> {
        final Observable<? extends TInput> source;
        final Func0<? extends Subject<? super TInput, ? extends TIntermediate>> subjectFactory;
        final Func1<? super Observable<TIntermediate>, ? extends Observable<TResult>> resultSelector;

        public MulticastSubscribeFunc(Observable<? extends TInput> source,
                Func0<? extends Subject<? super TInput, ? extends TIntermediate>> subjectFactory,
                Func1<? super Observable<TIntermediate>, ? extends Observable<TResult>> resultSelector) {
            this.source = source;
            this.subjectFactory = subjectFactory;
            this.resultSelector = resultSelector;
        }

        @Override
        public Subscription onSubscribe(Observer<? super TResult> t1) {
            Observable<TResult> observable;
            ConnectableObservable<TIntermediate> connectable;
            try {
                Subject<? super TInput, ? extends TIntermediate> subject = subjectFactory.call();

                connectable = new MulticastConnectableObservable<TInput, TIntermediate>(source, subject);

                observable = resultSelector.call(connectable);
            } catch (Throwable t) {
                t1.onError(t);
                return Subscriptions.empty();
            }

            CompositeSubscription csub = new CompositeSubscription();

            csub.add(observable.subscribe(new SafeObserver<TResult>(
                    new SafeObservableSubscription(csub), t1)));
            csub.add(connectable.connect());

            return csub;
        }
    }
}


text:
module Segments.Base(
    GradientWeight,
    HighlightGroup(..),
    PromptContext,
    Segment(..),
    SegmentArgs,
    SegmentHandler,
    argLookup,
    argLookup',
    contextHandler,
    getPowerlineFile,
    modifySegText,
    simpleHandler,
    return2,
    ) where

import Control.Monad (liftM)
import Data.Maybe (maybeToList)
import Rainbow (Radiant)
import System.Directory (createDirectoryIfMissing, getTemporaryDirectory)
import System.FilePath ((</>))
import System.Posix.User (getLoginName)

import CommandArgs
import Config.Schema (SegmentArgs, argLookup, argLookup')
import Util

-- TODO: figure out how segments can log failure

-- Placeholder for info passed in via command-line arguments
type PromptContext = CommandArgs

type SegmentHandler = SegmentArgs -> PromptContext -> IO [Segment]

-- A rendered segment.
data Segment = Segment {
                    segmentGroup :: HighlightGroup,
                    segmentText  :: String   -- text in the segment
                }
             | Divider {
                    divFore :: Radiant,
                    divBack :: Radiant,
                    divText :: String
                } deriving (Show, Eq)

type GradientWeight = Float
data HighlightGroup = HighlightGroup {
                        hlGroup :: String,                  -- highlight group to use - may be colour or gradient
                        hlValue :: Maybe GradientWeight     -- gradient value, if defined. Value spans 0 (least alert) to 1 (most alert)
                    } | NoHighlight
                    deriving (Show, Eq)

modifySegText :: (String -> String) -> Segment -> Segment
modifySegText f s = s { segmentText = f (segmentText s) }

-- Wrapper for handlers which don't use any context
simpleHandler :: String -> IO (Maybe String) -> SegmentHandler
simpleHandler hlGroupName f _ _ = maybeToList <$> Segment hlGroup' `lift2` f where
    lift2 = liftM . liftM
    hlGroup' = HighlightGroup hlGroupName Nothing

-- Wrapper for handlers which show a value provided in the command args
contextHandler :: Show a => String -> (CommandArgs -> a) -> SegmentHandler
contextHandler hlGroupName field _ args = return2 . Segment hlGroup' . show $ field args where
    hlGroup' = HighlightGroup hlGroupName Nothing

-- Helper method: returns the path to a file with the given name.
-- Ensures the parent directory exists.
-- Used by segments which need to maintain state between invocations.
getPowerlineFile :: String -> IO String
getPowerlineFile name = do
    root <- (</> ".powerline-hs") <$> getTemporaryDirectory
    username <- getLoginName
    createDirectoryIfMissing False root
    return $ root </> name ++ "_" ++ username


text:
"""Test core config."""
from unittest.mock import patch

import pytest

from homeassistant.bootstrap import async_setup_component
from homeassistant.components import config
from homeassistant.components.websocket_api.const import TYPE_RESULT
from homeassistant.const import CONF_UNIT_SYSTEM, CONF_UNIT_SYSTEM_IMPERIAL
from homeassistant.util import dt as dt_util, location

ORIG_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE

@pytest.fixture
async def client(hass, hass_ws_client):
    """Fixture that can interact with the config manager API."""
    with patch.object(config, "SECTIONS", ["core"]):
        assert await async_setup_component(hass, "config", {})
    return await hass_ws_client(hass)

async def test_validate_config_ok(hass, hass_client):
    """Test checking config."""
    with patch.object(config, "SECTIONS", ["core"]):
        await async_setup_component(hass, "config", {})

    client = await hass_client()

    with patch(
        "homeassistant.components.config.core.async_check_ha_config_file",
        return_value=None,
    ):
        resp = await client.post("/api/config/core/check_config")

    assert resp.status == 200
    result = await resp.json()
    assert result["result"] == "valid"
    assert result["errors"] is None

    with patch(
        "homeassistant.components.config.core.async_check_ha_config_file",
        return_value="beer",
    ):
        resp = await client.post("/api/config/core/check_config")

    assert resp.status == 200
    result = await resp.json()
    assert result["result"] == "invalid"
    assert result["errors"] == "beer"

async def test_websocket_core_update(hass, client):
    """Test core config update websocket command."""
    assert hass.config.latitude != 60
    assert hass.config.longitude != 50
    assert hass.config.elevation != 25
    assert hass.config.location_name != "Huis"
    assert hass.config.units.name != CONF_UNIT_SYSTEM_IMPERIAL
    assert hass.config.time_zone != "America/New_York"
    assert hass.config.external_url != "https://www.example.com"
    assert hass.config.internal_url != "http://example.com"
    assert hass.config.currency == "EUR"

    with patch("homeassistant.util.dt.set_default_time_zone") as mock_set_tz:
        await client.send_json(
            {
                "id": 5,
                "type": "config/core/update",
                "latitude": 60,
                "longitude": 50,
                "elevation": 25,
                "location_name": "Huis",
                CONF_UNIT_SYSTEM: CONF_UNIT_SYSTEM_IMPERIAL,
                "time_zone": "America/New_York",
                "external_url": "https://www.example.com",
                "internal_url": "http://example.local",
                "currency": "USD",
            }
        )

        msg = await client.receive_json()

    assert msg["id"] == 5
    assert msg["type"] == TYPE_RESULT
    assert msg["success"]
    assert hass.config.latitude == 60
    assert hass.config.longitude == 50
    assert hass.config.elevation == 25
    assert hass.config.location_name == "Huis"
    assert hass.config.units.name == CONF_UNIT_SYSTEM_IMPERIAL
    assert hass.config.external_url == "https://www.example.com"
    assert hass.config.internal_url == "http://example.local"
    assert hass.config.currency == "USD"

    assert len(mock_set_tz.mock_calls) == 1
    assert mock_set_tz.mock_calls[0][1][0] == dt_util.get_time_zone("America/New_York")

async def test_websocket_core_update_not_admin(hass, hass_ws_client, hass_admin_user):
    """Test core config fails for non admin."""
    hass_admin_user.groups = []
    with patch.object(config, "SECTIONS", ["core"]):
        await async_setup_component(hass, "config", {})

    client = await hass_ws_client(hass)
    await client.send_json({"id": 6, "type": "config/core/update", "latitude": 23})

    msg = await client.receive_json()

    assert msg["id"] == 6
    assert msg["type"] == TYPE_RESULT
    assert not msg["success"]
    assert msg["error"]["code"] == "unauthorized"

async def test_websocket_bad_core_update(hass, client):
    """Test core config update fails with bad parameters."""
    await client.send_json({"id": 7, "type": "config/core/update", "latituude": 23})

    msg = await client.receive_json()

    assert msg["id"] == 7
    assert msg["type"] == TYPE_RESULT
    assert not msg["success"]
    assert msg["error"]["code"] == "invalid_format"

async def test_detect_config(hass, client):
    """Test detect config."""
    with patch(
        "homeassistant.util.location.async_detect_location_info",
        return_value=None,
    ):
        await client.send_json({"id": 1, "type": "config/core/detect"})

        msg = await client.receive_json()

    assert msg["success"] is True
    assert msg["result"] == {}

async def test_detect_config_fail(hass, client):
    """Test detect config."""
    with patch(
        "homeassistant.util.location.async_detect_location_info",
        return_value=location.LocationInfo(
            ip=None,
            country_code=None,
            currency=None,
            region_code=None,
            region_name=None,
            city=None,
            zip_code=None,
            latitude=None,
            longitude=None,
            use_metric=True,
            time_zone="Europe/Amsterdam",
        ),
    ):
        await client.send_json({"id": 1, "type": "config/core/detect"})

        msg = await client.receive_json()

    assert msg["success"] is True
    assert msg["result"] == {"unit_system": "metric", "time_zone": "Europe/Amsterdam"}


text:
New coffee compiler can compile this directly into Javascript

License for common Javascript: MIT or Apache

## Top-level SQLitePlugin objects

- root window object:

    root = @

- SQLitePlugin object is defined by a constructor function and prototype member functions:

    SQLitePlugin = (openargs, openSuccess, openError) ->
      console.log "SQLitePlugin openargs: #{JSON.stringify openargs}"

      if !(openargs and openargs['name'])
        throw new Error("Cannot create a SQLitePlugin instance without a db name")

      dbname = openargs.name

      @openargs = openargs
      @dbname = dbname

      @openSuccess = openSuccess
      @openError = openError

      @openSuccess or
        @openSuccess = ->
          console.log "DB opened: " + dbname
          return

      @openError or
        @openError = (e) ->
          console.log e.message
          return

      #@bg = !!openargs.bgType and openargs.bgType == 1
      @bg =
        if !openargs.bgType
          # default to true for iOS only (due to memory issue)
          ((navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/iPhone/i)))
        else
          openargs.bgType == 1

      @open @openSuccess, @openError
      return

    SQLitePlugin::databaseFeatures = isSQLitePluginDatabase: true
    SQLitePlugin::openDBs = {}

    SQLitePlugin::txQ = []

    SQLitePlugin::addTransaction = (t) ->
      @txQ.push t
      if @txQ.length is 1
        t.start()
      return

    SQLitePlugin::transaction = (fn, error, success) ->
      @addTransaction new SQLitePluginTransaction(this, fn, error, success, true)
      return

    SQLitePlugin::startNextTransaction = ->
      @txQ.shift()
      if @txQ[0]
        @txQ[0].start()
      return

    SQLitePlugin::open = (success, error) ->
      unless @dbname of @openDBs
        @openDBs[@dbname] = true
        cordova.exec success, error, "SQLitePlugin", "open", [ @openargs ]

      return

    SQLitePlugin::close = (success, error) ->
      #console.log "SQLitePlugin.prototype.close"

      if @dbname of @openDBs
        delete @openDBs[@dbname]

        cordova.exec null, null, "SQLitePlugin", "close", [ { path: @dbname } ]

      return

    SQLitePlugin::executeSql = (statement, params, success, error) ->
      mysuccess = (t, r) -> if !!success then success r
      myerror = (t, e) -> if !!error then error e

      myfn = (tx) ->
        tx.executeSql(statement, params, mysuccess, myerror)
        return

      @addTransaction new SQLitePluginTransaction(this, myfn, myerror, mysuccess, false)
      return

- Deprecated pragma API, use db.executeSql() instead:

    pcb = -> 1

    ###
    DEPRECATED AND WILL BE REMOVED:
    ###
    SQLitePlugin::executePragmaStatement = (statement, success, error) ->
      console.log "SQLitePlugin::executePragmaStatement"
      pcb = success

      cordova.exec (-> 1), error, "SQLitePlugin", "executePragmaStatement", [ @dbname, statement ]
      return

    ###
    FUTURE TBD GONE: Required for db.executePragmStatement() callback ONLY:
    ###
    SQLitePluginCallback =
      p1: (id, result) ->
        console.log "PRAGMA CB"

        mycb = pcb
        pcb = -> 1
        mycb result

        return

- SQLitePluginTransaction object for batching:

    ###
    Transaction batching object:
    ###
    SQLitePluginTransaction = (db, fn, error, success, txlock) ->
      if typeof(fn) != "function"
        ###
        This is consistent with the implementation in Chrome -- it
        throws if you pass anything other than a function. This also
        prevents us from stalling our txQueue if somebody passes a
        false value for fn.
        ###
        throw new Error("transaction expected a function")

      @db = db
      @fn = fn
      @error = error
      @success = success
      @txlock = txlock
      @executes = []

      if txlock
        @executeSql "BEGIN", [], null, (tx, err) ->
          throw new Error("unable to begin transaction: " + err.message)

      return

    SQLitePluginTransaction::start = ->
      try
        unless @fn
          return
        @fn this
        @fn = null
        @run()
      catch err
        ###
        If "fn" throws, we must report the whole transaction as failed.
        ###
        @db.startNextTransaction()
        if @error
          @error err
      return

    SQLitePluginTransaction::executeSql = (sql, values, success, error) ->
      qid = @executes.length

      @executes.push
        success: success
        error: error
        qid: qid

        sql: sql
        params: values || []

      return

    SQLitePluginTransaction::handleStatementSuccess = (handler, response) ->
      if !handler
        return

      rows = response.rows || []
      payload =
        rows:
          item: (i) ->
            rows[i]

          length: rows.length

        rowsAffected: response.rowsAffected or 0
        insertId: response.insertId or undefined

      handler this, payload

      return

    SQLitePluginTransaction::handleStatementFailure = (handler, response) ->
      if !handler
        throw new Error "a statement with no error handler failed: " + response.message
      if handler(this, response)
        throw new Error "a statement error callback did not return false"
      return

    SQLitePluginTransaction::run = ->
      txFailure = null

      tropts = []
      batchExecutes = @executes
      waiting = batchExecutes.length
      @executes = []
      tx = this

      handlerFor = (index, didSucceed) ->
        (response) ->
          try
            if didSucceed
              tx.handleStatementSuccess batchExecutes[index].success, response
            else
              tx.handleStatementFailure batchExecutes[index].error, response
          catch err
            txFailure = err  unless txFailure

          if --waiting == 0
            if txFailure
              tx.abort txFailure
            else if tx.executes.length > 0
              ###
              new requests have been issued by the callback
              handlers, so run another batch.
              ###
              tx.run()
            else
              tx.finish()

          return

      i = 0

      mycbmap = {}

      while i < batchExecutes.length
        request = batchExecutes[i]

        qid = request.qid

        mycbmap[qid] =
          success: handlerFor(i, true)
          error: handlerFor(i, false)

        tropts.push
          qid: qid
          # for ios version:
          query: [request.sql].concat(request.params)
          sql: request.sql
          params: request.params

        i++

      mycb = (result) ->
        #console.log "mycb result #{JSON.stringify result}"

        for r in result
          type = r.type
          qid = r.qid
          res = r.result

          q = mycbmap[qid]

          if q
            if q[type]
              q[type] res

        return

      mycommand = if @db.bg then "backgroundExecuteSqlBatch" else "executeSqlBatch"
      cordova.exec mycb, null, "SQLitePlugin", mycommand, [{dbargs: {dbname: @db.dbname}, executes: tropts}]

      return

    SQLitePluginTransaction::abort = (txFailure) ->
      if @finalized then return
      tx = @

      succeeded = (tx) ->
        tx.db.startNextTransaction()
        if tx.error then tx.error txFailure
        return

      failed = (tx, err) ->
        tx.db.startNextTransaction()
        if tx.error then tx.error new Error("error while trying to roll back: " + err.message)
        return

      @finalized = true

      if @txlock
        @executeSql "ROLLBACK", [], succeeded, failed
        @run()
      else
        succeeded(tx)

      return

    SQLitePluginTransaction::finish = ->
      if @finalized then return
      tx = @

      succeeded = (tx) ->
        tx.db.startNextTransaction()
        if tx.success then tx.success()
        return

      failed = (tx, err) ->
        tx.db.startNextTransaction()
        if tx.error then tx.error new Error("error while trying to commit: " + err.message)
        return

      @finalized = true

      if @txlock
        @executeSql "COMMIT", [], succeeded, failed
        @run()
      else
        succeeded(tx)

      return

- SQLite plugin object factory:

    SQLiteFactory =
      ###
      NOTE: this function should NOT be translated from Javascript
      back to CoffeeScript by js2coffee.
      If this function is edited in Javascript then someone will
      have to translate it back to CoffeeScript by hand.
      ###
      opendb: ->
        if arguments.length < 1 then return null

        first = arguments[0]
        openargs = null
        okcb = null
        errorcb = null

        if first.constructor == String
          openargs = {name: first}

          if arguments.length >= 5
            okcb = arguments[4]
            if arguments.length > 5 then errorcb = arguments[5]

        else
          openargs = first

          if arguments.length >= 2
            okcb = arguments[1]
            if arguments.length > 2 then errorcb = arguments[2]

        new SQLitePlugin openargs, okcb, errorcb

      deleteDb: (databaseName, success, error) ->
        cordova.exec success, error, "SQLitePlugin", "delete", [{ path: databaseName }]

    ###
    FUTURE TBD GONE: Required for db.executePragmStatement() callback ONLY:
    ###
    root.SQLitePluginCallback = SQLitePluginCallback

- Exported API:

    root.sqlitePlugin =
      sqliteFeatures:
        isSQLitePlugin: true

      openDatabase: SQLiteFactory.opendb
      deleteDatabase: SQLiteFactory.deleteDb