text:
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGeneration
{
    public class SymbolEditorTests
    {
        private readonly SyntaxGenerator g = SyntaxGenerator.GetGenerator(new CustomWorkspace(), LanguageNames.CSharp);

        private Solution GetSolution(params string[] sources)
        {
            var ws = new CustomWorkspace();
            var pid = ProjectId.CreateNewId();

            var docs = sources.Select((s, i) =>
                DocumentInfo.Create(
                    DocumentId.CreateNewId(pid),
                    name: "code" + i,
                    loader: TextLoader.From(TextAndVersion.Create(SourceText.From(s), VersionStamp.Default)))).ToList();

            var proj = ProjectInfo.Create(pid, VersionStamp.Default, "test", "test.dll", LanguageNames.CSharp, documents: docs);

            return ws.AddProject(proj).Solution;
        }

        private IEnumerable<ISymbol> GetSymbols(Solution solution, string name)
        {
            var compilation = solution.Projects.First().GetCompilationAsync().Result;
            return compilation.GlobalNamespace.GetMembers(name);
        }

        private string GetActual(Document document)
        {
            document = Simplifier.ReduceAsync(document).Result;
            document = Formatter.FormatAsync(document, Formatter.Annotation).Result;
            document = Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation).Result;
            return document.GetSyntaxRootAsync().Result.ToFullString();
        }

        [Fact]
        public void TestEditOneDeclaration()
        {
            var code =
@"class C
{
}";

            var expected =
@"class C
{
    void m()
    {
    }
}";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))).Result;
            Assert.Equal(1, newSymbol.GetMembers("m").Length);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestSequentialEdits()
        {
            var code =
@"class C
{
}";

            var expected =
@"class C
{
    void m()
    {
    }

    void m2()
    {
    }
}";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, g.MethodDeclaration("m"))).Result;
            Assert.Equal(1, newSymbol.GetMembers("m").Length);
            Assert.Equal(0, newSymbol.GetMembers("m2").Length);

            newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, g.MethodDeclaration("m2"))).Result;
            Assert.Equal(1, newSymbol.GetMembers("m").Length);
            Assert.Equal(1, newSymbol.GetMembers("m2").Length);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestSequentialEdit_NewSymbols()
        {
            var code =
@"class C
{
}";

            var expected =
@"class C
{
    void m()
    {
    }

    void m2()
    {
    }
}";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))).Result;
            Assert.Equal(1, newSymbol.GetMembers("m").Length);
            Assert.Equal(0, newSymbol.GetMembers("m2").Length);

            newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(newSymbol, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))).Result;
            Assert.Equal(1, newSymbol.GetMembers("m").Length);
            Assert.Equal(1, newSymbol.GetMembers("m2").Length);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestSequentialEdits_SeparateSymbols()
        {
            var code =
@"class A
{
}

class B
{
}";

            var expected =
@"class A
{
    void ma()
    {
    }
}

class B
{
    void mb()
    {
    }
}";

            var solution = GetSolution(code);
            var comp = solution.Projects.First().GetCompilationAsync().Result;
            var symbolA = comp.GlobalNamespace.GetMembers("A").First();
            var symbolB = comp.GlobalNamespace.GetMembers("B").First();

            var editor = SymbolEditor.Create(solution);

            var newSymbolA = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbolA, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("ma"))).Result;
            Assert.Equal(1, newSymbolA.GetMembers("ma").Length);

            var newSymbolB = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbolB, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("mb"))).Result;
            Assert.Equal(1, newSymbolB.GetMembers("mb").Length);

            var actual = GetActual(editor.GetChangedDocuments().First());
            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestSequentialEdits_SeparateSymbolsAndFiles()
        {
            var code1 =
@"class A
{
}";

            var code2 =
@"class B
{
}";

            var expected1 =
@"class A
{
    void ma()
    {
    }
}";

            var expected2 =
@"class B
{
    void mb()
    {
    }
}";

            var solution = GetSolution(code1, code2);
            var comp = solution.Projects.First().GetCompilationAsync().Result;
            var symbolA = comp.GlobalNamespace.GetMembers("A").First();
            var symbolB = comp.GlobalNamespace.GetMembers("B").First();

            var editor = SymbolEditor.Create(solution);

            var newSymbolA = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbolA, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("ma"))).Result;
            Assert.Equal(1, newSymbolA.GetMembers("ma").Length);

            var newSymbolB = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbolB, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("mb"))).Result;
            Assert.Equal(1, newSymbolB.GetMembers("mb").Length);

            var docs = editor.GetChangedDocuments().ToList();
            var actual1 = GetActual(docs[0]);
            var actual2 = GetActual(docs[1]);

            Assert.Equal(expected1, actual1);
            Assert.Equal(expected2, actual2);
        }

        [Fact]
        public void TestEditAllDeclarations_SameFile()
        {
            var code =
@"public partial class C
{
}

public partial class C
{
}";

            var expected =
@"internal partial class C
{
}

internal partial class C
{
}";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditAllDeclarationsAsync(symbol, (e, d) => e.SetAccessibility(d, Accessibility.Internal)).Result;

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestEditAllDeclarations_MultipleFiles()
        {
            var code1 =
@"class C
{
}";

            var code2 =
@"class C
{
    void M() {}
}";

            var expected1 =
@"public class C
{
}";

            var expected2 =
@"public class C
{
    void M() {}
}";

            var solution = GetSolution(code1, code2);
            var comp = solution.Projects.First().GetCompilationAsync().Result;
            var symbol = comp.GlobalNamespace.GetMembers("C").First();

            var editor = SymbolEditor.Create(solution);
            var newSymbol = (INamedTypeSymbol)editor.EditAllDeclarationsAsync(symbol, (e, d) => e.SetAccessibility(d, Accessibility.Public)).Result;

            var docs = editor.GetChangedDocuments().ToList();
            var actual1 = GetActual(docs[0]);
            var actual2 = GetActual(docs[1]);

            Assert.Equal(expected1, actual1);
            Assert.Equal(expected2, actual2);
        }

        [Fact]
        public void TestEditDeclarationWithLocation_Last()
        {
            var code =
@"partial class C
{
}

partial class C
{
}";

            var expected =
@"partial class C
{
}

partial class C
{
    void m()
    {
    }
}";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var location = symbol.Locations.Last();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))).Result;
            Assert.Equal(1, newSymbol.GetMembers("m").Length);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestEditDeclarationWithLocation_First()
        {
            var code =
@"partial class C
{
}

partial class C
{
}";

            var expected =
@"partial class C
{
    void m()
    {
    }
}

partial class C
{
}";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var location = symbol.Locations.First();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))).Result;
            Assert.Equal(1, newSymbol.GetMembers("m").Length);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestEditDeclarationWithLocation_SequentialEdits_SameLocation()
        {
            var code =
@"partial class C
{
}

partial class C
{
}";

            var expected =
@"partial class C
{
}

partial class C
{
    void m()
    {
    }

    void m2()
    {
    }
}";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var location = symbol.Locations.Last();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))).Result;
            Assert.Equal(1, newSymbol.GetMembers("m").Length);

            // reuse location from original symbol/solution
            var newSymbol2 = (INamedTypeSymbol)editor.EditOneDeclarationAsync(newSymbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))).Result;
            Assert.Equal(1, newSymbol2.GetMembers("m").Length);
            Assert.Equal(1, newSymbol2.GetMembers("m2").Length);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestEditDeclarationWithLocation_SequentialEdits_NewLocation()
        {
            var code =
@"partial class C
{
}

partial class C
{
}";

            var expected =
@"partial class C
{
}

partial class C
{
    void m()
    {
    }

    void m2()
    {
    }
}";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var location = symbol.Locations.Last();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, location, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m"))).Result;
            Assert.Equal(1, newSymbol.GetMembers("m").Length);

            // use location from new symbol
            var newLocation = newSymbol.Locations.Last();
            var newSymbol2 = (INamedTypeSymbol)editor.EditOneDeclarationAsync(newSymbol, newLocation, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))).Result;
            Assert.Equal(1, newSymbol2.GetMembers("m").Length);
            Assert.Equal(1, newSymbol2.GetMembers("m2").Length);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestEditDeclarationWithMember()
        {
            var code =
@"partial class C
{
}

partial class C
{
    void m()
    {
    }
}";

            var expected =
@"partial class C
{
}

partial class C
{
    void m()
    {
    }

    void m2()
    {
    }
}";

            var solution = GetSolution(code);
            var symbol = (INamedTypeSymbol)GetSymbols(solution, "C").First();
            var member = symbol.GetMembers("m").First();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, member, (e, d) => e.AddMember(d, e.Generator.MethodDeclaration("m2"))).Result;
            Assert.Equal(1, newSymbol.GetMembers("m").Length);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestChangeLogicalIdentityReturnsCorrectSymbol_OneDeclaration()
        {
            // proves that APIs return the correct new symbol even after a change that changes the symbol's logical identity.
            var code =
@"class C
{
}";

            var expected =
@"class X
{
}";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, (e, d) => e.SetName(d, "X")).Result;
            Assert.Equal("X", newSymbol.Name);

            // original symbols cannot be rebound after identity change.
            var reboundSymbol = editor.GetCurrentSymbolAsync(symbol).Result;
            Assert.Null(reboundSymbol);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestChangeLogicalIdentityReturnsCorrectSymbol_AllDeclarations()
        {
            // proves that APIs return the correct new symbol even after a change that changes the symbol's logical identity.
            var code =
@"partial class C
{
}

partial class C
{
}";

            var expected =
@"partial class X
{
}

partial class X
{
}";
            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditAllDeclarationsAsync(symbol, (e, d) => e.SetName(d, "X")).Result;
            Assert.Equal("X", newSymbol.Name);

            // original symbols cannot be rebound after identity change.
            var reboundSymbol = editor.GetCurrentSymbolAsync(symbol).Result;
            Assert.Null(reboundSymbol);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestRemovedDeclarationReturnsNull()
        {
            var code =
@"class C
{
}";

            var expected =
@"";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, (e, d) => e.RemoveNode(d)).Result;
            Assert.Null(newSymbol);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestRemovedOneOfManyDeclarationsReturnsChangedSymbol()
        {
            var code =
@"partial class C
{
}

partial class C
{
}";

            var expected =
@"
partial class C
{
}";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbol, (e, d) => e.RemoveNode(d)).Result;
            Assert.NotNull(newSymbol);
            Assert.Equal("C", newSymbol.Name);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestRemoveAllOfManyDeclarationsReturnsNull()
        {
            var code =
@"partial class C
{
}

partial class C
{
}";

            var expected =
@"
";

            var solution = GetSolution(code);
            var symbol = GetSymbols(solution, "C").First();
            var editor = SymbolEditor.Create(solution);

            var newSymbol = (INamedTypeSymbol)editor.EditAllDeclarationsAsync(symbol, (e, d) => e.RemoveNode(d)).Result;
            Assert.Null(newSymbol);

            var actual = GetActual(editor.GetChangedDocuments().First());

            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestRemoveFieldFromMultiFieldDeclaration()
        {
            var code =
@"class C
{
    public int X, Y;
}";

            var expected =
@"class C
{
    public int Y;
}";

            var expected2 =
@"class C
{
}";

            var solution = GetSolution(code);
            var symbol = (INamedTypeSymbol)GetSymbols(solution, "C").First();
            var symbolX = symbol.GetMembers("X").First();
            var symbolY = symbol.GetMembers("Y").First();

            var editor = SymbolEditor.Create(solution);

            // remove X -- should remove only part of the field declaration.
            var newSymbolX = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbolX, (e, d) => e.RemoveNode(d)).Result;
            Assert.Null(newSymbolX);

            var actual = GetActual(editor.GetChangedDocuments().First());
            Assert.Equal(expected, actual);

            // now remove Y -- should remove entire remaining field declaration
            var newSymbolY = (INamedTypeSymbol)editor.EditOneDeclarationAsync(symbolY, (e, d) => e.RemoveNode(d)).Result;
            Assert.Null(newSymbolY);

            actual = GetActual(editor.GetChangedDocuments().First());
            Assert.Equal(expected2, actual);
        }
    }
}


text:
package utils

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

var (
	client    *http.Client
	Transport *http.Transport
)

// -------- init() --------
func init() {
	Transport = &http.Transport{
		MaxIdleConnsPerHost: 1024,
	}
	client = &http.Client{
		Transport: Transport,
	}
}

// -------- wait_http_response() --------
func wait_http_response(url string, rsp *http.Response, err error) ([]byte, error) {
	if err != nil {
		return nil, fmt.Errorf("Wait http response %s: %v", url, err)
	}
	if rsp.StatusCode >= 400 {
		return nil, fmt.Errorf("%s: %s", url, rsp.Status)
	}

	rsp_body, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		return nil, fmt.Errorf("Read response body: %v", err)
	}

	return rsp_body, nil
}

