text:
published: true
title: How to test Webhooks
description: An example on how to test SendGrid Webhooks by NUnit using ngrok in .NET
layout: post
tags: [csharp, dotnet, webhook, NUnit, sendgrid, ngrok]
comments: true
---

During integrating with [SendGrid's webhook](https://sendgrid.com/docs/API_Reference/Event_Webhook/getting_started_event_webhook.html) in order to get status of email delivery I came across obstacles on how to test it. Because I'm a lazy developer I wanted to have an automated test for my integration. But it is not obvious how to do that from the first sight.

The webhook works this way that external system calls my application's API. It means I have to run/host API right in the test so it will be available for external consumers such as `SendGrid`.

## Problem

I don't have a public IP address on my computer where I'm going to run the test. The computer is under NAT. How to expose a local port from my computer to the internet? Even more, `SendGrid` requires to have HTTPS enabled. (╯°□°)╯︵ ┻━┻ I have to overcome this problem as well.

`SendGrid` suggested to looking into [ngrok](https://sendgrid.com/blog/test-webhooks-ngrok/).

## Solution

[ngrok](https://ngrok.com/product) can expose local port to the internet via HTTPS. Moreover, I can control `ngrok` via its API in order to get the public address for the port. Here is a small wrapper around `ngrok`:

```c#
public class NgrokTunnel : IDisposable
{
    private readonly Process _process;

    public NgrokTunnel(int localPort)
    {
        _process = new Process
        {
            StartInfo = new ProcessStartInfo("ngrok", "http " + localPort)
            {
                WindowStyle = ProcessWindowStyle.Minimized
            }
        };
        _process.Start();
    }

    public string PublicTunnelUrl
    {
        get
        {
            for (int i = 0; i <= 10; i++)
                try
                {
                    var ngrokApi = "http://127.0.0.1:4040/api/tunnels/command_line";
                    var json = new WebClient().DownloadString(ngrokApi);
                    return (string) JsonConvert.DeserializeObject<dynamic>(json).public_url;
                }
                catch (Exception)
                {
                    if (i == 10) throw;
                    Thread.Sleep(200);
                }
            throw new TimeoutException();
        }
    }

    public void Dispose()
    {
        _process.Kill();
    }
}
```
No more obstacles for writing the test. I'm going to send an email and wait until `SendGrid` gives me update about the status of email delivery via webhook call. Finally, the test is like this:

```c#
[Test]
public async Task It_should_listen_for_webhooks()
{
    // Given
    var messageId = Guid.NewGuid().ToString();
    var onWebhookReceived = new TaskCompletionSource<Webhook>();
    Task.Delay(TimeSpan.FromMinutes(3))
        .ContinueWith(_ => onWebhookReceived.TrySetCanceled());

    async Task OnWebhookAppeared(IOwinContext ctx, Func<Task> _)
    {
        var json = new StreamReader(ctx.Request.Body).ReadToEnd();
        var webhook = JsonConvert.DeserializeObject<Webhook[]>(json)
            .FirstOrDefault(e => e.MyId == messageId);
        if (webhook != null)
            onWebhookReceived.TrySetResult(webhook);
    }

    using (var localApi = new HttpServer().Use(OnWebhookAppeared).Start())
    using (var ngrok = new NgrokTunnel(localPort: localApi.ApiBaseUrl.Port))
    {
        // When
        await RegisterWebhookUrl(ngrok.PublicTunnelUrl);
        await SendTestEmail(messageId);

        // Then
        var webhook = await onWebhookReceived.Task;
        Assert.That(webhook, Is.Not.Null);
        Assert.That(webhook.Event, Is.EqualTo("processed"));
    }
}
```
How cool it is that `SendGrid` calls `OnWebhookAppeared` method written right in the test. `HttpServer` is a wrapper for `Microsoft.Owin`-thing to self-host my API. `RegisterWebhookUrl` and `SendTestEmail` methods are just calling SendGrid API.

Once, the test is running you will see `ngrok` console window displaying its state and statistics:

![alt text](/img/ngrok-console.png "ngrok console")

After ~15 sec it becomes green!

![alt text](/img/SendGridClientTests-result.png "ngrok console")

```text
   _                             .-.
  / )  .-.    ___          __   (   )
 ( (  (   ) .'___)        (__'-._) (
  \ '._) (,'.'               '.     '-.
   '.      /  "\               '    -. '.
     )    /   \ \   .-.   ,'.   )  (  ',_)    _
   .'    (     \ \ (   \ . .' .'    )    .-. ( \
  (  .''. '.    \ \|  .' .' ,',--, /    (   ) ) )
   \ \   ', :    \    .-'  ( (  ( (     _) (,' /
    \ \   : :    )  / _     ' .  \ \  ,'      /
  ,' ,'   : ;   /  /,' '.   /.'  / / ( (\    (
  '.'      "   (    .-'. \       ''   \_)\    \
                \  |    \ \__             )    )
              ___\ |     \___;           /  , /
             /  ___)                    (  ( (
             '.'                         ) ;) ;
                                        (_/(_/
```
Since I'm using external systems (`SendGrid`, `ngrok`) the test can be unstable. Full version of the test is [here](https://github.com/gaevoy/Gaev.Blog.Examples/tree/1.0.0/Gaev.Blog.Examples.WebhookTests).


text:
class FontCursorMisc < Formula
  desc "X.Org Fonts: font cursor misc"
  homepage "https://www.x.org/"
  ### http://www.linuxfromscratch.org/blfs/view/svn/x/x7font.html
  url "https://www.x.org/pub/individual/font/font-cursor-misc-1.0.3.tar.bz2"
  mirror "https://xorg.freedesktop.org/archive/individual/font/font-cursor-misc-1.0.3.tar.bz2"
  mirror "https://ftp.x.org/archive/individual/font/font-cursor-misc-1.0.3.tar.bz2"
  sha256 "17363eb35eece2e08144da5f060c70103b59d0972b4f4d77fd84c9a7a2dba635"
  revision 2
  # tag "linuxbrew"

  bottle do
    root_url "https://linuxbrew.bintray.com/bottles-xorg"
    sha256 x86_64_linux: "de0f977e9ca43b831f8d93b177a4bbec4ebd71b0ec7db9cb4a289a3dad30e0af"
  end

  keg_only "part of Xorg-fonts package"

  depends_on "bzip2" => [:build, :recommended]
  depends_on "font-util" => :build
  depends_on "fontconfig" => :build
  depends_on "linuxbrew/xorg/bdftopcf" => :build
  depends_on "linuxbrew/xorg/mkfontscale" => :build
  depends_on "pkg-config" => :build

  def install
    args = %W[
      --prefix=#{prefix}
      --sysconfdir=#{etc}
      --localstatedir=#{var}
      --disable-dependency-tracking
      --disable-silent-rules
      --with-fontrootdir=#{share}/fonts/X11
    ]
    args << "--with-compression=bzip2" if build.with? "bzip2"

    system "./configure", *args
    system "make"
    system "make", "install"
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
	<?xml-stylesheet type="text/xsl" href="modx.prosilver.en.xsl"?>
		<!--For security purposes, please check: http://www.phpbb.com/mods/ for the latest version of this MOD. Although MODs are checked before being allowed in the MODs Database there is no guarantee that there are no security problems within the MOD. No support will be given for MODs not found within the MODs Database which can be found at http://www.phpbb.com/mods/-->
		<mod xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.phpbb.com/mods/xml/modx-1.2.5.xsd">
	<header>
		<license>http://opensource.org/licenses/gpl-license.php GNU General Public License v2</license>
			<title lang="en">mChat 1.2.10 to 1.2.11</title>
				<description lang="en">Updates mod to 1.2.11 from 1.2.10</description>
		<author-group>
			<author>
				<realname>Rich McGirr</realname>
				<username>RMcGirr83</username>
				<homepage>http://rmcgirr83.org</homepage>
			</author>
			<author>
				<realname>Shaun</realname>
				<username>djs596</username>
				<homepage>http://djs596.com</homepage>
      		<contributions-group>
      		  <contributions status="past" from="2009-08-13" to="2010-03-01" position="Developer"/>
      		</contributions-group>
			</author>
			<author>
				<realname>Stoker</realname>
				<username>Stokerpiller</username>
				<homepage>http://www.phpbb3bcodes.com</homepage>
      		<contributions-group>
      		  <contributions status="past" from="2009-08-13" to="2010-03-01" position="Developer"/>
      		</contributions-group>
			</author>
		</author-group>
		<mod-version>1.2.11</mod-version>
		<installation>
			<level>easy</level>
			<time>300</time>
			<target-version>3.0.5</target-version>
		</installation>
		<link-group>
			<link type="template" href="../install.xml" lang="en">Main Install File</link>
		</link-group>
	</header>
	<action-group>
		<copy>
			<file from="root/mchat.php" to="mchat.php" />
			<file from="root/mchat_install.php" to="mchat_install.php" />
			<file from="root/includes/*.*" to="includes/*.*" />
			<file from="root/styles/prosilver/template/mchat_body.html" to="styles/prosilver/template/mchat_body.html" />
			<file from="root/language/en/*.*" to="language/en/*.*" />
			<file from="root/adm/*.*" to="adm/*.*" />
		</copy>
		<open src="styles/prosilver/template/editor.js">
			<edit>
				<find><![CDATA[		for (sel_start = 0; range_all.compareEndPoints('StartToStart', range) < 0; sel_start++)]]></find>
					<action type="before-add"><![CDATA[try
			{]]></action>
			</edit>
			<edit>
				<find><![CDATA[		caretPos.end = txtarea.sel_start;]]></find>
					<action type="after-add"><![CDATA[}
			catch(e)
			{
			}]]></action>
			</edit>
		</open>
<diy-instructions lang="en"><![CDATA[1. Browse to the mchat_install.php file, this will update your database.
2. Delete the mchat_install.php file from the root of your forum.
3. Make all edits to all files and upload them to your forum.
4. Visit user/group permissions and set the permissions for the Mini Chat for your groups/users.
5. Purge the cache
6. Enjoy the Mod!!
]]></diy-instructions>
</action-group>
</mod>


text:
require 'test_helper'

class EmergenciaParteMensualsHelperTest < ActionView::TestCase
end


text:
layout: page
title: "LAWS 7201: Antitrust Statistics"
comments: true
description: "blanks"
keywords: "LAWS,7201,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 1.68%

**Percent incomplete**: 0.0%

**Average grade** (4.0 scale): 3.43

**Standard deviation in grades** (4.0 scale): 0.08

**Average workload** (raw): 4.04

**Standard deviation in workload** (raw): 0.58

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 5.65

**Standard deviation in course rating** (6 point scale): 0.15

**Average instructor rating** (6 point scale): 5.72

**Standard deviation in instructor rating** (6 point scale): 0.24

**Instructors**: John Francis, Neil Mcgill Gorsuch, Philip Weiser

#### GENERAL CLASS INFORMATION

**Years provided**: Spring 2011, Spring 2013, Spring 2014, Fall 2014, Fall 2015, Spring 2017

**Credits**: 3

**RAP/Honors class?** Neither

**Number of Sections**: 6

**Department**: LAWS

**College**: University of Colorado Law School

**Level**: Doctoral

**Activity**: LEC - Lecture


text:
require "spec_helper"
require "json"

RSpec.shared_examples "waveform generation" do |scale|
  RSpec.configure do |c|
    c.include DevHelpers
  end

  # get_samples(wavey_method) is from DevHelpers.

  def get_fixture(wavey_method, scale)
    file = File.expand_path("../fixtures/#{scale}-#{wavey_method}.json", __dir__)

    JSON.parse(File.read(file))
  end

  it "generates the correct waveforms (scale=#{scale})" do
    expect(get_samples("sawtooth", scale)).to eq(get_fixture("sawtooth", scale))
    expect(get_samples("silence", scale)).to eq(get_fixture("silence", scale))
    expect(get_samples("sine", scale)).to eq(get_fixture("sine", scale))
    expect(get_samples("square", scale)).to eq(get_fixture("square", scale))
    expect(get_samples("triangle", scale)).to eq(get_fixture("triangle", scale))
  end
end

RSpec.describe Wavey do
  include_examples "waveform generation", :small
  include_examples "waveform generation", :large
end


text:
import {
    Account,
    Chat,
    Game,
    IAccount,
    IChat,
    IGame,
    IInformation,
    IMessage,
    ISupport,
    ITableReload,
    ITournament,
    Tournament,
} from "@poker/api-server";

export interface IApiProvider {
    getGame(): IGame;
    getTournament(): ITournament;
    getChat(): IChat;
    getAccount(): IAccount;
}

declare let host: string;

export let DefaultApiProvider: IApiProvider = {
    getGame: () => new Game(host),
    getTournament: () => new Tournament(host),
    getChat: () => new Chat(host),
    getAccount: () => new Account(host),
};


text:
extern U32 HashPointer(StringTableEntry e);

SimNameDictionary::SimNameDictionary()
{
   hashTable = NULL;
   mutex = Mutex::createMutex();
}

SimNameDictionary::~SimNameDictionary()
{
   delete[] hashTable;
   Mutex::destroyMutex(mutex);
}

void SimNameDictionary::insert(SimObject* obj)
{
   if(!obj->objectName)
      return;

   Mutex::lockMutex(mutex);

   if(!hashTable)
   {
      hashTable = new SimObject *[DefaultTableSize];
      hashTableSize = DefaultTableSize;
      hashEntryCount = 0;
      S32 i;
      for(i = 0; i < hashTableSize; i++)
         hashTable[i] = NULL;
   }
   S32 idx = HashPointer(obj->objectName) % hashTableSize;
   obj->nextNameObject = hashTable[idx];
   hashTable[idx] = obj;
   hashEntryCount++;
   if(hashEntryCount > hashTableSize)
   {
      // resize the hash table
      S32 i;
      SimObject *head = NULL, *walk, *temp;
   	for(i = 0; i < hashTableSize; i++) {
   		walk = hashTable[i];
         while(walk)
         {
            temp = walk->nextNameObject;
            walk->nextNameObject = head;
            head = walk;
            walk = temp;
         }
   	}
      delete[] hashTable;
      hashTableSize = hashTableSize * 2 + 1;
      hashTable = new SimObject *[hashTableSize];

      for(i = 0; i < hashTableSize;i++)
         hashTable[i] = NULL;
      while(head)
      {
         temp = head->nextNameObject;
         idx = HashPointer(head->objectName) % hashTableSize;
         head->nextNameObject = hashTable[idx];
         hashTable[idx] = head;
         head = temp;
      }
   }
   Mutex::unlockMutex(mutex);
}

SimObject* SimNameDictionary::find(StringTableEntry name)
{
   // NULL is a valid lookup - it will always return NULL
   if(!hashTable)
      return NULL;

   Mutex::lockMutex(mutex);

   S32 idx = HashPointer(name) % hashTableSize;
   SimObject *walk = hashTable[idx];
   while(walk)
   {
      if(walk->objectName == name)
      {
         Mutex::unlockMutex(mutex);
         return walk;
      }
      walk = walk->nextNameObject;
   }

   Mutex::unlockMutex(mutex);
   return NULL;
}

void SimNameDictionary::remove(SimObject* obj)
{
   if(!obj->objectName)
      return;

   Mutex::lockMutex(mutex);

   SimObject **walk = &hashTable[HashPointer(obj->objectName) % hashTableSize];
   while(*walk)
   {
      if(*walk == obj)
      {
         *walk = obj->nextNameObject;
			obj->nextNameObject = (SimObject*)-1;
         hashEntryCount--;

         Mutex::unlockMutex(mutex);
         return;
      }
      walk = &((*walk)->nextNameObject);
   }

   Mutex::unlockMutex(mutex);
}

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

SimManagerNameDictionary::SimManagerNameDictionary()
{
   hashTable = new SimObject *[DefaultTableSize];
   hashTableSize = DefaultTableSize;
   hashEntryCount = 0;
   S32 i;
   for(i = 0; i < hashTableSize; i++)
      hashTable[i] = NULL;
   mutex = Mutex::createMutex();
}

SimManagerNameDictionary::~SimManagerNameDictionary()
{
   delete[] hashTable;
   Mutex::destroyMutex(mutex);
}

void SimManagerNameDictionary::insert(SimObject* obj)
{
   if(!obj->objectName)
      return;

   Mutex::lockMutex(mutex);

   S32 idx = HashPointer(obj->objectName) % hashTableSize;
   obj->nextManagerNameObject = hashTable[idx];
   hashTable[idx] = obj;
   hashEntryCount++;
   if(hashEntryCount > hashTableSize)
   {
      // resize the hash table
      S32 i;
      SimObject *head = NULL, *walk, *temp;
   	for(i = 0; i < hashTableSize; i++) {
   		walk = hashTable[i];
         while(walk)
         {
            temp = walk->nextManagerNameObject;
            walk->nextManagerNameObject = head;
            head = walk;
            walk = temp;
         }
   	}
      delete[] hashTable;
      hashTableSize = hashTableSize * 2 + 1;
      hashTable = new SimObject *[hashTableSize];

      for(i = 0; i < hashTableSize;i++)
         hashTable[i] = NULL;
      while(head)
      {
         temp = head->nextManagerNameObject;
         idx = HashPointer(head->objectName) % hashTableSize;
         head->nextManagerNameObject = hashTable[idx];
         hashTable[idx] = head;
         head = temp;
      }
   }

   Mutex::unlockMutex(mutex);
}

SimObject* SimManagerNameDictionary::find(StringTableEntry name)
{
   // NULL is a valid lookup - it will always return NULL

   Mutex::lockMutex(mutex);

   S32 idx = HashPointer(name) % hashTableSize;
   SimObject *walk = hashTable[idx];
   while(walk)
   {
      if(walk->objectName == name)
      {
         Mutex::unlockMutex(mutex);
         return walk;
      }
      walk = walk->nextManagerNameObject;
   }

   Mutex::unlockMutex(mutex);
   return NULL;
}

void SimManagerNameDictionary::remove(SimObject* obj)
{
   if(!obj->objectName)
      return;

   Mutex::lockMutex(mutex);

   SimObject **walk = &hashTable[HashPointer(obj->objectName) % hashTableSize];
   while(*walk)
   {
      if(*walk == obj)
      {
         *walk = obj->nextManagerNameObject;
			obj->nextManagerNameObject = (SimObject*)-1;
         hashEntryCount--;

         Mutex::unlockMutex(mutex);
         return;
      }
      walk = &((*walk)->nextManagerNameObject);
   }

   Mutex::unlockMutex(mutex);
}

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

SimIdDictionary::SimIdDictionary()
{
   for(S32 i = 0; i < DefaultTableSize; i++)
      table[i] = NULL;
   mutex = Mutex::createMutex();
}

SimIdDictionary::~SimIdDictionary()
{
   Mutex::destroyMutex(mutex);
}

void SimIdDictionary::insert(SimObject* obj)
{
   Mutex::lockMutex(mutex);

   S32 idx = obj->getId() & TableBitMask;
   obj->nextIdObject = table[idx];
   AssertFatal( obj->nextIdObject != obj, "SimIdDictionary::insert - Creating Infinite Loop linking to self!" );
   table[idx] = obj;

   Mutex::unlockMutex(mutex);
}

SimObject* SimIdDictionary::find(S32 id)
{
   Mutex::lockMutex(mutex);

   S32 idx = id & TableBitMask;
   SimObject *walk = table[idx];
   while(walk)
   {
      if(walk->getId() == U32(id))
      {
         Mutex::unlockMutex(mutex);
         return walk;
      }
      walk = walk->nextIdObject;
   }

   Mutex::unlockMutex(mutex);

   return NULL;
}

void SimIdDictionary::remove(SimObject* obj)
{
   Mutex::lockMutex(mutex);

   SimObject **walk = &table[obj->getId() & TableBitMask];
   while(*walk && *walk != obj)
      walk = &((*walk)->nextIdObject);
   if(*walk)
      *walk = obj->nextIdObject;

   Mutex::unlockMutex(mutex);
}

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


text:
package com.sun.jini.thread;

import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.jini.constants.TimeConstants;

/**
 * An abstract class for building tasks that retry on failure after a
 * timeout period.  This builds upon TaskManager for task
 * execution and WakeupManager for retry scheduling.  You
 * extend RetryTask, implementing tryOnce to
 * represent a single attempt at the task.  If tryOnce
 * returns true, the attempt was successful and the task
 * is complete.  If tryOnce returns false,
 * the task is scheduled for a future retry using WakeupManager.
 *

 * The default retry times are defined by this class's implementation
 * of retryTime.  You can override this method to
 * change the retry times.
 *

 * It is legal to reuse the same task again and again, but only after
 * the task is complete and reset has been called.
 * Inserting the same task multiple times before it has either been
 * cancelled or completed successfully will generate unpredictable
 * behavior.

 *
 * This class uses the {@link Logger} named
 * com.sun.jini.thread.RetryTask to log information at
 * the following logging levels:

 *
 *

 *
 *
  Level  Description
 *
 *
  FINEST  after a failed attempt, when should
 *                       the task be scheduled for a re-try
 *
 *

 *
 * @author Sun Microsystems, Inc.
 *
 * @see TaskManager
 * @see WakeupManager
 */
import com.sun.jini.thread.WakeupManager.Ticket;

public abstract class RetryTask implements TaskManager.Task, TimeConstants {
    private TaskManager	  manager;	// the TaskManager for this task
    private RetryTime	  retry;	// the retry object for this task
    private boolean	  cancelled;	// have we been cancelled?
    private boolean	  complete;	// have we completed successfully?
    private Ticket	  ticket;	// the WakeupManager ticket
    private long	  startTime;	// the time when we were created or
                                        //   last reset
    private int		  attempt;	// the current attempt number
    private WakeupManager wakeup;       // WakeupManager for retry scheduling

    /**
     * Default delay backoff times.  These are converted from
     * intervals to "time since start" by the static block below.
     *
     * @see #retryTime
     */
    private static final long[] delays = {
	 0, // First value is never read
	 1 * SECONDS,
	 5 * SECONDS,
	10 * SECONDS,
	 1 * MINUTES,
	 1 * MINUTES,
	 5 * MINUTES,
    };

    /** Logger for this class */
    private static final Logger logger =
	Logger.getLogger("com.sun.jini.thread.RetryTask");

    /**
     * Create a new RetryTask that will be scheduled with
     * the given task manager, and which will perform retry scheduling
     * using the given wakeup manager.
     */
    public RetryTask(TaskManager manager, WakeupManager wakeupManager) {
	this.manager = manager;
        this.wakeup = wakeupManager;
	reset();
    }

    /**
     * Make a single attempt.  Return true if the attempt
     * was successful.  If the attempt is not successful, the task
     * will be scheduled for a future retry.
     */
    public abstract boolean tryOnce();

    /**
     * The run method used as a
     * TaskManager.Task.  This invokes
     * tryOnce.  If it is not successful, it schedules
     * the task for a future retry at the time it gets by invoking
     * retryTime.
     *
     * @see #tryOnce
     * @see #startTime
     */
    public void run() {
	synchronized (this) {		// avoid retry if cancelled
	    if (cancelled)		// if they cancelled
		return;			// do nothing
	}

	boolean success = tryOnce();

	synchronized (this) {
	    if (!success) {		// if at first we don't succeed ...
		attempt++;
		long at = retryTime();	// ... try, try again

		if (logger.isLoggable(Level.FINEST)) {
		    logger.log(Level.FINEST, "retry of {0} in {1} ms",
		        new Object[]{this,
			    new Long(at - System.currentTimeMillis())});
		}

		if (retry == null)	// only create it if we need to
		    retry = new RetryTime();
		ticket = wakeup.schedule(at, retry);
	    } else {
		complete = true;
		notifyAll();		// see waitFor()
	    }
	}
    }

    /**
     * Return the next time at which we should make another attempt.
     * This is not an interval, but the actual time.
     *

     * The implementation is free to do as it pleases with the policy
     * here.  The default implementation is to delay using intervals of
     * 1 second, 5 seconds, 10 seconds, 1 minute, and 1 minute between
     * attempts, and then retrying every five minutes forever.
     *

     * The default implementation assumes it is being called from
     * the default run method and that the current thread
     * holds the lock on this object. If the caller does
     * not own the lock the result is undefined and could result in an
     * exception.
     */
    public long retryTime() {
	assert Thread.holdsLock(this): "thread does not hold lock";
	int index = (attempt < delays.length ? attempt : delays.length - 1);
	return delays[index] + System.currentTimeMillis();
    }

    /**
     * Return the time this task was created, or the last
     * time {@link #reset reset} was called.
     */
    public synchronized long startTime() {
	return startTime;
    }

    /**
     * Return the attempt number, starting with zero.
     */
    public synchronized int attempt() {
	return attempt;
    }

    /**
     * Cancel the retrying of the task.  This ensures that there will be
     * no further attempts to invoke tryOnce.  It will not
     * interfere with any ongoing invocation of tryOnce
     * unless a subclass overrides this to do so.  Any override of this
     * method should invoke super.cancel().
     */
    public synchronized void cancel() {
	cancelled = true;
	if (ticket != null)
	    wakeup.cancel(ticket);
	notifyAll();		// see waitFor()
    }

    /**
     * Return true if cancel has been invoked.
     */
    public synchronized boolean cancelled() {
	return cancelled;
    }

    /**
     * Return true if tryOnce has returned
     * successfully.
     */
    public synchronized boolean complete() {
	return complete;
    }

    public synchronized boolean waitFor() throws InterruptedException {
	while (!cancelled && !complete)
	    wait();
	return complete;
    }

    /**
     * Reset values for a new use of this task.
     */
    public synchronized void reset() {
	cancel();		// remove from the wakeup queue
	startTime = System.currentTimeMillis();
	cancelled = false;
	complete = false;
	ticket = null;
	attempt = 0;
    }

    /**
     * This is the runnable class for the WakeupManager,
     * since we need different implementations of
     * WakeupManager.run and
     * TaskManager.run.
     */
    private class RetryTime implements Runnable {
	/**
	 * Time to retry the task.
	 */
	public void run() {
	    synchronized (RetryTask.this) {
		ticket = null;
	    }
	    manager.add(RetryTask.this);
	}
    };
}


text:
package org.apereo.cas.config;

import org.apereo.cas.adaptors.redis.services.RedisServiceRegistryDao;
import org.apereo.cas.adaptors.redis.services.RegisteredServiceRedisTemplate;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.model.support.redis.RedisServiceRegistryProperties;
import org.apereo.cas.redis.core.RedisObjectFactory;
import org.apereo.cas.services.ServiceRegistryDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * This is {@link RedisServiceRegistryConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@Configuration("redisServiceRegistryConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class RedisServiceRegistryConfiguration {

    @Autowired
    private CasConfigurationProperties casProperties;

    @Bean
    @RefreshScope
    public RedisConnectionFactory redisConnectionFactory() {
        final RedisServiceRegistryProperties redis = casProperties.getServiceRegistry().getRedis();
        final RedisObjectFactory obj = new RedisObjectFactory();
        return obj.newRedisConnectionFactory(redis);
    }

    @Bean
    @RefreshScope
    public RedisTemplate registeredServiceRedisTemplate() {
        return new RegisteredServiceRedisTemplate(redisConnectionFactory());
    }

    @Bean
    @RefreshScope
    public ServiceRegistryDao serviceRegistryDao() {
        return new RedisServiceRegistryDao(registeredServiceRedisTemplate());
    }
}


text:
package com.poloniumarts.chartdemo;

import com.polonium.linechart.Line;
import com.polonium.linechart.LineChartView;
import com.polonium.linechart.LinePoint;
import com.poloniumarts.chartdemo.DefaultChartFragment.OnFragmentInteractionListener;

import android.app.Activity;
import android.graphics.DashPathEffect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class SmoothLinesChartFragment extends Fragment {

    private OnFragmentInteractionListener mListener;
    private LineChartView chart;
    private String title;

    public static SmoothLinesChartFragment newInstance(String title) {
        SmoothLinesChartFragment fragment = new SmoothLinesChartFragment();
        fragment.title = title;
        return fragment;
    }

    public SmoothLinesChartFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getActivity().getActionBar().setTitle(title);
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        ((TextView) view.findViewById(R.id.description)).setText(R.string.description_smooth);

        chart = (LineChartView) view.findViewById(R.id.chart);
        chart.setViewPort(0, 0, 100, 160);
        chart.setGridSize(10, 0, 20, 0);
        chart.addLine(generateLine(0, 360, 5, 10, 50).setFilled(true).smoothLine(4));
        chart.addLine(generateLine(0, 360, 5, 60, 90).setColor(0xffff8800).smoothLine(1));
        chart.addLine(generateLine(0, 360, 5, 100, 150).setColor(0xff669900).smoothLine(8));
        setHasOptionsMenu(true);
        return view;
    }

    private Line generateLine(int startX, int endX, int step, int minY, int maxY) {
        Line line = new Line(getActivity());
        for (int i = startX; i <= endX; i += step) {
            line.addPoint(new LinePoint(getActivity(), i, (int) (Math.random() * (maxY - minY) + minY)));
        }
        return line;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

}


text:
namespace stats
{
  struct GeneralInfo
  {
    GeneralInfo() : m_count(0), m_size(0), m_names(0), m_length(0), m_area(0) {}

    void Add(uint64_t szBytes, double len = 0, double area = 0, bool hasName = false)
    {
      if (szBytes > 0)
      {
        ++m_count;
        m_size += szBytes;
        m_length += len;
        m_area += area;
        if (hasName)
          ++m_names;
      }
    }

    uint64_t m_count;
    uint64_t m_size;
    uint64_t m_names;
    double m_length;
    double m_area;
  };

  template <class T, int Tag>
  struct IntegralType
  {
    T m_val;
    explicit IntegralType(T v) : m_val(v) {}
    bool operator<(IntegralType const & rhs) const { return m_val < rhs.m_val; }
  };

  using ClassifType = IntegralType<uint32_t, 0>;
  using CountType = IntegralType<uint32_t, 1>;
  using AreaType = IntegralType<size_t, 2>;

  struct MapInfo
  {
    std::map<feature::GeomType, GeneralInfo> m_byGeomType;
    std::map<ClassifType, GeneralInfo> m_byClassifType;
    std::map<CountType, GeneralInfo> m_byPointsCount, m_byTrgCount;
    std::map<AreaType, GeneralInfo> m_byAreaSize;

    GeneralInfo m_inner[3];
  };

  void FileContainerStatistic(std::string const & fPath);

  void CalcStatistic(std::string const & fPath, MapInfo & info);
  void PrintStatistic(MapInfo & info);
  void PrintTypeStatistic(MapInfo & info);
}


text:
interface AnyObject {[k: string]: any}

interface Command {
	(this: typeof MessageParser.globalContext, target: string, room: typeof Rooms.globalRoom | typeof Users.self, user: typeof Users.self, cmd?: string, time?: number): void;
}


text:
<?php

namespace user\manager;

class ValidationRuleManager{

	protected $username = array(
		'field' => 'username',
		'label' => 'Username',
		'rules' => 'trim|required|alpha_numeric|valid_username|unique_username'
	);

	protected $password = array(
		'field' => 'password',
		'label' => 'Password',
		'rules' => 'trim|required'
	);

	protected $confPassword=	array(
		'field' => 'confPassword',
		'label' => 'Confirm Password',
		'rules' => 'trim|required|matches[password]'
	);

	protected $email = array(
		'field' => 'email',
		'label' => 'Email Address',
		'rules' => 'trim|required|valid_email|unique_email'
	);

	protected $firstname = array(
		'field' => 'firstname',
		'label' => 'First Name',
		'rules' => 'trim|required'
	);

	protected $lastname = array(
		'field' => 'lastname',
		'label' => 'Last Name',
		'rules' => 'trim|required'
	);

	protected $dateOfBirth = array(
		'field' => 'dateOfBirth',
		'label' => 'Date of Birth',
		'rules' => 'trim'
	);

	protected $gender = array(
		'field' => 'gender',
		'label' => 'Gender',
		'rules' => 'trim|required'
	);

	protected $phoneNumber = array(
		'field' => 'phoneNumber',
		'label' => 'Phone Number',
		'rules' => 'trim'
	);

	protected $mobileNumber = array(
		'field' => 'mobileNumber',
		'label' => 'Mobile Number',
		'rules' => 'trim'
	);

	protected $address = array(
		'field' => 'address',
		'label' => 'Address',
		'rules' => 'trim'
	);

	protected $biography = array(
		'field' => 'biography',
		'label' => 'Biography',
		'rules' => 'trim'
	);

	protected $website = array(
		'field' => 'website',
		'label' => 'Website',
		'rules' => 'trim|valid_url'
	);

	protected $facebookId = array(
		'field' => 'facebookId',
		'label' => 'Facbook URL',
		'rules' => 'trim|valid_url'
	);

	protected $gplusId = array(
		'field' => 'gplusId',
		'label' => 'Google Plus URL',
		'rules' => 'trim|valid_url'
	);

	protected $twitterId = array(
		'field' => 'twiiterId',
		'label' => 'Twitter URL',
		'rules' => 'trim|valid_url'
	);

	protected $group =	array(
		'field' => 'group',
		'label' => 'Group',
		'rules' => 'trim|required|valid_user_group'
	);

	public function getRules($array)
	{
		$rules = array();
		foreach($array as $key)
		{
			$rules[] = $this->$key;
		}
		return $rules;
	}

	function getAllRules()
	{
		$classProps = get_class_vars(__class__);
		$rules = array();

		foreach ($classProps as $key => $value) {
			$rules[] = $this->$key;
		}
		return $rules;
	}
}


text:
void initialize() {
    mfp_register("Hello World!");
}


text:
package org.dynmap.storage.mysql;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.dynmap.DynmapCore;
import org.dynmap.DynmapWorld;
import org.dynmap.Log;
import org.dynmap.MapType;
import org.dynmap.WebAuthManager;
import org.dynmap.MapType.ImageVariant;
import org.dynmap.PlayerFaces.FaceType;
import org.dynmap.storage.MapStorage;
import org.dynmap.storage.MapStorageTile;
import org.dynmap.storage.MapStorageTileEnumCB;
import org.dynmap.utils.BufferInputStream;
import org.dynmap.utils.BufferOutputStream;

public class MySQLMapStorage extends MapStorage {
    private String connectionString;
    private String userid;
    private String password;
    private String database;
    private String hostname;
    private String prefix = "";
    private String tableTiles;
    private String tableMaps;
    private String tableFaces;
    private String tableMarkerIcons;
    private String tableMarkerFiles;
    private String tableStandaloneFiles;
    private String tableSchemaVersion;

    private int port;
    private static final int POOLSIZE = 5;
    private Connection[] cpool = new Connection[POOLSIZE];
    private int cpoolCount = 0;
    private static final Charset UTF8 = Charset.forName("UTF-8");

    public class StorageTile extends MapStorageTile {
        private Integer mapkey;
        private String uri;
        protected StorageTile(DynmapWorld world, MapType map, int x, int y,
                int zoom, ImageVariant var) {
            super(world, map, x, y, zoom, var);

            mapkey = getMapKey(world, map, var);

            if (zoom > 0) {
                uri = map.getPrefix() + var.variantSuffix + "/"+ (x >> 5) + "_" + (y >> 5) + "/" + "zzzzzzzzzzzzzzzz".substring(0, zoom) + "_" + x + "_" + y + "." + map.getImageFormat().getFileExt();
            }
            else {
                uri = map.getPrefix() + var.variantSuffix + "/"+ (x >> 5) + "_" + (y >> 5) + "/" + x + "_" + y + "." + map.getImageFormat().getFileExt();
            }
        }

        @Override
        public boolean exists() {
            if (mapkey == null) return false;
            boolean rslt = false;
            Connection c = null;
            boolean err = false;
            try {
                c = getConnection();
                Statement stmt = c.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT HashCode FROM " + tableTiles + " WHERE MapID=" + mapkey + " AND x=" + x + " AND y=" + y + " AND zoom=" + zoom + ";");
                rslt = rs.next();
                rs.close();
                stmt.close();
            } catch (SQLException x) {
                Log.severe("Tile exists error - " + x.getMessage());
                err = true;
            } finally {
                releaseConnection(c, err);
            }
            return rslt;
        }

        @Override
        public boolean matchesHashCode(long hash) {
            if (mapkey == null) return false;
            boolean rslt = false;
            Connection c = null;
            boolean err = false;
            try {
                c = getConnection();
                Statement stmt = c.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT HashCode FROM " + tableTiles + " WHERE MapID=" + mapkey + " AND x=" + x + " AND y=" + y + " AND zoom=" + zoom + ";");
                if (rs.next()) {
                    long v = rs.getLong("HashCode");
                    rslt = (v == hash);
                }
                rs.close();
                stmt.close();
            } catch (SQLException x) {
                Log.severe("Tile matches hash error - " + x.getMessage());
                err = true;
            } finally {
                releaseConnection(c, err);
            }
            return rslt;
        }

        @Override
        public TileRead read() {
            if (mapkey == null) return null;
            TileRead rslt = null;
            Connection c = null;
            boolean err = false;
            try {
                c = getConnection();
                Statement stmt = c.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT HashCode,LastUpdate,Format,Image FROM " + tableTiles + " WHERE MapID=" + mapkey + " AND x=" + x + " AND y=" + y + " AND zoom=" + zoom + ";");
                if (rs.next()) {
                    rslt = new TileRead();
                    rslt.hashCode = rs.getLong("HashCode");
                    rslt.lastModified = rs.getLong("LastUpdate");
                    rslt.format = MapType.ImageEncoding.fromOrd(rs.getInt("Format"));
                    byte[] img = rs.getBytes("Image");
                    rslt.image = new BufferInputStream(img);
                }
                rs.close();
                stmt.close();
            } catch (SQLException x) {
                Log.severe("Tile read error - " + x.getMessage());
                err = true;
            } finally {
                releaseConnection(c, err);
            }
            return rslt;
        }

        @Override
        public boolean write(long hash, BufferOutputStream encImage) {
            if (mapkey == null) return false;
            Connection c = null;
            boolean err = false;
            boolean exists = exists();
            // If delete, and doesn't exist, quit
            if ((encImage == null) && (!exists)) return false;

            try {
                c = getConnection();
                PreparedStatement stmt;
                if (encImage == null) { // If delete
                    stmt = c.prepareStatement("DELETE FROM " + tableTiles + " WHERE MapID=? AND x=? and y=? AND zoom=?;");
                    stmt.setInt(1, mapkey);
                    stmt.setInt(2, x);
                    stmt.setInt(3, y);
                    stmt.setInt(4, zoom);
                }
                else if (exists) {
                    stmt = c.prepareStatement("UPDATE " + tableTiles + " SET HashCode=?, LastUpdate=?, Format=?, Image=? WHERE MapID=? AND x=? and y=? AND zoom=?;");
                    stmt.setLong(1, hash);
                    stmt.setLong(2, System.currentTimeMillis());
                    stmt.setInt(3, map.getImageFormat().getEncoding().ordinal());
                    stmt.setBinaryStream(4, new BufferInputStream(encImage.buf, encImage.len), encImage.len);
                    stmt.setInt(5, mapkey);
                    stmt.setInt(6, x);
                    stmt.setInt(7, y);
                    stmt.setInt(8, zoom);
                }
                else {
                    stmt = c.prepareStatement("INSERT INTO " + tableTiles + " (MapID,x,y,zoom,HashCode,LastUpdate,Format,Image) VALUES (?,?,?,?,?,?,?,?);");
                    stmt.setInt(1, mapkey);
                    stmt.setInt(2, x);
                    stmt.setInt(3, y);
                    stmt.setInt(4, zoom);
                    stmt.setLong(5, hash);
                    stmt.setLong(6, System.currentTimeMillis());
                    stmt.setInt(7, map.getImageFormat().getEncoding().ordinal());
                    stmt.setBinaryStream(8, new BufferInputStream(encImage.buf, encImage.len), encImage.len);
               }
                stmt.executeUpdate();
                stmt.close();
                // Signal update for zoom out
                if (zoom == 0) {
                    world.enqueueZoomOutUpdate(this);
                }
            } catch (SQLException x) {
                Log.severe("Tile write error - " + x.getMessage());
                err = true;
            } finally {
                releaseConnection(c, err);
            }
            return !err;
        }

        @Override
        public boolean getWriteLock() {
            return MySQLMapStorage.this.getWriteLock(uri);
        }

        @Override
        public void releaseWriteLock() {
            MySQLMapStorage.this.releaseWriteLock(uri);
        }

        @Override
        public boolean getReadLock(long timeout) {
            return MySQLMapStorage.this.getReadLock(uri, timeout);
        }

        @Override
        public void releaseReadLock() {
            MySQLMapStorage.this.releaseReadLock(uri);
        }

        @Override
        public void cleanup() {
        }

        @Override
        public String getURI() {
            return uri;
        }

        @Override
        public void enqueueZoomOutUpdate() {
            world.enqueueZoomOutUpdate(this);
        }

        @Override
        public MapStorageTile getZoomOutTile() {
            int xx, yy;
            int step = 1 << zoom;
            if(x >= 0)
                xx = x - (x % (2*step));
            else
                xx = x + (x % (2*step));
            yy = -y;
            if(yy >= 0)
                yy = yy - (yy % (2*step));
            else
                yy = yy + (yy % (2*step));
            yy = -yy;
            return new StorageTile(world, map, xx, yy, zoom+1, var);
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof StorageTile) {
                StorageTile st = (StorageTile) o;
                return uri.equals(st.uri);
            }
            return false;
        }

        @Override
        public int hashCode() {
            return uri.hashCode();
        }
    }

    public MySQLMapStorage() {
    }

    @Override
    public boolean init(DynmapCore core) {
        if (!super.init(core)) {
            return false;
        }
        database = core.configuration.getString("storage/database", "dynmap");
        hostname = core.configuration.getString("storage/hostname", "localhost");
        port = core.configuration.getInteger("storage/port", 3306);
        userid = core.configuration.getString("storage/userid", "dynmap");
        password = core.configuration.getString("storage/password", "dynmap");
        prefix = core.configuration.getString("storage/prefix", "");
        tableTiles = prefix + "Tiles";
        tableMaps = prefix + "Maps";
        tableFaces = prefix + "Faces";
        tableMarkerIcons = prefix + "MarkerIcons";
        tableMarkerFiles = prefix + "MarkerFiles";
        tableStandaloneFiles = prefix + "StandaloneFiles";
        tableSchemaVersion = prefix + "SchemaVersion";

        connectionString = "jdbc:mysql://" + hostname + ":" + port + "/" + database;
        Log.info("Opening MySQL database " + hostname + ":" + port + "/" + database + " as map store");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // Initialize/update tables, if needed
            if(!initializeTables()) {
                return false;
            }
        } catch (ClassNotFoundException cnfx) {
            Log.severe("MySQL-JDBC classes not found - MySQL data source not usable");
            return false;
        }
        return writeConfigPHP(core);
    }

    private boolean writeConfigPHP(DynmapCore core) {
        FileWriter fw = null;
        try {
            fw = new FileWriter(new File(baseStandaloneDir, "MySQL_config.php"));
            fw.write("<?php\n$dbname = \'");
            fw.write(WebAuthManager.esc(database));
            fw.write("\';\n");
            fw.write("$dbhost = \'");
            fw.write(WebAuthManager.esc(hostname));
            fw.write("\';\n");
            fw.write("$dbport = ");
            fw.write(Integer.toString(port));
            fw.write(";\n");
            fw.write("$dbuserid = \'");
            fw.write(WebAuthManager.esc(userid));
            fw.write("\';\n");
            fw.write("$dbpassword = \'");
            fw.write(WebAuthManager.esc(password));
            fw.write("\';\n");
            fw.write("$dbprefix = \'");
            fw.write(WebAuthManager.esc(prefix));
            fw.write("\';\n");
            fw.write("$loginenabled = ");
            fw.write(core.isLoginSupportEnabled()?"true;\n":"false;\n");
            fw.write("?>\n");
        } catch (IOException iox) {
            Log.severe("Error writing MySQL_config.php", iox);
            return false;
        } finally {
            if (fw != null) {
                try { fw.close(); } catch (IOException x) {}
            }
        }
        return true;
    }
    private int getSchemaVersion() {
        int ver = 0;
        boolean err = false;
        Connection c = null;
        try {
            c = getConnection();    // Get connection (create DB if needed)
            Statement stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery( "SELECT level FROM " + tableSchemaVersion + ";");
            if (rs.next()) {
                ver = rs.getInt("level");
            }
            rs.close();
            stmt.close();
        } catch (SQLException x) {
            err = true;
        } finally {
            if (c != null) { releaseConnection(c, err); }
        }
        return ver;
    }

    private void doUpdate(Connection c, String sql) throws SQLException {
        Statement stmt = c.createStatement();
        stmt.executeUpdate(sql);
        stmt.close();
    }

    private HashMap<String, Integer> mapKey = new HashMap<String, Integer>();

    private void doLoadMaps() {
        Connection c = null;
        boolean err = false;

        mapKey.clear();
        // Read the maps table - cache results
        try {
            c = getConnection();
            Statement stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * from " + tableMaps + ";");
            while (rs.next()) {
                int key = rs.getInt("ID");
                String worldID = rs.getString("WorldID");
                String mapID = rs.getString("MapID");
                String variant = rs.getString("Variant");
                long serverid = rs.getLong("ServerID");
                if (serverid == serverID) { // One of ours
                    mapKey.put(worldID + ":" + mapID + ":" + variant, key);
                }
            }
            rs.close();
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Error loading map table - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
            c = null;
        }
    }

    private Integer getMapKey(DynmapWorld w, MapType mt, ImageVariant var) {
        String id = w.getName() + ":" + mt.getPrefix() + ":" + var.toString();
        synchronized(mapKey) {
            Integer k = mapKey.get(id);
            if (k == null) {    // No hit: new value so we need to add it to table
                Connection c = null;
                boolean err = false;
                try {
                    c = getConnection();
                    // Insert row
                    PreparedStatement stmt = c.prepareStatement("INSERT INTO " + tableMaps + " (WorldID,MapID,Variant,ServerID) VALUES (?, ?, ?, ?);");
                    stmt.setString(1, w.getName());
                    stmt.setString(2, mt.getPrefix());
                    stmt.setString(3, var.toString());
                    stmt.setLong(4, serverID);
                    stmt.executeUpdate();
                    stmt.close();
                    //  Query key assigned
                    stmt = c.prepareStatement("SELECT ID FROM " + tableMaps + " WHERE WorldID = ? AND MapID = ? AND Variant = ? AND ServerID = ?;");
                    stmt.setString(1, w.getName());
                    stmt.setString(2, mt.getPrefix());
                    stmt.setString(3, var.toString());
                    stmt.setLong(4, serverID);
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next()) {
                        k = rs.getInt("ID");
                        mapKey.put(id, k);
                    }
                    rs.close();
                    stmt.close();
                } catch (SQLException x) {
                    Log.severe("Error updating Maps table - " + x.getMessage());
                    err = true;
                } finally {
                    releaseConnection(c, err);
                }
            }

            return k;
        }
    }

    private boolean initializeTables() {
        Connection c = null;
        boolean err = false;
        int version = getSchemaVersion();   // Get the existing schema version for the DB (if any)
        // If new, add our tables
        if (version == 0) {
            try {
                c = getConnection();
                doUpdate(c, "CREATE TABLE " + tableMaps + " (ID INTEGER PRIMARY KEY AUTO_INCREMENT, WorldID VARCHAR(64) NOT NULL, MapID VARCHAR(64) NOT NULL, Variant VARCHAR(16) NOT NULL, ServerID BIGINT NOT NULL DEFAULT 0)");
                doUpdate(c, "CREATE TABLE " + tableTiles + " (MapID INT NOT NULL, x INT NOT NULL, y INT NOT NULL, zoom INT NOT NULL, HashCode BIGINT NOT NULL, LastUpdate BIGINT NOT NULL, Format INT NOT NULL, Image BLOB, PRIMARY KEY(MapID, x, y, zoom))");
                doUpdate(c, "CREATE TABLE " + tableFaces + " (PlayerName VARCHAR(64) NOT NULL, TypeID INT NOT NULL, Image BLOB, PRIMARY KEY(PlayerName, TypeID))");
                doUpdate(c, "CREATE TABLE " + tableMarkerIcons + " (IconName VARCHAR(128) PRIMARY KEY NOT NULL, Image BLOB)");
                doUpdate(c, "CREATE TABLE " + tableMarkerFiles + " (FileName VARCHAR(128) PRIMARY KEY NOT NULL, Content MEDIUMTEXT)");
                doUpdate(c, "CREATE TABLE " + tableStandaloneFiles + " (FileName VARCHAR(128) NOT NULL, ServerID BIGINT NOT NULL DEFAULT 0, Content MEDIUMTEXT, PRIMARY KEY (FileName, ServerID))");
                doUpdate(c, "CREATE TABLE " + tableSchemaVersion + " (level INT PRIMARY KEY NOT NULL)");
                doUpdate(c, "INSERT INTO " + tableSchemaVersion + " (level) VALUES (3)");
            } catch (SQLException x) {
                Log.severe("Error creating tables - " + x.getMessage());
                err = true;
                return false;
            } finally {
                releaseConnection(c, err);
                c = null;
            }
        }
        else if (version == 1) {
            try {
                c = getConnection();
                doUpdate(c, "CREATE TABLE " + tableStandaloneFiles + " (FileName VARCHAR(128) NOT NULL, ServerID BIGINT NOT NULL DEFAULT 0, Content MEDIUMTEXT, PRIMARY KEY (FileName, ServerID))");
                doUpdate(c, "ALTER TABLE " + tableMaps + " ADD COLUMN ServerID BIGINT NOT NULL DEFAULT 0 AFTER Variant");
                doUpdate(c, "UPDATE " + tableSchemaVersion + " SET level=3 WHERE level = 1;");
            } catch (SQLException x) {
                Log.severe("Error creating tables - " + x.getMessage());
                err = true;
                return false;
            } finally {
                releaseConnection(c, err);
                c = null;
            }
        }
        else if (version == 2) {
            try {
                c = getConnection();
                doUpdate(c, "DELETE FROM " + tableStandaloneFiles + ";");
                doUpdate(c, "ALTER TABLE " + tableStandaloneFiles + " DROP COLUMN Content;");
                doUpdate(c, "ALTER TABLE " + tableStandaloneFiles + " ADD COLUMN Content MEDIUMTEXT;");
                doUpdate(c, "UPDATE " + tableSchemaVersion + " SET level=3 WHERE level = 2;");
            } catch (SQLException x) {
                Log.severe("Error creating tables - " + x.getMessage());
                err = true;
                return false;
            } finally {
                releaseConnection(c, err);
                c = null;
            }
        }
        // Load maps table - cache results
        doLoadMaps();

        return true;
    }

    private Connection getConnection() throws SQLException {
        Connection c = null;
        synchronized (cpool) {
            while (c == null) {
                for (int i = 0; i < cpool.length; i++) {    // See if available connection
                    if (cpool[i] != null) { // Found one
                        c = cpool[i];
                        cpool[i] = null;
                        break;
                    }
                }
                if (c == null) {
                    if (cpoolCount < POOLSIZE) {  // Still more we can have
                        c = DriverManager.getConnection(connectionString, userid, password);
                        configureConnection(c);
                        cpoolCount++;
                    }
                    else {
                        try {
                            cpool.wait();
                        } catch (InterruptedException e) {
                            throw new SQLException("Interruped");
                        }
                    }
                }
            }
        }
        return c;
    }

    private static Connection configureConnection(Connection conn) throws SQLException {
        return conn;
    }

    private void releaseConnection(Connection c, boolean err) {
        if (c == null) return;
        synchronized (cpool) {
            if (!err)  {  // Find slot to keep it in pool
                for (int i = 0; i < POOLSIZE; i++) {
                    if (cpool[i] == null) {
                        cpool[i] = c;
                        c = null; // Mark it recovered (no close needed
                        cpool.notifyAll();
                        break;
                    }
                }
            }
            if (c != null) {  // If broken, just toss it
                try { c.close(); } catch (SQLException x) {}
                cpoolCount--;   // And reduce count
                cpool.notifyAll();
            }
        }
    }

    @Override
    public MapStorageTile getTile(DynmapWorld world, MapType map, int x, int y,
            int zoom, ImageVariant var) {
        return new StorageTile(world, map, x, y, zoom, var);
    }

    @Override
    public MapStorageTile getTile(DynmapWorld world, String uri) {
        String[] suri = uri.split("/");
        if (suri.length < 2) return null;
        String mname = suri[0]; // Map URI - might include variant
        MapType mt = null;
        ImageVariant imgvar = null;
        // Find matching map type and image variant
        for (int mti = 0; (mt == null) && (mti < world.maps.size()); mti++) {
            MapType type = world.maps.get(mti);
            ImageVariant[] var = type.getVariants();
            for (int ivi = 0; (imgvar == null) && (ivi < var.length); ivi++) {
                if (mname.equals(type.getPrefix() + var[ivi].variantSuffix)) {
                    mt = type;
                    imgvar = var[ivi];
                }
            }
        }
        if (mt == null) {   // Not found?
            return null;
        }
        // Now, take the last section and parse out coordinates and zoom
        String fname = suri[suri.length-1];
        String[] coord = fname.split("[_\\.]");
        if (coord.length < 3) { // 3 or 4
            return null;
        }
        int zoom = 0;
        int x, y;
        try {
            if (coord[0].charAt(0) == 'z') {
                zoom = coord[0].length();
                x = Integer.parseInt(coord[1]);
                y = Integer.parseInt(coord[2]);
            }
            else {
                x = Integer.parseInt(coord[0]);
                y = Integer.parseInt(coord[1]);
            }
            return getTile(world, mt, x, y, zoom, imgvar);
        } catch (NumberFormatException nfx) {
            return null;
        }
    }

    @Override
    public void enumMapTiles(DynmapWorld world, MapType map,
            MapStorageTileEnumCB cb) {
        List<MapType> mtlist;

        if (map != null) {
            mtlist = Collections.singletonList(map);
        }
        else {  // Else, add all directories under world directory (for maps)
            mtlist = new ArrayList<MapType>(world.maps);
        }
        for (MapType mt : mtlist) {
            ImageVariant[] vars = mt.getVariants();
            for (ImageVariant var : vars) {
                processEnumMapTiles(world, mt, var, cb);
            }
        }
    }
    private void processEnumMapTiles(DynmapWorld world, MapType map, ImageVariant var, MapStorageTileEnumCB cb) {
        Connection c = null;
        boolean err = false;
        Integer mapkey = getMapKey(world, map, var);
        if (mapkey == null) return;
        try {
            c = getConnection();
            // Query tiles for given mapkey
            Statement stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT x,y,zoom,Format FROM " + tableTiles + " WHERE MapID=" + mapkey + ";");
            while (rs.next()) {
                StorageTile st = new StorageTile(world, map, rs.getInt("x"), rs.getInt("y"), rs.getInt("zoom"), var);
                cb.tileFound(st, MapType.ImageEncoding.fromOrd(rs.getInt("Format")));
                st.cleanup();
            }
            rs.close();
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Tile enum error - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
        }
    }

    @Override
    public void purgeMapTiles(DynmapWorld world, MapType map) {
        List<MapType> mtlist;

        if (map != null) {
            mtlist = Collections.singletonList(map);
        }
        else {  // Else, add all directories under world directory (for maps)
            mtlist = new ArrayList<MapType>(world.maps);
        }
        for (MapType mt : mtlist) {
            ImageVariant[] vars = mt.getVariants();
            for (ImageVariant var : vars) {
                processPurgeMapTiles(world, mt, var);
            }
        }
    }
    private void processPurgeMapTiles(DynmapWorld world, MapType map, ImageVariant var) {
        Connection c = null;
        boolean err = false;
        Integer mapkey = getMapKey(world, map, var);
        if (mapkey == null) return;
        try {
            c = getConnection();
            // Query tiles for given mapkey
            Statement stmt = c.createStatement();
            stmt.executeUpdate("DELETE FROM " + tableTiles + " WHERE MapID=" + mapkey + ";");
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Tile purge error - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
        }
    }

    @Override
    public boolean setPlayerFaceImage(String playername, FaceType facetype,
            BufferOutputStream encImage) {
        Connection c = null;
        boolean err = false;
        boolean exists = hasPlayerFaceImage(playername, facetype);
        // If delete, and doesn't exist, quit
        if ((encImage == null) && (!exists)) return false;

        try {
            c = getConnection();
            PreparedStatement stmt;
            if (encImage == null) { // If delete
                stmt = c.prepareStatement("DELETE FROM " + tableFaces + " WHERE PlayerName=? AND TypeIDx=?;");
                stmt.setString(1, playername);
                stmt.setInt(2, facetype.typeID);
            }
            else if (exists) {
                stmt = c.prepareStatement("UPDATE " + tableFaces + " SET Image=? WHERE PlayerName=? AND TypeID=?;");
                stmt.setBinaryStream(1, new BufferInputStream(encImage.buf, encImage.len), encImage.len);
                stmt.setString(2, playername);
                stmt.setInt(3, facetype.typeID);
            }
            else {
                stmt = c.prepareStatement("INSERT INTO " + tableFaces + " (PlayerName,TypeID,Image) VALUES (?,?,?);");
                stmt.setString(1, playername);
                stmt.setInt(2, facetype.typeID);
                stmt.setBinaryStream(3, new BufferInputStream(encImage.buf, encImage.len), encImage.len);
            }
            stmt.executeUpdate();
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Face write error - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
        }
        return !err;
    }

    @Override
    public BufferInputStream getPlayerFaceImage(String playername,
            FaceType facetype) {
        Connection c = null;
        boolean err = false;
        BufferInputStream image = null;
        try {
            c = getConnection();
            PreparedStatement stmt = c.prepareStatement("SELECT Image FROM " + tableFaces + " WHERE PlayerName=? AND TypeID=?;");
            stmt.setString(1, playername);
            stmt.setInt(2, facetype.typeID);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                byte[] img = rs.getBytes("Image");
                image = new BufferInputStream(img);
            }
            rs.close();
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Face read error - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
        }
        return image;
    }

    @Override
    public boolean hasPlayerFaceImage(String playername, FaceType facetype) {
        Connection c = null;
        boolean err = false;
        boolean exists = false;
        try {
            c = getConnection();
            PreparedStatement stmt = c.prepareStatement("SELECT TypeID FROM " + tableFaces + " WHERE PlayerName=? AND TypeID=?;");
            stmt.setString(1, playername);
            stmt.setInt(2, facetype.typeID);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                exists = true;
            }
            rs.close();
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Face exists error - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
        }
        return exists;
    }

    @Override
    public boolean setMarkerImage(String markerid, BufferOutputStream encImage) {
        Connection c = null;
        boolean err = false;

        try {
            c = getConnection();
            boolean exists = false;
            PreparedStatement stmt;
            stmt = c.prepareStatement("SELECT IconName FROM " + tableMarkerIcons + " WHERE IconName=?;");
            stmt.setString(1, markerid);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                exists = true;
            }
            rs.close();
            stmt.close();
            if (encImage == null) { // If delete
                // If delete, and doesn't exist, quit
                if (!exists) return false;
                stmt = c.prepareStatement("DELETE FROM " + tableMarkerIcons + " WHERE IconName=?;");
                stmt.setString(1, markerid);
                stmt.executeUpdate();
            }
            else if (exists) {
                stmt = c.prepareStatement("UPDATE " + tableMarkerIcons + " SET Image=? WHERE IconName=?;");
                stmt.setBinaryStream(1, new BufferInputStream(encImage.buf, encImage.len), encImage.len);
                stmt.setString(2, markerid);
            }
            else {
                stmt = c.prepareStatement("INSERT INTO " + tableMarkerIcons + " (IconName,Image) VALUES (?,?);");
                stmt.setString(1, markerid);
                stmt.setBinaryStream(2, new BufferInputStream(encImage.buf, encImage.len), encImage.len);
            }
            stmt.executeUpdate();
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Marker write error - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
        }
        return !err;
    }

    @Override
    public BufferInputStream getMarkerImage(String markerid) {
        Connection c = null;
        boolean err = false;
        BufferInputStream image = null;
        try {
            c = getConnection();
            PreparedStatement stmt = c.prepareStatement("SELECT Image FROM " + tableMarkerIcons + " WHERE IconName=?;");
            stmt.setString(1, markerid);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                byte[] img = rs.getBytes("Image");
                image = new BufferInputStream(img);
            }
            rs.close();
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Marker read error - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
        }
        return image;
    }

    @Override
    public boolean setMarkerFile(String world, String content) {
        Connection c = null;
        boolean err = false;

        try {
            c = getConnection();
            boolean exists = false;
            PreparedStatement stmt;
            stmt = c.prepareStatement("SELECT FileName FROM " + tableMarkerFiles + " WHERE FileName=?;");
            stmt.setString(1, world);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                exists = true;
            }
            rs.close();
            stmt.close();
            if (content == null) { // If delete
                // If delete, and doesn't exist, quit
                if (!exists) return false;
                stmt = c.prepareStatement("DELETE FROM " + tableMarkerFiles + " WHERE FileName=?;");
                stmt.setString(1, world);
                stmt.executeUpdate();
            }
            else if (exists) {
                stmt = c.prepareStatement("UPDATE " + tableMarkerFiles + " SET Content=? WHERE FileName=?;");
                stmt.setBytes(1, content.getBytes(UTF8));
                stmt.setString(2, world);
            }
            else {
                stmt = c.prepareStatement("INSERT INTO " + tableMarkerFiles + " (FileName,Content) VALUES (?,?);");
                stmt.setString(1, world);
                stmt.setBytes(2, content.getBytes(UTF8));
            }
            stmt.executeUpdate();
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Marker file write error - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
        }
        return !err;
    }

    @Override
    public String getMarkerFile(String world) {
        Connection c = null;
        boolean err = false;
        String content = null;
        try {
            c = getConnection();
            PreparedStatement stmt = c.prepareStatement("SELECT Content FROM " + tableMarkerFiles + " WHERE FileName=?;");
            stmt.setString(1, world);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                byte[] img = rs.getBytes("Content");
                content = new String(img, UTF8);
            }
            rs.close();
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Marker file read error - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
        }
        return content;
    }

    @Override
    public String getMarkersURI(boolean login_enabled) {
        return "standalone/MySQL_markers.php?marker=";
   }

    @Override
    public String getTilesURI(boolean login_enabled) {
        return "standalone/MySQL_tiles.php?tile=";
    }

    @Override
    public String getConfigurationJSONURI(boolean login_enabled) {
        return "standalone/MySQL_configuration.php"; // ?serverid={serverid}";
    }

    @Override
    public String getUpdateJSONURI(boolean login_enabled) {
        return "standalone/MySQL_update.php?world={world}&ts={timestamp}"; // &serverid={serverid}";
    }

    @Override
    public String getSendMessageURI() {
        return "standalone/MySQL_sendmessage.php";
    }

    @Override
    public BufferInputStream getStandaloneFile(String fileid) {
        Connection c = null;
        boolean err = false;
        BufferInputStream content = null;
        try {
            c = getConnection();
            PreparedStatement stmt = c.prepareStatement("SELECT Content FROM " + tableStandaloneFiles + " WHERE FileName=? AND ServerID=?;");
            stmt.setString(1, fileid);
            stmt.setLong(2, serverID);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                byte[] img = rs.getBytes("Content");
                content = new BufferInputStream(img);
            }
            rs.close();
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Standalone file read error - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
        }
        return content;
    }

    @Override
    public boolean setStandaloneFile(String fileid, BufferOutputStream content) {
        Connection c = null;
        boolean err = false;

        try {
            c = getConnection();
            boolean exists = false;
            PreparedStatement stmt;
            stmt = c.prepareStatement("SELECT FileName FROM " + tableStandaloneFiles + " WHERE FileName=? AND ServerID=?;");
            stmt.setString(1, fileid);
            stmt.setLong(2, serverID);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                exists = true;
            }
            rs.close();
            stmt.close();
            if (content == null) { // If delete
                // If delete, and doesn't exist, quit
                if (!exists) return true;
                stmt = c.prepareStatement("DELETE FROM " + tableStandaloneFiles + " WHERE FileName=? AND ServerID=?;");
                stmt.setString(1, fileid);
                stmt.setLong(2, serverID);
                stmt.executeUpdate();
            }
            else if (exists) {
                stmt = c.prepareStatement("UPDATE " + tableStandaloneFiles + " SET Content=? WHERE FileName=? AND ServerID=?;");
                stmt.setBinaryStream(1, new BufferInputStream(content.buf, content.len), content.len);
                stmt.setString(2, fileid);
                stmt.setLong(3, serverID);
            }
            else {
                stmt = c.prepareStatement("INSERT INTO " + tableStandaloneFiles + " (FileName,ServerID,Content) VALUES (?,?,?);");
                stmt.setString(1, fileid);
                stmt.setLong(2, serverID);
                stmt.setBinaryStream(3, new BufferInputStream(content.buf, content.len), content.len);
            }
            stmt.executeUpdate();
            stmt.close();
        } catch (SQLException x) {
            Log.severe("Standalone file write error - " + x.getMessage());
            err = true;
        } finally {
            releaseConnection(c, err);
        }
        return !err;
    }
    @Override
    public boolean wrapStandaloneJSON(boolean login_enabled) {
        return false;
    }
    @Override
    public boolean wrapStandalonePHP() {
        return false;
    }
    @Override
    public String getStandaloneLoginURI() {
        return "standalone/MySQL_login.php";
    }
    @Override
    public String getStandaloneRegisterURI() {
        return "standalone/MySQL_register.php";
    }
    @Override
    public void setLoginEnabled(DynmapCore core) {
        writeConfigPHP(core);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>org.vitanov</groupId>
    <artifactId>myApplication</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.12.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.12.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.2.11</version>
        </dependency>

    </dependencies>

</project>


text:
/*
 * InitAll.h
 *
 *  Created on: 2015-04-21
 *      Author:Hypocrisy
 */

#ifndef INITALL_H_
#define INITALL_H_

void InitGlobalVars();
void InitSensor();
void InitActuator();
void InitUltraSound();
void InitUI();
void InitReedPipe();
void InitAll();

#endif  /*  INITALL_H_  */


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="artist_image_size">40dp</dimen>
    <dimen name="small_padding">4dp</dimen>
    <dimen name="medium_padding">8dp</dimen>
    <dimen name="large_padding">12dp</dimen>
    <dimen name="xtra_large_padding">24dp</dimen>
    <dimen name="empty_offset">150dp</dimen>
    <dimen name="tile_height">56dp</dimen>
    <dimen name="text_padding">16dp</dimen>
    <dimen name="list_outer_padding">8dp</dimen>
    <dimen name="detail_backdrop_height">256dp</dimen>

    <dimen name="action_icon_size">40dp</dimen>

</resources>


text:
package enums // import "google.golang.org/genproto/googleapis/ads/googleads/v1/enums"

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "google.golang.org/genproto/googleapis/api/annotations"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

// The event type of conversions that are attributed to.
type ConversionAttributionEventTypeEnum_ConversionAttributionEventType int32

const (
	// Not specified.
	ConversionAttributionEventTypeEnum_UNSPECIFIED ConversionAttributionEventTypeEnum_ConversionAttributionEventType = 0
	// Represents value unknown in this version.
	ConversionAttributionEventTypeEnum_UNKNOWN ConversionAttributionEventTypeEnum_ConversionAttributionEventType = 1
	// The conversion is attributed to an impression.
	ConversionAttributionEventTypeEnum_IMPRESSION ConversionAttributionEventTypeEnum_ConversionAttributionEventType = 2
	// The conversion is attributed to an interaction.
	ConversionAttributionEventTypeEnum_INTERACTION ConversionAttributionEventTypeEnum_ConversionAttributionEventType = 3
)

var ConversionAttributionEventTypeEnum_ConversionAttributionEventType_name = map[int32]string{
	0: "UNSPECIFIED",
	1: "UNKNOWN",
	2: "IMPRESSION",
	3: "INTERACTION",
}
var ConversionAttributionEventTypeEnum_ConversionAttributionEventType_value = map[string]int32{
	"UNSPECIFIED": 0,
	"UNKNOWN":     1,
	"IMPRESSION":  2,
	"INTERACTION": 3,
}

func (x ConversionAttributionEventTypeEnum_ConversionAttributionEventType) String() string {
	return proto.EnumName(ConversionAttributionEventTypeEnum_ConversionAttributionEventType_name, int32(x))
}
func (ConversionAttributionEventTypeEnum_ConversionAttributionEventType) EnumDescriptor() ([]byte, []int) {
	return fileDescriptor_conversion_attribution_event_type_4687ee459e143dd0, []int{0, 0}
}

// Container for enum indicating the event type the conversion is attributed to.
type ConversionAttributionEventTypeEnum struct {
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *ConversionAttributionEventTypeEnum) Reset()         { *m = ConversionAttributionEventTypeEnum{} }
func (m *ConversionAttributionEventTypeEnum) String() string { return proto.CompactTextString(m) }
func (*ConversionAttributionEventTypeEnum) ProtoMessage()    {}
func (*ConversionAttributionEventTypeEnum) Descriptor() ([]byte, []int) {
	return fileDescriptor_conversion_attribution_event_type_4687ee459e143dd0, []int{0}
}
func (m *ConversionAttributionEventTypeEnum) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_ConversionAttributionEventTypeEnum.Unmarshal(m, b)
}
func (m *ConversionAttributionEventTypeEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_ConversionAttributionEventTypeEnum.Marshal(b, m, deterministic)
}
func (dst *ConversionAttributionEventTypeEnum) XXX_Merge(src proto.Message) {
	xxx_messageInfo_ConversionAttributionEventTypeEnum.Merge(dst, src)
}
func (m *ConversionAttributionEventTypeEnum) XXX_Size() int {
	return xxx_messageInfo_ConversionAttributionEventTypeEnum.Size(m)
}
func (m *ConversionAttributionEventTypeEnum) XXX_DiscardUnknown() {
	xxx_messageInfo_ConversionAttributionEventTypeEnum.DiscardUnknown(m)
}

