text:
using Shkembedjijnica.App.Core.Contracts;
using Shkembedjijnica.App.Core.DTOs;

namespace Shkembedjijnica.App.Core.Commands
{
    public class EmployeeInfoCommand : ICommand
    {
        private readonly IEmployeeController _employeeController;

        public EmployeeInfoCommand(IEmployeeController employeeController)
        {
            this._employeeController = employeeController;
        }
        public string Execute(string[] args)
        {
            int id = int.Parse(args[0]);
            EmployeeDto employee = this._employeeController.GetEmployeeInfo(id);
            string employeeInfo =
                $"ID: {employee.EmployeeId} - {employee.FirstName} {employee.LastName} - ${employee.Salary:f2}";
            return employeeInfo;

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
=begin

= SeasonDecorator

  - version:  6.002
  - author:   Leega

  Decorator for the Season model.
  Contains all presentation-logic centered methods.

=end
class SeasonDecorator < Draper::Decorator
  include Rails.application.routes.url_helpers
  delegate_all

  # Retrieves the season header year
  # with link to season ranking
  #
  def get_linked_header_year
    h.link_to( header_year, championships_ranking_regional_er_csi_path(id: object.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('championships.show_full_season') } )
  end
  #-- -------------------------------------------------------------------------
  #++

  # Retrieves the season header year
  # with link to season ranking
  #
  def get_linked_full_name
    h.link_to( get_full_name, championships_ranking_regional_er_csi_path(id: object.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('championships.show_full_season') } )
  end
  #-- -------------------------------------------------------------------------
  #++
end


text:
package io.druid.cli;

import io.airlift.airline.Command;
import io.druid.initialization.DruidModule;
import io.druid.initialization.Initialization;
import io.druid.server.StatusResource;

@Command(
    name = "version",
    description = "Returns Druid version information"
)
public class Version implements Runnable
{
  @Override
  public void run()
  {
    System.out.println(new StatusResource.Status(Initialization.getLoadedImplementations(DruidModule.class)));
  }
}


text:
package org.gradle.api.tasks.diagnostics.internal;

import org.gradle.api.Project;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.tasks.diagnostics.internal.text.DefaultTextReportBuilder;
import org.gradle.api.tasks.diagnostics.internal.text.TextReportBuilder;
import org.gradle.initialization.BuildClientMetaData;
import org.gradle.internal.concurrent.CompositeStoppable;
import org.gradle.logging.StyledTextOutput;
import org.gradle.logging.internal.StreamingStyledTextOutput;
import org.gradle.util.GUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * <p>A basic {@link ReportRenderer} which writes out a text report.
 */
public class TextReportRenderer implements ReportRenderer {
    private BuildClientMetaData clientMetaData;
    private FileResolver fileResolver;
    private StyledTextOutput textOutput;
    private TextReportBuilder builder;
    private boolean close;

    public void setFileResolver(FileResolver fileResolver) {
        this.fileResolver = fileResolver;
    }

    @Override
    public void setClientMetaData(BuildClientMetaData clientMetaData) {
        this.clientMetaData = clientMetaData;
    }

    @Override
    public void setOutput(StyledTextOutput textOutput) {
        setWriter(textOutput, false);
    }

    @Override
    public void setOutputFile(File file) throws IOException {
        cleanupWriter();
        setWriter(new StreamingStyledTextOutput(new BufferedWriter(new FileWriter(file))), true);
    }

    @Override
    public void startProject(Project project) {
        String header = createHeader(project);
        builder.heading(header);
    }

    protected String createHeader(Project project) {
        String header;
        if (project.getRootProject() == project) {
            header = "Root project";
        } else {
            header = String.format("Project %s", project.getPath());
        }
        if (GUtil.isTrue(project.getDescription())) {
            header = header + " - " + project.getDescription();
        }
        return header;
    }

    @Override
    public void completeProject(Project project) {
    }

    @Override
    public void complete() {
        cleanupWriter();
    }

    private void setWriter(StyledTextOutput styledTextOutput, boolean close) {
        this.textOutput = styledTextOutput;
        this.builder = new DefaultTextReportBuilder(textOutput, fileResolver);
        this.close = close;
    }

    private void cleanupWriter() {
        try {
            if (close) {
                CompositeStoppable.stoppable(textOutput).stop();
            }
        } finally {
            textOutput = null;
        }
    }

    public BuildClientMetaData getClientMetaData() {
        return clientMetaData;
    }

    public StyledTextOutput getTextOutput() {
        return textOutput;
    }

    public TextReportBuilder getBuilder() {
        return builder;
    }

}


text:
Authentication is controlled by the ``lux.extensions.rest`` extension which specify
the ``AUTHENTICATION_BACKENDS`` parameter. The parameter represents
a list of python dotted path to authentication backend classes.

## Authenitication Backend

An authentication backend class should derive from ``lux.core.AuthBase``

### AuthBackend.request(*request*)

This method is called when a new request is received. An authentication
backend should perform its authentication process or it can set objects in the ``request.cache``
object or both. This method should always return ``None`` and it can raise
Http errors.


text:
DIV.palette {
    display: inline-block;
    vertical-align: text-top;
}

DIV.palette SELECT {
    margin-bottom: 2px;
    width: 200px;
}

DIV.palette-title {
    color: white;
    background-color: black;
    text-align: center;
    font-weight: bold;
    margin-bottom: 3px;
    display: block;
    width: 200px;
}

DIV.palette-available {
    float: left;
}

DIV.palette-controls {
    margin: 5px 5px;
    float: left;
}

DIV.palette-controls > DIV {
    margin-top: 5px;
}

DIV.palette-controls > DIV:first-child {
    margin-top: 0;
}

DIV.palette-selected {
    float: left;
    clear: right;
}

DIV.palette > .help-block {
    clear: left;
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace BTDB.Collections
{
    public struct StructList<T> : IEnumerable<T>
    {
        T[]? _a;
        uint _count;

        public StructList(in StructList<T> from) : this()
        {
            if (from.Count > 0)
            {
                _count = from.Count;
                _a = new T[_count];
                Array.Copy(from._a!, _a, _count);
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [DebuggerStepThrough]
        public void Add(in T value)
        {
            if (_a == null || _count == _a.Length)
            {
                Expand();
            }

            _a![_count++] = value;
        }

        /// <summary>
        /// Adds value to a collection only if it is not already contained in collection
        /// </summary>
        /// <param name="value"></param>
        public bool AddUnique(in T value)
        {
            for (var i = 0u; i < _count; i++)
            {
                if (value!.Equals(_a![i]))
                {
                    return false;
                }
            }

            Add(value);
            return true;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [DebuggerStepThrough]
        public ref T AddRef()
        {
            if (_a == null || _count == _a.Length)
            {
                Expand();
            }

            return ref _a![_count++];
        }

        public ref T Insert(uint index) => ref Insert((int)index);
        public ref T Insert(Index index) => ref Insert(index.GetOffset((int)_count));

        public ref T Insert(int index)
        {
            if ((uint)index > _count) ThrowIndexOutOfRange(index);
            if (_a == null || _count == _a.Length)
            {
                Expand();
            }

            _count++;
            if (index + 1 < _count)
            {
                AsSpan(index, (int)_count - index - 1)
                    .CopyTo(AsSpan(index + 1, (int)(_count - index - 1)));
            }

            _a![index] = default!;
            return ref _a[index];
        }

        public void RemoveAt(Index index)
        {
            var idx = index.GetOffset((int)_count);
            if ((uint)idx >= _count) ThrowIndexOutOfRange(idx);
            AsSpan(idx + 1).CopyTo(AsSpan(idx));
            _count--;
            _a![_count] = default!;
        }

        public void RemoveItem(T item)
        {
            var index = IndexOf(item);
            if (index < 0) throw new ArgumentOutOfRangeException(nameof(item), item, "Item not found in list");
            RemoveAt(index);
        }

        public void Reserve(uint count)
        {
            if (count > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(count));
            if (count <= _count) return;
            Array.Resize(ref _a, (int)count);
        }

        public void Truncate()
        {
            if (_count == 0)
            {
                _a = null;
            }
            else
            {
                Array.Resize(ref _a, (int)_count);
            }
        }

        void Expand()
        {
            Array.Resize(ref _a, (int)Math.Min(int.MaxValue, Math.Max(2u, _count * 2)));
        }

        void Expand(uint count)
        {
            Array.Resize(ref _a, (int)Math.Min(int.MaxValue, Math.Max(count, _count * 2)));
        }

        public ref T this[int index]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            [DebuggerStepThrough]
            get
            {
                if ((uint)index >= _count)
                    ThrowIndexOutOfRange(index);
                return ref _a![index];
            }
        }

        public ref T this[uint index]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            [DebuggerStepThrough]
            get
            {
                if (index >= _count)
                    ThrowIndexOutOfRange(index);
                return ref _a![index];
            }
        }

        public ref T this[Index index]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            [DebuggerStepThrough]
            get => ref this[index.GetOffset((int)_count)];
        }

        public Span<T> this[Range range]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            [DebuggerStepThrough]
            get => AsSpan()[range];
        }

        public ref T Last
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            [DebuggerStepThrough]
            get
            {
                if (_count == 0) ThrowEmptyList();
                return ref _a![_count - 1];
            }
        }

        void ThrowIndexOutOfRange(uint index)
        {
            throw new ArgumentOutOfRangeException(nameof(index), index,
                "List has " + _count + " items. Accessing " + index);
        }

        void ThrowIndexOutOfRange(int index)
        {
            throw new ArgumentOutOfRangeException(nameof(index), index,
                "List has " + _count + " items. Accessing " + index);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Clear()
        {
            _count = 0;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void ClearAndTruncate()
        {
            _count = 0;
            _a = null;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [DebuggerStepThrough]
        public void Pop()
        {
            if (_count == 0)
            {
                ThrowEmptyList();
            }

            _count--;
        }

        static void ThrowEmptyList()
        {
            throw new InvalidOperationException("Cannot pop empty List");
        }

        public readonly uint Count
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            [DebuggerStepThrough]
            get => _count;
        }

        public T[] UnsafeBackingArray => _a!;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [DebuggerStepThrough]
        public Span<T> AsSpan()
        {
            return _a.AsSpan(0, (int)_count);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [DebuggerStepThrough]
        public static implicit operator ReadOnlySpan<T>(in StructList<T> value) => value.AsReadOnlySpan();

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [DebuggerStepThrough]
        public readonly ReadOnlySpan<T> AsReadOnlySpan()
        {
            return _a.AsSpan(0, (int)_count);
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [DebuggerStepThrough]
        public static implicit operator ReadOnlyMemory<T>(in StructList<T> value) => value.AsReadOnlyMemory();

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        [DebuggerStepThrough]
        public readonly ReadOnlyMemory<T> AsReadOnlyMemory()
        {
            return _a.AsMemory(0, (int)_count);
        }

        [DebuggerStepThrough]
        public Span<T> AsSpan(int start)
        {
            return AsSpan().Slice(start);
        }

        [DebuggerStepThrough]
        public readonly ReadOnlySpan<T> AsReadOnlySpan(int start)
        {
            return AsReadOnlySpan().Slice(start);
        }

        [DebuggerStepThrough]
        public Span<T> AsSpan(int start, int length)
        {
            return AsSpan().Slice(start, length);
        }

        [DebuggerStepThrough]
        public readonly ReadOnlySpan<T> AsReadOnlySpan(int start, int length)
        {
            return AsReadOnlySpan().Slice(start, length);
        }

        public struct Enumerator : IEnumerator<T>
        {
            int _position;
            int _count;
            T[] _array;

            public Enumerator(int count, T[] array)
            {
                _position = -1;
                _count = count;
                _array = array;
            }

            public bool MoveNext()
            {
                Debug.Assert(_position < _count);
                _position++;
                return _position < _count;
            }

            public void Reset()
            {
                _position = -1;
            }

            public readonly T Current => _array[_position];

            object IEnumerator.Current => Current!;

            public void Dispose()
            {
            }
        }

        public Enumerator GetEnumerator()
        {
            return new Enumerator((int)_count, _a!);
        }

        IEnumerator<T> IEnumerable<T>.GetEnumerator()
        {
            return new Enumerator((int)_count, _a!);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void TransferFrom(ref StructList<T> reference)
        {
            _a = reference._a;
            _count = reference._count;
            reference._a = null;
            reference._count = 0;
        }

        public void RepeatAdd(in T value, uint count)
        {
            if (count == 0) return;
            var totalCount = _count + count;
            if (_a == null || totalCount > _a.Length)
                Expand(totalCount);
            _a.AsSpan((int)_count, (int)count).Fill(value);
            _count = totalCount;
        }

        public void AddRange(in ReadOnlySpan<T> range)
        {
            if (range.IsEmpty)
                return;
            var count = _count + (uint)range.Length;
            if (_a == null || count > _a.Length)
                Expand(count);
            range.CopyTo(_a.AsSpan((int)_count));
            _count = count;
        }

        public readonly bool All(Predicate<T> predicate)
        {
            for (uint i = 0; i < _count; i++)
            {
                if (!predicate(_a![i]))
                    return false;
            }

            return true;
        }

        public readonly int IndexOf(in T value)
        {
            var comparer = EqualityComparer<T>.Default;
            for (uint i = 0; i < _count; i++)
            {
                if (comparer.Equals(_a![i], value))
                    return (int)i;
            }

            return -1;
        }

        public readonly T[] ToArray()
        {
            var res = new T[_count];
            AsReadOnlySpan().CopyTo(res);
            return res;
        }

        public void ReplaceItem(T originalItem, T newItem)
        {
            var index = IndexOf(originalItem);
            _a![index] = newItem;
        }

        public void ReplaceItem(T originalItem, in ReadOnlySpan<T> newItems)
        {
            var index = IndexOf(originalItem);
            if (index < 0)
                throw new ArgumentOutOfRangeException(nameof(originalItem), originalItem, "Item not found in List");
            var itemsToInsert = newItems.Length;
            if (itemsToInsert == 0)
            {
                RemoveAt(index);
                return;
            }

            if (itemsToInsert == 1)
            {
                _a![index] = newItems[0];
                return;
            }

            var totalCount = (uint)(_count + itemsToInsert - 1);
            if (totalCount > _a!.Length)
                Expand(totalCount);

            _count = totalCount;

            AsSpan(index + 1, (int)_count - (int)itemsToInsert - index).CopyTo(AsSpan((int)(index + itemsToInsert)));
            newItems.CopyTo(AsSpan(index));
        }

        public void InsertRange(Index index, in ReadOnlySpan<T> values)
        {
            var idx = index.GetOffset((int)_count);
            if ((uint)idx > _count) ThrowIndexOutOfRange(idx);
            if (values.IsEmpty) return;
            var totalCount = _count + (uint)values.Length;
            Expand(totalCount);
            _count = totalCount;
            AsSpan(idx, (int)_count - values.Length - idx).CopyTo(AsSpan(idx + values.Length));
            values.CopyTo(AsSpan(idx));
        }

        public void Sort(IComparer<T> comparer)
        {
            if (_count > 1)
                Array.Sort(_a!, 0, (int)_count, comparer);
        }
    }
}


text:
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <asm/system.h>
#include <linux/ioctl.h>
#include <linux/mtio.h>
#include <linux/delay.h>

#include <linux/ftape.h>
#include <linux/qic117.h>
#include "../lowlevel/ftape-tracing.h"
#include "../lowlevel/fdc-io.h"
#include "../lowlevel/ftape-io.h"
#include "../lowlevel/ftape-ctl.h"
#include "../lowlevel/ftape-rw.h"
#include "../lowlevel/ftape-write.h"
#include "../lowlevel/ftape-read.h"
#include "../lowlevel/ftape-init.h"
#include "../lowlevel/ftape-calibr.h"

/*      Global vars.
 */
/* NOTE: sectors start numbering at 1, all others at 0 ! */
ft_timeout_table ftape_timeout;
unsigned int ftape_tape_len;
volatile qic117_cmd_t ftape_current_command;
const struct qic117_command_table qic117_cmds[] = QIC117_COMMANDS;
int ftape_might_be_off_track;

/*      Local vars.
 */
static int diagnostic_mode;
static unsigned int ftape_udelay_count;
static unsigned int ftape_udelay_time;

void ftape_udelay(unsigned int usecs)
{
	volatile int count = (ftape_udelay_count * usecs +
                              ftape_udelay_count - 1) / ftape_udelay_time;
	volatile int i;

	while (count-- > 0) {
		for (i = 0; i < 20; ++i);
	}
}

void ftape_udelay_calibrate(void)
{
	ftape_calibrate("ftape_udelay",
			ftape_udelay, &ftape_udelay_count, &ftape_udelay_time);
}

/*      Delay (msec) routine.
 */
void ftape_sleep(unsigned int time)
{
	TRACE_FUN(ft_t_any);

	time *= 1000;   /* msecs -> usecs */
	if (time < FT_USPT) {
		/*  Time too small for scheduler, do a busy wait ! */
		ftape_udelay(time);
	} else {
		long timeout;
		unsigned long flags;
		unsigned int ticks = (time + FT_USPT - 1) / FT_USPT;

		TRACE(ft_t_any, "%d msec, %d ticks", time/1000, ticks);
		timeout = ticks;
		save_flags(flags);
		sti();
		msleep_interruptible(jiffies_to_msecs(timeout));
		/*  Mmm. Isn't current->blocked == 0xffffffff ?
		 */
		if (signal_pending(current)) {
			TRACE(ft_t_err, "awoken by non-blocked signal :-(");
		}
		restore_flags(flags);
	}
	TRACE_EXIT;
}

/*  send a command or parameter to the drive
 *  Generates # of step pulses.
 */
static inline int ft_send_to_drive(int arg)
{
	/*  Always wait for a command_timeout period to separate
	 *  individuals commands and/or parameters.
	 */
	ftape_sleep(3 * FT_MILLISECOND);
	/*  Keep cylinder nr within range, step towards home if possible.
	 */
	if (ftape_current_cylinder >= arg) {
		return fdc_seek(ftape_current_cylinder - arg);
	} else {
		return fdc_seek(ftape_current_cylinder + arg);
	}
}

/* forward */ int ftape_report_raw_drive_status(int *status);

static int ft_check_cmd_restrictions(qic117_cmd_t command)
{
	int status = -1;
	TRACE_FUN(ft_t_any);

	TRACE(ft_t_flow, "%s", qic117_cmds[command].name);
	/* A new motion command during an uninterruptible (motion)
	 *  command requires a ready status before the new command can
	 *  be issued. Otherwise a new motion command needs to be
	 *  checked against required status.
	 */
	if (qic117_cmds[command].cmd_type == motion &&
	    qic117_cmds[ftape_current_command].non_intr) {
		ftape_report_raw_drive_status(&status);
		if ((status & QIC_STATUS_READY) == 0) {
			TRACE(ft_t_noise,
			      "motion cmd (%d) during non-intr cmd (%d)",
			      command, ftape_current_command);
			TRACE(ft_t_noise, "waiting until drive gets ready");
			ftape_ready_wait(ftape_timeout.seek,
					 &status);
		}
	}
	if (qic117_cmds[command].mask != 0) {
		__u8 difference;
		/*  Some commands do require a certain status:
		 */
		if (status == -1) {	/* not yet set */
			ftape_report_raw_drive_status(&status);
		}
		difference = ((status ^ qic117_cmds[command].state) &
			      qic117_cmds[command].mask);
		/*  Wait until the drive gets
		 *  ready. This may last forever if
		 *  the drive never gets ready...
		 */
		while ((difference & QIC_STATUS_READY) != 0) {
			TRACE(ft_t_noise, "command %d issued while not ready",
			      command);
			TRACE(ft_t_noise, "waiting until drive gets ready");
			if (ftape_ready_wait(ftape_timeout.seek,
					     &status) == -EINTR) {
				/*  Bail out on signal !
				 */
				TRACE_ABORT(-EINTR, ft_t_warn,
				      "interrupted by non-blockable signal");
			}
			difference = ((status ^ qic117_cmds[command].state) &
				      qic117_cmds[command].mask);
		}
		while ((difference & QIC_STATUS_ERROR) != 0) {
			int err;
			qic117_cmd_t cmd;

			TRACE(ft_t_noise,
			      "command %d issued while error pending",
			      command);
			TRACE(ft_t_noise, "clearing error status");
			ftape_report_error(&err, &cmd, 1);
			ftape_report_raw_drive_status(&status);
			difference = ((status ^ qic117_cmds[command].state) &
				      qic117_cmds[command].mask);
			if ((difference & QIC_STATUS_ERROR) != 0) {
				/*  Bail out on fatal signal !
				 */
				FT_SIGNAL_EXIT(_NEVER_BLOCK);
			}
		}
		if (difference) {
			/*  Any remaining difference can't be solved
			 *  here.
			 */
			if (difference & (QIC_STATUS_CARTRIDGE_PRESENT |
					  QIC_STATUS_NEW_CARTRIDGE |
					  QIC_STATUS_REFERENCED)) {
				TRACE(ft_t_warn,
				      "Fatal: tape removed or reinserted !");
				ft_failure = 1;
			} else {
				TRACE(ft_t_err, "wrong state: 0x%02x should be: 0x%02x",
				      status & qic117_cmds[command].mask,
				      qic117_cmds[command].state);
			}
			TRACE_EXIT -EIO;
		}
		if (~status & QIC_STATUS_READY & qic117_cmds[command].mask) {
			TRACE_ABORT(-EBUSY, ft_t_err, "Bad: still busy!");
		}
	}
	TRACE_EXIT 0;
}

/*      Issue a tape command:
 */
int ftape_command(qic117_cmd_t command)
{
	int result = 0;
	static int level;
	TRACE_FUN(ft_t_any);

	if ((unsigned int)command > NR_ITEMS(qic117_cmds)) {
		/*  This is a bug we'll want to know about too.
		 */
		TRACE_ABORT(-EIO, ft_t_bug, "bug - bad command: %d", command);
	}
	if (++level > 5) { /*  This is a bug we'll want to know about. */
		--level;
		TRACE_ABORT(-EIO, ft_t_bug, "bug - recursion for command: %d",
			    command);
	}
	/*  disable logging and restriction check for some commands,
	 *  check all other commands that have a prescribed starting
	 *  status.
	 */
	if (diagnostic_mode) {
		TRACE(ft_t_flow, "diagnostic command %d", command);
	} else if (command == QIC_REPORT_DRIVE_STATUS ||
		   command == QIC_REPORT_NEXT_BIT) {
		TRACE(ft_t_any, "%s", qic117_cmds[command].name);
	} else {
		TRACE_CATCH(ft_check_cmd_restrictions(command), --level);
	}
	/*  Now all conditions are met or result was < 0.
	 */
	result = ft_send_to_drive((unsigned int)command);
	if (qic117_cmds[command].cmd_type == motion &&
	    command != QIC_LOGICAL_FORWARD && command != QIC_STOP_TAPE) {
		ft_location.known = 0;
	}
	ftape_current_command = command;
	--level;
	TRACE_EXIT result;
}

/*      Send a tape command parameter:
 *      Generates command # of step pulses.
 *      Skips tape-status call !
 */
int ftape_parameter(unsigned int parameter)
{
	TRACE_FUN(ft_t_any);

	TRACE(ft_t_flow, "called with parameter = %d", parameter);
	TRACE_EXIT ft_send_to_drive(parameter + 2);
}

/*      Wait for the drive to get ready.
 *      timeout time in milli-seconds
 *      Returned status is valid if result != -EIO
 *
 *      Should we allow to be killed by SIGINT?  (^C)
 *      Would be nice at least for large timeouts.
 */
int ftape_ready_wait(unsigned int timeout, int *status)
{
	unsigned long t0;
	unsigned int poll_delay;
	int signal_retries;
	TRACE_FUN(ft_t_any);

	/*  the following ** REALLY ** reduces the system load when
	 *  e.g. one simply rewinds or retensions. The tape is slow
	 *  anyway. It is really not necessary to detect error
	 *  conditions with 1/10 seconds granularity
	 *
	 *  On my AMD 133MHZ 486: 100 ms: 23% system load
	 *                        1  sec:  5%
	 *                        5  sec:  0.6%, yeah
	 */
	if (timeout <= FT_SECOND) {
		poll_delay = 100 * FT_MILLISECOND;
		signal_retries = 20; /* two seconds */
	} else if (timeout < 20 * FT_SECOND) {
		TRACE(ft_t_flow, "setting poll delay to 1 second");
		poll_delay = FT_SECOND;
		signal_retries = 2; /* two seconds */
	} else {
		TRACE(ft_t_flow, "setting poll delay to 5 seconds");
		poll_delay = 5 * FT_SECOND;
		signal_retries = 1; /* five seconds */
	}
	for (;;) {
		t0 = jiffies;
		TRACE_CATCH(ftape_report_raw_drive_status(status),);
		if (*status & QIC_STATUS_READY) {
			TRACE_EXIT 0;
		}
		if (!signal_retries--) {
			FT_SIGNAL_EXIT(_NEVER_BLOCK);
		}
		if ((int)timeout >= 0) {
			/* this will fail when jiffies wraps around about
			 * once every year :-)
			 */
			timeout -= ((jiffies - t0) * FT_SECOND) / HZ;
			if (timeout <= 0) {
				TRACE_ABORT(-ETIME, ft_t_err, "timeout");
			}
			ftape_sleep(poll_delay);
			timeout -= poll_delay;
		} else {
			ftape_sleep(poll_delay);
		}
	}
	TRACE_EXIT -ETIME;
}

/*      Issue command and wait up to timeout milli seconds for drive ready
 */
int ftape_command_wait(qic117_cmd_t command, unsigned int timeout, int *status)
{
	int result;

	/* Drive should be ready, issue command
	 */
	result = ftape_command(command);
	if (result >= 0) {
		result = ftape_ready_wait(timeout, status);
	}
	return result;
}

static int ftape_parameter_wait(unsigned int parm, unsigned int timeout, int *status)
{
	int result;

	/* Drive should be ready, issue command
	 */
	result = ftape_parameter(parm);
	if (result >= 0) {
		result = ftape_ready_wait(timeout, status);
	}
	return result;
}

/*--------------------------------------------------------------------------
 *      Report operations
 */

/* Query the drive about its status.  The command is sent and
   result_length bits of status are returned (2 extra bits are read
   for start and stop). */

int ftape_report_operation(int *status,
			   qic117_cmd_t command,
			   int result_length)
{
	int i, st3;
	unsigned int t0;
	unsigned int dt;
	TRACE_FUN(ft_t_any);

	TRACE_CATCH(ftape_command(command),);
	t0 = ftape_timestamp();
	i = 0;
	do {
		++i;
		ftape_sleep(3 * FT_MILLISECOND);	/* see remark below */
		TRACE_CATCH(fdc_sense_drive_status(&st3),);
		dt = ftape_timediff(t0, ftape_timestamp());
		/*  Ack should be asserted within Ttimout + Tack = 6 msec.
		 *  Looks like some drives fail to do this so extend this
		 *  period to 300 msec.
		 */
	} while (!(st3 & ST3_TRACK_0) && dt < 300000);
	if (!(st3 & ST3_TRACK_0)) {
		TRACE(ft_t_err,
		      "No acknowledge after %u msec. (%i iter)", dt / 1000, i);
		TRACE_ABORT(-EIO, ft_t_err, "timeout on Acknowledge");
	}
	/*  dt may be larger than expected because of other tasks
	 *  scheduled while we were sleeping.
	 */
	if (i > 1 && dt > 6000) {
		TRACE(ft_t_err, "Acknowledge after %u msec. (%i iter)",
		      dt / 1000, i);
	}
	*status = 0;
	for (i = 0; i < result_length + 1; i++) {
		TRACE_CATCH(ftape_command(QIC_REPORT_NEXT_BIT),);
		TRACE_CATCH(fdc_sense_drive_status(&st3),);
		if (i < result_length) {
			*status |= ((st3 & ST3_TRACK_0) ? 1 : 0) << i;
		} else if ((st3 & ST3_TRACK_0) == 0) {
			TRACE_ABORT(-EIO, ft_t_err, "missing status stop bit");
		}
	}
	/* this command will put track zero and index back into normal state */
	(void)ftape_command(QIC_REPORT_NEXT_BIT);
	TRACE_EXIT 0;
}

/* Report the current drive status. */

int ftape_report_raw_drive_status(int *status)
{
	int result;
	int count = 0;
	TRACE_FUN(ft_t_any);

	do {
		result = ftape_report_operation(status,
						QIC_REPORT_DRIVE_STATUS, 8);
	} while (result < 0 && ++count <= 3);
	if (result < 0) {
		TRACE_ABORT(-EIO, ft_t_err,
			    "report_operation failed after %d trials", count);
	}
	if ((*status & 0xff) == 0xff) {
		TRACE_ABORT(-EIO, ft_t_err,
			    "impossible drive status 0xff");
	}
	if (*status & QIC_STATUS_READY) {
		ftape_current_command = QIC_NO_COMMAND; /* completed */
	}
	ft_last_status.status.drive_status = (__u8)(*status & 0xff);
	TRACE_EXIT 0;
}

int ftape_report_drive_status(int *status)
{
	TRACE_FUN(ft_t_any);

	TRACE_CATCH(ftape_report_raw_drive_status(status),);
	if (*status & QIC_STATUS_NEW_CARTRIDGE ||
	    !(*status & QIC_STATUS_CARTRIDGE_PRESENT)) {
		ft_failure = 1;	/* will inhibit further operations */
		TRACE_EXIT -EIO;
	}
	if (*status & QIC_STATUS_READY && *status & QIC_STATUS_ERROR) {
		/*  Let caller handle all errors */
		TRACE_ABORT(1, ft_t_warn, "warning: error status set!");
	}
	TRACE_EXIT 0;
}

int ftape_report_error(unsigned int *error,
		       qic117_cmd_t *command, int report)
{
	static const ftape_error ftape_errors[] = QIC117_ERRORS;
	int code;
	TRACE_FUN(ft_t_any);

	TRACE_CATCH(ftape_report_operation(&code, QIC_REPORT_ERROR_CODE, 16),);
	*error   = (unsigned int)(code & 0xff);
	*command = (qic117_cmd_t)((code>>8)&0xff);
	/*  remember hardware status, maybe useful for status ioctls
	 */
	ft_last_error.error.command = (__u8)*command;
	ft_last_error.error.error   = (__u8)*error;
	if (!report) {
		TRACE_EXIT 0;
	}
	if (*error == 0) {
		TRACE_ABORT(0, ft_t_info, "No error");
	}
	TRACE(ft_t_info, "errorcode: %d", *error);
	if (*error < NR_ITEMS(ftape_errors)) {
		TRACE(ft_t_noise, "%sFatal ERROR:",
		      (ftape_errors[*error].fatal ? "" : "Non-"));
		TRACE(ft_t_noise, "%s ...", ftape_errors[*error].message);
	} else {
		TRACE(ft_t_noise, "Unknown ERROR !");
	}
	if ((unsigned int)*command < NR_ITEMS(qic117_cmds) &&
	    qic117_cmds[*command].name != NULL) {
		TRACE(ft_t_noise, "... caused by command \'%s\'",
		      qic117_cmds[*command].name);
	} else {
		TRACE(ft_t_noise, "... caused by unknown command %d",
		      *command);
	}
	TRACE_EXIT 0;
}

int ftape_report_configuration(qic_model *model,
			       unsigned int *rate,
			       int *qic_std,
			       int *tape_len)
{
	int result;
	int config;
	int status;
	static const unsigned int qic_rates[ 4] = { 250, 2000, 500, 1000 };
	TRACE_FUN(ft_t_any);

	result = ftape_report_operation(&config,
					QIC_REPORT_DRIVE_CONFIGURATION, 8);
	if (result < 0) {
		ft_last_status.status.drive_config = (__u8)0x00;
		*model = prehistoric;
		*rate = 500;
		*qic_std = QIC_TAPE_QIC40;
		*tape_len = 205;
		TRACE_EXIT 0;
	} else {
		ft_last_status.status.drive_config = (__u8)(config & 0xff);
	}
	*rate = qic_rates[(config & QIC_CONFIG_RATE_MASK) >> QIC_CONFIG_RATE_SHIFT];
	result = ftape_report_operation(&status, QIC_REPORT_TAPE_STATUS, 8);
	if (result < 0) {
		ft_last_status.status.tape_status = (__u8)0x00;
		/* pre- QIC117 rev C spec. drive, QIC_CONFIG_80 bit is valid.
		 */
		*qic_std = (config & QIC_CONFIG_80) ?
			QIC_TAPE_QIC80 : QIC_TAPE_QIC40;
		/* ?? how's about 425ft tapes? */
		*tape_len = (config & QIC_CONFIG_LONG) ? 307 : 0;
		*model = pre_qic117c;
		result = 0;
	} else {
		ft_last_status.status.tape_status = (__u8)(status & 0xff);
		*model = post_qic117b;
		TRACE(ft_t_any, "report tape status result = %02x", status);
		/* post- QIC117 rev C spec. drive, QIC_CONFIG_80 bit is
		 * invalid.
		 */
		switch (status & QIC_TAPE_STD_MASK) {
		case QIC_TAPE_QIC40:
		case QIC_TAPE_QIC80:
		case QIC_TAPE_QIC3020:
		case QIC_TAPE_QIC3010:
			*qic_std = status & QIC_TAPE_STD_MASK;
			break;
		default:
			*qic_std = -1;
			break;
		}
		switch (status & QIC_TAPE_LEN_MASK) {
		case QIC_TAPE_205FT:
			/* 205 or 425+ ft 550 Oe tape */
			*tape_len = 0;
			break;
		case QIC_TAPE_307FT:
			/* 307.5 ft 550 Oe Extended Length (XL) tape */
			*tape_len = 307;
			break;
		case QIC_TAPE_VARIABLE:
			/* Variable length 550 Oe tape */
			*tape_len = 0;
			break;
		case QIC_TAPE_1100FT:
			/* 1100 ft 550 Oe tape */
			*tape_len = 1100;
			break;
		case QIC_TAPE_FLEX:
			/* Variable length 900 Oe tape */
			*tape_len = 0;
			break;
		default:
			*tape_len = -1;
			break;
		}
		if (*qic_std == -1 || *tape_len == -1) {
			TRACE(ft_t_any,
			      "post qic-117b spec drive with unknown tape");
		}
		result = *tape_len == -1 ? -EIO : 0;
		if (status & QIC_TAPE_WIDE) {
			switch (*qic_std) {
			case QIC_TAPE_QIC80:
				TRACE(ft_t_info, "TR-1 tape detected");
				break;
			case QIC_TAPE_QIC3010:
				TRACE(ft_t_info, "TR-2 tape detected");
				break;
			case QIC_TAPE_QIC3020:
				TRACE(ft_t_info, "TR-3 tape detected");
				break;
			default:
				TRACE(ft_t_warn,
				      "Unknown Travan tape type detected");
				break;
			}
		}
	}
	TRACE_EXIT (result < 0) ? -EIO : 0;
}

static int ftape_report_rom_version(int *version)
{

	if (ftape_report_operation(version, QIC_REPORT_ROM_VERSION, 8) < 0) {
		return -EIO;
	} else {
		return 0;
	}
}

void ftape_report_vendor_id(unsigned int *id)
{
	int result;
	TRACE_FUN(ft_t_any);

	/* We'll try to get a vendor id from the drive.  First
	 * according to the QIC-117 spec, a 16-bit id is requested.
	 * If that fails we'll try an 8-bit version, otherwise we'll
	 * try an undocumented query.
	 */
	result = ftape_report_operation((int *) id, QIC_REPORT_VENDOR_ID, 16);
	if (result < 0) {
		result = ftape_report_operation((int *) id,
						QIC_REPORT_VENDOR_ID, 8);
		if (result < 0) {
			/* The following is an undocumented call found
			 * in the CMS code.
			 */
			result = ftape_report_operation((int *) id, 24, 8);
			if (result < 0) {
				*id = UNKNOWN_VENDOR;
			} else {
				TRACE(ft_t_noise, "got old 8 bit id: %04x",
				      *id);
				*id |= 0x20000;
			}
		} else {
			TRACE(ft_t_noise, "got 8 bit id: %04x", *id);
			*id |= 0x10000;
		}
	} else {
		TRACE(ft_t_noise, "got 16 bit id: %04x", *id);
	}
	if (*id == 0x0047) {
		int version;
		int sign;

		if (ftape_report_rom_version(&version) < 0) {
			TRACE(ft_t_bug, "report rom version failed");
			TRACE_EXIT;
		}
		TRACE(ft_t_noise, "CMS rom version: %d", version);
		ftape_command(QIC_ENTER_DIAGNOSTIC_1);
		ftape_command(QIC_ENTER_DIAGNOSTIC_1);
		diagnostic_mode = 1;
		if (ftape_report_operation(&sign, 9, 8) < 0) {
			unsigned int error;
			qic117_cmd_t command;

			ftape_report_error(&error, &command, 1);
			ftape_command(QIC_ENTER_PRIMARY_MODE);
			diagnostic_mode = 0;
			TRACE_EXIT;	/* failure ! */
		} else {
			TRACE(ft_t_noise, "CMS signature: %02x", sign);
		}
		if (sign == 0xa5) {
			result = ftape_report_operation(&sign, 37, 8);
			if (result < 0) {
				if (version >= 63) {
					*id = 0x8880;
					TRACE(ft_t_noise,
					      "This is an Iomega drive !");
				} else {
					*id = 0x0047;
					TRACE(ft_t_noise,
					      "This is a real CMS drive !");
				}
			} else {
				*id = 0x0047;
				TRACE(ft_t_noise, "CMS status: %d", sign);
			}
		} else {
			*id = UNKNOWN_VENDOR;
		}
		ftape_command(QIC_ENTER_PRIMARY_MODE);
		diagnostic_mode = 0;
	}
	TRACE_EXIT;
}

static int qic_rate_code(unsigned int rate)
{
	switch (rate) {
	case 250:
		return QIC_CONFIG_RATE_250;
	case 500:
		return QIC_CONFIG_RATE_500;
	case 1000:
		return QIC_CONFIG_RATE_1000;
	case 2000:
		return QIC_CONFIG_RATE_2000;
	default:
		return QIC_CONFIG_RATE_500;
	}
}

static int ftape_set_rate_test(unsigned int *max_rate)
{
	unsigned int error;
	qic117_cmd_t command;
	int status;
	int supported = 0;
	TRACE_FUN(ft_t_any);

	/*  Check if the drive does support the select rate command
	 *  by testing all different settings. If any one is accepted
	 *  we assume the command is supported, else not.
	 */
	for (*max_rate = 2000; *max_rate >= 250; *max_rate /= 2) {
		if (ftape_command(QIC_SELECT_RATE) < 0) {
			continue;
		}
		if (ftape_parameter_wait(qic_rate_code(*max_rate),
					 1 * FT_SECOND, &status) < 0) {
			continue;
		}
		if (status & QIC_STATUS_ERROR) {
			ftape_report_error(&error, &command, 0);
			continue;
		}
		supported = 1; /* did accept a request */
		break;
	}
	TRACE(ft_t_noise, "Select Rate command is%s supported",
	      supported ? "" : " not");
	TRACE_EXIT supported;
}

int ftape_set_data_rate(unsigned int new_rate /* Kbps */, unsigned int qic_std)
{
	int status;
	int result = 0;
	unsigned int data_rate = new_rate;
	static int supported;
	int rate_changed = 0;
	qic_model dummy_model;
	unsigned int dummy_qic_std, dummy_tape_len;
	TRACE_FUN(ft_t_any);

	if (ft_drive_max_rate == 0) { /* first time */
		supported = ftape_set_rate_test(&ft_drive_max_rate);
	}
	if (supported) {
		ftape_command(QIC_SELECT_RATE);
		result = ftape_parameter_wait(qic_rate_code(new_rate),
					      1 * FT_SECOND, &status);
		if (result >= 0 && !(status & QIC_STATUS_ERROR)) {
			rate_changed = 1;
		}
	}
	TRACE_CATCH(result = ftape_report_configuration(&dummy_model,
							&data_rate,
							&dummy_qic_std,
							&dummy_tape_len),);
	if (data_rate != new_rate) {
		if (!supported) {
			TRACE(ft_t_warn, "Rate change not supported!");
		} else if (rate_changed) {
			TRACE(ft_t_warn, "Requested: %d, got %d",
			      new_rate, data_rate);
		} else {
			TRACE(ft_t_warn, "Rate change failed!");
		}
		result = -EINVAL;
	}
	/*
	 *  Set data rate and write precompensation as specified:
	 *
	 *            |  QIC-40/80  | QIC-3010/3020
	 *   rate     |   precomp   |    precomp
	 *  ----------+-------------+--------------
	 *  250 Kbps. |   250 ns.   |     0 ns.
	 *  500 Kbps. |   125 ns.   |     0 ns.
	 *    1 Mbps. |    42 ns.   |     0 ns.
	 *    2 Mbps  |      N/A    |     0 ns.
	 */
	if ((qic_std == QIC_TAPE_QIC40 && data_rate > 500) ||
	    (qic_std == QIC_TAPE_QIC80 && data_rate > 1000)) {
		TRACE_ABORT(-EINVAL,
			    ft_t_warn, "Datarate too high for QIC-mode");
	}
	TRACE_CATCH(fdc_set_data_rate(data_rate),_res = -EINVAL);
	ft_data_rate = data_rate;
	if (qic_std == QIC_TAPE_QIC40 || qic_std == QIC_TAPE_QIC80) {
		switch (data_rate) {
		case 250:
			fdc_set_write_precomp(250);
			break;
		default:
		case 500:
			fdc_set_write_precomp(125);
			break;
		case 1000:
			fdc_set_write_precomp(42);
			break;
		}
	} else {
		fdc_set_write_precomp(0);
	}
	TRACE_EXIT result;
}

/*  The next two functions are used to cope with excessive overrun errors
 */
int ftape_increase_threshold(void)
{
	TRACE_FUN(ft_t_flow);

	if (fdc.type < i82077 || ft_fdc_threshold >= 12) {
		TRACE_ABORT(-EIO, ft_t_err, "cannot increase fifo threshold");
	}
	if (fdc_fifo_threshold(++ft_fdc_threshold, NULL, NULL, NULL) < 0) {
		TRACE(ft_t_err, "cannot increase fifo threshold");
		ft_fdc_threshold --;
		fdc_reset();
	}
	TRACE(ft_t_info, "New FIFO threshold: %d", ft_fdc_threshold);
	TRACE_EXIT 0;
}

int ftape_half_data_rate(void)
{
	if (ft_data_rate < 500) {
		return -1;
	}
	if (ftape_set_data_rate(ft_data_rate / 2, ft_qic_std) < 0) {
		return -EIO;
	}
	ftape_calc_timeouts(ft_qic_std, ft_data_rate, ftape_tape_len);
	return 0;
}

/*      Seek the head to the specified track.
 */
int ftape_seek_head_to_track(unsigned int track)
{
	int status;
	TRACE_FUN(ft_t_any);

	ft_location.track = -1; /* remains set in case of error */
	if (track >= ft_tracks_per_tape) {
		TRACE_ABORT(-EINVAL, ft_t_bug, "track out of bounds");
	}
	TRACE(ft_t_flow, "seeking track %d", track);
	TRACE_CATCH(ftape_command(QIC_SEEK_HEAD_TO_TRACK),);
	TRACE_CATCH(ftape_parameter_wait(track, ftape_timeout.head_seek,
					 &status),);
	ft_location.track = track;
	ftape_might_be_off_track = 0;
	TRACE_EXIT 0;
}

int ftape_wakeup_drive(wake_up_types method)
{
	int status;
	int motor_on = 0;
	TRACE_FUN(ft_t_any);

	switch (method) {
	case wake_up_colorado:
		TRACE_CATCH(ftape_command(QIC_PHANTOM_SELECT),);
		TRACE_CATCH(ftape_parameter(0 /* ft_drive_sel ?? */),);
		break;
	case wake_up_mountain:
		TRACE_CATCH(ftape_command(QIC_SOFT_SELECT),);
		ftape_sleep(FT_MILLISECOND);	/* NEEDED */
		TRACE_CATCH(ftape_parameter(18),);
		break;
	case wake_up_insight:
		ftape_sleep(100 * FT_MILLISECOND);
		motor_on = 1;
		fdc_motor(motor_on);	/* enable is done by motor-on */
	case no_wake_up:
		break;
	default:
		TRACE_EXIT -ENODEV;	/* unknown wakeup method */
		break;
	}
	/*  If wakeup succeeded we shouldn't get an error here..
	 */
	TRACE_CATCH(ftape_report_raw_drive_status(&status),
		    if (motor_on) {
			    fdc_motor(0);
		    });
	TRACE_EXIT 0;
}

int ftape_put_drive_to_sleep(wake_up_types method)
{
	TRACE_FUN(ft_t_any);

	switch (method) {
	case wake_up_colorado:
		TRACE_CATCH(ftape_command(QIC_PHANTOM_DESELECT),);
		break;
	case wake_up_mountain:
		TRACE_CATCH(ftape_command(QIC_SOFT_DESELECT),);
		break;
	case wake_up_insight:
		fdc_motor(0);	/* enable is done by motor-on */
	case no_wake_up:	/* no wakeup / no sleep ! */
		break;
	default:
		TRACE_EXIT -ENODEV;	/* unknown wakeup method */
	}
	TRACE_EXIT 0;
}

int ftape_reset_drive(void)
{
	int result = 0;
	int status;
	unsigned int err_code;
	qic117_cmd_t err_command;
	int i;
	TRACE_FUN(ft_t_any);

	/*  We want to re-establish contact with our drive.  Fire a
	 *  number of reset commands (single step pulses) and pray for
	 *  success.
	 */
	for (i = 0; i < 2; ++i) {
		TRACE(ft_t_flow, "Resetting fdc");
		fdc_reset();
		ftape_sleep(10 * FT_MILLISECOND);
		TRACE(ft_t_flow, "Reset command to drive");
		result = ftape_command(QIC_RESET);
		if (result == 0) {
			ftape_sleep(1 * FT_SECOND); /*  drive not
						     *  accessible
						     *  during 1 second
						     */
			TRACE(ft_t_flow, "Re-selecting drive");

			/* Strange, the QIC-117 specs don't mention
			 * this but the drive gets deselected after a
			 * soft reset !  So we need to enable it
			 * again.
			 */
			if (ftape_wakeup_drive(ft_drive_type.wake_up) < 0) {
				TRACE(ft_t_err, "Wakeup failed !");
			}
			TRACE(ft_t_flow, "Waiting until drive gets ready");
			result= ftape_ready_wait(ftape_timeout.reset, &status);
			if (result == 0 && (status & QIC_STATUS_ERROR)) {
				result = ftape_report_error(&err_code,
							    &err_command, 1);
				if (result == 0 && err_code == 27) {
					/*  Okay, drive saw reset
					 *  command and responded as it
					 *  should
					 */
					break;
				} else {
					result = -EIO;
				}
			} else {
				result = -EIO;
			}
		}
		FT_SIGNAL_EXIT(_DONT_BLOCK);
	}
	if (result != 0) {
		TRACE(ft_t_err, "General failure to reset tape drive");
	} else {
		/*  Restore correct settings: keep original rate
		 */
		ftape_set_data_rate(ft_data_rate, ft_qic_std);
	}
	ftape_init_drive_needed = 1;
	TRACE_EXIT result;
}


text:
package org.apache.ignite.internal.processors.rest.client.message;

import java.io.Externalizable;

/**
 * A client handshake response, containing result
 * code.
 */
public class GridClientHandshakeResponse extends GridClientAbstractMessage {
    /** */
    private static final long serialVersionUID = 0L;

    /** */
    public static final byte CODE_OK = 0;

    /** Response, indicating successful handshake. */
    public static final GridClientHandshakeResponse OK = new GridClientHandshakeResponse(CODE_OK);

    /** */
    private byte resCode;

    /**
     * Constructor for {@link Externalizable}.
     */
    public GridClientHandshakeResponse() {
        // No-op.
    }

    /**
     * Constructor.
     *
     * @param resCode Result code.
     */
    public GridClientHandshakeResponse(byte resCode) {
        this.resCode = resCode;
    }

    /**
     * @return Result code.
     */
    public byte resultCode() {
        return resCode;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return getClass().getSimpleName() + " [resCode=" + resCode + ']';
    }
}


text:
<?php

declare (strict_types = 1);

namespace BinSoul\Net\Http\Router\Matcher;

use BinSoul\Net\Http\Router\Route;

/**
 * Matches a list of paths with parameter placeholders.
 *
 * Parameters can be defined in the following format:
 *
 * [prefix+][name][=format[(length)]][?]
 *
 *
 * - Prefix: Any number of characters except "]" and "+" followed by a single "+".
 * - Name: A single character followed by characters, numbers or "_".
 * - Format: "=" followed by a defined format name optionally followed a length definition.
 * - Length: A single number or a number range enclosed in parenthesis.
 * - Marker: If the definition ends with a single "?" the parameter is optional.
 *
 * For example the parameter definition:
 *
 *
 * /[year=number(4)][/+month=number(1-2)?]/[name].html
 *
 *
 * would match:
 *
 *
 * /2015/09/article.html
 * /2015/9/article.html
 * /2015/article.html
 *
 */
class ParameterMatcher extends RegexMatcher
{
    /** Regex for the parameter prefix */
    const PREFIX = '((?<prefix>.*?)\+)?';
    /** Regex for the parameter name */
    const NAME = '(?<name>[a-z][a-z0-9\_]*?)';
    /** Regex for the parameter format */
    const FORMAT = '((=)((?<format>[a-z]+)(\((?<length>[0-9]+(-[0-9]+)?)\))?))?';
    /** Regex for the parameter marker */
    const OPTIONAL = '(?<optional>\?)?';

    /**
     * Map of defined format names.
     *
     * @var string[]
     */
    private static $formats = [
      'any' => '[^/]',
      'char' => '[a-z]',
      'number' => '[0-9]',
      'alpha' => '[a-z0-9_\-]',
    ];

    public function match(Route $route)
    {
        $map = [];
        foreach ($this->map as $path => $parameters) {
            if (!preg_match_all('/\[(.*?)\]/i', $path, $matches, PREG_SET_ORDER)) {
                $map[$path] = $parameters;

                continue;
            }

            $target = $path;
            foreach ($matches as $key => $match) {
                $target = str_replace($match[0], '~~'.$key.'~~', $target);
            }

            $target = preg_quote($target, '#');

            foreach ($matches as $key => $match) {
                $parts = $this->parseParameter($match[1]);

                $format = $this->buildFormatRegex($parts['format'], $parts['length']);
                $regex = '(?<'.$parts['name'].'>'.$format.')';

                if ($parts['prefix'] != '') {
                    $regex = '('.preg_quote($parts['prefix'], '#').$regex.')';
                }

                if ($parts['optional']) {
                    $regex .= '?';
                }

                $target = str_replace('~~'.$key.'~~', $regex, $target);
            }

            $map[$target] = $parameters;
        }

        $this->matchRegularExpressions($route, $map, $this->allowPartialMatches);
    }

    /**
     * Parses a parameter definition and returns the parts.
     *
     * @param string $string
     *
     * @return mixed[]
     */
    private function parseParameter(string $string): array
    {
        if (!preg_match('#^'.self::PREFIX.''.self::NAME.''.self::FORMAT.self::OPTIONAL.'$#', $string, $matches)) {
            throw new \InvalidArgumentException(sprintf('Invalid parameter definition "%s" found.', $string));
        }

        $result = [];
        foreach ($matches as $key => $match) {
            if (!is_int($key)) {
                $result[$key] = $match;
            }
        }

        $result = array_merge(
            [
                'prefix' => '',
                'name' => '',
                'format' => 'any',
                'length' => '',
                'optional' => false,
            ],
            $result
        );

        if ($result['format'] == '') {
            $result['format'] = 'any';
        }

        $result['optional'] = $result['optional'] === '?';

        return $result;
    }

    /**
     * Builds a regex for the parameter format.
     *
     * @param string $format
     * @param string $length
     *
     * @return string
     */
    private function buildFormatRegex(string $format, string $length): string
    {
        if (!isset(self::$formats[$format])) {
            throw new \InvalidArgumentException(sprintf('Unknown format "%s" found.', $format));
        }

        $result = self::$formats[$format];

        if ($length == '') {
            return $result.'+';
        }

        $parts = explode('-', $length);
        if (count($parts) == 1) {
            return $result.'{'.$parts[0].'}';
        }

        return $result.'{'.$parts[0].','.$parts[1].'}';
    }
}


text:
package net.oschina.app.ui;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import net.oschina.app.AppContext;
import net.oschina.app.R;
import net.oschina.app.base.BaseFragment;
import net.oschina.app.bean.SimpleBackPage;
import net.oschina.app.util.TDevice;
import net.oschina.app.util.UIHelper;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 侧滑菜单界面
 *
 * @author FireAnt(http://my.oschina.net/LittleDY)
 * @created 2014年9月25日 下午6:00:05
 */
public class NavigationDrawerFragment extends BaseFragment implements
        OnClickListener {

    /**
     * Remember the position of the selected item.
     */
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    /**
     * A pointer to the current callbacks instance (the Activity).
     */
    private NavigationDrawerCallbacks mCallbacks;

    /**
     * Helper component that ties the action bar to the navigation drawer.
     */
    private ActionBarDrawerToggle mDrawerToggle;

    private DrawerLayout mDrawerLayout;
    private View mDrawerListView;
    private View mFragmentContainerView;

    private int mCurrentSelectedPosition = 0;
    private boolean mFromSavedInstanceState;

    @InjectView(R.id.menu_item_quests)
    View mMenu_item_quests;

    @InjectView(R.id.menu_item_opensoft)
    View mMenu_item_opensoft;

    @InjectView(R.id.menu_item_blog)
    View mMenu_item_blog;

    @InjectView(R.id.menu_item_gitapp)
    View mMenu_item_gitapp;

    @InjectView(R.id.menu_item_setting)
    View mMenu_item_setting;

    @InjectView(R.id.menu_item_theme)
    View mMenu_item_theme;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            mCurrentSelectedPosition = savedInstanceState
                    .getInt(STATE_SELECTED_POSITION);
            mFromSavedInstanceState = true;
        }

        selectItem(mCurrentSelectedPosition);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mDrawerListView = inflater.inflate(R.layout.fragment_navigation_drawer,
                container, false);
        mDrawerListView.setOnClickListener(this);
        ButterKnife.inject(this, mDrawerListView);
        initView(mDrawerListView);
        initData();
        return mDrawerListView;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.menu_item_quests:
                UIHelper.showSimpleBack(getActivity(), SimpleBackPage.QUEST);
                break;
            case R.id.menu_item_opensoft:
                UIHelper.showSimpleBack(getActivity(),
                        SimpleBackPage.OPENSOURCE_SOFTWARE);
                break;
            case R.id.menu_item_blog:
                UIHelper.showSimpleBack(getActivity(), SimpleBackPage.BLOG);
                break;
            case R.id.menu_item_gitapp:

                boolean res = TDevice.openAppActivity(getActivity(),
                        "net.oschina.gitapp", "net.oschina.gitapp.WelcomePage");

                if (!res) {
                    if (!TDevice.isHaveMarket(getActivity())) {
                        UIHelper.openSysBrowser(getActivity(),
                                "http://git.oschina.net/appclient");
                    } else {
                        TDevice.gotoMarket(getActivity(), "net.oschina.gitapp");
                    }
                }
                break;
            case R.id.menu_item_setting:
                UIHelper.showSetting(getActivity());
                break;
            case R.id.menu_item_theme:
                switchTheme();
                break;
            default:
                break;

        }
        mDrawerLayout.postDelayed(new Runnable() {

            @Override
            public void run() {
                mDrawerLayout.closeDrawers();
            }
        }, 800);
    }

    private void switchTheme() {
        if (AppContext.getNightModeSwitch()) {
            AppContext.setNightModeSwitch(false);
        } else {
            AppContext.setNightModeSwitch(true);
        }

        if (AppContext.getNightModeSwitch()) {
            getActivity().setTheme(R.style.AppBaseTheme_Night);
        } else {
            getActivity().setTheme(R.style.AppBaseTheme_Light);
        }

        getActivity().recreate();
    }

    @Override
    public void initView(View view) {

        TextView night = (TextView) view.findViewById(R.id.tv_night);
        if (AppContext.getNightModeSwitch()) {
            night.setText("日间");
        } else {
            night.setText("夜间");
        }

        mMenu_item_opensoft.setOnClickListener(this);
        mMenu_item_blog.setOnClickListener(this);
        mMenu_item_quests.setOnClickListener(this);

        mMenu_item_setting.setOnClickListener(this);
        mMenu_item_theme.setOnClickListener(this);

        mMenu_item_gitapp.setOnClickListener(this);
    }

    @Override
    public void initData() {
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null
                && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    /**
     * Users of this fragment must call this method to set up the navigation
     * drawer interactions.
     *
     * @param fragmentId   The android:id of this fragment in its activity's layout.
     * @param drawerLayout The DrawerLayout containing this fragment's UI.
     */
    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        // set a custom shadow that overlays the main content when the drawer
        // opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
                GravityCompat.START);
        // set up the drawer's list view with items and click listener

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout,
                null, R.string.navigation_drawer_open,
                R.string.navigation_drawer_close) {

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActivity().invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActivity().invalidateOptionsMenu();
            }
        };

        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    public void openDrawerMenu() {
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    private void selectItem(int position) {
        mCurrentSelectedPosition = position;
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        if (mCallbacks != null) {
            mCallbacks.onNavigationDrawerItemSelected(position);
        }
    }

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

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

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private ActionBar getActionBar() {
        return ((ActionBarActivity) getActivity()).getSupportActionBar();
    }

    public interface NavigationDrawerCallbacks {
        void onNavigationDrawerItemSelected(int position);
    }
}


text:
#ifndef __GSL_PERMUTE_SHORT_H__
#define __GSL_PERMUTE_SHORT_H__

#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_permutation.h>

#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif

__BEGIN_DECLS

int gsl_permute_short (const size_t * p, short * data, const size_t stride, const size_t n);
int gsl_permute_short_inverse (const size_t * p, short * data, const size_t stride, const size_t n);

__END_DECLS

#endif /* __GSL_PERMUTE_SHORT_H__ */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using ApiParser;
using ManagedApiBuilder;
using Moq;
using NUnit.Framework;

namespace ToolTests
{
    public abstract class CSharpGeneratorContext
    {
        protected CSharpGenerator iGenerator;

        [SetUp]
        public void SetUp()
        {
            iGenerator = new CSharpGenerator(
                    new[]{"sp_color", "sp_flavor", "sp_speed"},
                    new[]{"sp_person", "sp_room", "sp_item", "sp_room_callbacks"},
                    new[]{"sp_file", "sp_device"},
                    new[]{"sp_ready_cb", "sp_finished_cb"},
                    new[]{
                        new ApiStructConfiguration{
                            NativeName="sp_person",
                            ManagedName="SpotifyPerson",
                            ForcePublic=false,
                            SuppressFunctions={"sp_person_difficult_function"}
                        }
                    },
                    new[]{
                        new ApiEnumConfiguration{
                            NativeName = "sp_speed",
                            ManagedName = "SpotifySpeed",
                            NativeConstantPrefix = "SP_SPEED_",
                            ManagedConstantPrefix = "_"
                        },
                        new ApiEnumConfiguration{
                            NativeName = "sp_flavor",
                            ManagedName = "Flavor",
                            NativeConstantPrefix = "SP_FLAVOR_",
                            ManagedConstantPrefix = ""
                        },
                    },
                    MakeFunctionFactory()
                );
        }

        protected virtual IFunctionFactory MakeFunctionFactory()
        {
            return new DefaultFunctionFactory();
        }
    }

    public class WhenGeneratingAnEmptyStruct : CSharpGeneratorContext
    {
        protected string iResult;

        [SetUp]
        public void GenerateStruct()
        {
            iResult = iGenerator.GenerateStruct("", "sp_room", new StructCType("room_tag"));
        }

        [Test]
        public void TheResultShouldNotBePublic()
        {
            Assert.That(iResult, Is.Not.StringContaining("public"));
        }

        [Test]
        public void TheResultShouldKeepTheSameName()
        {
            Assert.That(iResult, Is.StringContaining("sp_room"));
        }

        [Test]
        public void TheResultShouldHaveNoContents()
        {
            Assert.That(iResult, Is.StringMatching(@"(?s).*\{\s*\}"));
        }
    }

    public class WhenGeneratingAStructWithSomeMembers : CSharpGeneratorContext
    {
        protected string iResult;

        [SetUp]
        public void GenerateStruct()
        {
            iResult = iGenerator.GenerateStruct("", "sp_room",
                new StructCType("room_tag")
                {
                    Fields = {
                        new Declaration{Name="height", CType=new NamedCType("int")},
                        new Declaration{Name="name", CType=new PointerCType(new NamedCType("char"){Qualifiers={"const"}})},
                        new Declaration{Name="capacity", CType=new NamedCType("size_t")},
                        new Declaration{Name="lit", CType=new NamedCType("bool")},
                        new Declaration{Name="blob", CType=new PointerCType(new NamedCType("void"))},
                    }
                });
        }

        [Test]
        public void TheFieldsShouldBeDeclaredInOrder()
        {
            const string anything = ".*";
            Assert.That(iResult, Is.StringMatching(
                "(?s)" +
                anything + "height;" +
                anything + "name;" +
                anything + "capacity;" +
                anything + "lit;" +
                anything + "blob;" +
                anything));
        }

        [Test]
        public void AnIntNativeField_ShouldBe_AnIntManagedField()
        {
            const string anything = ".*";
            Assert.That(iResult, Is.StringMatching(
                "(?s)" + anything + "public int @height;" + anything));
        }

        [Test]
        public void AConstCharStarNativeField_ShouldBe_AnIntPtrManagedField()
        {
            const string anything = ".*";
            Assert.That(iResult, Is.StringMatching(
                "(?s)" + anything + "public IntPtr @name;" + anything));
        }

        [Test]
        public void ASizeTNativeField_ShouldBe_AUIntPtrManagedField()
        {
            const string anything = ".*";
            Assert.That(iResult, Is.StringMatching(
                "(?s)" + anything + "public UIntPtr @capacity;" + anything));
        }

        [Test]
        public void ABoolNativeField_ShouldBe_ABoolManagedFieldWithByteMarshalling()
        {
            const string anything = ".*";
            Func<string, string> esc = x=>x.Replace(".", "\\.").Replace("(", "\\(").Replace(")", "\\)").Replace("[", "\\[").Replace("]","\\]");
            Assert.That(iResult, Is.StringMatching(
                "(?s)" + anything + esc("[MarshalAs(UnmanagedType.I1)]") + @"\s*" + "public bool @lit;" + anything));
        }
    }

    public class WhenGeneratingAnEnumWithSomeConstants : CSharpGeneratorContext
    {
        protected string iResult;

        [SetUp]
        public void GenerateStruct()
        {
            iResult = iGenerator.GenerateEnumDeclaration("", "sp_flavor",
                new EnumCType("flavor_tag")
                {
                    Constants = {
                        new EnumConstant{Name="SP_FLAVOR_MINT", Value=6},
                        new EnumConstant{Name="SP_FLAVOR_STRAWBERRY_AND_ONION", Value=34},
                        new EnumConstant{Name="SP_FLAVOR_BURNT_POTATO", Value=77},
                        new EnumConstant{Name="SP_FLAVOR_TARMAC", Value=4},
                    }
                });
        }

        [Test]
        public void TheEnumShouldBePublic()
        {
            Assert.That(iResult, Is.StringMatching(@"(?s)\s*public.*"));
        }

        [Test]
        public void TheEnumShouldHaveTheCorrectName()
        {
            Assert.That(iResult, Is.StringMatching(@"(?s).* Flavor\s*{.*"));
        }

        [Test]
        public void TheEnumShouldHaveTheConstantsInOrder()
        {
            Assert.That(iResult, Is.StringMatching(@"(?s).*\{.*Mint.*StrawberryAndOnion.*BurntPotato.*Tarmac.*\}"));
        }

        [TestCase("Mint", "6")]
        [TestCase("StrawberryAndOnion", "34")]
        [TestCase("BurntPotato", "77")]
        [TestCase("Tarmac", "4")]
        public void TheEnumShouldHaveTheCorrectConstantValues(string aName, string aValue)
        {
            const string singleLineMode = "(?s)";
            const string sp = @"\s*";
            const string any = @"\.*";
            Action<string> chk = s => Assert.That(iResult, Is.StringMatching(s));
            chk(singleLineMode + @".*" + aName + sp + "=" + sp + aValue +  sp + "," + any);
        }
    }

    public class ClassGenerationTests : CSharpGeneratorContext
    {
        public CType Void { get { return new NamedCType("void"); } }
        public CType Int { get { return new NamedCType("int"); } }
        public CType Byte { get { return new NamedCType("byte"); } }
        public CType SizeT { get { return new NamedCType("size_t"); } }
        public CType Char { get { return new NamedCType("char"); } }
        public CType Bool { get { return new NamedCType("bool"); } }
        public CType SpUint64 { get { return new NamedCType("sp_uint64"); } }
        public CType ConstChar { get { return new NamedCType("char"){Qualifiers={"const"}}; } }
        public CType VoidPtr { get { return new PointerCType(Void); } }
        public CType IntPtr { get { return new PointerCType(Int); } }
        public CType CharPtr { get { return new PointerCType(Char); } }
        public CType ConstCharPtr { get { return new PointerCType(ConstChar); } }
        public CType BoolPtr { get { return new PointerCType(Bool); } }
        public CType SizeTPtr { get { return new PointerCType(SizeT); } }
        public CType SpUint64Ptr { get { return new PointerCType(SpUint64); } }
        public CType IntArray { get { return new ArrayCType(null, Int); } }
        public CType IntArrayFive { get { return new ArrayCType(5, Int); } }
        public CType IntArrayTen { get { return new ArrayCType(10, Int); } }
        public CType ByteArray { get { return new ArrayCType(null, Byte); } }
        public CType CharArray { get { return new ArrayCType(null, Char); } }
        public CType CharArrayTen { get { return new ArrayCType(10, Char); } }
        public CType CharArraySixty { get { return new ArrayCType(60, Char); } }

        // These tests are rather unusual because of the need to be strongly
        // data-driven. GetTestData defines one entry for each native function
        // spec that we want to generate a class from. It also specifies the
        // expected C# specification of both the P/Invoke declaration and the
        // managed wrapper method. These terse entries are expanded into several
        // tests each by GenerateTestCases below. The test cases are all
        // attached to the RunTests "test", which demultiplexes them back to
        // the appropriate test methods.

        IEnumerable<TestCase> GetTestData()
        {
            var data = new []{
                new TestCase{
                    Name = "WhenMapping('void x(byte[])')",
                    // ByteArrayArgumentTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("alpha", ByteArray) },
                    Suppressed = true,
                    PInvokeArgs = { new ArgInfo {Name="alpha", Type="IntPtr"} },
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMappingCallbackStruct",
                    // void xxx(sp_room_callbacks * callbacks);
                    // CallbackStructArgumentTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("callbacks", new PointerCType(new NamedCType("sp_room_callbacks"))) },
                    Suppressed = true,
                    PInvokeArgs = { new ArgInfo {Name="callbacks", Type="IntPtr"} },
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMappingFunctionPointer",
                    // void xxx(sp_ready_cb * ready_callback);
                    // FunctionPointerArgumentTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("ready_callback", new PointerCType(new NamedCType("sp_ready_cb"))) },
                    Suppressed = true,
                    PInvokeArgs = { new ArgInfo {Name="ready_callback", Type="sp_ready_cb"} },
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMappingHandleArgument",
                    // void xxx(sp_device * device);
                    // HandleArgumentTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("device", new PointerCType(new NamedCType("sp_device"))) },
                    ManagedArgs = { new ArgInfo {Name="device", Type="Device"} },
                    PInvokeArgs = { new ArgInfo {Name="device", Type="IntPtr"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMapping('void x(handle **, int)')",
                    // void xxx(sp_device ** devices, int num_devices);
                    // HandleArrayArgumentTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("devices", new PointerCType(new PointerCType(new NamedCType("sp_device")))), Decl("num_devices", Int) },
                    ManagedArgs = { new ArgInfo {Name="devices", Type="Device[]"} },
                    PInvokeArgs = { new ArgInfo {Name="devices", Type="IntPtr"}, new ArgInfo {Name="num_devices", Type="int"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMapping('handle *x()')",
                    // sp_device * xxx();
                    // HandleReturnTransformer
                    NativeRet = new PointerCType(new NamedCType("sp_device")),
                    NativeArgs = { },
                    ManagedArgs = { },
                    PInvokeArgs = { },
                    ManagedRet = "Device",
                    PInvokeRet = "IntPtr",
                },
                new TestCase{
                    // void xxx(int * alpha)
                    // RefArgumentTransformer
                    Name = "WhenMapping('void x(int *)')",
                    NativeRet = Void,
                    NativeArgs = { Decl("alpha", IntPtr ) },
                    ManagedArgs = { new ArgInfo {Name="alpha", Type="ref int"} },
                    PInvokeArgs = { new ArgInfo {Name="alpha", Type="ref int"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    // void xxx(bool * beta)
                    // RefArgumentTransformer
                    Name = "WhenMapping('void x(bool *)')",
                    NativeRet = Void,
                    NativeArgs = { Decl("beta", BoolPtr ) },
                    ManagedArgs = { new ArgInfo {Name="beta", Type="ref bool"} },
                    PInvokeArgs = { new ArgInfo {Name="beta", Type="[MarshalAs(UnmanagedType.I1)]ref bool"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    // void xxx(size_t * gamma)
                    // RefArgumentTransformer
                    Name = "WhenMapping('void x(size_t *)')",
                    NativeRet = Void,
                    NativeArgs = { Decl("gamma", SizeTPtr ) },
                    ManagedArgs = { new ArgInfo {Name="gamma", Type="ref UIntPtr"} },
                    PInvokeArgs = { new ArgInfo {Name="gamma", Type="ref UIntPtr"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMapping('void x(sp_uint64 *)')",
                    // void xxx(sp_uint64 * delta)
                    // RefArgumentTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("delta", SpUint64Ptr ) },
                    ManagedArgs = { new ArgInfo {Name="delta", Type="ref ulong"} },
                    PInvokeArgs = { new ArgInfo {Name="delta", Type="ref ulong"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMappingRefEnum",
                    // void xxx(sp_flavor * epsilon)
                    // RefArgumentTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("epsilon", new PointerCType(new NamedCType("sp_flavor"))) },
                    ManagedArgs = { new ArgInfo {Name="epsilon", Type="ref Flavor"} },
                    PInvokeArgs = { new ArgInfo {Name="epsilon", Type="ref Flavor"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMappingRefHandle",
                    // void xxx(sp_device ** device)
                    // RefHandleArgumentTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("device", new PointerCType(new PointerCType(new NamedCType("sp_device")))) },
                    Suppressed = true,
                    PInvokeArgs = { new ArgInfo {Name="device", Type="ref IntPtr"} },
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMappingRefStruct",
                    // void xxx(sp_room * room)
                    // RefStructTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("room", new PointerCType(new NamedCType("sp_room"))) },
                    PInvokeArgs = { new ArgInfo {Name="room", Type="ref sp_room"} },
                    Suppressed = true, // There are few enough such functions that we write them by hand.
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMapping('const char * x()')",
                    // SimpleStringReturnTransformer
                    NativeRet = ConstCharPtr,
                    NativeArgs = { },
                    ManagedArgs = { },
                    ManagedRet = "string",
                    PInvokeArgs = { },
                    PInvokeRet = "IntPtr",
                },
                new TestCase{
                    Name = "WhenMapping('sp_error x()')",
                    // SpotifyErrorReturnTransformer
                    NativeRet = new NamedCType("sp_error"),
                    NativeArgs = { },
                    ManagedArgs = { },
                    ManagedRet = "void",
                    PInvokeArgs = { },
                    PInvokeRet = "SpotifyError", // Note that in the overrides we explicitly renamed sp_error to SpotifyError.
                },
                new TestCase{
                    Name = "WhenMapping('void x(const char *)')",
                    // StringArgumentTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("alpha", ConstCharPtr) },
                    ManagedArgs = { new ArgInfo {Name="alpha", Type="string"} },
                    PInvokeArgs = { new ArgInfo {Name="alpha", Type="IntPtr"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMapping('int x(char *, size_t)')",
                    // StringReturnTransformer
                    // Yes, we're testing with buffer_len as size_t but the return type int.
                    // This is how sp_session_remembered_user is declared.
                    NativeRet = Int,
                    NativeArgs = { Decl("buffer", CharPtr), Decl("buffer_len", SizeT) },
                    ManagedArgs = { },
                    PInvokeArgs = { new ArgInfo {Name="buffer", Type="IntPtr"}, new ArgInfo{Name="buffer_len", Type="UIntPtr"} },
                    ManagedRet = "string",
                    PInvokeRet = "int",
                },
                new TestCase{
                    Name = "WhenMappingThisPointer",
                    // void xxx(sp_file * file);
                    // ThisPointerArgumentTransformer
                    // (Note: all the methods we generate during these tests are on the 'File'
                    // class. Most don't start with an sp_file * argument, so they are generated
                    // as static methods. This one should generate as an instance method.)
                    // TODO: Assert that the generator sets IsStatic=false
                    NativeRet = Void,
                    NativeArgs = { Decl("file", new PointerCType(new NamedCType("sp_file"))) },
                    ManagedArgs = { },
                    PInvokeArgs = { new ArgInfo {Name="file", Type="IntPtr"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    // void xxx(int alpha)
                    // TrivialArgumentTransformer
                    Name = "WhenMapping('void x(int)')",
                    NativeRet = Void,
                    NativeArgs = { Decl("alpha", Int ) },
                    ManagedArgs = { new ArgInfo {Name="alpha", Type="int"} },
                    PInvokeArgs = { new ArgInfo {Name="alpha", Type="int"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    // void xxx(bool beta)
                    // TrivialArgumentTransformer
                    Name = "WhenMapping('void x(bool)')",
                    NativeRet = Void,
                    NativeArgs = { Decl("beta", Bool ) },
                    ManagedArgs = { new ArgInfo {Name="beta", Type="bool"} },
                    PInvokeArgs = { new ArgInfo {Name="beta", Type="[MarshalAs(UnmanagedType.I1)]bool"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    // void xxx(size_t gamma)
                    // TrivialArgumentTransformer
                    Name = "WhenMapping('void x(size_t)')",
                    NativeRet = Void,
                    NativeArgs = { Decl("gamma", SizeT ) },
                    ManagedArgs = { new ArgInfo {Name="gamma", Type="UIntPtr"} },
                    PInvokeArgs = { new ArgInfo {Name="gamma", Type="UIntPtr"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMappingEnum",
                    // void xxx(sp_flavor epsilon)
                    // TrivialArgumentTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("epsilon", new NamedCType("sp_flavor")) },
                    ManagedArgs = { new ArgInfo {Name="epsilon", Type="Flavor"} },
                    PInvokeArgs = { new ArgInfo {Name="epsilon", Type="Flavor"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    // void xxx(int* alpha, int num_alpha)
                    // TrivialArrayArgumentTransformer
                    Name = "WhenMapping('void x(int *, int)')",
                    NativeRet = Void,
                    NativeArgs = { Decl("alpha", IntPtr ), Decl("num_alpha", Int) },
                    ManagedArgs = { new ArgInfo {Name="alpha", Type="int[]"} },
                    PInvokeArgs = { new ArgInfo {Name="alpha", Type="IntPtr"}, new ArgInfo {Name="num_alpha", Type="int"} },
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    // TrivialReturnTransformer
                    Name = "WhenMapping('int x()')",
                    NativeRet = Int,
                    NativeArgs = {},
                    ManagedArgs = {},
                    PInvokeArgs = {},
                    ManagedRet = "int",
                    PInvokeRet = "int",
                },
                new TestCase{
                    // TrivialReturnTransformer
                    Name = "WhenMapping('bool x()')",
                    NativeRet = Bool,
                    NativeArgs = {},
                    ManagedArgs = {},
                    PInvokeArgs = {},
                    ManagedRet = "bool",
                    PInvokeRet = "[MarshalAs(UnmanagedType.I1)]bool",
                },
                new TestCase{
                    Name = "WhenMapping('sp_uint64 x()')",
                    // TrivialReturnTransformer
                    NativeRet = SpUint64,
                    NativeArgs = {},
                    ManagedArgs = {},
                    PInvokeArgs = {},
                    ManagedRet = "ulong",
                    PInvokeRet = "ulong",
                },
                new TestCase{
                    Name = "WhenMappingEnumReturn",
                    // sp_flavor xxx()
                    // TrivialReturnTransformer
                    NativeRet = new NamedCType("sp_flavor"),
                    NativeArgs = {},
                    ManagedArgs = {},
                    PInvokeArgs = {},
                    ManagedRet = "Flavor",
                    PInvokeRet = "Flavor",
                },
                new TestCase{
                    Name = "WhenMapping('void x(char *, int)')",
                    // UnknownLengthStringReturnTransformer
                    // Note: This transformation is very narrowly targeted to avoid
                    // the risk of it misfiring. It only applies when the char* arg
                    // is called 'buffer' and the int arg is called 'buffer_size'.
                    NativeRet = Void,
                    NativeArgs = { Decl("buffer", CharPtr), Decl("buffer_size", Int) },
                    ManagedArgs = { },
                    PInvokeArgs = { new ArgInfo {Name="buffer", Type="IntPtr"}, new ArgInfo{Name="buffer_size", Type="int"} },
                    ManagedRet = "string",
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMapping('void x(void)')",
                    // VoidArgumentListTransformer
                    // Note: This is only here because our parser is pretty simple
                    // and doesn't know that (void) is C syntax for an empty
                    // argument list.
                    NativeRet = Void,
                    NativeArgs = { Decl("", Void) },
                    ManagedArgs = { },
                    PInvokeArgs = {},
                    ManagedRet = "void",
                    PInvokeRet = "void",
                },
                new TestCase{
                    Name = "WhenMapping('void x(void *)')",
                    // VoidStarArgumentTransformer
                    NativeRet = Void,
                    NativeArgs = { Decl("alpha", VoidPtr) },
                    Suppressed = true,
                    PInvokeArgs = { new ArgInfo {Name="alpha", Type="IntPtr"} },
                    PInvokeRet = "void",
                },
            };
            return data;
        }

        public KeyValuePair<string, FunctionCType> Function(string aName, CType aReturnType, Declaration[] aArgTypes)
        {
            return new KeyValuePair<string, FunctionCType>(aName, FuncType(aReturnType, aArgTypes));
        }
        public FunctionCType FuncType(CType aReturnType, Declaration[] aArgTypes)
        {
            var func = new FunctionCType(aReturnType);
            func.Arguments.AddRange(aArgTypes);
            return func;
        }
        public Declaration Decl(string aName, CType aType)
        {
            return new Declaration{Name = aName, CType = aType};
        }

        protected Mock<IFunctionGenerator> iAssemblerMock;
        protected IFunctionGenerator iAssembler;
        protected List<string> iManagedParameterOrder;
        protected List<string> iPInvokeParameterOrder;

        [SetUp]
        public void ResetParameterOrder()
        {
            iManagedParameterOrder = new List<string>();
            iPInvokeParameterOrder = new List<string>();
        }

        protected override IFunctionFactory MakeFunctionFactory()
        {
            iAssemblerMock = new Mock<IFunctionGenerator>();
            iAssembler = iAssemblerMock.Object;
            var factory = new Mock<IFunctionFactory>();
            factory.Setup(x => x.CreateAssembler(It.IsAny<string>(), It.IsAny<string>())).Returns((string nativeName, string managedName)=>iAssembler);
            factory.Setup(x => x.CreateAnalyser(It.IsAny<List<Declaration>>(), It.IsAny<CType>())).Returns((
                List<Declaration> decls, CType retType)=>new FunctionSpecificationAnalyser(decls, retType));
            iAssemblerMock
                .Setup(x=>x.AddManagedParameter(It.IsAny<string>(), It.IsAny<CSharpType>()))
                .Callback((string name, CSharpType t) => iManagedParameterOrder.Add(name));
            iAssemblerMock
                .Setup(x=>x.AddPInvokeParameter(It.IsAny<CSharpType>(), It.IsAny<string>(), It.IsAny<string>()))
                .Callback((CSharpType t, string name, string expr) => iPInvokeParameterOrder.Add(name));
            return factory.Object;
        }

        [TestCaseSource("GenerateTestCases")]
        public void RunTestCases(Action<ClassGenerationTests> aAction)
        {
            aAction(this);
        }

        void GenerateClass(CType aRetType, Declaration[] aParameters)
        {
            iGenerator.GenerateCSharpClass("", "sp_file", new[]{
                Function("sp_file_do_something", aRetType, aParameters)
            });
        }

        void CheckManagedParameterWasGenerated(CType aRetType, Declaration[] aParameters, string aExpectedParameterName, string aExpectedCSharpType)
        {
            GenerateClass(aRetType, aParameters);
            iAssemblerMock.Verify(x => x.AddManagedParameter(aExpectedParameterName, It.Is<CSharpType>(y => y.ToString() == aExpectedCSharpType)));
        }

        void CheckManagedParameterOrder(CType aRetType, Declaration[] aParameters, string[] aOrder)
        {
            GenerateClass(aRetType, aParameters);
            Assert.That(iManagedParameterOrder, Is.EqualTo(aOrder));
        }

        void CheckManagedReturnType(CType aRetType, Declaration[] aParameters, string aExpectedReturnType)
        {
            GenerateClass(aRetType, aParameters);
            if (aExpectedReturnType == "void")
            {
                // void is the default, so we won't actually need to have called SetManagedReturn.
                iAssemblerMock.Verify(x => x.SetManagedReturn(It.Is<CSharpType>(y => y.ToString() == "void")), Times.AtMostOnce());
                iAssemblerMock.Verify(x => x.SetManagedReturn(It.Is<CSharpType>(y => y.ToString() != "void")), Times.Never());
            }
            else
            {
                iAssemblerMock.Verify(x => x.SetManagedReturn(It.Is<CSharpType>(y => y.ToString() == aExpectedReturnType)));
                iAssemblerMock.Verify(x => x.SetManagedReturn(It.Is<CSharpType>(y => y.ToString() != aExpectedReturnType)), Times.Never());
            }
        }

        void CheckPInvokeParameterWasGenerated(CType aRetType, Declaration[] aParameters, string aExpectedParameterName, string aExpectedCSharpType)
        {
            GenerateClass(aRetType, aParameters);
            iAssemblerMock.Verify(x => x.AddPInvokeParameter(It.Is<CSharpType>(y => y.ToString() == aExpectedCSharpType), aExpectedParameterName, It.IsAny<string>()));
        }

        void CheckPInvokeParameterOrder(CType aRetType, Declaration[] aParameters, string[] aOrder)
        {
            GenerateClass(aRetType, aParameters);
            Assert.That(iPInvokeParameterOrder, Is.EqualTo(aOrder));
        }

        void CheckPInvokeReturnType(CType aRetType, Declaration[] aParameters, string aExpectedReturnType)
        {
            GenerateClass(aRetType, aParameters);
            if (aExpectedReturnType == "void")
            {
                iAssemblerMock.Verify(x => x.SetPInvokeReturn(It.IsAny<CSharpType>(), It.IsAny<string>()), Times.Never());
            }
            else
            {
                iAssemblerMock.Verify(x => x.SetPInvokeReturn(It.Is<CSharpType>(y => y.ToString() == aExpectedReturnType), It.IsAny<string>()));
            }
        }

        void CheckWhetherManagedWrapperWasSuppressed(CType aRetType, Declaration[] aParameters, bool aSuppressed)
        {
            GenerateClass(aRetType, aParameters);
            iAssemblerMock.Verify(x => x.SuppressManagedWrapper(), aSuppressed ? Times.Once() : Times.Never());
        }

        static Action<ClassGenerationTests> MkAct(Action<ClassGenerationTests> aAction)
        {
            return aAction;
        }

        class ArgInfo
        {
            public string Name;
            public string Type;
        }
        class TestCase
        {
            public List<Declaration> NativeArgs = new List<Declaration>();
            public List<ArgInfo> ManagedArgs = new List<ArgInfo>();
            public List<ArgInfo> PInvokeArgs = new List<ArgInfo>();
            public CType NativeRet;
            public string ManagedRet;
            public string PInvokeRet;
            public bool Suppressed;
            public string Name;
        }

        public IEnumerable<TestCaseData> GenerateTestCases()
        {
            // Note: This used to be a generator (yield-return) method, but
            // Mono's C# compiler before version 2.11.2 is broken and makes
            // a mess of the results.
            // See Xamarin bug 4641.
            List<TestCaseData> testcases = new List<TestCaseData>();
            var data = GetTestData();
            foreach (var item in data)
            {
                var nativeRetType = item.NativeRet;
                var nativeArgs = item.NativeArgs.ToArray();
                var testName = item.Name;
                Console.WriteLine("nativeArgs: {0}", String.Join(", ", nativeArgs.Select(x=>x.ToString())));

                bool suppressed = item.Suppressed;
                testcases.Add(new TestCaseData(MkAct(x=>x.CheckWhetherManagedWrapperWasSuppressed(nativeRetType, nativeArgs, suppressed)))
                    .SetName(String.Format("{0}_CheckWhetherManagedWrapperWasSuppressed({1})", testName, suppressed)));
                if (!suppressed)
                {
                    // Check each managed argument was present with the correct type.
                    foreach (var managedArg in item.ManagedArgs)
                    {
                        var managedArgName = managedArg.Name;
                        var managedArgType = managedArg.Type;
                        testcases.Add(new TestCaseData(MkAct(x => x.CheckManagedParameterWasGenerated(nativeRetType,
                            nativeArgs, managedArgName, managedArgType)))
                            .SetName(String.Format("{0}_CheckManagedParameterWasGenerated({1}, {2}, {3}, {4})", testName, nativeRetType, nativeArgs, managedArgName, managedArgType)));
                    }

                    // Check all the managed arguments were in the right order.
                    var managedArgOrder = item.ManagedArgs.Select(x => x.Name).ToArray();
                    testcases.Add(new TestCaseData(MkAct(x => x.CheckManagedParameterOrder(nativeRetType, nativeArgs, managedArgOrder)))
                        .SetName(String.Format("{0}_CheckManagedParameterOrder({1}, {2}, {3})", testName, nativeRetType, nativeArgs, managedArgOrder)));

                    // Check the managed return type was correct.
                    var managedRet = item.ManagedRet;
                    testcases.Add(new TestCaseData(MkAct(x => x.CheckManagedReturnType(nativeRetType, nativeArgs, managedRet)))
                        .SetName(String.Format("{0}_CheckManagedReturnType({1}, {2}, {3})", testName, nativeRetType, nativeArgs, managedRet)));
                }

                // Check each pinvoke argument was present with the correct type.
                foreach (var pinvokeArg in item.PInvokeArgs)
                {
                    var pinvokeArgName = pinvokeArg.Name;
                    var pinvokeArgType = pinvokeArg.Type;
                    testcases.Add(new TestCaseData(
                        MkAct(x=>x.CheckPInvokeParameterWasGenerated(nativeRetType,nativeArgs, pinvokeArgName, pinvokeArgType)))
                        .SetName(String.Format("{0}_CheckPInvokeParameterWasGenerated({1}, {2}, {3}, {4})",testName, nativeRetType, nativeArgs, pinvokeArgName, pinvokeArgType)));
                }

                // Check all the P/Invoke arguments were in the right order.
                var pinvokeArgOrder = item.PInvokeArgs.Select(x=>x.Name).ToArray();
                testcases.Add(new TestCaseData(MkAct(x=>x.CheckPInvokeParameterOrder(nativeRetType, nativeArgs, pinvokeArgOrder)))
                    .SetName(String.Format("{0}_CheckPInvokeParameterOrder({1}, {2}, {3})", testName, nativeRetType, nativeArgs, pinvokeArgOrder)));

                // Check the P/Invoke return type was correct.
                var pinvokeRet = item.PInvokeRet;
                testcases.Add(new TestCaseData(MkAct(x=>x.CheckPInvokeReturnType(nativeRetType, nativeArgs, pinvokeRet)))
                    .SetName(String.Format("{0}_CheckPInvokeReturnType({1}, {2}, {3})", testName, nativeRetType, nativeArgs, pinvokeRet)));
            }
            return testcases;
        }
    }
}


text:
import { IEdible } from './IEdible';

export type IMagicPotion = IEdible<'l'>;