// ======== HttpPostBytes() ========
func HttpPostBytes(url string, body []byte) ([]byte, error) {
	rsp, err := client.Post(url, "application/octet-stream", bytes.NewReader(body))
	defer rsp.Body.Close()

	return wait_http_response(url, rsp, err)
}

// ======== HttpPost() ========
func HttpPost(url string, values url.Values) ([]byte, error) {
	rsp, err := client.PostForm(url, values)
	defer rsp.Body.Close()

	return wait_http_response(url, rsp, err)
}

// ======== HttpGet() ========
func HttpGet(url string) ([]byte, error) {
	rsp, err := client.Get(url)
	defer rsp.Body.Close()

	return wait_http_response(url, rsp, err)
}

// ======== HttpDelete() ========
func HttpDelete(url string) error {
	req, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		return err
	}

	rsp, err := client.Do(req)
	defer rsp.Body.Close()
	if err != nil {
		return err
	}
	body, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		return err
	}
	switch rsp.StatusCode {
	case http.StatusNotFound, http.StatusAccepted, http.StatusOK:
		return nil
	}

	m := make(map[string]interface{})
	if err := json.Unmarshal(body, m); err == nil {
		if s, ok := m["error"].(string); ok {
			return errors.New(s)
		}
	}

	return errors.New(string(body))
}

// ======== HttpDoRequest() ========
func HttpDoRequest(req *http.Request) (*http.Response, error) {
	return client.Do(req)
}

// ======== HttpDownloadFile() ========
func HttpDownloadFile(url string) (filename string, rc io.ReadCloser, err error) {
	rsp, err := client.Get(url)
	if err != nil {
		return "", nil, err
	}
	contentDisposition := rsp.Header["Content-Disposition"]
	if len(contentDisposition) > 0 {
		if strings.HasPrefix(contentDisposition[0], "filename=") {
			filename = contentDisposition[0][len("filename="):]
			filename = strings.Trim(filename, "\"")
		}
	}
	rc = rsp.Body
	return
}

// ======== HttpPost_by_Func ========
func HttpPost_by_Func(url string, values url.Values, allocatedBuf []byte, eachBufferFn func([]byte, int)) error {
	rsp, err := client.PostForm(url, values)
	defer rsp.Body.Close()
	if err != nil {
		return err
	}
	if rsp.StatusCode != 200 {
		return fmt.Errorf("%s: %s", url, rsp.Status)
	}
	for {
		n, err := rsp.Body.Read(allocatedBuf)
		if n > 0 {
			eachBufferFn(allocatedBuf, n)
		}
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}
	}
	return nil
}

// ======== HttpPost_by_Reader() ========
func HttpPost_by_reader(url string, values url.Values, readFn func(io.Reader) error) error {
	rsp, err := client.PostForm(url, values)
	defer rsp.Body.Close()
	if err != nil {
		return err
	}
	if rsp.StatusCode != 200 {
		return fmt.Errorf("%s: %s", url, rsp.Status)
	}
	return readFn(rsp.Body)
}

redpajama_set_name: RedPajamaGithub


text:
var notFoundView = require("./../../view/notFound/notFound.handlebars");

function notfound(ctx, next) {
    var spa = $('.spa');
    spa
        .empty()
        .append(notFoundView);

}

module.exports = notfound;


text:
<?php

/* $Id$ */

/**
 * Classes used to manipulate rational numbers.
 *
 * @author Martin Geisler <mgeisler@users.sourceforge.net>
 * @version $Revision$
 * @date $Date$
 * @license http://www.gnu.org/licenses/gpl.html GNU General Public
 * License (GPL)
 * @package PEL
 */

/**#@+ Required class definitions. */
require_once('PelEntryLong.php');
/**#@-*/

/**
 * Class for holding unsigned rational numbers.
 *
 * This class can hold rational numbers, consisting of a numerator and
 * denominator both of which are of type unsigned long.  Each rational
 * is represented by an array with just two entries: the numerator and
 * the denominator, in that order.
 *
 * The class can hold either just a single rational or an array of
 * rationals.  The class will be used to manipulate any of the Exif
 * tags which can have format {@link PelFormat::RATIONAL} like in this
 * example:
 *
 * <code>
 * $resolution = $ifd->getEntry(PelTag::X_RESOLUTION);
 * $resolution->setValue(array(1, 300));
 * </code>
 *
 * Here the x-resolution is adjusted to 1/300, which will be 300 DPI,
 * unless the {@link PelTag::RESOLUTION_UNIT resolution unit} is set
 * to something different than 2 which means inches.
 *
 * @author Martin Geisler <mgeisler@users.sourceforge.net>
 * @package PEL
 */
class PelEntryRational extends PelEntryLong {

  /**
   * Make a new entry that can hold an unsigned rational.
   *
   * @param PelTag the tag which this entry represents.  This should
   * be one of the constants defined in {@link PelTag}, e.g., {@link
   * PelTag::X_RESOLUTION}, or any other tag which can have format
   * {@link PelFormat::RATIONAL}.
   *
   * @param array $value... the rational(s) that this entry will
   * represent.  The arguments passed must obey the same rules as the
   * argument to {@link setValue}, namely that each argument should be
   * an array with two entries, both of which must be within range of
   * an unsigned long (32 bit), that is between 0 and 4294967295
   * (inclusive).  If not, then a {@link PelOverflowException} will be
   * thrown.
   */
  function __construct($tag /* $value... */) {
    $this->tag       = $tag;
    $this->format    = PelFormat::RATIONAL;
    $this->dimension = 2;
    $this->min       = 0;
    $this->max       = 4294967295;

    $value = func_get_args();
    array_shift($value);
    $this->setValueArray($value);
  }

  /**
   * Format a rational number.
   *
   * The rational will be returned as a string with a slash '/'
   * between the numerator and denominator.
   *
   * @param array the rational which will be formatted.
   *
   * @param boolean not used.
   *
   * @return string the rational formatted as a string suitable for
   * display.
   */
  function formatNumber($number, $brief = false) {
    return $number[0] . '/' . $number[1];
  }

  /**
   * Get the value of an entry as text.
   *
   * The value will be returned in a format suitable for presentation,
   * e.g., rationals will be returned as 'x/y', ASCII strings will be
   * returned as themselves etc.
   *
   * @param boolean some values can be returned in a long or more
   * brief form, and this parameter controls that.
   *
   * @return string the value as text.
   */
  function getText($brief = false) {
    if (isset($this->value[0]))
      $v = $this->value[0];

    switch ($this->tag) {
    case PelTag::FNUMBER:
      //CC (e->components, 1, v);
      return Pel::fmt('f/%.01f', $v[0]/$v[1]);

    case PelTag::APERTURE_VALUE:
      //CC (e->components, 1, v);
      //if (!v_rat.denominator) return (NULL);
      return Pel::fmt('f/%.01f', pow(2, $v[0]/$v[1]/2));

    case PelTag::FOCAL_LENGTH:
      //CC (e->components, 1, v);
      //if (!v_rat.denominator) return (NULL);
      return Pel::fmt('%.1f mm', $v[0]/$v[1]);

    case PelTag::SUBJECT_DISTANCE:
      //CC (e->components, 1, v);
      //if (!v_rat.denominator) return (NULL);
      return Pel::fmt('%.1f m', $v[0]/$v[1]);

    case PelTag::EXPOSURE_TIME:
      //CC (e->components, 1, v);
      //if (!v_rat.denominator) return (NULL);
      if ($v[0]/$v[1] < 1)
        return Pel::fmt('1/%d sec.', $v[1]/$v[0]);
      else
        return Pel::fmt('%d sec.', $v[0]/$v[1]);

    case PelTag::GPS_LATITUDE:
    case PelTag::GPS_LONGITUDE:
      $degrees = $this->value[0][0]/$this->value[0][1];
      $minutes = $this->value[1][0]/$this->value[1][1];
      $seconds = $this->value[2][0]/$this->value[2][1];

      return sprintf('%s° %s\' %s" (%.2f°)',
                     $degrees, $minutes, $seconds,
                     $degrees + $minutes/60 + $seconds/3600);

    default:
      return parent::getText($brief);
    }
  }
}

/**
 * Class for holding signed rational numbers.
 *
 * This class can hold rational numbers, consisting of a numerator and
 * denominator both of which are of type unsigned long.  Each rational
 * is represented by an array with just two entries: the numerator and
 * the denominator, in that order.
 *
 * The class can hold either just a single rational or an array of
 * rationals.  The class will be used to manipulate any of the Exif
 * tags which can have format {@link PelFormat::SRATIONAL}.
 *
 * @author Martin Geisler <mgeisler@users.sourceforge.net>
 * @package PEL
 */
class PelEntrySRational extends PelEntrySLong {

  /**
   * Make a new entry that can hold a signed rational.
   *
   * @param PelTag the tag which this entry represents.  This should
   * be one of the constants defined in {@link PelTag}, e.g., {@link
   * PelTag::SHUTTER_SPEED_VALUE}, or any other tag which can have
   * format {@link PelFormat::SRATIONAL}.
   *
   * @param array $value... the rational(s) that this entry will
   * represent.  The arguments passed must obey the same rules as the
   * argument to {@link setValue}, namely that each argument should be
   * an array with two entries, both of which must be within range of
   * a signed long (32 bit), that is between -2147483648 and
   * 2147483647 (inclusive).  If not, then a {@link
   * PelOverflowException} will be thrown.
   */
  function __construct($tag /* $value... */) {
    $this->tag       = $tag;
    $this->format    = PelFormat::SRATIONAL;
    $this->dimension = 2;
    $this->min       = -2147483648;
    $this->max       = 2147483647;

    $value = func_get_args();
    array_shift($value);
    $this->setValueArray($value);
  }