var xxx_messageInfo_ConversionAttributionEventTypeEnum proto.InternalMessageInfo

func init() {
	proto.RegisterType((*ConversionAttributionEventTypeEnum)(nil), "google.ads.googleads.v1.enums.ConversionAttributionEventTypeEnum")
	proto.RegisterEnum("google.ads.googleads.v1.enums.ConversionAttributionEventTypeEnum_ConversionAttributionEventType", ConversionAttributionEventTypeEnum_ConversionAttributionEventType_name, ConversionAttributionEventTypeEnum_ConversionAttributionEventType_value)
}

func init() {
	proto.RegisterFile("google/ads/googleads/v1/enums/conversion_attribution_event_type.proto", fileDescriptor_conversion_attribution_event_type_4687ee459e143dd0)
}

var fileDescriptor_conversion_attribution_event_type_4687ee459e143dd0 = []byte{
	// 325 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x50, 0xdf, 0x4a, 0xfb, 0x30,
	0x18, 0xfd, 0xb5, 0x83, 0x9f, 0x90, 0x81, 0x8e, 0x5e, 0x8a, 0x13, 0x36, 0xef, 0x53, 0x8a, 0x77,
	0xf1, 0x2a, 0x9b, 0x71, 0x14, 0xb1, 0x2b, 0xfb, 0x27, 0x48, 0x61, 0x64, 0x6b, 0x08, 0x85, 0x2d,
	0x29, 0x4d, 0x56, 0xd8, 0x03, 0xf8, 0x22, 0x5e, 0xfa, 0x28, 0x3e, 0x8a, 0x4f, 0xe0, 0xa5, 0x24,
	0x71, 0xf5, 0xca, 0xde, 0x84, 0x43, 0xbe, 0xf3, 0x9d, 0xf3, 0x9d, 0x03, 0x08, 0x97, 0x92, 0xef,
	0x58, 0x48, 0x73, 0x15, 0x3a, 0x68, 0x50, 0x1d, 0x85, 0x4c, 0x1c, 0xf6, 0x2a, 0xdc, 0x4a, 0x51,
	0xb3, 0x4a, 0x15, 0x52, 0xac, 0xa9, 0xd6, 0x55, 0xb1, 0x39, 0x68, 0x83, 0x59, 0xcd, 0x84, 0x5e,
	0xeb, 0x63, 0xc9, 0x60, 0x59, 0x49, 0x2d, 0x83, 0xbe, 0xdb, 0x85, 0x34, 0x57, 0xb0, 0x91, 0x81,
	0x75, 0x04, 0xad, 0xcc, 0xe5, 0xd5, 0xc9, 0xa5, 0x2c, 0x42, 0x2a, 0x84, 0xd4, 0xd4, 0xc8, 0x28,
	0xb7, 0x3c, 0x7c, 0xf5, 0xc0, 0x70, 0xdc, 0x18, 0xe1, 0x5f, 0x1f, 0x62, 0x6c, 0x16, 0xc7, 0x92,
	0x11, 0x71, 0xd8, 0x0f, 0xd7, 0xe0, 0xba, 0x9d, 0x15, 0x5c, 0x80, 0xee, 0x32, 0x99, 0xa7, 0x64,
	0x1c, 0x3f, 0xc4, 0xe4, 0xbe, 0xf7, 0x2f, 0xe8, 0x82, 0xb3, 0x65, 0xf2, 0x98, 0x4c, 0x9f, 0x93,
	0x9e, 0x17, 0x9c, 0x03, 0x10, 0x3f, 0xa5, 0x33, 0x32, 0x9f, 0xc7, 0xd3, 0xa4, 0xe7, 0x1b, 0x76,
	0x9c, 0x2c, 0xc8, 0x0c, 0x8f, 0x17, 0xe6, 0xa3, 0x33, 0xfa, 0xf2, 0xc0, 0x60, 0x2b, 0xf7, 0xb0,
	0x35, 0xcb, 0xe8, 0xa6, 0xfd, 0x88, 0xd4, 0x44, 0x4a, 0xbd, 0x97, 0xd1, 0x8f, 0x0a, 0x97, 0x3b,
	0x2a, 0x38, 0x94, 0x15, 0x0f, 0x39, 0x13, 0x36, 0xf0, 0xa9, 0xe8, 0xb2, 0x50, 0x7f, 0xf4, 0x7e,
	0x67, 0xdf, 0x37, 0xbf, 0x33, 0xc1, 0xf8, 0xdd, 0xef, 0x4f, 0x9c, 0x14, 0xce, 0x15, 0x74, 0xd0,
	0xa0, 0x55, 0x04, 0x4d, 0x2d, 0xea, 0xe3, 0x34, 0xcf, 0x70, 0xae, 0xb2, 0x66, 0x9e, 0xad, 0xa2,
	0xcc, 0xce, 0x3f, 0xfd, 0x81, 0xfb, 0x44, 0x08, 0xe7, 0x0a, 0xa1, 0x86, 0x81, 0xd0, 0x2a, 0x42,
	0xc8, 0x72, 0x36, 0xff, 0xed, 0x61, 0xb7, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x2d, 0xc5, 0x1f,
	0x04, 0x0f, 0x02, 0x00, 0x00,
}


text:
package net.krazyweb.util;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class FileUtils {

	public static List<Path> listFiles(final Path path) throws IOException {
		List<Path> paths = new ArrayList<>();
		listFiles(path, paths);
		return paths;
	}

	public static void listFiles(final Path path, final List<Path> paths) throws IOException {
		if (Files.isDirectory(path)) {
			List<Path> files = Files.list(path).collect(Collectors.toList());
			for (Path path1 : files) {
				listFiles(path1, paths);
			}
		} else {
			paths.add(path);
		}
	}

}


text: from lib import <caret>


text:
require 'spec_helper'
require 'mailgun_rails/client'

describe MailgunRails::Client do
  let(:client){MailgunRails::Client.new(:some_api_key, :some_domain)}

  describe "#send_message" do
    it 'should make a POST rest request passing the parameters to the mailgun end point' do
      expected_url = "https://api:some_api_key@api.mailgun.net/v3/some_domain/messages"
      RestClient::Request.stub(:execute).with({ method: :post, url: expected_url, payload: { foo: :bar }, verify_ssl: true})
      client.send_message foo: :bar
    end
  end
end


text:
    <ui-input-container class="no-margin">
        <input type="text"
               ng-class="uiClass"
               name="{{uiName}}"
               ng-readonly="switchOpened"
               ng-pattern="/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/"
               class="txt-color-switch"
               ng-model="ngModel"
               ng-focus="switchOpen()"
               style="user-select: none"
               autocomplete="off"
               ng-style="{'color': uiShape == 'round-rectangle' && 'transparent'}">
        Cor
    </ui-input-container>