  /**
   * Format a rational number.
   *
   * The rational will be returned as a string with a slash '/'
   * between the numerator and denominator.  Care is taken to display
   * '-1/2' instead of the ugly but mathematically equivalent '1/-2'.
   *
   * @param array the rational which will be formatted.
   *
   * @param boolean not used.
   *
   * @return string the rational formatted as a string suitable for
   * display.
   */
  function formatNumber($number, $brief = false) {
    if ($number[1] < 0)
      /* Turn output like 1/-2 into -1/2. */
      return (-$number[0]) . '/' . (-$number[1]);
    else
      return $number[0] . '/' . $number[1];
  }

  /**
   * Get the value of an entry as text.
   *
   * The value will be returned in a format suitable for presentation,
   * e.g., rationals will be returned as 'x/y', ASCII strings will be
   * returned as themselves etc.
   *
   * @param boolean some values can be returned in a long or more
   * brief form, and this parameter controls that.
   *
   * @return string the value as text.
   */
  function getText($brief = false) {
    if (isset($this->value[0]))
      $v = $this->value[0];

    switch ($this->tag) {
    case PelTag::SHUTTER_SPEED_VALUE:
      //CC (e->components, 1, v);
      //if (!v_srat.denominator) return (NULL);
      return Pel::fmt('%.0f/%.0f sec. (APEX: %d)',
                      $v[0], $v[1], pow(sqrt(2), $v[0]/$v[1]));

    case PelTag::BRIGHTNESS_VALUE:
      //CC (e->components, 1, v);
      //
      // TODO: figure out the APEX thing, or remove this so that it is
      // handled by the default clause at the bottom.
      return sprintf('%d/%d', $v[0], $v[1]);
      //FIXME: How do I calculate the APEX value?

    case PelTag::EXPOSURE_BIAS_VALUE:
      //CC (e->components, 1, v);
      //if (!v_srat.denominator) return (NULL);
      return sprintf('%s%.01f', $v[0]*$v[1] > 0 ? '+' : '', $v[0]/$v[1]);

    default:
      return parent::getText($brief);
    }
  }

}

?>


text:
\chapter{References} \label{references}
\printbibliography


text:
class YamlConfig
  def run
    'example'
  end
end


text:
package com.ideaknow.api.client.model.glass;

import android.os.Parcel;
import android.os.Parcelable;
import com.ideaknow.api.client.model.accounts.AccountsListModel;
import com.ideaknow.api.client.model.agent.AgentModel;
import com.ideaknow.api.client.model.session.SessionModel;

public class SessionAgentAccountsModel implements Parcelable {

    private SessionModel session;
    private AccountsListModel accountList;
    private AgentModel agent;

    public SessionAgentAccountsModel() {
    }

    public SessionModel getSession() {
        return session;
    }

    public void setSession(SessionModel session) {
        this.session = session;
    }

    public AccountsListModel getAccountList() {
        return accountList;
    }

    public void setAccountList(AccountsListModel accountList) {
        this.accountList = accountList;
    }

    public AgentModel getAgent() {
        return agent;
    }

    public void setAgent(AgentModel agent) {
        this.agent = agent;
    }

    @Override
    public String toString() {
        return "SessionAgentAccountsModel{" +
                "session=" + session +
                ", accountList=" + accountList +
                ", agent=" + agent +
                '}';
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeParcelable(this.session, 0);
        dest.writeParcelable(this.accountList, 0);
        dest.writeParcelable(this.agent, 0);
    }

    private SessionAgentAccountsModel(Parcel in) {
        this.session = in.readParcelable(SessionModel.class.getClassLoader());
        this.accountList = in.readParcelable(AccountsListModel.class.getClassLoader());
        this.agent = in.readParcelable(AgentModel.class.getClassLoader());
    }

    public static Parcelable.Creator<SessionAgentAccountsModel> CREATOR = new Parcelable.Creator<SessionAgentAccountsModel>() {
        public SessionAgentAccountsModel createFromParcel(Parcel source) {
            return new SessionAgentAccountsModel(source);
        }

        public SessionAgentAccountsModel[] newArray(int size) {
            return new SessionAgentAccountsModel[size];
        }
    };
}


text:
import _ from 'lodash';
import expect from 'expect.js';
import ngMock from 'ng_mock';
import VisProvider from 'ui/vis';
import VisAggConfigProvider from 'ui/vis/agg_config';
import FixturesStubbedLogstashIndexPatternProvider from 'fixtures/stubbed_logstash_index_pattern';
import AggTypesParamTypesCalculateIntervalProvider from 'ui/agg_types/param_types/_calculate_interval';

describe('calculateInterval()', function () {
  let AggConfig;
  let indexPattern;
  let Vis;
  let createFilter;
  let calculateInterval;

  beforeEach(ngMock.module('kibana'));
  beforeEach(ngMock.inject(function (Private) {
    Vis = Private(VisProvider);
    AggConfig = Private(VisAggConfigProvider);
    indexPattern = Private(FixturesStubbedLogstashIndexPatternProvider);
    calculateInterval = Private(AggTypesParamTypesCalculateIntervalProvider);
  }));

  const testInterval = function (option, expected) {
    const msg = 'should return ' + JSON.stringify(expected) + ' for ' + option;
    it(msg, function () {
      const vis = new Vis(indexPattern, {
        type: 'histogram',
        aggs: [ { type: 'date_histogram', schema: 'segment', params: { field: '@timestamp', interval: option } } ]
      });
      const aggConfig = vis.aggs.byTypeName.date_histogram[0];
      const interval = calculateInterval(aggConfig);
      _.each(expected, function (val, key) {
        expect(interval).to.have.property(key, val);
      });
    });

  };

  testInterval('auto', {
    interval: 30000,
    metricScale: 1,
    description: '30 sec'
  });

  testInterval('second', {
    interval: 10000,
    metricScale: 0.1,
    description: 'second'
  });

  testInterval('minute', {
    interval: 60000,
    metricScale: 1,
    description: 'minute'
  });

  testInterval('hour', {
    interval: 3600000,
    metricScale: 1,
    description: 'hour'
  });

  testInterval('day', {
    interval: 86400000,
    metricScale: 1,
    description: 'day'
  });

  testInterval('week', {
    interval: 604800000,
    metricScale: 1,
    description: 'week'
  });

  testInterval('month', {
    interval: 2592000000,
    metricScale: 1,
    description: 'month'
  });

  testInterval('year', {
    interval: 31536000000,
    metricScale: 1,
    description: 'year'
  });

});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
GrailsScaffolder (Grails 1.0.4)
</TITLE>

<META NAME="keywords" CONTENT="org.codehaus.groovy.grails.scaffolding.GrailsScaffolder interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.codehaus.groovy.grails.scaffolding

Interface GrailsScaffolder

All Known Implementing Classes:
DefaultGrailsScaffolder

public interface GrailsScaffolder

An interface that facilitates the required methods for using Scaffolding within GrailsControllers

Since:

30 Nov 2005

Author:

Graeme Rocher

Field Summary

static String[]
ACTION_NAMES

static String
CREATE_ACTION

static String
DELETE_ACTION

static String
EDIT_ACTION

static String
FIND_ACTION

static String
INDEX_ACTION

static String
LIST_ACTION

static String
SAVE_ACTION

static String
SEARCH_ACTION

static String
SHOW_ACTION

static String
UPDATE_ACTION

Method Summary

 groovy.lang.Closure
getAction(groovy.lang.GroovyObject controller,
          String actionName)

 String
getActionName(groovy.lang.Closure action)

          Returns the action name for the specified closure instance

 ScaffoldRequestHandler
getScaffoldRequestHandler()

 String[]
getSupportedActionNames()

 boolean
supportsAction(String actionName)

Field Detail

INDEX_ACTION

static final String INDEX_ACTION

See Also:
Constant Field Values

LIST_ACTION

static final String LIST_ACTION

See Also:
Constant Field Values

SHOW_ACTION

static final String SHOW_ACTION

See Also:
Constant Field Values

EDIT_ACTION

static final String EDIT_ACTION

See Also:
Constant Field Values

DELETE_ACTION

static final String DELETE_ACTION

See Also:
Constant Field Values

CREATE_ACTION

static final String CREATE_ACTION

See Also:
Constant Field Values

SAVE_ACTION

static final String SAVE_ACTION

See Also:
Constant Field Values

UPDATE_ACTION

static final String UPDATE_ACTION

See Also:
Constant Field Values

SEARCH_ACTION

static final String SEARCH_ACTION

See Also:
Constant Field Values

FIND_ACTION

static final String FIND_ACTION

See Also:
Constant Field Values

ACTION_NAMES

static final String[] ACTION_NAMES

Method Detail

supportsAction

boolean supportsAction(String actionName)

Parameters:
actionName - The name of the action

Returns:
True if the action is supported by the scaffolder

getSupportedActionNames

String[] getSupportedActionNames()

Returns:
A String array of actions names supported by the scaffolder

getAction

groovy.lang.Closure getAction(groovy.lang.GroovyObject controller,
                              String actionName)

Parameters:
actionName -

Returns:
A Closure instance for the specified action name

getActionName

String getActionName(groovy.lang.Closure action)

Returns the action name for the specified closure instance

Parameters:
action - The closure action

Returns:
The name of the action

getScaffoldRequestHandler

ScaffoldRequestHandler getScaffoldRequestHandler()

Returns:
The ScaffoldRequestHandler instance

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright (c) 2005-2006 The Grails project


text:
package pluginactionfakes

import (
	sync "sync"

	pluginaction "code.cloudfoundry.org/cli/actor/pluginaction"
	plugin "code.cloudfoundry.org/cli/api/plugin"
)