text:
#ifndef UNALLOCATION_INFO_H
#define UNALLOCATION_INFO_H

#include <string.h>
#include <jni.h>
#include "hashmap.h"

// helper functionality for native unallocation information
// shall be a class, implementation shall not be in header...

struct UnallocationInfo {
	long size;
	int count;
	int* recId;
};

typedef HashMap<int, long> AggregatedUnallocationMap;
typedef HashMap<long, UnallocationInfo*> UnallocationInfoMap;
static AggregatedUnallocationMap aggregatedUnallocationMap;
static UnallocationInfoMap unallocationInfoMap;
static jmethodID identityHashCodeMethod;
static jmethodID unallocatedMethod;

inline char* newString(size_t len, const char* data = 0) {
	char* result = new char[len + 1];
	result[len] = 0;
	if (NULL != data) {
		strncpy(result, data, len);
	}
	return result;
}

inline char* cloneString(char* src) {
	return newString(strlen(src), src);
}

inline void deleteString(char* s) {
	delete s;
}

char* newJString(JNIEnv *env, jstring s) {
	jsize strLen = env->GetStringUTFLength(s);
	const char* str = env->GetStringUTFChars(s, NULL);
	char* result = newString(strLen, str);
	env->ReleaseStringUTFChars(s, str);
	return result;
}

int systemHashCode(JNIEnv *env, jobject object) {
	if (0 == identityHashCodeMethod) {
		jclass sys_class = env->FindClass("java/lang/System");
		if (env->ExceptionOccurred()) {
			env->ExceptionDescribe();
		}
		identityHashCodeMethod = env->GetMethodID(sys_class, "identityHashCode", "(Ljava/lang/Object;)I");
		if (0 == identityHashCodeMethod) {
			printf("METHOD identityHashCode NOT FOUND!\n");
		}
	}
	if (0 != identityHashCodeMethod) {
		return env->CallIntMethod(NULL, identityHashCodeMethod, object);
	} else {
		return 0;
	}
}

UnallocationInfo * getUnallocationInfo(JNIEnv *env,
#if defined(WITH_JVMTI)
jvmtiEnv *jvmti,
#endif
jobject allocated) {
	UnallocationInfo* result = NULL;
#if defined(WITH_JVMTI)
    if (0 != jvmti) {
    	jlong tag_ptr;
    	jvmtiError error = jvmti->GetTag(allocated, &tag_ptr);
    	if (JVMTI_ERROR_NONE != error) {
			printf("ERROR: cannot get object tag (%d)\n", error);
		} else {
			result = (UnallocationInfo*) tag_ptr;
		}
    } else {
		printf("ERROR: No JVMTI environment present for setTag\n");
    }
#else
    UnallocationInfo** find = unallocationInfoMap.findp(systemHashCode(env, allocated));
	if (NULL != find) {
	    result = *find;
	}
#endif
	return result;
}