type FakePluginClient struct {
	DownloadPluginStub        func(string, string, plugin.ProxyReader) error
	downloadPluginMutex       sync.RWMutex
	downloadPluginArgsForCall []struct {
		arg1 string
		arg2 string
		arg3 plugin.ProxyReader
	}
	downloadPluginReturns struct {
		result1 error
	}
	downloadPluginReturnsOnCall map[int]struct {
		result1 error
	}
	GetPluginRepositoryStub        func(string) (plugin.PluginRepository, error)
	getPluginRepositoryMutex       sync.RWMutex
	getPluginRepositoryArgsForCall []struct {
		arg1 string
	}
	getPluginRepositoryReturns struct {
		result1 plugin.PluginRepository
		result2 error
	}
	getPluginRepositoryReturnsOnCall map[int]struct {
		result1 plugin.PluginRepository
		result2 error
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakePluginClient) DownloadPlugin(arg1 string, arg2 string, arg3 plugin.ProxyReader) error {
	fake.downloadPluginMutex.Lock()
	ret, specificReturn := fake.downloadPluginReturnsOnCall[len(fake.downloadPluginArgsForCall)]
	fake.downloadPluginArgsForCall = append(fake.downloadPluginArgsForCall, struct {
		arg1 string
		arg2 string
		arg3 plugin.ProxyReader
	}{arg1, arg2, arg3})
	fake.recordInvocation("DownloadPlugin", []interface{}{arg1, arg2, arg3})
	fake.downloadPluginMutex.Unlock()
	if fake.DownloadPluginStub != nil {
		return fake.DownloadPluginStub(arg1, arg2, arg3)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.downloadPluginReturns
	return fakeReturns.result1
}

func (fake *FakePluginClient) DownloadPluginCallCount() int {
	fake.downloadPluginMutex.RLock()
	defer fake.downloadPluginMutex.RUnlock()
	return len(fake.downloadPluginArgsForCall)
}

func (fake *FakePluginClient) DownloadPluginCalls(stub func(string, string, plugin.ProxyReader) error) {
	fake.downloadPluginMutex.Lock()
	defer fake.downloadPluginMutex.Unlock()
	fake.DownloadPluginStub = stub
}

func (fake *FakePluginClient) DownloadPluginArgsForCall(i int) (string, string, plugin.ProxyReader) {
	fake.downloadPluginMutex.RLock()
	defer fake.downloadPluginMutex.RUnlock()
	argsForCall := fake.downloadPluginArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}

func (fake *FakePluginClient) DownloadPluginReturns(result1 error) {
	fake.downloadPluginMutex.Lock()
	defer fake.downloadPluginMutex.Unlock()
	fake.DownloadPluginStub = nil
	fake.downloadPluginReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakePluginClient) DownloadPluginReturnsOnCall(i int, result1 error) {
	fake.downloadPluginMutex.Lock()
	defer fake.downloadPluginMutex.Unlock()
	fake.DownloadPluginStub = nil
	if fake.downloadPluginReturnsOnCall == nil {
		fake.downloadPluginReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.downloadPluginReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakePluginClient) GetPluginRepository(arg1 string) (plugin.PluginRepository, error) {
	fake.getPluginRepositoryMutex.Lock()
	ret, specificReturn := fake.getPluginRepositoryReturnsOnCall[len(fake.getPluginRepositoryArgsForCall)]
	fake.getPluginRepositoryArgsForCall = append(fake.getPluginRepositoryArgsForCall, struct {
		arg1 string
	}{arg1})
	fake.recordInvocation("GetPluginRepository", []interface{}{arg1})
	fake.getPluginRepositoryMutex.Unlock()
	if fake.GetPluginRepositoryStub != nil {
		return fake.GetPluginRepositoryStub(arg1)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	fakeReturns := fake.getPluginRepositoryReturns
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *FakePluginClient) GetPluginRepositoryCallCount() int {
	fake.getPluginRepositoryMutex.RLock()
	defer fake.getPluginRepositoryMutex.RUnlock()
	return len(fake.getPluginRepositoryArgsForCall)
}

func (fake *FakePluginClient) GetPluginRepositoryCalls(stub func(string) (plugin.PluginRepository, error)) {
	fake.getPluginRepositoryMutex.Lock()
	defer fake.getPluginRepositoryMutex.Unlock()
	fake.GetPluginRepositoryStub = stub
}

func (fake *FakePluginClient) GetPluginRepositoryArgsForCall(i int) string {
	fake.getPluginRepositoryMutex.RLock()
	defer fake.getPluginRepositoryMutex.RUnlock()
	argsForCall := fake.getPluginRepositoryArgsForCall[i]
	return argsForCall.arg1
}

func (fake *FakePluginClient) GetPluginRepositoryReturns(result1 plugin.PluginRepository, result2 error) {
	fake.getPluginRepositoryMutex.Lock()
	defer fake.getPluginRepositoryMutex.Unlock()
	fake.GetPluginRepositoryStub = nil
	fake.getPluginRepositoryReturns = struct {
		result1 plugin.PluginRepository
		result2 error
	}{result1, result2}
}

func (fake *FakePluginClient) GetPluginRepositoryReturnsOnCall(i int, result1 plugin.PluginRepository, result2 error) {
	fake.getPluginRepositoryMutex.Lock()
	defer fake.getPluginRepositoryMutex.Unlock()
	fake.GetPluginRepositoryStub = nil
	if fake.getPluginRepositoryReturnsOnCall == nil {
		fake.getPluginRepositoryReturnsOnCall = make(map[int]struct {
			result1 plugin.PluginRepository
			result2 error
		})
	}
	fake.getPluginRepositoryReturnsOnCall[i] = struct {
		result1 plugin.PluginRepository
		result2 error
	}{result1, result2}
}

func (fake *FakePluginClient) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.downloadPluginMutex.RLock()
	defer fake.downloadPluginMutex.RUnlock()
	fake.getPluginRepositoryMutex.RLock()
	defer fake.getPluginRepositoryMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *FakePluginClient) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ pluginaction.PluginClient = new(FakePluginClient)


text:
@interface TableViewSample : UIViewController

@end


text:
package de.hardwarespielerei.can.tinycan;

import de.hardwarespielerei.can.tinycan.jna.NativeAccess;

/**
 * Describes an {@link NativeAccess#ERROR_GENERAL} error from Tiny-CAN.
 * Subclasses describe specific errors.
 *
 * @author gabriel
 */
public class TinyCANException extends java.lang.Exception
{
	/**
	 *
	 */
	private static final long serialVersionUID = 5376569765457518837L;

	/**
	 * @param returnCode
	 *            contains the native return code.
	 * @param message
	 *            references the detail message. The detail message is saved for
	 *            later retrieval by the {@link Throwable#getMessage()} method.
	 */
	protected TinyCANException(int returnCode, String message)
	{
		super(message + " RC = " + returnCode);
	}

	/**
	 * Throws the Tiny-CAN exception corresponding to the given native return
	 * code. Returns without any effect on {@link NativeAccess#ERROR_OK} return
	 * code.
	 *
	 * @param rc
	 *            contains the native return code.
	 * @param message
	 *            references the detail message. The detail message is saved for
	 *            later retrieval by the {@link Throwable#getMessage()} method.
	 * @throws TinyCANException
	 *             on errors while accessing Tiny-CAN.
	 */
	protected static void throwOnErrorCode(int rc, String message)
			throws TinyCANException
	{
		switch (rc)
		{
			case NativeAccess.ERROR_OK:
				// everything OK, do nothing...
				break;
			case NativeAccess.ERROR_DRIVER_NOT_INITIALIZED:
				throw new DriverNotInitalizedException(rc, message);
			case NativeAccess.ERROR_INVALID_PARAMETER:
				throw new InvalidParameterException(rc, message);
			case NativeAccess.ERROR_INVALID_INDEX:
				throw new InvalidIndexException(rc, message);
			case NativeAccess.ERROR_INVALID_CHANNEL:
				throw new InvalidChannelException(rc, message);
			case NativeAccess.ERROR_FIFO_WRITE:
				throw new FIFOWriteException(rc, message);
			case NativeAccess.ERROR_BUFFER_WRITE:
				throw new BufferWriteException(rc, message);
			case NativeAccess.ERROR_FIFO_READ:
				throw new FIFOReadException(rc, message);
			case NativeAccess.ERROR_BUFFER_READ:
				throw new BufferReadException(rc, message);
			case NativeAccess.ERROR_VARIABLE_NOT_FOUND:
				throw new VariableNotFoundException(rc, message);
			case NativeAccess.ERROR_VARIABLE_NOT_READABLE:
				throw new VariableNotReadableException(rc, message);
			case NativeAccess.ERROR_VARIABLE_READ_BUFFER_EXCEEDED:
				throw new VariableReadBufferExceededException(rc, message);
			case NativeAccess.ERROR_VARIABLE_NOT_WRITABLE:
				throw new VariableNotWriteableException(rc, message);
			case NativeAccess.ERROR_STRING_TOO_BIG:
				throw new StringToBigException(rc, message);
			case NativeAccess.ERROR_MINIMUM_UNDERRUN:
				throw new MinimumExceededException(rc, message);
			case NativeAccess.ERROR_MAXIMUM_EXCEEDED:
				throw new MaximumExceededException(rc, message);
			case NativeAccess.ERROR_ACCESS_DENIED:
				throw new AccessDeniedException(rc, message);
			case NativeAccess.ERROR_INVALID_CAN_SPEED:
				throw new InvalidCANSpeedException(rc, message);
			case NativeAccess.ERROR_INVALID_BAUD_RATE:
				throw new InvalidBaudRateException(rc, message);
			case NativeAccess.ERROR_VALUE_NOT_SET:
				throw new ValueNotSetException(rc, message);
			case NativeAccess.ERROR_HARDWARE_CONNECTION:
				throw new HardwareConnectionException(rc, message);
			case NativeAccess.ERROR_HARDWARE_COMMUNICATION:
				throw new HardwareCommunicationException(rc, message);
			case NativeAccess.ERROR_HARDWARE_PARAMETER:
				throw new HardwareParameterException(rc, message);
			case NativeAccess.ERROR_MEMORY_LOW:
				throw new MemoryLowException(rc, message);
			case NativeAccess.ERROR_SYSTEM_RESSOURCES:
				throw new SystemRessourcesException(rc, message);
			case NativeAccess.ERROR_SYSTEM_CALL:
				throw new SystemCallException(rc, message);
			case NativeAccess.ERROR_MAIN_THREAD_BUSY:
				throw new MainThreadBusyException(rc, message);
			case NativeAccess.ERROR_GENERAL:
			default:
				throw new TinyCANException(rc, message);
		}
	}
}


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AngularFireModule } from 'angularfire2';
import { CovalentCoreModule } from '@covalent/core';
import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';
import { RouterStoreModule } from '@ngrx/router-store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';

import './rxjs-extensions';

import { AppComponent } from './app.component';
import { GeoModule } from './geo/geo.module';
import { CurrentSearchEffectService } from './state-management/effects/current-search-effect.service';
import { GeoHeaderModule } from './geo-header/geo-header.module';
import { FooterModule } from './footer/footer.module';
import { PlacesModule } from './places/places.module';
import { SharedModule } from './shared/shared.module';
import { AppRoutingModule } from './app-routing.module';
import { reducer } from './state-management/reducers/index';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    CovalentCoreModule.forRoot(),
    StoreModule.provideStore(reducer),
    RouterStoreModule.connectRouter(),
    EffectsModule.run(CurrentSearchEffectService),
    // TODO remove on prod
    // StoreDevtoolsModule.instrumentOnlyWithExtension(),
    SharedModule,
    GeoModule,
    GeoHeaderModule,
    FooterModule,
    PlacesModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
package org.scalajs.testsuite.utils

import java.{lang => jl, util => ju}

import org.scalajs.testsuite.utils.AssertThrows._

import scala.collection.JavaConverters._

trait CollectionsTestBase {

  val range: Range = 0 to 30

  class A extends jl.Comparable[A] {
    def compareTo(o: A): Int = this.##.compareTo(o.##)
  }

  class B extends A

  class C extends B

  class CustomComparable(val v: Int) extends jl.Comparable[CustomComparable] {
    override def compareTo(o: CustomComparable): Int =
      (v % 8).compareTo(o.v % 8)

    override def toString(): String =
      s"CustomComparable($v)"
  }

  def testCollectionUnmodifiability[E](coll: ju.Collection[E], elem: E): Unit = {
    expectThrows(classOf[UnsupportedOperationException], coll.add(elem))
    expectThrows(classOf[UnsupportedOperationException],
        coll.addAll(Seq.empty[E].asJava))
    expectThrows(classOf[UnsupportedOperationException], coll.clear())
    expectThrows(classOf[UnsupportedOperationException], coll.remove(elem))
    expectThrows(classOf[UnsupportedOperationException],
        coll.removeAll(Seq.empty[E].asJava))
    expectThrows(classOf[UnsupportedOperationException],
        coll.retainAll(Seq.empty[E].asJava))
    testIteratorsUnmodifiability(() => coll.iterator())
  }

  def testSetUnmodifiability[E](set: ju.Set[E], elem: E): Unit =
    testCollectionUnmodifiability(set, elem)

  def testSortedSetUnmodifiability[E](set: ju.SortedSet[E], elem: E,
      recursive: Boolean = false): Unit = {
    testSetUnmodifiability(set, elem)
    def testSubsets(ss: ju.SortedSet[E]) = {
      if (recursive) testSetUnmodifiability(ss, elem)
      else testSortedSetUnmodifiability(ss, elem, true)
    }
    testSubsets(set.headSet(elem))
    testSubsets(set.tailSet(elem))
    testSubsets(set.subSet(elem, elem))
  }

  def testListUnmodifiability[E](list: ju.List[E], elem: E,
      recursive: Boolean = false): Unit = {
    testCollectionUnmodifiability(list, elem)
    expectThrows(classOf[UnsupportedOperationException], list.add(0, elem))
    expectThrows(classOf[UnsupportedOperationException],
        list.addAll(0, Seq.empty[E].asJava))
    expectThrows(classOf[UnsupportedOperationException], list.remove(0))
    expectThrows(classOf[UnsupportedOperationException], list.set(0, elem))
    def testSublist(sl: ju.List[E]): Unit = {
      if (recursive) testCollectionUnmodifiability(sl, elem)
      else testListUnmodifiability(sl, elem, true)
    }
    testSublist(list.subList(0, list.size / 2))
    testListIteratorsUnmodifiability(() => list.listIterator(), elem)
    testListIteratorsUnmodifiability(() => list.listIterator(0), elem)
  }

  def testOnFirstPositionOfIterator[Iter <: ju.Iterator[_]](
      newIter: () => Iter, action: Iter => Unit,
      expectedException: Option[Class[_ <: Throwable]]): Unit = {
    val it = newIter()
    if (it.hasNext) {
      it.next()
      expectedException match {
        case Some(exClass) => expectThrows(exClass, action(it))
        case None => action(it)
      }
    }
  }

  def testMapUnmodifiability[K, V](map: ju.Map[K, V], key: K, value: V): Unit = {
    expectThrows(classOf[UnsupportedOperationException], map.clear())
    expectThrows(classOf[UnsupportedOperationException], map.put(key, value))
    expectThrows(classOf[UnsupportedOperationException],
        map.putAll(Map.empty[K, V].asJava))
    testSetUnmodifiability(map.entrySet(),
        new ju.AbstractMap.SimpleImmutableEntry(key, value))
    testSetUnmodifiability(map.keySet(), key)
    testCollectionUnmodifiability(map.values(), value)
  }

  def testSortedMapUnmodifiability[K, V](map: ju.SortedMap[K, V], key: K, value: V,
      recursive: Boolean = false): Unit = {
    testMapUnmodifiability(map, key, value)
    def testSubmap(sm: ju.SortedMap[K, V]) = {
      if (recursive) testMapUnmodifiability(sm, key, value)
      else testSortedMapUnmodifiability(sm, key, value, true)
    }
    testSubmap(map.headMap(key))
    testSubmap(map.tailMap(key))
    testSubmap(map.subMap(key, key))
  }

  def testIteratorsUnmodifiability[E](newIter: () => ju.Iterator[E]): Unit = {
    testOnFirstPositionOfIterator[ju.Iterator[E]](newIter, _.remove(),
        Some(classOf[UnsupportedOperationException]))
  }

  def testListIteratorsUnmodifiability[E](newIter: () => ju.ListIterator[E],
      elem: E): Unit = {
    testIteratorsUnmodifiability(newIter)
    testOnFirstPositionOfIterator[ju.ListIterator[E]](newIter, _.add(elem),
        Some(classOf[UnsupportedOperationException]))
    testOnFirstPositionOfIterator[ju.ListIterator[E]](newIter, _.set(elem),
        Some(classOf[UnsupportedOperationException]))
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zzll.Net.Framework.Helper;
using Newtonsoft.Json;

namespace Zzll.Net.Framework.TcpService
{
    /// <summary>
    /// Tcp服务端处理器
    /// </summary>
    public class Service : BaseHandle<Config>
    {
        #region ==========属性==========
        /// <summary>
        /// TCP服务
        /// </summary>
        protected TcpService svr { get; set; }
        /// <summary>
        /// 当前在线用户量
        /// </summary>
        public int ClientOnlineCount
        {
            get
            {
                return svr.SessionTable.Count;
            }
        }

        #endregion

        /// <summary>
        /// 启动Tcp服务端
        /// </summary>
        public override void Start(Func<Request, Response> func)
        {
            if (base.config == null)
                throw new Exception("未设置Tcp服务端服务配置");
            //设置回调函数
            base.Handle_Event = func;
            if (config.Port <= 0)
                return;
            svr = new TcpService(config.Port, config.Encoding);
            svr.Suffix = config.Suffix;
            svr.DefaultMaxClient = config.DefaultMaxClient;
            svr.ServerStart += new TcpService.Dlgestr(ServerStart);
            svr.ServerError += new TcpService.Dlgestr(ServerError);
            svr.ServerStop += new TcpService.Dlgestr(ServerStop);
            svr.ClientRecvData += new TcpService.NetEvent(ClientRecvData);
            svr.ClientClose += new TcpService.NetClientEvent(ClientClose);
            svr.ClientConn += new TcpService.NetClientEvent(ClientConn);
            svr.IsHeartbeat = config.IsHeartbeat;
            svr.Start();
            Console.WriteLine(DateTime.Now.ToString("MM-dd HH:mm:ss:fff") + " 服务器启动,开放端口:" + config.Port);
            LogHelper.Add("启动TCP通讯服务->StartService", config.Port, LogType.TcpService);
        }

        #region ========通讯服务========
        /// <summary>
        /// 消息发送
        /// </summary>
        /// <param name="resp">响应对象</param>
        public void Send(Response resp)
        {
            if (resp == null)//响应为空
                return;
            Session client = ((TcpServiceRequest)resp.req).client;
            if (client == null)
                return;
            LogHelper.Add(client.Id + "->" + resp.id + "->Send", resp.para, LogType.TcpService);
            //获取IP白名单加密方式
            ClientWhite white = config.ClientWhiteList.Find(f => f.ClientIp.Split(',').Contains(client.ConnIp));
            if (white == null)
            {
                LogHelper.Add("【ERROR】" + client.ConnIp, "未在白名单找到报文", LogType.Error);
                return;
            }
            if (white.encryptType != EncryptType.Normal)
                LogHelper.Add(client.Id + "->" + resp.id + "->加密获取密文", resp.para, LogType.TcpService);
            resp.para = Encryption(resp.para, white);
            //返回响应
            svr.Send(client, resp.para);
        }
        /// <summary>
        /// 数据接收事件
        /// </summary>
        /// <param name="msg">请求报文</param>
        /// <param name="client">会话上下文</param>
        void ClientRecvData(string msg, Session client)
        {
            try
            {
                //生成请求唯一标示
                long id = Utils.GetReqId();

                #region 获取请求对象
                LogHelper.Add(client.Id + "->" + id + "->ClientRecvData", msg, LogType.TcpService);

                //获取IP白名单
                ClientWhite white = config.ClientWhiteList.Find(f => f.ClientIp.Split(',').Contains(client.ConnIp));
                if (white == null)
                {
                    LogHelper.Add("【ERROR】" + id, "未在白名单找到报文", LogType.Error);
                    return;
                }
                try
                {
                    msg = Decryption(msg, white); //报文解密
                }
                catch (Exception ex)
                {
                    LogHelper.Add("【ERROR】" + id + "->报文解密失败", ex.Message, LogType.Error);
                    return;
                }

                if (white.encryptType != EncryptType.Normal)
                    LogHelper.Add(client.Id + "->" + id + "->解密获取明文", msg, LogType.TcpService);

                TcpServiceRequest req = null;
                try
                {
                    req = JsonConvert.DeserializeObject<TcpServiceRequest>(msg);
                    req.id = id;
                    req.channel = RequestChannel.TcpService;
                    req.client = client;
                }
                catch (Exception ex)
                {
                    LogHelper.Add("【ERROR】" + id + "->启动处理,报文解析错误", ex.Message, LogType.Error);
                    return;
                }
                if (req == null)
                {
                    LogHelper.Add("【ERROR】" + id + "->启动处理,报文解析错误", msg, LogType.Error);
                    return;
                }
                //判断该客户端是否允许访问该功能
                if (!white.FuncList.Split(',').Contains("ALL") && !white.FuncList.Split(',').Contains(req.code))
                {
                    LogHelper.Add(id.ToString(), "该服务器不支持此功能", LogType.Error);
                    return;
                }
                #endregion

                //发送给处理区
                if (base.Handle_Event == null)
                    return;
                Response resp = base.Handle_Event(req);
                if (resp == null)
                {
                    LogHelper.Add("【ERROR】" + id, "响应为空", LogType.Error);
                    return;
                }
                //发送响应报文00
                Send(resp);
            }
            catch (Exception ex)
            {
                svr.Send(client, "0");
                LogHelper.Add("【ERROR】" + client.Id + "->请求,内部错误", "msg:" + msg + ";" + ex.Message, LogType.Error);
            }
        }
        /// <summary>
        /// 客户端断开事件
        /// </summary>
        /// <param name="e"></param>
        void ClientClose(Session e)
        {
            LogHelper.Add(e.Id + "->ClientClose", "IP:" + e.ConnIp + ",Port:" + e.Port, LogType.TcpService);
        }
        /// <summary>
        /// 客户端连接事件
        /// </summary>
        /// <param name="e"></param>
        void ClientConn(Session e)
        {
            LogHelper.Add(e.Id + "->ClientConn", "IP:" + e.ConnIp + ",Port:" + e.Port, LogType.TcpService);
            //判断IP是否在白名单中
            if (config.ClientWhiteList.Where(f => f.ClientIp.Split(',').Contains(e.ConnIp)).Count() == 0)
            {
                LogHelper.Add(e.Id.ToString(), "客户端不在白名单", LogType.Error);
                svr.Close(e.Client);
                return;
            }
        }
        /// <summary>
        /// 服务启动事件
        /// </summary>
        /// <param name="msg"></param>
        void ServerStart(string msg)
        {
            LogHelper.Add("->ServerStart", msg, LogType.TcpService);
        }
        /// <summary>
        /// 服务处理失败事件
        /// </summary>
        /// <param name="msg"></param>
        void ServerError(string msg)
        {
            LogHelper.Add("->ServerError", msg, LogType.TcpService);

        }
        /// <summary>
        /// 服务停止事件
        /// </summary>
        /// <param name="msg"></param>
        void ServerStop(string msg)
        {
            LogHelper.Add("->ServerStop", msg, LogType.TcpService);
        }
        #endregion

        #region ========加密机制========
        /// <summary>
        /// 加密报文
        /// </summary>
        /// <param name="packets">明文</param>
        /// <param name="white">白名单设置</param>
        /// <returns></returns>
        public string Encryption(string packets, ClientWhite white)
        {
            if (white.encryptType == EncryptType.DES3)
            {
                #region DES3层加密
                string secretKey = Helper.Encryption.getKey(white.Secretkey);//获取秘钥
                                                                             //生成签名
                string sign = Helper.Encryption.EncryptMD5(packets, new EncodHelper(config.Encoding).ToEncoding());
                //获取报文密文
                string ciphertext = Helper.Encryption.Encrypt3ECB(packets, secretKey, new EncodHelper(config.Encoding).ToEncoding());
                string length = ciphertext.Length.ToString();
                for (int i = length.Length; i < 6; i++)
                {
                    length = "0" + length;
                }
                packets = length + ciphertext + sign;
                return packets;
                #endregion
            }
            else if (white.encryptType == EncryptType.MD5)
            {
                #region MD5签名验证
                string secretKey = Helper.Encryption.getKey(white.Secretkey);//获取秘钥
                string sign = Helper.Encryption.EncryptMD5(packets + secretKey, new EncodHelper(config.Encoding).ToEncoding());//获取报文签名
                return packets + sign;
                #endregion
            }
            else
                return packets;
        }

        /// <summary>
        /// 解密报文
        /// </summary>
        /// <param name="packets">密文</param>
        /// <param name="white">白名单设置</param>
        /// <returns></returns>
        public string Decryption(string packets, ClientWhite white)
        {
            if (white.encryptType == EncryptType.DES3)
            {
                #region DES3层加密
                string secretKey = Helper.Encryption.getKey(white.Secretkey);
                Encoding e = new EncodHelper(config.Encoding).ToEncoding();
                //获取签名长度
                int length = Convert.ToInt32(packets.Substring(0, 6));
                //获取签名
                string sgin = packets.Substring(length + 6, 32);
                //获取加密的报文
                string ciphertext = packets.Substring(6, length);
                //进行解密报文
                string data = Helper.Encryption.Decrypt3ECB(ciphertext, secretKey, e);
                //验证报文是否正确
                ciphertext = Helper.Encryption.EncryptMD5(data, e);
                if (!ciphertext.Equals(sgin))
                    throw new Exception("报文签名无效");
                return data;
                #endregion
            }
            else if (white.encryptType == EncryptType.MD5)
            {
                #region MD5签名验证
                string secretKey = Helper.Encryption.getKey(white.Secretkey);
                //截取报文的Sign
                string reqSign = packets.Substring(packets.Length - 32, 32);
                //获取报文信息
                string packet = packets.Substring(0, packets.Length - 32);
                //生成报文签名
                string sign = Helper.Encryption.EncryptMD5(packets + secretKey, new EncodHelper(config.Encoding).ToEncoding());//获取报文签名
                if (sign == reqSign)
                    throw new Exception("报文签名无效");
                return packet;
                #endregion
            }
            else
                return packets;

        }
        #endregion
    }
}


text:
namespace blink {

const int kPageWidth = 800;
const int kPageHeight = 600;

class MockPrintContext : public PrintContext {
public:
    MockPrintContext(LocalFrame* frame) : PrintContext(frame) { }

    void outputLinkedDestinations(GraphicsContext& context, const IntRect& pageRect)
    {
        PrintContext::outputLinkedDestinations(context, pageRect);
    }
};

class MockCanvas : public SkCanvas {
public:
    enum OperationType {
        DrawRect,
        DrawPoint
    };

    struct Operation {
        OperationType type;
        SkRect rect;
    };

    MockCanvas() : SkCanvas(kPageWidth, kPageHeight) { }

    void onDrawRect(const SkRect& rect, const SkPaint& paint) override
    {
        if (!paint.getAnnotation())
            return;
        Operation operation = { DrawRect, rect };
        getTotalMatrix().mapRect(&operation.rect);
        m_recordedOperations.append(operation);
    }

    void onDrawPoints(PointMode mode, size_t count, const SkPoint pts[], const SkPaint& paint) override
    {
        if (!paint.getAnnotation())
            return;
        ASSERT_EQ(1u, count); // Only called from drawPoint().
        SkPoint point = getTotalMatrix().mapXY(pts[0].x(), pts[0].y());
        Operation operation = { DrawPoint, SkRect::MakeXYWH(point.x(), point.y(), 0, 0) };
        m_recordedOperations.append(operation);
    }

    const Vector<Operation>& recordedOperations() const { return m_recordedOperations; }

private:
    Vector<Operation> m_recordedOperations;
};

class PrintContextTest : public RenderingTest {
protected:
    explicit PrintContextTest(PassOwnPtrWillBeRawPtr<FrameLoaderClient> frameLoaderClient = nullptr)
        : RenderingTest(frameLoaderClient)
        , m_printContext(adoptPtrWillBeNoop(new MockPrintContext(document().frame()))) { }

    MockPrintContext& printContext() { return *m_printContext.get(); }

    void setBodyInnerHTML(String bodyContent)
    {
        document().body()->setAttribute(HTMLNames::styleAttr, "margin: 0");
        document().body()->setInnerHTML(bodyContent, ASSERT_NO_EXCEPTION);
    }

    void printSinglePage(SkCanvas& canvas)
    {
        IntRect pageRect(0, 0, kPageWidth, kPageHeight);
        printContext().begin(pageRect.width(), pageRect.height());
        document().view()->updateAllLifecyclePhases();
        SkPictureBuilder pictureBuilder(pageRect);
        GraphicsContext& context = pictureBuilder.context();
        context.setPrinting(true);
        document().view()->paintContents(context, GlobalPaintPrinting, pageRect);
        {
            DrawingRecorder recorder(context, *document().layoutView(), DisplayItem::PrintedContentDestinationLocations, pageRect);
            printContext().outputLinkedDestinations(context, pageRect);
        }
        pictureBuilder.endRecording()->playback(&canvas);
        printContext().end();
    }

    static String absoluteBlockHtmlForLink(int x, int y, int width, int height, const char* url, const char* children = nullptr)
    {
        TextStream ts;
        ts << "<a style='position: absolute; left: " << x << "px; top: " << y << "px; width: " << width << "px; height: " << height
            << "px' href='" << url << "'>" << (children ? children : url) << "";
        return ts.release();
    }

    static String inlineHtmlForLink(const char* url, const char* children = nullptr)
    {
        TextStream ts;
        ts << "<a href='" << url << "'>" << (children ? children : url) << "";
        return ts.release();
    }

    static String htmlForAnchor(int x, int y, const char* name, const char* textContent)
    {
        TextStream ts;
        ts << "<a name='" << name << "' style='position: absolute; left: " << x << "px; top: " << y << "px'>" << textContent << "";
        return ts.release();
    }

    void testBasicLinkTarget();

private:
    OwnPtr<DummyPageHolder> m_pageHolder;
    OwnPtrWillBePersistent<MockPrintContext> m_printContext;
};

class PrintContextFrameTest : public PrintContextTest {
public:
    PrintContextFrameTest() : PrintContextTest(SingleChildFrameLoaderClient::create()) { }
};

#define EXPECT_SKRECT_EQ(expectedX, expectedY, expectedWidth, expectedHeight, actualRect) \
    EXPECT_EQ(expectedX, actualRect.x()); \
    EXPECT_EQ(expectedY, actualRect.y()); \
    EXPECT_EQ(expectedWidth, actualRect.width()); \
    EXPECT_EQ(expectedHeight, actualRect.height());

void PrintContextTest::testBasicLinkTarget()
{
    MockCanvas canvas;
    setBodyInnerHTML(absoluteBlockHtmlForLink(50, 60, 70, 80, "http://www.google.com")
        + absoluteBlockHtmlForLink(150, 160, 170, 180, "http://www.google.com#fragment"));
    printSinglePage(canvas);

    const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
    ASSERT_EQ(2u, operations.size());
    EXPECT_EQ(MockCanvas::DrawRect, operations[0].type);
    EXPECT_SKRECT_EQ(50, 60, 70, 80, operations[0].rect);
    EXPECT_EQ(MockCanvas::DrawRect, operations[1].type);
    EXPECT_SKRECT_EQ(150, 160, 170, 180, operations[1].rect);
    // We should also check if the annotation is correct but Skia doesn't export
    // SkAnnotation API.
}

TEST_F(PrintContextTest, LinkTarget)
{
    testBasicLinkTarget();
}

TEST_F(PrintContextTest, LinkTargetComplex)
{
    MockCanvas canvas;
    setBodyInnerHTML("
"
        // Link in anonymous block before a block.
        + inlineHtmlForLink("http://www.google.com", "")
        + "
 " + inlineHtmlForLink("http://www.google1.com", "") + "
"
        // Link in anonymous block after a block, containing another block
        + inlineHtmlForLink("http://www.google2.com", "
BLOCK
")
        // Link embedded in inlines
        + "
"
        + inlineHtmlForLink("http://www.google3.com", "")
        + ""
        // Link embedded in relatively positioned inline
        + "
"
        + inlineHtmlForLink("http://www.google3.com", "")
        + ""
        + "
");
    printSinglePage(canvas);

    const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
    ASSERT_EQ(4u, operations.size());
    EXPECT_EQ(MockCanvas::DrawRect, operations[0].type);
    EXPECT_SKRECT_EQ(0, 0, 111, 10, operations[0].rect);
    EXPECT_EQ(MockCanvas::DrawRect, operations[1].type);
    EXPECT_SKRECT_EQ(0, 10, 122, 20, operations[1].rect);
    EXPECT_EQ(MockCanvas::DrawRect, operations[2].type);
    EXPECT_SKRECT_EQ(0, 100, 144, 40, operations[2].rect);
    EXPECT_EQ(MockCanvas::DrawRect, operations[3].type);
    EXPECT_SKRECT_EQ(50, 190, 155, 50, operations[3].rect);
}

TEST_F(PrintContextTest, LinkTargetSvg)
{
    MockCanvas canvas;
    setBodyInnerHTML("<svg width='100' height='100'>"
        "<rect x='20' y='20' width='50' height='50'/>"
        "<text x='10' y='90'><tspan>google</tspan></text>"
        "</svg>");
    printSinglePage(canvas);

    const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
    ASSERT_EQ(2u, operations.size());
    EXPECT_EQ(MockCanvas::DrawRect, operations[0].type);
    EXPECT_SKRECT_EQ(20, 20, 50, 50, operations[0].rect);
    EXPECT_EQ(MockCanvas::DrawRect, operations[1].type);
    EXPECT_EQ(10, operations[1].rect.x());
    EXPECT_GE(90, operations[1].rect.y());
}

TEST_F(PrintContextTest, LinkedTarget)
{
    MockCanvas canvas;
    document().setBaseURLOverride(KURL(ParsedURLString, "http://a.com/"));
    setBodyInnerHTML(absoluteBlockHtmlForLink(50, 60, 70, 80, "#fragment") // Generates a Link_Named_Dest_Key annotation
        + absoluteBlockHtmlForLink(150, 160, 170, 180, "#not-found") // Generates no annotation
        + htmlForAnchor(250, 260, "fragment", "fragment") // Generates a Define_Named_Dest_Key annotation
        + htmlForAnchor(350, 360, "fragment-not-used", "fragment-not-used")); // Generates no annotation
    printSinglePage(canvas);

    const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
    ASSERT_EQ(2u, operations.size());
    EXPECT_EQ(MockCanvas::DrawRect, operations[0].type);
    EXPECT_SKRECT_EQ(50, 60, 70, 80, operations[0].rect);
    EXPECT_EQ(MockCanvas::DrawPoint, operations[1].type);
    EXPECT_SKRECT_EQ(250, 260, 0, 0, operations[1].rect);
}

TEST_F(PrintContextTest, EmptyLinkedTarget)
{
    MockCanvas canvas;
    document().setBaseURLOverride(KURL(ParsedURLString, "http://a.com/"));
    setBodyInnerHTML(absoluteBlockHtmlForLink(50, 60, 70, 80, "#fragment")
        + htmlForAnchor(250, 260, "fragment", ""));
    printSinglePage(canvas);

    const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
    ASSERT_EQ(2u, operations.size());
    EXPECT_EQ(MockCanvas::DrawRect, operations[0].type);
    EXPECT_SKRECT_EQ(50, 60, 70, 80, operations[0].rect);
    EXPECT_EQ(MockCanvas::DrawPoint, operations[1].type);
    EXPECT_SKRECT_EQ(250, 260, 0, 0, operations[1].rect);
}

TEST_F(PrintContextTest, LinkTargetBoundingBox)
{
    MockCanvas canvas;
    setBodyInnerHTML(absoluteBlockHtmlForLink(50, 60, 70, 20, "http://www.google.com", ""));
    printSinglePage(canvas);

    const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
    ASSERT_EQ(1u, operations.size());
    EXPECT_EQ(MockCanvas::DrawRect, operations[0].type);
    EXPECT_SKRECT_EQ(50, 60, 200, 100, operations[0].rect);
}

TEST_F(PrintContextFrameTest, WithSubframe)
{
    MockCanvas canvas;
    document().setBaseURLOverride(KURL(ParsedURLString, "http://a.com/"));
    setBodyInnerHTML(""
        "");

    setupChildIframe("frame", absoluteBlockHtmlForLink(50, 60, 70, 80, "#fragment")
        + absoluteBlockHtmlForLink(150, 160, 170, 180, "http://www.google.com")
        + absoluteBlockHtmlForLink(250, 260, 270, 280, "http://www.google.com#fragment"));

    printSinglePage(canvas);

    const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
    ASSERT_EQ(2u, operations.size());
    EXPECT_EQ(MockCanvas::DrawRect, operations[0].type);
    EXPECT_SKRECT_EQ(250, 260, 170, 180, operations[0].rect);
    EXPECT_EQ(MockCanvas::DrawRect, operations[1].type);
    EXPECT_SKRECT_EQ(350, 360, 270, 280, operations[1].rect);
}

TEST_F(PrintContextFrameTest, WithScrolledSubframe)
{
    MockCanvas canvas;
    document().setBaseURLOverride(KURL(ParsedURLString, "http://a.com/"));
    setBodyInnerHTML(""
        "");

    Document& frameDocument = setupChildIframe("frame", absoluteBlockHtmlForLink(10, 10, 20, 20, "http://invisible.com")
        + absoluteBlockHtmlForLink(50, 60, 70, 80, "http://partly.visible.com")
        + absoluteBlockHtmlForLink(150, 160, 170, 180, "http://www.google.com")
        + absoluteBlockHtmlForLink(250, 260, 270, 280, "http://www.google.com#fragment")
        + absoluteBlockHtmlForLink(850, 860, 70, 80, "http://another.invisible.com"));

    frameDocument.domWindow()->scrollTo(100, 100);

    printSinglePage(canvas);

    const Vector<MockCanvas::Operation>& operations = canvas.recordedOperations();
    ASSERT_EQ(3u, operations.size());
    EXPECT_EQ(MockCanvas::DrawRect, operations[0].type);
    EXPECT_SKRECT_EQ(50, 60, 70, 80, operations[0].rect); // FIXME: the rect should be clipped.
    EXPECT_EQ(MockCanvas::DrawRect, operations[1].type);
    EXPECT_SKRECT_EQ(150, 160, 170, 180, operations[1].rect);
    EXPECT_EQ(MockCanvas::DrawRect, operations[2].type);
    EXPECT_SKRECT_EQ(250, 260, 270, 280, operations[2].rect);
}

} // namespace blink


text:
import * as authentication from 'feathers-authentication';
import * as jwt from 'feathers-authentication-jwt';
import * as local from 'feathers-authentication-local';

export default function () {
  const app = this;
  const config = app.get('authentication');

  // Set up authentication with the secret
  app.configure(authentication(config));
  app.configure(jwt());
  app.configure(local(config.local));

  // The `authentication` service is used to create a JWT.
  // The before `create` hook registers strategies that can be used
  // to create a new valid JWT (e.g. local or oauth2)
  app.service('authentication').hooks({
    before: {
      create: [
        authentication.hooks.authenticate(config.strategies)
      ],
      remove: [
        authentication.hooks.authenticate('jwt')
      ]
    }
  });
};


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.stuy.commands;

/**
 *
 * @author English
 */
public class ConveyorAssistAcquire extends CommandBase {

    public ConveyorAssistAcquire() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(conveyor);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        if (conveyor.ballAtBottom() && !conveyor.ballAtTop() && acquirer.isAcquiring()) {
            conveyor.convey();
        }
        else {
            conveyor.stop();
        }
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
        conveyor.stop();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


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

namespace Yaaf.Xmpp.Runtime
{
    /// <summary>
    /// Exception when plugins fail, cannot be created or added.
    /// </summary>
#if FULL_NET
	[Serializable]
#endif
	public class PluginManagerException : Exception {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public PluginManagerException() { }
        /// <summary>
        /// Creates the exception with the given message.
        /// </summary>
        public PluginManagerException(string message) : base(message) { }
        /// <summary>
        /// Creates the exception with the given message and inner exception.
        /// </summary>
        public PluginManagerException(string message, Exception inner) : base(message, inner) { }
#if FULL_NET
        /// <summary>
        /// Constructor provided for serialization.
        /// </summary>
		protected PluginManagerException (
		  System.Runtime.Serialization.SerializationInfo info,
		  System.Runtime.Serialization.StreamingContext context)
			: base (info, context) { }
#endif
    }
    /// <summary>
    /// A plugin manager interface for registering and querying plugins.
    /// </summary>
    /// <typeparam name="TPlugin"></typeparam>
	public interface IPluginManager<TPlugin> {
		/// <summary>
		/// Try to not use this member, because if you do its your responsibility that the plugin is initialized with the proper service instances!
		/// Use the generic version of this method instead to get automatic service resolution!
		/// </summary>
		/// <param name="plugin">the plugin to register.</param>
		void RegisterPlugin (TPlugin plugin);

        /// <summary>
        /// Returns all currently registered plugins.
        /// </summary>
        /// <returns></returns>
		IEnumerable<TPlugin> GetPlugins ();

		/// <summary>
		/// Returns true if the current PluginManager has the plugin specified by the parameter
		/// </summary>
		bool HasPlugin (TPlugin instance);

		/// <summary>
		/// Returns true if the current PluginManager has the plugin specified by the type parameter
		/// </summary>
		/// <typeparam name="T"></typeparam>
		bool HasPluginOf<T> () where T : TPlugin;
	}

	/// <summary>
	/// A PluginManager where every plugin is a ServiceProvider.
	/// </summary>
	public interface IServicePluginManager<TPlugin> : IPluginManager<TPlugin> where TPlugin : class, IPluginServiceProvider {
		/// <summary>
		/// Registers a plugin, 't must be the concrete plugin type
		/// If your plugin has custom initialisation parameters just setup the Ninject kernel before calling this method.
		/// NOTE: all Runtime specific services are already setup! (like ILocalDelivery or ICoreRuntimeApi for example, note also that you even can get the IKernel instance!)
		/// </summary>
		void RegisterPlugin<T> () where T : class, TPlugin; // Not in IPluginManager because we cannot assume that we can create instances.

		///// <summary>
		///// Try to not use this member, because if you do its your responsibility that the plugin is initialized with the proper service instances!
		///// Use the generic version of this method instead to get automatic service resolution!
		///// </summary>
		///// <param name="plugin">the plugin to register.</param>
		//[Obsolete ("This member should not be used, if you MUST use it file a bug report! Use RegisterPlugin<T> instead.")]
		//override void RegisterPlugin(TPlugin plugin);

        /// <summary>
        /// Gets a service instance which is provided by an previously registered plugin
        /// </summary>
        /// <typeparam name="U"></typeparam>
        /// <returns></returns>
		U GetPluginService<U> () where U : class;
	}
    /// <summary>
    /// Extension methods for the Plugin Manager interfaces.
    /// </summary>
	public static class RuntimePluginManagerExtensions {
		//public static Tuple RequirePlugin<T, U> (this IRuntimePluginManager<U> service) where T : U
		//{
		//	return Tuple.Create (service.ServiceType, service.ServiceInstance);
		//}
	}

}


text:
var async               = require('async')
  , i18n                = require('jade-i18n')
  ;

var asyncFs             = require('./util/async_fs')

  , config              = require('./config')
  , LOCALES_NAME_REGEXP = config.LOCALES_NAME_REGEXP
  ;

exports.i18n  = i18n;

exports._     = i18n.helpers._;

/******************************************************************************
 * Setup phrases as defined by `locale_file`, watches `locale_file` for
 * changes and makes changes accordingly. Also removes all the phrases on file
 * deletion.
 *
 * @param locale_file {Object} The FileEventEmitter object of the current locale
 * file.
 *
 * @param matches {Array} Array of the matched patterns of the RegExp selecting
 * this locale file.
 *
 * @param callback {Function} A callback of the form `function(err)`
 */
function setupLocale(locale_file, matches, callback) {

  var locale  = require(locale_file.path)
    , lang    = matches[1]
    , phrase
    ;

  function setupPhrases(locale) {

    var translation
      ;

    for (var phrase in locale) {

      translation = locale[phrase];

      i18n.phrase(lang, phrase, translation);

    }

  }

  function removePhrases(locale) {

    for (var phrase in locale) {

      i18n.phrase(lang, phrase, undefined);

    }

  }

  locale_file.on('change', function(curr, prev) {

    delete require.cache[locale_file.path];

    removePhrases(locale);

    locale = require(locale_file.path);

    setupPhrases(locale);

  });

  locale_file.on('destroy', function(curr, prev) {

    delete require.cache[locale_file.path];

    removePhrases(locale);

  });

  setupPhrases(locale);

  if (callback) { callback(null) };

}

/******************************************************************************
 * Setups the localized strings, also watches the `locales` directory for new
 * files or changes and calls `setupLocale` accordingly.
 *
 * @param locales_folder_file {Object} The FileEventEmitter object of the
 * `locales` folder.
 *
 * @param callback {Function} A callback of the form `function(err)`
 */
exports.setup = function() {

  var args                = Array.prototype.slice.call(arguments)

    , locales_folder_file = args.shift()

    , callback            = args.pop()
    ;

  asyncFs.mapDir(

      locales_folder_file.path

    , [ LOCALES_NAME_REGEXP, setupLocale ]

    , callback

  );

}


text:
layout: page
title: Townsend 20th Anniversary
date: 2016-05-24
author: Lisa Kent
tags: weekly links, java
status: published
summary: Donec ut erat at arcu semper sodales eget sed ante.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 03/18/2019
  endDate: 03/21/2019
  ctyhocn: LACOLHX
  groupCode: T2A
published: true
---
Sed efficitur porta ligula eget mollis. Nulla sit amet fringilla erat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam iaculis felis nec dapibus vulputate. Vivamus mollis vehicula nibh vel tristique. Pellentesque vitae orci felis. Suspendisse potenti. Nam et lobortis tellus.

* Etiam eu lorem non neque fringilla rutrum ac vitae eros
* Fusce a ligula dictum, faucibus erat vel, rhoncus lacus
* Nunc eget velit vel turpis pellentesque posuere eu ac leo
* Cras sodales ipsum a mi semper venenatis
* Nullam at eros ac urna commodo molestie
* Nam a diam id sem facilisis rhoncus.

Duis vel urna suscipit, commodo sem porttitor, sollicitudin nisi. Nulla metus sem, efficitur non pellentesque id, vestibulum ut diam. Pellentesque ac semper ex, id dapibus lorem. Sed vel ex eu nunc dictum auctor. Vivamus eu velit et tellus eleifend consectetur quis vitae quam. Donec nec diam vel ipsum ullamcorper bibendum sed et sem. Aenean molestie volutpat augue, a molestie dolor efficitur eget. Proin interdum in quam finibus ornare. Vivamus semper ipsum erat, quis pellentesque nibh dignissim eleifend. Morbi sed risus ipsum. Quisque sodales, neque id viverra fringilla, erat massa sodales libero, in bibendum lacus risus sed augue.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ISyncable</title>
<meta name="date" content="2014-11-03">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.rogansoft.sync

Interface ISyncable

public interface ISyncable

ISyncable must be implemented by class that represents data to be synced.

 Includes:

Property accessors to remote datastore id

Property accessors to "last updated" sequence number

Methods to map fields between remote and local datastores

Author:

SAS

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.Long
getLastUpdatedSequence()

Getter for "last updated" sequence number.

java.lang.String
getRemoteId()

Getter for remote id that uniquely identifies syncable data item.

void
mapFromLocal(ISyncable local)

Map fields from local syncable data instance.

void
mapFromRemote(ISyncable remote)

Map fields from remote syncable data instance.

void
setLastUpdatedSequence(java.lang.Long value)

Setter for "last updated" sequence number.

void
setRemoteId(java.lang.String id)

Setter for remote id that uniquely identifies syncable data item.

Method Detail

getRemoteId

java.lang.String getRemoteId()

Getter for remote id that uniquely identifies syncable data item.  Used by syncmanager
 to match local/remote syncable items.

Returns:

Remote datastore id

setRemoteId

void setRemoteId(java.lang.String id)

Setter for remote id that uniquely identifies syncable data item.

Parameters:

id - Remote datastore id

getLastUpdatedSequence

java.lang.Long getLastUpdatedSequence()

Getter for "last updated" sequence number.

Returns:

Last updated sequence number

setLastUpdatedSequence

void setLastUpdatedSequence(java.lang.Long value)

Setter for "last updated" sequence number.

Parameters:

value - Last updated sequence number

mapFromRemote

void mapFromRemote(ISyncable remote)

Map fields from remote syncable data instance.

Parameters:

remote - Remote syncable item to map from

mapFromLocal

void mapFromLocal(ISyncable local)

Map fields from local syncable data instance.

Parameters:

local - Local syncable item to map from

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#ifndef QWT_ROUND_SCALE_DRAW_H
#define QWT_ROUND_SCALE_DRAW_H

#include "qwt_global.h"
#include "qwt_abstract_scale_draw.h"
#include <qpoint.h>

class QPen;

/*!
  \brief A class for drawing round scales

  QwtRoundScaleDraw can be used to draw round scales.
  The circle segment can be adjusted by QwtRoundScaleDraw::setAngleRange().
  The geometry of the scale can be specified with
  QwtRoundScaleDraw::moveCenter() and QwtRoundScaleDraw::setRadius().

  After a scale division has been specified as a QwtScaleDiv object
  using QwtAbstractScaleDraw::setScaleDiv(const QwtScaleDiv &s),
  the scale can be drawn with the QwtAbstractScaleDraw::draw() member.
*/

class QWT_EXPORT QwtRoundScaleDraw: public QwtAbstractScaleDraw
{
public:
    QwtRoundScaleDraw();
    virtual ~QwtRoundScaleDraw();

    void setRadius( int radius );
    int radius() const;

    void moveCenter( double x, double y );
    void moveCenter( const QPointF & );
    QPointF center() const;

    void setAngleRange( double angle1, double angle2 );

    virtual double extent( const QFont & ) const;

protected:
    virtual void drawTick( QPainter *p, double val, double len ) const;
    virtual void drawBackbone( QPainter *p ) const;
    virtual void drawLabel( QPainter *p, double val ) const;

private:
    QwtRoundScaleDraw( const QwtRoundScaleDraw & );
    QwtRoundScaleDraw &operator=( const QwtRoundScaleDraw &other );

    class PrivateData;
    PrivateData *d_data;
};

//! Move the center of the scale draw, leaving the radius unchanged
inline void QwtRoundScaleDraw::moveCenter( double x, double y )
{
    moveCenter( QPointF( x, y ) );
}

#endif


text:
package com.david.algorithm_study;

import java.util.Arrays;
import java.util.HashMap;

/**
 *
 * @author dailiwei
 *
 */
public class TwoSum {

	public static void main(String[] args) {
		// sortArray(new int[] { 2, 7, 11, 152 });
		int[] resultArr = twoSum(new int[] { 2, 7, 11, 15 }, 13);
		System.out.println(Arrays.toString(resultArr));
	}

	private static int[] twoSum(int[] numbers, int target) {
		int n = numbers.length;
		int[] result = new int[2];
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		for (int i = 0; i < n; i++) {
			if (map.containsKey(numbers[i])) {
				result[0] = map.get(numbers[i]) + 1;
				result[1] = i + 1;
				break;
			} else {
				map.put(target - numbers[i], i);
			}
		}
		return result;
	}

	private static void sortArray(int[] arr) {
		System.out.println("before = " + Arrays.toString(arr));
		Arrays.sort(arr);
		System.out.println("after = " + Arrays.toString(arr));
	}
}


text:
import sys
import typing
import pytest
import pyuavcan

TransportPack = typing.Tuple[pyuavcan.transport.Transport, pyuavcan.transport.Transport, bool]

TransportFactory = typing.Callable[[typing.Optional[int], typing.Optional[int]], TransportPack]
"""
The factory yields two new transports connected to the same (virtual) bus so that they can intercommunicate.
The boolean flag is True if the transports are capable of sending anonymous transfers.
"""

def _generate() -> typing.Iterator[typing.Callable[[], typing.Iterator[TransportFactory]]]:
    """
    We use the unwieldy generator syntax to leverage the setup/teardown functionality provided by PyTest.
    """

    def can_mock_media() -> typing.Iterator[TransportFactory]:
        """
        The mock media fixture allows us to test configurations with limited acceptance filter configurations.
        Also, the mock media allows Classic CAN and CAN FD nodes to co-exist easily,
        whereas the virtual bus emulated by SocketCAN has certain limitations there
        (a frame with BRS set cannot be received by receiver for which FD is not enabled).
        """
        from pyuavcan.transport.can import CANTransport
        from tests.transport.can.media.mock import MockMedia

        def fact(nid_a: typing.Optional[int], nid_b: typing.Optional[int]) -> TransportPack:
            bus: typing.Set[MockMedia] = set()
            media_a = MockMedia(bus, 8, 1)
            media_b = MockMedia(bus, 64, 2)  # Heterogeneous setup
            assert bus == {media_a, media_b}
            return CANTransport(media_a, nid_a), CANTransport(media_b, nid_b), True

        yield fact

    yield can_mock_media

    def can_mock_media_triply_redundant() -> typing.Iterator[TransportFactory]:
        from pyuavcan.transport.redundant import RedundantTransport
        from pyuavcan.transport.can import CANTransport
        from tests.transport.can.media.mock import MockMedia

        def factory(nid_a: typing.Optional[int], nid_b: typing.Optional[int]) -> TransportPack:
            bus_0: typing.Set[MockMedia] = set()
            bus_1: typing.Set[MockMedia] = set()
            bus_2: typing.Set[MockMedia] = set()

            def one(nid: typing.Optional[int]) -> RedundantTransport:
                red = RedundantTransport()
                red.attach_inferior(CANTransport(MockMedia(bus_0, 8, 1), nid))  # Heterogeneous setup (CAN classic)
                red.attach_inferior(CANTransport(MockMedia(bus_1, 32, 2), nid))  # Heterogeneous setup (CAN FD)
                red.attach_inferior(CANTransport(MockMedia(bus_2, 64, 3), nid))  # Heterogeneous setup (CAN FD)
                return red

            return one(nid_a), one(nid_b), True

        yield factory

    yield can_mock_media_triply_redundant

    if sys.platform.startswith("linux"):

        def can_socketcan_vcan0() -> typing.Iterator[TransportFactory]:
            from pyuavcan.transport.can import CANTransport
            from pyuavcan.transport.can.media.socketcan import SocketCANMedia

            yield lambda nid_a, nid_b: (
                CANTransport(SocketCANMedia("vcan0", 16), nid_a),
                CANTransport(SocketCANMedia("vcan0", 64), nid_b),
                True,
            )

        yield can_socketcan_vcan0

        def can_socketcan_vcan0_vcan1() -> typing.Iterator[TransportFactory]:
            from pyuavcan.transport.redundant import RedundantTransport
            from pyuavcan.transport.can import CANTransport
            from pyuavcan.transport.can.media.socketcan import SocketCANMedia

            def one(nid: typing.Optional[int]) -> RedundantTransport:
                red = RedundantTransport()
                red.attach_inferior(CANTransport(SocketCANMedia("vcan0", 64), nid))
                red.attach_inferior(CANTransport(SocketCANMedia("vcan1", 32), nid))
                return red

            yield lambda nid_a, nid_b: (one(nid_a), one(nid_b), True)

        yield can_socketcan_vcan0_vcan1

    def serial_tunneled_via_tcp() -> typing.Iterator[TransportFactory]:
        from pyuavcan.transport.serial import SerialTransport
        from tests.transport.serial import VIRTUAL_BUS_URI

        yield lambda nid_a, nid_b: (
            SerialTransport(VIRTUAL_BUS_URI, nid_a),
            SerialTransport(VIRTUAL_BUS_URI, nid_b),
            True,
        )

    yield serial_tunneled_via_tcp

    def udp_loopback() -> typing.Iterator[TransportFactory]:
        from pyuavcan.transport.udp import UDPTransport

        def one(nid: typing.Optional[int]) -> UDPTransport:
            return UDPTransport("127.0.0.1", local_node_id=nid)

        yield lambda nid_a, nid_b: (one(nid_a), one(nid_b), False)

    yield udp_loopback

    def heterogeneous_udp_serial() -> typing.Iterator[TransportFactory]:
        from pyuavcan.transport.redundant import RedundantTransport
        from pyuavcan.transport.udp import UDPTransport
        from pyuavcan.transport.serial import SerialTransport
        from tests.transport.serial import VIRTUAL_BUS_URI

        def one(nid: typing.Optional[int]) -> RedundantTransport:
            red = RedundantTransport()
            red.attach_inferior(UDPTransport("127.0.0.1", local_node_id=nid))
            red.attach_inferior(SerialTransport(VIRTUAL_BUS_URI, nid))
            print("UDP+SERIAL:", red)
            return red

        yield lambda nid_a, nid_b: (one(nid_a), one(nid_b), False)

    yield heterogeneous_udp_serial

@pytest.fixture(params=list(_generate()))
def transport_factory(request: typing.Any) -> typing.Iterable[TransportFactory]:
    """
    This parametrized fixture generates multiple transport factories to run the test against different transports.
    """
    yield from request.param()