void storeUnallocationInfo(JNIEnv *env,
#if defined(WITH_JVMTI)
jvmtiEnv *jvmti,
#endif
jobject allocated, UnallocationInfo *info) {
#if defined(WITH_JVMTI)
    if (0 != jvmti) {
    	jvmtiError error = jvmti->SetTag(allocated, (jlong) info);
    	if (JVMTI_ERROR_NONE != error) {
			printf("ERROR: cannot tag object (%d)\n", error);
		}
    } else {
		printf("ERROR: No JVMTI environment present for setTag\n");
    }
#else
    unallocationInfoMap.insert(systemHashCode(env, allocated), info);
#endif
}

UnallocationInfo* createSimpleUnallocationInfo(JNIEnv *env,
	jlong size, jint recId) {
	UnallocationInfo* info = new UnallocationInfo;
	info->size = size;
	info->count = 0;
	info->recId = (int*) recId; // save memory!
	return info;
}

/*UnallocationInfo* createMultiUnallocationInfo(JNIEnv *env,
	jlong size, jint count, jobjectArray recId) {
	UnallocationInfo* info = new UnallocationInfo;
	info->count = count;
	info->size = size;
	info->recId = new char*[count];
	for (int i = 0; i < count; i++) {
		jstring id = (jstring) env->GetObjectArrayElement(recId, i);
		info->recId[i] = newJString(env, id);
	}
	return info;
}*/

void initUnallocationInfoMap() {
}

void deleteUnallocationInfo(UnallocationInfo* info) {
	if (info->count > 0) {
	    delete info->recId;
	}
	delete info;
}

void transferAggregatedUnallocationToJava(JNIEnv *env, jobject receiver) {
	initUnallocatedMethod(env);
	// clear data structure anyway
	for (AggregatedUnallocationMap::Iterator it = aggregatedUnallocationMap.first();
		it; it.next()) {
		int recId = it.key();
		long size = it.value();
		callUnallocated(env, receiver, recId, (jlong) size);
	}
	aggregatedUnallocationMap.clear();
}

void doneUnallocation() {
	for (UnallocationInfoMap::Iterator it = unallocationInfoMap.first();
		it; it.next()) {
		deleteUnallocationInfo(it.value());
	}
	unallocationInfoMap.done();
	aggregatedUnallocationMap.done();
	clearUnallocatedJni();
}

inline void transferToAggMap(int recId, long size) {
	long* recIdSize = aggregatedUnallocationMap.findp(recId);
	if (NULL == recIdSize) {
		aggregatedUnallocationMap.insert(recId, size);
	} else {
		*recIdSize += size;
	}
}

inline void freeUnallocationInfo(UnallocationInfo* info) {
	if (0 == info->count) {
		transferToAggMap((int)info->recId, info->size);
	} else {
		for (int i = 0; i < info->count; i++) {
			transferToAggMap(info->recId[i], info->size);
 		}
 	}
 	deleteUnallocationInfo(info);
}


text:
/**
 * This file is part of the CernVM File System.
 */

#include <gtest/gtest.h>

#include "catalog_mgr_rw.h"
#include "catalog_test_tools.h"
#include "download.h"
#include "statistics.h"
#include "upload.h"

using namespace std;  // NOLINT

namespace {

// Create some default hashes for DirSpec
const char* g_hashes[] = {"b026324c6904b2a9cb4b88d6d61c81d100000000",
                          "26ab0db90d72e28ad0ba1e22ee51051000000000",
                          "6d7fce9fee471194aa8b5b6e47267f0300000000",
                          "48a24b70a0b376535542b996af51739800000000",
                          "1dcca23355272056f04fe8bf20edfce000000000",
                          "1111111111111111111111111111111111111111",
                          "a34b51ff1b544f7f8d14e0fa5141830f00000000",
                          "6521257477da480594743cb7b24535ff00000000",
};

const size_t g_file_size = 4096;

// Create directory specification for later repositories
DirSpec MakeBaseSpec() {
  DirSpec spec;

  // adding "/dir"
  EXPECT_TRUE(spec.AddDirectory("dir", "", g_file_size));

  // adding "/dir/file1"
  EXPECT_TRUE(spec.AddFile("file1", "dir", g_hashes[0], g_file_size));

  // adding "/dir/dir"
  EXPECT_TRUE(spec.AddDirectory("dir",  "dir", g_file_size));
  EXPECT_TRUE(spec.AddDirectory("dir2", "dir", g_file_size));
  EXPECT_TRUE(spec.AddDirectory("dir3", "dir", g_file_size));

  // adding "/file3"
  EXPECT_TRUE(spec.AddFile("file3", "", g_hashes[2], g_file_size));

  // adding "/dir/dir/file2"
  EXPECT_TRUE(spec.AddFile("file2", "dir/dir", g_hashes[1], g_file_size));

  // adding "/dir/dir2/file2"
  EXPECT_TRUE(spec.AddFile("file2", "dir/dir2", g_hashes[3], g_file_size));

  // adding "/dir/dir3/file2"
  EXPECT_TRUE(spec.AddFile("file2", "dir/dir3", g_hashes[4], g_file_size));

  // Adding Deeply nested catalog
  EXPECT_TRUE(spec.AddDirectory("dir",  "dir/dir", g_file_size));
  EXPECT_TRUE(spec.AddDirectory("dir",  "dir/dir/dir", g_file_size));
  EXPECT_TRUE(
    spec.AddFile("file1",  "dir/dir/dir/dir", g_hashes[0], g_file_size));
  EXPECT_TRUE(spec.AddNestedCatalog("dir/dir/dir"));

  // adding sub-nested catalogs
  EXPECT_TRUE(spec.AddDirectory("sub1", "dir/dir/dir", g_file_size));
  EXPECT_TRUE(spec.AddFile("file1", "dir/dir/dir/sub1",
                           g_hashes[6], g_file_size));
  EXPECT_TRUE(spec.AddNestedCatalog("dir/dir/dir/sub1"));
  EXPECT_TRUE(spec.AddDirectory("sub2", "dir/dir/dir", g_file_size));
  EXPECT_TRUE(spec.AddFile("file2", "dir/dir/dir/sub2",
                           g_hashes[7], g_file_size));
  EXPECT_TRUE(spec.AddNestedCatalog("dir/dir/dir/sub2"));

  return spec;
}

}  // anonymous namespace

namespace catalog {

class T_CatalogMgrRw : public ::testing::Test {
 protected:
  virtual void SetUp() {
  }

  virtual void TearDown() {
  }
};

TEST_F(T_CatalogMgrRw, CloneTreeFailSlow) {
  CatalogTestTool tester("clone_tree_fail_slow");
  EXPECT_TRUE(tester.Init());

  DirSpec spec = MakeBaseSpec();
  EXPECT_TRUE(tester.ApplyAtRootHash(tester.manifest()->catalog_hash(), spec));

  catalog::WritableCatalogManager *catalog_mgr = tester.catalog_mgr();
  EXPECT_DEATH(catalog_mgr->CloneTree("", ""), ".*");
  EXPECT_DEATH(catalog_mgr->CloneTree("", "clone"), ".*");
  EXPECT_DEATH(catalog_mgr->CloneTree("dir", ""), ".*");
  EXPECT_DEATH(catalog_mgr->CloneTree("dir", "dir"), ".*");
  EXPECT_DEATH(catalog_mgr->CloneTree("dir", "dir/clone"), ".*");
  EXPECT_DEATH(catalog_mgr->CloneTree("void", "clone"), ".*");
  EXPECT_DEATH(catalog_mgr->CloneTree("dir/file1", "clone"), ".*");
  EXPECT_DEATH(catalog_mgr->CloneTree("dir", "void/clone"), ".*");
  EXPECT_DEATH(catalog_mgr->CloneTree("dir/dir", "dir/dir2"), ".*");
}

TEST_F(T_CatalogMgrRw, CloneTree) {
  CatalogTestTool tester("clone_tree");
  EXPECT_TRUE(tester.Init());

  DirSpec spec = MakeBaseSpec();
  EXPECT_TRUE(tester.ApplyAtRootHash(tester.manifest()->catalog_hash(), spec));

  catalog::WritableCatalogManager *catalog_mgr = tester.catalog_mgr();
  catalog_mgr->CloneTree("dir", "clone");

  DirectoryEntry dirent;
  EXPECT_TRUE(catalog_mgr->LookupPath("/clone/dir/dir/dir/file1",
                                      kLookupSole, &dirent));
  EXPECT_STREQ(g_hashes[0], dirent.checksum().ToString().c_str());
  EXPECT_EQ(g_file_size, dirent.size());

  EXPECT_TRUE(catalog_mgr->LookupPath("/clone/dir/dir",
                                      kLookupSole, &dirent));
  EXPECT_TRUE(dirent.IsNestedCatalogRoot());
}

TEST_F(T_CatalogMgrRw, SwapNestedCatalog) {
  CatalogTestTool tester("swap_nested_catalog");
  EXPECT_TRUE(tester.Init());

  DirSpec spec = MakeBaseSpec();
  EXPECT_TRUE(tester.ApplyAtRootHash(tester.manifest()->catalog_hash(), spec));

  catalog::WritableCatalogManager *catalog_mgr = tester.catalog_mgr();

  // Look up sub1 and sub2 nested catalogs
  PathString path;
  shash::Any sub1_hash;
  shash::Any sub2_hash;
  uint64_t sub1_size;
  uint64_t sub2_size;
  EXPECT_TRUE(catalog_mgr->LookupNested(PathString("/dir/dir/dir/sub1"),
                                        &path, &sub1_hash, &sub1_size));
  EXPECT_TRUE(catalog_mgr->LookupNested(PathString("/dir/dir/dir/sub2"),
                                        &path, &sub2_hash, &sub2_size));

  // Swap sub1 with itself
  DirectoryEntry dirent;
  catalog_mgr->DetachNested();
  catalog_mgr->SwapNestedCatalog("dir/dir/dir/sub1", sub1_hash, sub1_size);
  EXPECT_TRUE(catalog_mgr->LookupPath("/dir/dir/dir/sub1/file1",
                                      kLookupSole, &dirent));
  EXPECT_STREQ(g_hashes[6], dirent.checksum().ToString().c_str());

  // Swap sub1 and sub2
  catalog_mgr->DetachNested();
  catalog_mgr->SwapNestedCatalog("dir/dir/dir/sub1", sub2_hash, sub2_size);
  catalog_mgr->SwapNestedCatalog("dir/dir/dir/sub2", sub1_hash, sub1_size);
  EXPECT_TRUE(catalog_mgr->LookupPath("/dir/dir/dir/sub1/file2",
                                      kLookupSole, &dirent));
  EXPECT_STREQ(g_hashes[7], dirent.checksum().ToString().c_str());
  EXPECT_TRUE(catalog_mgr->LookupPath("/dir/dir/dir/sub2/file1",
                                      kLookupSole, &dirent));
  EXPECT_STREQ(g_hashes[6], dirent.checksum().ToString().c_str());
}

TEST_F(T_CatalogMgrRw, SwapNestedCatalogFailSlow) {
  CatalogTestTool tester("swap_nested_catalog_fail_slow");
  EXPECT_TRUE(tester.Init());

  DirSpec spec = MakeBaseSpec();
  EXPECT_TRUE(tester.ApplyAtRootHash(tester.manifest()->catalog_hash(), spec));

  catalog::WritableCatalogManager *catalog_mgr = tester.catalog_mgr();

  // Look up sub1 and sub2 nested catalogs
  PathString path;
  shash::Any sub1_hash;
  shash::Any sub2_hash;
  uint64_t sub1_size;
  uint64_t sub2_size;
  EXPECT_TRUE(catalog_mgr->LookupNested(PathString("/dir/dir/dir/sub1"),
                                        &path, &sub1_hash, &sub1_size));
  EXPECT_TRUE(catalog_mgr->LookupNested(PathString("/dir/dir/dir/sub2"),
                                        &path, &sub2_hash, &sub2_size));

  // Create nonexistent nested catalog hash
  shash::Any subX_hash(shash::kMd5,
                       shash::HexPtr("3e25960a79dbc69b674cd4ec67a72c62"),
                       shash::kSuffixCatalog);
  uint64_t subX_size = 42;

  // Fail if parent catalog does not exist
  catalog_mgr->DetachNested();
  EXPECT_DEATH(catalog_mgr->SwapNestedCatalog("no/such/dir/sub1",
                                              sub1_hash, sub1_size),
               "could not find parent");

  // Fail for directory that is not a nested catalog
  catalog_mgr->DetachNested();
  EXPECT_DEATH(catalog_mgr->SwapNestedCatalog("dir/dir",
                                              sub1_hash, sub1_size),
               "not found in parent");

  // Fail for nested catalog that is already attached and modified
  EXPECT_TRUE(catalog_mgr->LookupNested(PathString("/dir/dir/dir/sub1"),
                                        &path, &sub1_hash, &sub1_size));
  catalog_mgr->RemoveFile("dir/dir/dir/sub1/file1");
  EXPECT_DEATH(catalog_mgr->SwapNestedCatalog("dir/dir/dir/sub1",
                                              sub1_hash, sub1_size),
               "already modified");

  // Fail for non-existent catalog
  catalog_mgr->DetachNested();
  EXPECT_DEATH(catalog_mgr->SwapNestedCatalog("dir/dir/dir/sub1",
                                              subX_hash, subX_size),
               "failed to load");
}

}  // namespace catalog