text:
class Formula
  def fails_with_llvm msg=nil, data=nil
    opoo "Calling fails_with_llvm in the install method is deprecated"
    puts "Use the fails_with DSL instead"
  end

  def fails_with_llvm?
    fails_with? :llvm
  end

  def self.fails_with_llvm msg=nil, data={}
    data = msg if Hash === msg
    fails_with(:llvm) { build(data.delete(:build).to_i) }
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.twuni.common.net.http.responder;

import static org.twuni.common.net.http.util.MIMEUtils.getContentType;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.twuni.common.net.http.request.Request;
import org.twuni.common.net.http.response.Response;
import org.twuni.common.net.http.response.Status;

public class FileResponder implements Responder {

	private final Logger log = LoggerFactory.getLogger( getClass() );

	private final File parent;

	public FileResponder( File parent ) {
		this.parent = parent;
	}

	@Override
	public Response respondTo( Request request ) {
		try {
			File file = new File( parent, request.getResource() );
			byte [] buffer = readFully( file );
			return new Response( Status.OK, getContentType( file.getName(), buffer ), buffer );
		} catch( FileNotFoundException exception ) {
			return new Response( Status.NOT_FOUND );
		} catch( IOException exception ) {
			log.warn( exception.toString() );
			return new Response( Status.INTERNAL_SERVER_ERROR );
		}
	}

	protected byte [] readFully( File file ) throws FileNotFoundException, IOException {
		FileInputStream in = new FileInputStream( file );
		byte [] buffer = new byte [(int) file.length()];
		for( int length = 0; length < buffer.length; length += in.read( buffer, length, buffer.length - length ) ) {
		}
		in.close();
		return buffer;
	}

}


text:
@class IDEiOSImageSection, NSDictionary, NSString;

@protocol IDEiOSImageSectionDelegate
- (NSString *)deploymentOS;
- (BOOL)iPadTargeted;
- (BOOL)iPhoneTargeted;
- (BOOL)statusBarHiddenForImageSection:(IDEiOSImageSection *)arg1;
- (NSString *)imageSection:(IDEiOSImageSection *)arg1 expandedValueForString:(NSString *)arg2;
- (NSDictionary *)iconFilePathSetsByIconBaseNameForImageSection:(IDEiOSImageSection *)arg1;
- (id <IDEInfoPlistCoordination>)infoPlistCoordinatorForImageSection:(IDEiOSImageSection *)arg1;
@end


text:
@implementation NSObject (Addtions)

//-(id)initWithDictionary:(NSDictionary *)dic
//{
//    self = [[NSObject alloc]init];
//
//    if (self) {
//
//        if ([dic isKindOfClass:[NSDictionary class]]) {
//            [self setValuesForKeysWithDictionary:dic];
//        }
//    }
//    return self;
//}
//
//-(void)setValue:(id)value forUndefinedKey:(NSString *)key
//{
//    NSLog(@"forUndefinedKey %@",key);
//}

@end


text:
namespace sync_sessions {

class MockSyncSessionsClient : public SyncSessionsClient {
 public:
  // By default, ShouldSyncURL() always returns true.
  MockSyncSessionsClient();
  ~MockSyncSessionsClient() override;
  MOCK_METHOD(SessionSyncPrefs*, GetSessionSyncPrefs, (), (override));
  MOCK_METHOD(syncer::RepeatingModelTypeStoreFactory,
              GetStoreFactory,
              (),
              (override));
  MOCK_METHOD(void, ClearAllOnDemandFavicons, (), (override));
  MOCK_METHOD(bool, ShouldSyncURL, (const GURL& url), (const override));
  MOCK_METHOD(bool,
              IsRecentLocalCacheGuid,
              (const std::string& cache_guid),
              (const override));
  MOCK_METHOD(SyncedWindowDelegatesGetter*,
              GetSyncedWindowDelegatesGetter,
              (),
              (override));
  MOCK_METHOD(LocalSessionEventRouter*,
              GetLocalSessionEventRouter,
              (),
              (override));
};

}  // namespace sync_sessions

#endif  // COMPONENTS_SYNC_SESSIONS_MOCK_SYNC_SESSIONS_CLIENT_H_


text:
using System.Diagnostics;
using Utilities.DataTypes;
using Xunit;

namespace UnitTests.DataTypes
{
    public class ProcessExtensions
    {
        [Fact]
        public void GetInformation()
        {
            string Value = Process.GetProcesses().GetInformation();
            Assert.NotNull(Value);
        }
    }
}


text:
'use strict';

import type {DataID, Disposable} from 'relay-runtime';

const useRelayEnvironment = require('./useRelayEnvironment');
const {useEffect, useRef} = require('react');

/**
 * This hook subscribes a callback to the invalidation state of the given data
 * ids.
 * Any time the invalidation state of the given data ids changes, the provided
 * callback will be called.
 * If new ids or a new callback are provided, the subscription will be
 * re-established and the previous one will be disposed.
 * The subscription will automatically be disposed on unmount
 */
function useSubscribeToInvalidationState(
  dataIDs: $ReadOnlyArray<DataID>,
  callback: () => void,
): Disposable {
  const environment = useRelayEnvironment();
  const disposableRef = useRef(null);

  const stableDataIDs = Array.from(dataIDs).sort().join('');
  useEffect(() => {
    const store = environment.getStore();
    const invalidationState = store.lookupInvalidationState(dataIDs);
    const disposable = store.subscribeToInvalidationState(
      invalidationState,
      callback,
    );
    disposableRef.current = disposable;
    return () => disposable.dispose();

    // Intentionally excluding dataIDs, since we're using stableDataIDs
    // instead
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [stableDataIDs, callback, environment]);

  return {
    dispose: () => {
      if (disposableRef.current != null) {
        disposableRef.current.dispose();
      }
    },
  };
}

module.exports = useSubscribeToInvalidationState;


text:
package api

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
)

// Attach opens a file by name, and unmarshal its JSON data.
// Will proceed to setup the API if not already done so.
func (a *API) Attach(filename string) {
	a.path = filepath.Dir(filename)
	f, err := os.Open(filename)
	defer f.Close()
	if err != nil {
		panic(err)
	}
	if err := json.NewDecoder(f).Decode(a); err != nil {
		panic(fmt.Errorf("failed to decode %s, err: %v", filename, err))
	}
}

// AttachString will unmarshal a raw JSON string, and setup the
// API if not already done so.
func (a *API) AttachString(str string) {
	json.Unmarshal([]byte(str), a)

	if !a.initialized {
		a.Setup()
	}
}

// Setup initializes the API.
func (a *API) Setup() {
	a.setMetadataEndpointsKey()
	a.writeShapeNames()
	a.resolveReferences()
	a.fixStutterNames()
	a.renameExportable()
	if !a.NoRenameToplevelShapes {
		a.renameToplevelShapes()
	}

	a.renameCollidingFields()
	a.updateTopLevelShapeReferences()
	a.createInputOutputShapes()
	a.suppressEventStreams()
	a.customizationPasses()

	if !a.NoRemoveUnusedShapes {
		a.removeUnusedShapes()
	}

	if !a.NoValidataShapeMethods {
		a.addShapeValidations()
	}

	a.initialized = true
}


text:
php-translation
===============

provide the tr() method for outputting translated strings


text:
"use strict"

const init  = require('../../init'),
      log   = require('loglevel')

module.exports = {
  command: 'init',
  desc: 'Initialize directory structure for experiments',

  builder: {},
  handler: (argv) => {
    log.setLevel(argv.v ? 'debug' : 'info')
    init()
  }
}


text:
package org.nd4j.linalg.api.ndarray;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.nd4j.linalg.BaseNd4jTest;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;
import org.nd4j.linalg.indexing.NDArrayIndex;

import java.io.*;

import static org.junit.Assert.assertEquals;

/**
 * Created by Alex on 28/04/2016.
 */
@RunWith(Parameterized.class)
public class TestSerialization extends BaseNd4jTest {

    public TestSerialization(Nd4jBackend backend) {
        super(backend);
    }

    @Test
    public void testSerializationFullArrayNd4jWriteRead() throws Exception {
        int length = 100;
        INDArray arr = Nd4j.linspace(1,length,length).reshape('c',10,10);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try(DataOutputStream dos = new DataOutputStream(baos)){
            Nd4j.write(arr,dos);
        }
        byte[] bytes = baos.toByteArray();

        INDArray arr2;
        try( DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes))){
            arr2 = Nd4j.read(dis);
        }

        assertEquals(arr,arr2);
    }

    @Test
    public void testSerializationFullArrayJava() throws Exception {
        int length = 100;
        INDArray arr = Nd4j.linspace(1,length,length).reshape('c',10,10);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try(ObjectOutputStream oos = new ObjectOutputStream(baos)){
            oos.writeObject(arr);
        }
        byte[] bytes = baos.toByteArray();

        INDArray arr2;
        try( ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes))){
            arr2 = (INDArray) ois.readObject();
        }

        assertEquals(arr,arr2);
    }

    @Test
    public void testSerializationOnViewsNd4jWriteRead() throws Exception {
        int length = 100;
        INDArray arr = Nd4j.linspace(1,length,length).reshape('c',10,10);

        INDArray sub = arr.get(NDArrayIndex.interval(5,10), NDArrayIndex.interval(5,10));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try(DataOutputStream dos = new DataOutputStream(baos)){
            Nd4j.write(sub,dos);
        }
        byte[] bytes = baos.toByteArray();

        INDArray arr2;
        try( DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes))){
            arr2 = Nd4j.read(dis);
        }

        assertEquals(sub,arr2);
    }

    @Test
    public void testSerializationOnViewsJava() throws Exception {
        int length = 100;
        INDArray arr = Nd4j.linspace(1,length,length).reshape('c',10,10);

        INDArray sub = arr.get(NDArrayIndex.interval(5,10), NDArrayIndex.interval(5,10));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try(ObjectOutputStream oos = new ObjectOutputStream(baos)){
            oos.writeObject(sub);
        }
        byte[] bytes = baos.toByteArray();

        INDArray arr2;
        try( ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes))){
            arr2 = (INDArray) ois.readObject();
        }

        assertEquals(sub,arr2);
    }

    @Override
    public char ordering() {
        return 'c';
    }
}


text:
module Sukremore
  module Modules
    class Email < Base
      MODULE_NAME= 'EmailAddresses'
      # GET  --------------------
      # Returns the ID for the given email if it exists, false otherwise.
      def email_id? email
        raise "email can't be nil" if email == nil
        sugar_resp = @client.get_entry_list(MODULE_NAME, {
            :query => 'email_address=\''+ email +'\'',#"email_address IN ('#{email}')", # the SQL WHERE clause without the word "where".
            :order_by => '', # the SQL ORDER BY clause without the phrase "order by".
            :offset => '0', # the record offset from which to start.
            :select_fields => ['email_address'],
            :max_results => '1',
            #:link_name_to_fields_array => [{:name => 'id'}, {:value => ['id', 'name']}],
            :deleted => 0, # exclude deleted records
            :favorites => false # if only records marked as favorites should be returned.
          }
        )
        if sugar_resp['entry_list'].any?
          sugar_resp['entry_list'][0]['id']
        else
          false
        end
      end

      # SET
      # insert email.
      # Returns the email id on success, otherwise returns nil.
      def insert_email email
        raise "really? add new a new empty account?" if email.nil? or email.empty?

        email_params = {
          email_address: email,
          email_address_caps: email.upcase,
          invalid_email: false,
          opt_out: false,
          created_at: Time.now,
          updated: Time.now
        }

        @client.set_entry Email::MODULE_NAME, email_params
      end

    end
  end
end


text:
<?php

use opensrs\domains\authentication\AuthenticationChangePassword;

/**
 * @group authentication
 * @group AuthenticationChangePassword
 */
class AuthenticationChangePasswordTest extends PHPUnit_Framework_TestCase
{
    protected $fund = 'authChangePassword';

    protected $validSubmission = array(
        'attributes' => array(
            /*
             * Required: one of 'cookie' or 'domain'
             *
             * cookie: authentication cookie
             *   * see domains\cookie\CookieSet
             * domain: the relevant domain (only
             *   required if 'cookie' is not sent)
             */
            'cookie' => '',
            'domain' => '',

            /*
             * Required
             *
             * The new password for the registrant
             */
            'reg_password' => '',
            ),
        );

    /**
     * Valid submission should complete with no
     * exception thrown.
     *
     *
     * @group validsubmission
     */
    public function testValidSubmission()
    {
        $data = json_decode(json_encode($this->validSubmission));

        $data->attributes->cookie = md5(time());
        $data->attributes->domain = 'phptest'.time().'.com';
        $data->attributes->reg_password = password_hash(md5(time()), PASSWORD_BCRYPT);

        $ns = new AuthenticationChangePassword('array', $data);

        $this->assertTrue($ns instanceof AuthenticationChangePassword);
    }

    /**
     * Data Provider for Invalid Submission test.
     */
    public function submissionFields()
    {
        return array(
            'missing reg_password' => array('reg_password'),
            );
    }

    /**
     * Invalid submission should throw an exception.
     *
     *
     * @dataProvider submissionFields
     * @group invalidsubmission
     */
    public function testInvalidSubmissionFieldsMissing($field, $parent = 'attributes', $message = null)
    {
        $data = json_decode(json_encode($this->validSubmission));

        $data->attributes->cookie = md5(time());
        $data->attributes->domain = 'phptest'.time().'.com';
        $data->attributes->reg_password = password_hash(md5(time()), PASSWORD_BCRYPT);

        if (is_null($message)) {
            $this->setExpectedExceptionRegExp(
              'opensrs\Exception',
              "/$field.*not defined/"
              );
        } else {
            $this->setExpectedExceptionRegExp(
              'opensrs\Exception',
              "/$message/"
              );
        }

        // clear field being tested
        if (is_null($parent)) {
            unset($data->$field);
        } else {
            unset($data->$parent->$field);
        }

        $ns = new AuthenticationChangePassword('array', $data);
    }
}


text:
package org.flysnow.cloud.buildmeta.wsclient.ui.model;

import java.util.Map;

import org.flysnow.cloud.buildmeta.wsclient.domain.model.Build;

public class GetBuildsMapResponse {

	private Map<String, Build> mapBuilds;

	public Map<String, Build> getMapBuilds() {
		return mapBuilds;
	}

	public void setMapBuilds(Map<String, Build> mapBuilds) {
		this.mapBuilds = mapBuilds;
	}

}


text:
package com.xnfh.bjhospital.config;

import android.app.Application;
import android.content.Context;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

/**
 * Created by wangxuewei on 2017/10/17.
 */
public class MyApplication extends Application {
    private static MyApplication myApplication;
    @Override
    public void onCreate() {
        super.onCreate();
        myApplication = this;
        initOkGo();

    }
    public static Context getAppContext() {
        return myApplication;
    }

    private void initOkGo() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("okgo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);//显示数据的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);//log级别颜色
        builder.addInterceptor(loggingInterceptor);//添加okgo的debug日志

        //设置超时时间
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间
        //设置超时时间
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间
        OkGo.getInstance().init(this)
                .setOkHttpClient(builder.build())
                .setCacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间,默认永不过期,可以不传
                .setRetryCount(3);
    }
}


text:
<?php
function conectarse()
{
	$servidor="localhost";
	$usuario="root";
	$password="";
	$bd="mis_contactos";

	$conectar = new mysqli($servidor,$usuario,$password,$bd);
	return $conectar;
}

$conexion = conectarse();
?>


text:
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
         xmlns:context="http://www.springframework.net/context">

	<context:component-scan base-assemblies="Spring.Core.Configuration.Tests">
		<!-- to test type load exception -->
		<context:include-filter type="assignable" expression="XmlAssemblyTypeScanner.Test.Include1.NotValid, Spring.Core.Configuration.Tests"/>

		<context:include-filter type="assignable" expression="XmlAssemblyTypeScanner.Test.Include1.IFunny, Spring.Core.Configuration.Tests"/>
		<context:include-filter type="assignable" expression="XmlAssemblyTypeScanner.Test.Include2.FunnyAbstract, Spring.Core.Configuration.Tests"/>
	</context:component-scan>

</objects>


text:
stereosynth
===========

Stereo video synthesis using PatchMatch

Idea
----
Synthesize a stereo video from a collection of exemplar stereo videos and a new target mono video stream using a Nearest Neighbor Field (NNF) (here [PatchMatch](http://gfx.cs.princeton.edu/gfx/pubs/Barnes_2009_PAR/index.php)).

Method
------
**Basic method**:
Given exemplar stereo streams `(L,R)` and a new mono stream `L'` (assumed to be the left stream arbitrarily), we synthesize the right stream `R'` by finding nearest neighbor patches from `L'` to `L` and then using the corresponding patch of `R` for `R'`.

  * using 2D patches: temporal coherence might be a problem if treating the frames independently, if bootstrapping PatchMatch with the result of the previous (or next) frame, then it gets alleviated
  * using 3D patches: temporal coherence will be fine, but dimensionality will slow down the computation a lot (though it partially takes care of working with multiple exemplars)
  * using multiple exemplars: how do we sample a huge exemplar?

TODO
----

  1. Add tests!
  2. Experiment with multiple patch sizes and image scales
  3. Fix meanshift voting

Unknowns
--------

  * best patch size
  * best image resolution => maybe use a multi-resolution approach (at least for the NNF)
  * how to work with multiple exemplars?
  * whether to use 2D or 3D patches

License
-------
Released under the [MIT license](http://opensource.org/licenses/MIT).


text:
#import "MSGraphServiceModels.h"
#import "core/MSOrcObjectizer.h"

/** Implementation for MSGraphServiceSearchResult
 *
 */
@implementation MSGraphServiceSearchResult

@synthesize odataType = _odataType;

+ (NSDictionary *) $$$_$$$propertiesNamesMappings
{
    static NSDictionary *_$$$_$$$propertiesNamesMappings=nil;

        if(_$$$_$$$propertiesNamesMappings==nil) {

        _$$$_$$$propertiesNamesMappings=[[NSDictionary alloc] initWithObjectsAndKeys:  @"onClickTelemetryUrl", @"onClickTelemetryUrl", nil];

    }

    return _$$$_$$$propertiesNamesMappings;
}

- (instancetype)init {

	if (self = [super init]) {

		_odataType = @"#microsoft.graph.searchResult";

    }

	return self;
}

- (instancetype) initWithDictionary: (NSDictionary *) dic {
    if((self = [self init])) {
        if(dic!=nil) {
		_onClickTelemetryUrl = (![dic objectForKey: @"onClickTelemetryUrl"] || [ [dic objectForKey: @"onClickTelemetryUrl"] isKindOfClass:[NSNull class]] )?_onClickTelemetryUrl:[[dic objectForKey: @"onClickTelemetryUrl"] copy];
    }
    [self.updatedValues removeAllObjects];
    }

    return self;
}

- (NSDictionary *) toDictionary {

    NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];

	{id curVal = [self.onClickTelemetryUrl copy];if (curVal!=nil) [dic setValue: curVal forKey: @"onClickTelemetryUrl"];}
    [dic setValue: @"#microsoft.graph.searchResult" forKey: @"@odata.type"];

    return dic;
}

- (NSDictionary *) toUpdatedValuesDictionary {

    NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];

	{id curVal = self.onClickTelemetryUrl;
    if([self.updatedValues containsObject:@"onClickTelemetryUrl"])
    {
                [dic setValue: curVal==nil?[NSNull null]:[curVal copy] forKey: @"onClickTelemetryUrl"];
            }
    }
    return dic;
}

/** Setter implementation for property onClickTelemetryUrl
 *
 */
- (void) setOnClickTelemetryUrl: (NSString *) value {
    _onClickTelemetryUrl = value;
    [self valueChangedFor:@"onClickTelemetryUrl"];
}

@end


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

namespace Free.Core.Drawing
{
	///
	/// Describes a generic single-channel/band raster (<see cref="PlanarConfiguration"/> is always <see cref="PlanarConfiguration.Continuously"/>).
	///
	/// <typeparam name="T">The type of the raster.</typeparam>
	public class Raster<T> : TiledImage where T : struct, IEquatable<T>
	{
		#region Const
		///
		/// Return value for <see cref="ChannelTypes"/>, for <see cref="ChannelType.Byte"/>.
		///
		protected static readonly ChannelType[] ChannelTypeByte = new ChannelType[] { ChannelType.Byte };

		///
		/// Return value for <see cref="ChannelTypes"/>, for <see cref="ChannelType.SByte"/>.
		///
		protected static readonly ChannelType[] ChannelTypeSByte = new ChannelType[] { ChannelType.SByte };

		///
		/// Return value for <see cref="ChannelTypes"/>, for <see cref="ChannelType.SShort"/>.
		///
		protected static readonly ChannelType[] ChannelTypeSShort = new ChannelType[] { ChannelType.SShort };

		///
		/// Return value for <see cref="ChannelTypes"/>, for <see cref="ChannelType.UShort"/>.
		///
		protected static readonly ChannelType[] ChannelTypeUShort = new ChannelType[] { ChannelType.UShort };

		///
		/// Return value for <see cref="ChannelTypes"/>, for <see cref="ChannelType.SInt"/>.
		///
		protected static readonly ChannelType[] ChannelTypeSInt = new ChannelType[] { ChannelType.SInt };

		///
		/// Return value for <see cref="ChannelTypes"/>, for <see cref="ChannelType.UInt"/>.
		///
		protected static readonly ChannelType[] ChannelTypeUInt = new ChannelType[] { ChannelType.UInt };

		///
		/// Return value for <see cref="ChannelTypes"/>, for <see cref="ChannelType.SLong"/>.
		///
		protected static readonly ChannelType[] ChannelTypeSLong = new ChannelType[] { ChannelType.SLong };

		///
		/// Return value for <see cref="ChannelTypes"/>, for <see cref="ChannelType.ULong"/>.
		///
		protected static readonly ChannelType[] ChannelTypeULong = new ChannelType[] { ChannelType.ULong };

		///
		/// Return value for <see cref="ChannelTypes"/>, for <see cref="ChannelType.Single"/>.
		///
		protected static readonly ChannelType[] ChannelTypeSingle = new ChannelType[] { ChannelType.Single };

		///
		/// Return value for <see cref="ChannelTypes"/>, for <see cref="ChannelType.Double"/>.
		///
		protected static readonly ChannelType[] ChannelTypeDouble = new ChannelType[] { ChannelType.Double };

		///
		/// Return value for <see cref="ChannelTypes"/>, for <see cref="ChannelType.Structure"/>.
		///
		protected static readonly ChannelType[] ChannelTypeStructure = new ChannelType[] { ChannelType.Structure };

		///
		/// Default width for tiles.
		///
		public const int DefaultTileWidth = 256;

		///
		/// Default height for tiles.
		///
		public const int DefaultTileHeight = 256;
		#endregion

		#region Variables
		///
		/// Contains the elements of the raster. Only change access this directly, if you know what you are doing.
		///
		/// <remarks>
		/// <para>Layout: An array of TileCountX*TileCountY arrays of <see cref="TileWidth"/>*<see cref="TileHeight"/> elements each.
		/// </para>
		/// <para>ATTENTION: Do not reference the same tile more than once, in the main array. Unless you know what you are doing.</para>
		/// <para>ATTENTION: Do not share the same tile with other raster.</para>
		/// </remarks>
		public T[][] Data; // Tiled
		#endregion

		#region Properties

		///
		/// Gets/Sets the value of the specified cell.
		///
		/// <param name="x">The column of the cell.</param>
		/// <param name="y">The row of the cell.</param>
		/// <returns>The value of the cell.</returns>
		public T this[int x, int y]
		{
			get
			{
				if (x < 0 || x >= Width) throw new IndexOutOfRangeException(nameof(x) + " index must be greater or equal to zero (0), and smaller than the " + nameof(Width) + ".");
				if (y < 0 || y >= Height) throw new IndexOutOfRangeException(nameof(y) + " index must be greater or equal to zero (0), and smaller than the " + nameof(Height) + ".");

				int xTile = x / TileWidth;
				int yTile = y / TileHeight;

				int xInTile = x % TileWidth;
				int yInTile = y % TileHeight;

				return Data[yTile * NumberOfTileX + xTile][yInTile * TileWidth + xInTile];
			}
			set
			{
				if (x < 0 || x >= Width) throw new IndexOutOfRangeException(nameof(x) + " index must be greater or equal to zero (0), and smaller than the " + nameof(Width) + ".");
				if (y < 0 || y >= Height) throw new IndexOutOfRangeException(nameof(y) + " index must be greater or equal to zero (0), and smaller than the " + nameof(Height) + ".");

				int xTile = x / TileWidth;
				int yTile = y / TileHeight;

				int xInTile = x % TileWidth;
				int yInTile = y % TileHeight;

				Data[yTile * NumberOfTileX + xTile][yInTile * TileWidth + xInTile] = value;
			}
		}

		///
		/// Gets the number of tiles in x-direction.
		///
		public int NumberOfTileX { get; }

		///
		/// Gets the number of tiles in y-direction.
		///
		public int NumberOfTileY { get; }

		#region Implements ImageCommons
		///
		/// Gets the width of the raster.
		///
		public int Width { get; protected set; }

		///
		/// Gets the height of the raster.
		///
		public int Height { get; protected set; }

		///
		/// Gets the number of channels in the raster. This is always one (1).
		///
		public int NumberOfChannels { get { return 1; } }

		///
		/// Gets the types of the raster.
		///
		public ChannelType[] ChannelTypes { get; protected set; }

		///
		/// Gets the planar configuration of the raster storage. This is always <see cref="PlanarConfiguration.Continuously"/>,
		/// since only one (1) channel is support by this object.
		///
		public PlanarConfiguration PlanarConfiguration { get { return PlanarConfiguration.Continuously; } }

		///
		/// Gets the layout of the raster storage.
		///
		public StorageLayout StorageLayout { get { return Data != null ? (Data.Length == 1 ? StorageLayout.SingleChunked : StorageLayout.Tiled) : StorageLayout.Tiled; } }
		#endregion

		#region Implements TiledImage
		///
		/// Gets the width of the tiles in the raster. All tiles have the same width (number of samples).
		///
		public int TileWidth { get; protected set; }

		///
		/// Gets the height of the tiles in the raster. All tiles have the same height (number of lines).
		///
		public int TileHeight { get; protected set; }
		#endregion

		#endregion

		#region Statics
		///
		/// Caches the neighboursXYOffsets and maxDistance values for previous requested radii.
		///
		public static Dictionary<double, Tuple<int, int[]>> NeighboursXYOffsetsCache = new Dictionary<double, Tuple<int, int[]>>();

		///
		/// Generates the relatives x- and y-coordinates of the elements at the lattice points with a maximum distance to the center of <paramref name="radius"/>.
		///
		/// <param name="radius">The radius.</param>
		/// <param name="maxDistance">The maximum integral distance in x or y dimension of a lattice point to the center.</param>
		/// <returns>An array containing the relatives x- and y-coordinates of the elements at the lattice points with a maximum distance to the center of <paramref name="radius"/>.</returns>
		public static int[] GenerateNeighboursXYOffsets(double radius, out int maxDistance)
		{
			if (double.IsInfinity(radius) || double.IsNaN(radius)) throw new ArgumentException("Must be a valid, non-infinte number.", nameof(radius));

			// Let's check the cache, whether we already calculated maxDistance and array for the given radius.
			Tuple<int, int[]> cached;
			if (NeighboursXYOffsetsCache.TryGetValue(radius, out cached))
			{
				maxDistance = cached.Item1;
				return cached.Item2;
			}

			// We could throw here, but that seems to be overkill, since we can fix this.
			double radiusAbs = Math.Abs(radius);
			if (radiusAbs < 1) radiusAbs = 1;

			int rad = (int)Math.Floor(radiusAbs);

			var ret = new List<int>();
			for (var y = -rad; y <= rad; y++)
			{
				for (var x = -rad; x <= rad; x++)
				{
					if (y * y + x * x > radiusAbs * radiusAbs) continue;
					ret.Add(x);
					ret.Add(y);
				}
			}

			int[] retArray = ret.ToArray();
			lock (NeighboursXYOffsetsCache)
			{
				NeighboursXYOffsetsCache[radius] = new Tuple<int, int[]>(rad, retArray);
			}

			maxDistance = rad;
			return retArray;
		}

		///
		/// Converts the alternating relative x- and y-coordinate values into index offsets for a specified <paramref name="tileWidth"/>.
		///
		/// <param name="neighboursXYOffsets">The array with alternating relative x- and y-coordinate values.</param>
		/// <param name="tileWidth">The tile width.</param>
		/// <returns>The index offsets as array.</returns>
		public static int[] ConvertToInTileIndexOffsets(int[] neighboursXYOffsets, int tileWidth)
		{
			if (null == neighboursXYOffsets) throw new ArgumentNullException(nameof(neighboursXYOffsets));
			if (tileWidth < 1) throw new ArgumentOutOfRangeException(nameof(tileWidth), "Must be greater zero (0).");
			if (neighboursXYOffsets.Length % 2 != 0) throw new ArgumentException("Must have an even number of elements.", nameof(neighboursXYOffsets));

			var ret = new int[neighboursXYOffsets.Length / 2];
			for (int i = 0, j = 0; j < ret.Length;)
			{
				int x = neighboursXYOffsets[i++];
				int y = neighboursXYOffsets[i++];
				ret[j++] = y * tileWidth + x;
			}
			return ret;
		}
		#endregion

		#region Constructors
		///
		/// Creates a new instance.
		///
		/// <param name="width">The width of the raster in cells. Must be greater zero (0)</param>
		/// <param name="height">The height of the raster in cells. Must be greater zero (0)</param>
		/// <param name="init">Indicates whether the <see cref="Data"/> array shall be created and initialized with default(<typeparamref name="T"/>).</param>
		/// <param name="tileWidth">The width of the tiles in cells. Must be greater zero (0).</param>
		/// <param name="tileHeight">The height of the tiles in cells. Must be greater zero (0).</param>
		public Raster(int width, int height, bool init, int tileWidth = DefaultTileWidth, int tileHeight = DefaultTileHeight)
		{
			if (width < 1) throw new ArgumentOutOfRangeException(nameof(width), "Must be greater zero (0).");
			if (height < 1) throw new ArgumentOutOfRangeException(nameof(height), "Must be greater zero (0).");
			if (tileWidth < 1) throw new ArgumentOutOfRangeException(nameof(tileWidth), "Must be greater zero (0).");
			if (tileHeight < 1) throw new ArgumentOutOfRangeException(nameof(tileHeight), "Must be greater zero (0).");

			Width = width;
			Height = height;
			TileWidth = tileWidth;
			TileHeight = tileHeight;

			NumberOfTileX = (width + tileWidth - 1) / tileWidth;
			NumberOfTileY = (height + tileHeight - 1) / tileHeight;

			Type type = typeof(T);
			if (typeof(byte) == type) ChannelTypes = ChannelTypeByte;
			else if (typeof(ushort) == type) ChannelTypes = ChannelTypeUShort;
			else if (typeof(uint) == type) ChannelTypes = ChannelTypeUInt;
			else if (typeof(ulong) == type) ChannelTypes = ChannelTypeULong;
			else if (typeof(float) == type) ChannelTypes = ChannelTypeSingle;
			else if (typeof(double) == type) ChannelTypes = ChannelTypeDouble;
			else if (typeof(sbyte) == type) ChannelTypes = ChannelTypeSByte;
			else if (typeof(short) == type) ChannelTypes = ChannelTypeSShort;
			else if (typeof(int) == type) ChannelTypes = ChannelTypeSInt;
			else if (typeof(long) == type) ChannelTypes = ChannelTypeSLong;
			else ChannelTypes = ChannelTypeStructure;

			if (init)
			{
				int tiles = NumberOfTileX * NumberOfTileY;
				int tileSize = TileWidth * TileHeight;

				Data = new T[tiles][];
				for (int i = 0; i < tiles; i++) Data[i] = new T[tileSize];
			}
		}
		#endregion

		#region Methods

		///
		/// Sets all cells with the specified value.
		///
		/// <param name="value">The value.</param>
		public void Clear(T value = default(T))
		{
			int tiles = Data.Length;
			int tileSize = TileWidth * TileHeight;

			for (int i = 0; i < tiles;)
			{
				T[] tile = Data[i++];
				for (int j = 0; j < tileSize;) tile[j++] = value;
			}
		}

		///
		/// Draws the content of a specified <paramref name="source"/> raster to this raster at the specified position.
		///
		/// <param name="x">The x position of the <paramref name="source"/> raster in this raster.</param>
		/// <param name="y">The y position of the <paramref name="source"/> raster in this raster.</param>
		/// <param name="source">The raster to draw.</param>
		public void Draw(int x, int y, Raster<T> source)
		{
			if (source == null) throw new ArgumentNullException(nameof(source));

			// First let check whether the images overlap.
			if (x + source.Width <= 0 || x >= Width) return;
			if (y + source.Height <= 0 || y >= Height) return;

			int dstStartX = Math.Max(x, 0);
			int dstStartY = Math.Max(y, 0);
			int dstEndX = Math.Min(x + source.Width, Width);
			int dstEndY = Math.Min(y + source.Height, Height);

			int amountX = dstEndX - dstStartX;
			int amountY = dstEndY - dstStartY;

			int startTileXDest = dstStartX / TileWidth;
			int startTileYDest = dstStartY / TileHeight;
			int endTileXDest = (dstEndX - 1) / TileWidth;
			int endTileYDest = (dstEndY - 1) / TileHeight;

			int srcY = Math.Max(-y, 0);
			int tileStartYDest = dstStartY % TileHeight;
			int tileAmountY = Math.Min(TileHeight - tileStartYDest, amountY);

			// Go thru all target tiles.
			for (int dstTileY = startTileYDest; dstTileY <= endTileYDest; dstTileY++)
			{
				amountX = dstEndX - dstStartX; // Reset amount.

				int srcX = Math.Max(-x, 0);
				int tileStartXDest = dstStartX % TileWidth;
				int tileAmountX = Math.Min(TileWidth - tileStartXDest, amountX);

				for (int dstTileX = startTileXDest; dstTileX <= endTileXDest; dstTileX++)
				{
					// The tile index is assumed for PlanarConfiguration == Continuously, DrawIntoTile will handle Separated case inside.
					DrawIntoTile(dstTileY * NumberOfTileX + dstTileX, source, tileStartXDest, tileStartYDest, srcX, srcY, tileAmountX, tileAmountY);

					srcX += tileAmountX;
					tileStartXDest = 0;
					amountX -= tileAmountX;
					tileAmountX = Math.Min(amountX, TileWidth);
				}

				srcY += tileAmountY;
				tileStartYDest = 0;
				amountY -= tileAmountY;
				tileAmountY = Math.Min(amountY, TileHeight);
			}
		}

		void DrawIntoTile(int tileIndex, Raster<T> source, int dstStartX, int dstStartY, int srcStartX, int srcStartY, int amountX, int amountY)
		{
			int srcEndX = srcStartX + amountX;
			int srcEndY = srcStartY + amountY;

			int startTileXSource = srcStartX / source.TileWidth;
			int startTileYSource = srcStartY / source.TileHeight;
			int endTileXSource = (srcEndX - 1) / source.TileWidth;
			int endTileYSource = (srcEndY - 1) / source.TileHeight;

			int amountXBackup = amountX;

			int dstStartOfLineInDestTile = dstStartY * TileWidth + dstStartX;

			int tileStartYSrc = srcStartY % source.TileHeight;
			int tileAmountY = Math.Min(source.TileHeight - tileStartYSrc, amountY);

			for (int srcTileY = startTileYSource; srcTileY <= endTileYSource; srcTileY++)
			{
				amountX = amountXBackup; // Reset amount.

				int dstStartOfSourceTileInDestTile = dstStartOfLineInDestTile;

				int tileStartXSrc = srcStartX % source.TileWidth;
				int tileAmountX = Math.Min(source.TileWidth - tileStartXSrc, amountX);

				for (int srcTileX = startTileXSource; srcTileX <= endTileXSource; srcTileX++)
				{
					var data = Data[tileIndex];
					int dstStartOfSourceLineInDestTile = dstStartOfSourceTileInDestTile;

					int srcStartOfLine = tileStartYSrc * source.TileWidth + tileStartXSrc;

					var srcData = source.Data[srcTileY * source.NumberOfTileX + srcTileX];

					for (int y = 0; y < tileAmountY; y++)
					{
						int dst = dstStartOfSourceLineInDestTile;
						int src = srcStartOfLine * source.NumberOfChannels;

						for (int x = 0; x < tileAmountX; x++)
							data[dst++] = srcData[src++];

						srcStartOfLine += source.TileWidth;
						dstStartOfSourceLineInDestTile += TileWidth;
					}

					dstStartOfSourceTileInDestTile += tileAmountX;

					tileStartXSrc = 0;
					amountX -= tileAmountX;
					tileAmountX = Math.Min(amountX, source.TileWidth);
				}

				dstStartOfLineInDestTile += tileAmountY * TileWidth;

				tileStartYSrc = 0;
				amountY -= tileAmountY;
				tileAmountY = Math.Min(amountY, source.TileHeight);
			}
		}

		///
		/// Gets a sub-raster at the specified position with the specified size. Requested areas outside the raster will be filled with the default(<typeparamref name="T"/>) values.
		///
		/// <param name="x">The x-position of the sub-raster in the raster.</param>
		/// <param name="y">The y-position of the sub-raster in the raster.</param>
		/// <param name="width">The width of the new raster.</param>
		/// <param name="height">The height of the new raster.</param>
		/// <param name="tileWidth">The width of the tiles in cells. If zero (0) or smaller, the tile width of the original is used.</param>
		/// <param name="tileHeight">The height of the tiles in cells. If zero (0) or smaller, the tile height of the original is used.</param>
		/// <returns>The sub-raster.</returns>
		public Raster<T> GetSubRaster(int x, int y, int width, int height, int tileWidth = DefaultTileWidth, int tileHeight = DefaultTileHeight)
		{
			if (tileWidth <= 0) tileWidth = TileWidth;
			if (tileHeight <= 0) tileHeight = TileHeight;

			// Create the result depending on this.
			Raster<T> ret = new Raster<T>(width, height, true, tileWidth, tileHeight);

			// Just draw this into the result image, and let Draw handle everything.
			ret.Draw(-x, -y, this);

			return ret;
		}

		///
		/// Gets the content of the specified tile (specified by tile index in <paramref name="x"/> and
		/// <paramref name="y"/> direction) as a new raster.
		///
		/// <param name="x">The index of the tile in x-direction.</param>
		/// <param name="y">The index of the tile in y-direction.</param>
		/// <returns>A raster.</returns>
		/// <exception cref="ArgumentOutOfRangeException">If at least one of <paramref name="x"/> and
		/// <paramref name="y"/> is negative, or refers to a tile outside the raster.</exception>
		public Raster<T> GetTile(int x, int y)
		{
			if (x < 0 || x >= NumberOfTileX) throw new ArgumentOutOfRangeException(nameof(x));
			if (y < 0 || y >= NumberOfTileY) throw new ArgumentOutOfRangeException(nameof(y));

			var ret = new Raster<T>(TileWidth, TileHeight, true, TileWidth, TileHeight);

			Data[y * NumberOfTileX + x].CopyTo(ret.Data[0], 0);

			return ret;
		}

		///
		/// Gets the content of the specified tile (specified by tile index in <paramref name="x"/> and
		/// <paramref name="y"/> direction) as a new raster.
		///
		/// <param name="x">The index of the tile in x-direction.</param>
		/// <param name="y">The index of the tile in y-direction.</param>
		/// <param name="channel">The index of the channel. Must always be zero (0).</param>
		/// <returns>A raster.</returns>
		/// <exception cref="ArgumentOutOfRangeException">If at least one of <paramref name="x"/> and
		/// <paramref name="y"/> is negative, or refers to a tile outside the raster.</exception>
		/// <exception cref="ArgumentOutOfRangeException">If <paramref name="channel"/> is not zero(0).</exception>
		public Raster<T> GetTile(int x, int y, int channel)
		{
			if (channel == 0) throw new ArgumentOutOfRangeException(nameof(channel), "Must be zero (0).");

			return GetTile(x, y);
		}

		#region Morphological operations
		///
		/// Dilates the default(<typeparamref name="T"/>) regions.
		///
		/// <param name="radius">The radius.</param>
		/// <returns>The raster with dilated default(<typeparamref name="T"/>) regions. Undilated cells keep their value.</returns>
		public Raster<T> Dilation(double radius)
		{
			int maxDistance;
			var neighboursXYOffsets = GenerateNeighboursXYOffsets(radius, out maxDistance);

			return Dilation(maxDistance, ConvertToInTileIndexOffsets(neighboursXYOffsets, TileWidth), neighboursXYOffsets);
		}

		///
		/// Dilates the default(<typeparamref name="T"/>) regions.
		///
		/// <param name="maxDistance">Distance of the furthest 'structuring elements' in one dimension from the current position [in number of cells].</param>
		/// <param name="neighboursInTileIndexOffsets">Relative index offset to the current position in a tile which define the structuring elements.</param>
		/// <param name="neighboursXYOffsets">Alternating relative x and y coordinate to the current position which define the structuring elements.</param>
		/// <returns>The raster with dilated default(<typeparamref name="T"/>) regions. Undilated cells keep their value.</returns>
		public Raster<T> Dilation(int maxDistance, int[] neighboursInTileIndexOffsets, int[] neighboursXYOffsets)
		{
			if (maxDistance <= 0) throw new ArgumentException("Must be greater than zero(0).", nameof(maxDistance));
			if (null == neighboursInTileIndexOffsets) throw new ArgumentNullException(nameof(neighboursInTileIndexOffsets));
			if (null == neighboursXYOffsets) throw new ArgumentNullException(nameof(neighboursXYOffsets));
			if (neighboursXYOffsets.Length % 2 != 0) throw new ArgumentException("Must have an even number of elements.", nameof(neighboursXYOffsets));
			if (neighboursXYOffsets.Length / 2 != neighboursInTileIndexOffsets.Length) throw new ArgumentException("Must have twice as many elements than " + nameof(neighboursInTileIndexOffsets) + ".", nameof(neighboursXYOffsets));

			// Local copies are faster.
			var dist = maxDistance;
			int[] nitio = neighboursInTileIndexOffsets, nxyo = neighboursXYOffsets;
			int width = Width, height = Height, tileWidth = TileWidth, tileHeight = TileHeight, numberOfTileX = NumberOfTileX;
			var orgData = Data;

			var ret = new Raster<T>(width, height, true, tileWidth, tileHeight);
			var retData = ret.Data;

			// Let's do it by tile to keep the data accesses local.
			for (int tile = 0; tile < retData.Length; tile++)
			{
				var retTile = retData[tile];
				var orgTile = orgData[tile];

				var tileStartX = tileWidth * (tile % numberOfTileX);
				var tileStartY = tileHeight * (tile / numberOfTileX);

				var amountX = Math.Min(width - tileStartX, tileWidth);
				var amountY = Math.Min(height - tileStartY, tileHeight);

				Parallel.For(0, amountY, line =>
				{
					bool fast = line > dist && line < amountY - dist; // We can use the neighboursInTileIndexOffsets when we're not at the border of the tile.

					var index = line * tileWidth;

					var rasterLine = line + tileStartY;

					for (int samp = 0; samp < amountX; samp++, index++)
					{
						bool found = false;
						if (fast && samp > dist && samp < amountX - dist) // We can use the neighboursInTileIndexOffsets when we're not at the border of the tile.
						{
							for (int i = 0; i < nitio.Length; i++)
							{
								if (orgTile[index + nitio[i]].Equals(default(T)))
								{
									retTile[index] = default(T);
									found = true;
									break;
								}
							}
						}
						else
						{
							var rasterSamp = samp + tileStartX;
							for (int i = 0; i < nxyo.Length;)
							{
								var x = rasterSamp + nxyo[i++]; // First read the x value...
								var y = rasterLine + nxyo[i++]; // ...then the y value.
								if (x < 0 || x >= width || y < 0 || y >= height) continue;

								int xTile = x / tileWidth, yTile = y / tileHeight, xInTile = x % tileWidth, yInTile = y % tileHeight;

								if (orgData[yTile * numberOfTileX + xTile][yInTile * tileWidth + xInTile].Equals(default(T)))
								{
									retTile[index] = default(T);
									found = true;
									break;
								}
							}
						}

						if (!found) retTile[index] = orgTile[index];
					}
				});
			}
			return ret;
		}

		///
		/// Erodes the default(<typeparamref name="T"/>) regions.
		///
		/// <param name="radius">The radius.</param>
		/// <param name="newValue">The value to use for non-default(<typeparamref name="T"/>) cells. Must be a non-default(<typeparamref name="T"/>) value.</param>
		/// <returns>The raster with values default((<typeparamref name="T"/>) and <paramref name="newValue"/>.</returns>
		public Raster<T> Erosion(double radius, T newValue)
		{
			int maxDistance;
			var neighboursXYOffsets = GenerateNeighboursXYOffsets(radius, out maxDistance);

			return Erosion(maxDistance, ConvertToInTileIndexOffsets(neighboursXYOffsets, TileWidth), neighboursXYOffsets, newValue);
		}

		///
		/// Erodes the default(<typeparamref name="T"/>) regions.
		///
		/// <param name="maxDistance">Distance of the furthest 'structuring elements' in one dimension from the current position [in number of cells].</param>
		/// <param name="neighboursInTileIndexOffsets">Relative index offset to the current position in a tile which define the structuring elements.</param>
		/// <param name="neighboursXYOffsets">Alternating relative x and y coordinate to the current position which define the structuring elements.</param>
		/// <param name="newValue">The value to use for non-default(<typeparamref name="T"/>) cells. Must be a non-default(<typeparamref name="T"/>) value.</param>
		/// <returns>The raster with values default((<typeparamref name="T"/>) and <paramref name="newValue"/>.</returns>
		public Raster<T> Erosion(int maxDistance, int[] neighboursInTileIndexOffsets, int[] neighboursXYOffsets, T newValue)
		{
			if (maxDistance <= 0) throw new ArgumentException("Must be greater than zero(0).", nameof(maxDistance));
			if (null == neighboursInTileIndexOffsets) throw new ArgumentNullException(nameof(neighboursInTileIndexOffsets));
			if (null == neighboursXYOffsets) throw new ArgumentNullException(nameof(neighboursXYOffsets));
			if (neighboursXYOffsets.Length % 2 != 0) throw new ArgumentException("Must have an even number of elements.", nameof(neighboursXYOffsets));
			if (neighboursXYOffsets.Length / 2 != neighboursInTileIndexOffsets.Length) throw new ArgumentException("Must have twice as many elements than " + nameof(neighboursInTileIndexOffsets) + ".", nameof(neighboursXYOffsets));
			if (newValue.Equals(default(T))) throw new ArgumentException("Must be a non-default value.", nameof(newValue));

			// Local copies are faster.
			var dist = maxDistance;
			int[] nitio = neighboursInTileIndexOffsets, nxyo = neighboursXYOffsets;
			int width = Width, height = Height, tileWidth = TileWidth, tileHeight = TileHeight, numberOfTileX = NumberOfTileX;
			var orgData = Data;

			var ret = new Raster<T>(width, height, true, tileWidth, tileHeight);
			var retData = ret.Data;

			// Let's do it by tile to keep the data accesses local.
			for (int tile = 0; tile < retData.Length; tile++)
			{
				var retTile = retData[tile];
				var orgTile = orgData[tile]; // Used for fast access path only.

				var tileStartX = tileWidth * (tile % numberOfTileX);
				var tileStartY = tileHeight * (tile / numberOfTileX);

				var amountX = Math.Min(width - tileStartX, tileWidth);
				var amountY = Math.Min(height - tileStartY, tileHeight);

				Parallel.For(0, amountY, line =>
				{
					bool fast = line > dist && line < amountY - dist; // We can use the neighboursInTileIndexOffsets when we're not at the border of the tile.

					var index = line * tileWidth;

					var rasterLine = line + tileStartY;

					for (int samp = 0; samp < amountX; samp++, index++)
					{
						if (fast && samp > dist && samp < amountX - dist) // We can use the neighboursInTileIndexOffsets when we're not at the border of the tile.
						{
							for (int i = 0; i < nitio.Length; i++)
							{
								if (!orgTile[index + nitio[i]].Equals(default(T)))
								{
									retTile[index] = newValue;
									break;
								}
							}
						}
						else
						{
							var rasterSamp = samp + tileStartX;
							for (int i = 0; i < nxyo.Length;)
							{
								var x = rasterSamp + nxyo[i++]; // First read the x value...
								var y = rasterLine + nxyo[i++]; // ...then the y value.
								if (x < 0 || x >= width || y < 0 || y >= height) continue;

								int xTile = x / tileWidth, yTile = y / tileHeight, xInTile = x % tileWidth, yInTile = y % tileHeight;

								if (!orgData[yTile * numberOfTileX + xTile][yInTile * tileWidth + xInTile].Equals(default(T)))
								{
									retTile[index] = newValue;
									break;
								}
							}
						}
					}
				});
			}
			return ret;
		}

		///
		/// Opens the default(<typeparamref name="T"/>) regions.
		///
		/// <param name="radius">The radius.</param>
		/// <param name="newValue">The value to use for non-default(<typeparamref name="T"/>) cells. Must be a non-default(<typeparamref name="T"/>) value.</param>
		/// <returns>The raster with values default((<typeparamref name="T"/>) and <paramref name="newValue"/>.</returns>
		public Raster<T> Opening(double radius, T newValue)
		{
			int maxDistance;
			var neighboursXYOffsets = GenerateNeighboursXYOffsets(radius, out maxDistance);
			var neighboursInTileIndexOffsets = ConvertToInTileIndexOffsets(neighboursXYOffsets, TileWidth);

			return Erosion(maxDistance, neighboursInTileIndexOffsets, neighboursXYOffsets, newValue).Dilation(maxDistance, neighboursInTileIndexOffsets, neighboursXYOffsets);
		}

		///
		/// Closes the default(<typeparamref name="T"/>) regions.
		///
		/// <param name="radius">The radius.</param>
		/// <param name="newValue">The value to use for non-default(<typeparamref name="T"/>) cells. Must be a non-default(<typeparamref name="T"/>) value.</param>
		/// <returns>The raster with values default((<typeparamref name="T"/>) and <paramref name="newValue"/>.</returns>
		public Raster<T> Closing(double radius, T newValue)
		{
			int maxDistance;
			var neighboursXYOffsets = GenerateNeighboursXYOffsets(radius, out maxDistance);
			var neighboursInTileIndexOffsets = ConvertToInTileIndexOffsets(neighboursXYOffsets, TileWidth);

			return Dilation(maxDistance, neighboursInTileIndexOffsets, neighboursXYOffsets).Erosion(maxDistance, neighboursInTileIndexOffsets, neighboursXYOffsets, newValue);
		}
		#endregion

		#region Filter
		///
		/// Performs a <paramref name="filterOperation"/> on a <see cref="Raster{T}"/>.
		///
		/// <typeparam name="A">The type of the resulting <see cref="Raster{T}"/>.</typeparam>
		/// <param name="filterOperation">The function to calculate the result value for a structure element.</param>
		/// <param name="radius">The radius.</param>
		/// <param name="borderValue">The value to be given to the <paramref name="filterOperation"/> for elements outside of the raster.</param>
		/// <returns>The raster with the filtered values.</returns>
		public Raster Filter(Func<T[], A> filterOperation, double radius, T borderValue) where A : struct, IEquatable
		{
			int maxDistance;
			var neighboursXYOffsets = GenerateNeighboursXYOffsets(radius, out maxDistance);
			var neighboursInTileIndexOffsets = ConvertToInTileIndexOffsets(neighboursXYOffsets, TileWidth);

			return Filter(filterOperation, maxDistance, neighboursInTileIndexOffsets, neighboursXYOffsets, borderValue);
		}

		///
		/// Performs a <paramref name="filterOperation"/> on a <see cref="Raster{T}"/>.
		///
		/// <typeparam name="A">The type of the resulting <see cref="Raster{T}"/>.</typeparam>
		/// <param name="filterOperation">The function to calculate the result value for a structure element.</param>
		/// <param name="maxDistance">Distance of the furthest 'structuring elements' in one dimension from the current position [in number of cells].</param>
		/// <param name="neighboursInTileIndexOffsets">Relative index offset to the current position in a tile which define the structuring elements.</param>
		/// <param name="neighboursXYOffsets">Alternating relative x and y coordinate to the current position which define the structuring elements.</param>
		/// <param name="borderValue">The value to be given to the <paramref name="filterOperation"/> for elements outside of the raster.</param>
		/// <returns>The raster with the filtered values.</returns>
		public Raster Filter(Func<T[], A> filterOperation, int maxDistance, int[] neighboursInTileIndexOffsets, int[] neighboursXYOffsets, T borderValue) where A : struct, IEquatable
		{
			if (maxDistance <= 0) throw new ArgumentException("Must be greater than zero(0).", nameof(maxDistance));
			if (null == neighboursInTileIndexOffsets) throw new ArgumentNullException(nameof(neighboursInTileIndexOffsets));
			if (null == neighboursXYOffsets) throw new ArgumentNullException(nameof(neighboursXYOffsets));
			if (neighboursXYOffsets.Length % 2 != 0) throw new ArgumentException("Must have an even number of elements.", nameof(neighboursXYOffsets));
			if (neighboursXYOffsets.Length / 2 != neighboursInTileIndexOffsets.Length) throw new ArgumentException("Must have twice as many elements than " + nameof(neighboursInTileIndexOffsets) + ".", nameof(neighboursXYOffsets));

			// Local copies are faster.
			var dist = maxDistance;
			int[] nitio = neighboursInTileIndexOffsets, nxyo = neighboursXYOffsets;
			int width = Width, height = Height, tileWidth = TileWidth, tileHeight = TileHeight, numberOfTileX = NumberOfTileX;
			var orgData = Data;

			var ret = new Raster(width, height, true, tileWidth, tileHeight);
			var retData = ret.Data;

			// Let's do it by tile to keep the data accesses local.
			for (int tile = 0; tile < retData.Length; tile++)
			{
				var retTile = retData[tile];
				var orgTile = orgData[tile]; // Used for fast access path only.

				var tileStartX = tileWidth * (tile % numberOfTileX);
				var tileStartY = tileHeight * (tile / numberOfTileX);

				var amountX = Math.Min(width - tileStartX, tileWidth);
				var amountY = Math.Min(height - tileStartY, tileHeight);

				Parallel.For(0, amountY, line =>
				{
					bool fast = line > dist && line < amountY - dist; // We can use the neighboursInTileIndexOffsets when we're not at the border of the tile.

					var index = line * tileWidth;

					var rasterLine = line + tileStartY;

					T[] structurElement = new T[nitio.Length];

					for (int samp = 0; samp < amountX; samp++, index++)
					{
						if (fast && samp > dist && samp < amountX - dist) // We can use the neighboursInTileIndexOffsets when we're not at the border of the tile.
						{
							for (int i = 0; i < nitio.Length; i++) structurElement[i] = orgTile[index + nitio[i]];
						}
						else
						{
							var rasterSamp = samp + tileStartX;
							for (int i = 0, a = 0; i < nxyo.Length; a++)
							{
								var x = rasterSamp + nxyo[i++]; // First read the x value...
								var y = rasterLine + nxyo[i++]; // ...then the y value.
								if (x < 0 || x >= width || y < 0 || y >= height)
								{
									structurElement[a] = borderValue;
									continue;
								}

								int xTile = x / tileWidth, yTile = y / tileHeight, xInTile = x % tileWidth, yInTile = y % tileHeight;

								structurElement[a] = orgData[yTile * numberOfTileX + xTile][yInTile * tileWidth + xInTile];
							}
						}

						retTile[index] = filterOperation(structurElement);
					}
				});
			}
			return ret;
		}
		#endregion

		#region Implements TiledImage
		TiledImage TiledImage.GetTile(int x, int y)
		{
			return GetTile(x, y);
		}

		TiledImage TiledImage.GetTile(int x, int y, int channel)
		{
			return GetTile(x, y, channel);
		}
		#endregion

		#endregion
	}
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.mortbay.jetty.client (Jetty Server Project 6.1.22 API)
</TITLE>

<META NAME="keywords" CONTENT="org.mortbay.jetty.client package">

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

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package org.mortbay.jetty.client

Interface Summary

HttpEventListener

Class Summary

Address

CachedExchange
An exchange that caches response status and fields for later use.

ContentExchange
A CachedExchange that retains response content for later use.

HttpClient
Http Client.

HttpConnection

HttpDestination

HttpEventListenerWrapper

HttpExchange
An HTTP client API that encapsulates Exchange with a HTTP server.

HttpExchange.CachedExchange
Deprecated. use CachedExchange

HttpExchange.ContentExchange
Deprecated. use ContentExchange

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Copyright © 1995-2009 Mort Bay Consulting. All Rights Reserved.


text:
__author__ = 'boonya'

from os import listdir, remove
from os.path import isfile, join, isdir, exists
from .interface import FileSystemInterface
from .exception import NotExistsException

class Direct(FileSystemInterface):
    container = None

    def __init__(self, container):
        """Constructor.

        :param string container:
        :return:
        """
        if not isdir(container) or not exists(container):
            raise ValueError(
                "'%s' is not a directory or does not exist." % container)

        self.container = container.rstrip('/')

    def list(self):
        return [f for f in listdir(self.container) if
                isfile(join(self.container, f))]

    def read(self, path):
        file_path = self.container + '/' + path

        if not exists(file_path) or not isfile(file_path):
            raise NotExistsException("'%s' is unknown file." % path)

        with open(file_path, 'r') as fh:
            data = fh.read()

        return data

    def write(self, path, data):
        file_path = self.container + '/' + path

        with open(file_path, 'w') as fh:
            fh.write(data)

        with open(file_path, 'r') as fh:
            result = fh.read()

        return result

    def remove(self, path):
        file_path = self.container + '/' + path

        if not exists(file_path) or not isfile(file_path):
            raise NotExistsException("'%s' is unknown file." % path)

        remove(file_path)

        return True


text:
package fommil.sjs

import shapeless.record._

object MixedAst {
  type Address = Record.`'city -> String, 'street -> String, 'house -> String`.T
  case class Person(name: String, address: Address)
  type Department = Record.`'name -> String, 'employees -> Vector[Person]`.T
}


text:
import copy
import random
import time

try:
    import scipy.stats
    beta = scipy.stats.beta
except ImportError:
    # This is necessary when using pypy, because there's no scipy
    pass

import numpy

##############################################################################
## Ensure that all randomness here is "pseudo", so results are consistent
##############################################################################
random.seed(1)            # Make results deterministic.
numpy.random.seed(1)      # Make results deterministic.

##############################################################################
## compute preference matrix from a profile of ballots
##############################################################################

def prefs(B,partial_ballots=False):
    """
    Input:
        B is a list of ballots; each ballot is a permutation of range(m)
             (or a prefix of such a permutation if ballots may be partial).
        partial_ballots is True if partial ballots may be present
    Return:
        matrix A of prefs according to ballots in B
        A[a][b] is number of ballots preferring a to b
    Procedure:
        partial ballots are randomly extended to make complete ballots
    """

    if partial_ballots==False:
        m = len(B[0])
        for ballot in B:
            assert sorted(ballot) == range(m)
    else:
        m = 1+max([max(ballot) for ballot in B])
        newB = []
        for ballot in B:
            if len(ballot)==m:
                newB.append(ballot)
                continue
            missingset = set(range(m))-set(ballot)
            missinglist = list(missingset)
            random.shuffle(missinglist)
            newballot = ballot + missinglist
            newB.append(newballot)
        B = newB

    A = [ [0 for j in range(m)] for i in range(m) ]
    for ballot in B:
        for i in range(len(ballot)):
            a = ballot[i]
            for j in range(i+1, len(ballot)):
                b = ballot[j]
                A[a][b] += 1
    return A

##############################################################################
## sample profiles for testing
##############################################################################

B1 = [ [0, 1, 2, 3],
       [1, 2, 0, 3],
       [3, 1, 2, 0],
       [1, 3, 0, 2],
       [2, 1, 0, 3]]

B2 = [ [ 0, 1, 2 ],
       [ 2, 1, 0 ]]

B3 = [ [ 0, 1, 2, 3, 4 ],
       [ 1, 2, 3, 4, 0 ],
       [ 1, 3, 4, 2, 0 ] ]

B4 = [ [   0, 1, 2, 3 ],             # cyclic !
       [   1, 2, 3, 0 ],
       [   2, 3, 0, 1 ],
       [   3, 0, 1, 2 ]] * 100

B5 = []
for _ in range(500):
    ballot = range(5)
    random.shuffle(ballot)
    B5.append(ballot)

B6 = [ [ 0, 2, 1 ],    # partial ballots
       [ 3 ],
       [ 2, 3] ]

##############################################################################
## beta distributions
##############################################################################

def sn(n, sk, fk):
    """
    Input sk = number of successes observed in k trials (k = sk+fk)
    Input fk = number of failures observed in k trials  (k = sk+fk)
    Input n = number of trials yet to see
    Ouput (sn, fn) = rv number of trials that may succeed/fail in those n trials
                     (integers between 0 and n, inclusive, with n=sn+fn
                     This is a randomized procedure, producing random output.
    Method: use beta distribution to predict p, then scale to range(0,n+1).
    """
    bd = beta(sk+1, fk+1)                     # create beta distribution
    assert n >= 0
    p = bd.rvs()                              # draw p from beta distribution
    sn = int(p*(n+1))
    if sn>n:                                  # could only happen if p = 1.000 !
        sn = n
    fn = n - sn
    return (sn, fn)

def sn_matrix(A, n):
    """
    Input: m x m matrix A of nonnegative numbers (0's on diag)
    Output: "Similar" matrix AA, with AA[i][j] + AA[j][i] == n
    """
    m = len(A)
    assert all([m == len(A[i]) for i in range(m)])
    assert all([A[i][i]==0 for i in range(m)])
    assert all([A[i][j]>=0 for i in range(m) for j in range(m)])

    AA = [[0 for j in range(m)] for i in range(m)]
    for i in range(m):
        for j in range(i+1,m):
            s = A[i][j]
            f = A[j][i]
            AA[i][j], AA[j][i] = sn(n, s, f)
    return AA

def test_sn_matrix():
    A = [ [ 0,  1,  2  ],
          [ 3,  0,  25 ],
          [ 100, 25, 0 ]]
    print A
    for _ in range(10):
        print sn_matrix(A, 100)

# test_sn_matrix()

##############################################################################
## end of beta distribution
##############################################################################

##############################################################################
## implementation of Tideman's ranked pairs method (RP)
##############################################################################

def sorted_pairs(A):
    """
    Input A is an m x m matrix of pairwise preferences (numbers)
          A[i][j] is number of voters preferring i to j
    Output is a sorted list of pairs, decreasing order of strength.
    (Ties broken using random numbers as tie-breakers.)
    """
    m = len(A[0])
    V = range(m)
    L = [(A[i][j], random.random(), i, j) for i in V for j in V if i != j ]
    L = sorted(L, reverse=True)
    matches = 0
    for x in xrange(len(L)-1):
        if L[x][0] is not L[x+1][0]:
            break
        else:
            matches += 1
    #if matches is not 0:
        # print L
        #print "There was a %d-way tie" % matches
    return [(i,j) for (Aij, rand, i, j) in L]

def test_sorted_pairs():
    A = [ [ 0, 6, 9 ],
          [ 7, 0, 11 ],
          [ 13, 12, 0 ]]
    assert sorted_pairs(A) == \
        [(2, 0), (2, 1), (1, 2), (0, 2), (1, 0), (0, 1)]
    # assertion always true since there are no ties...

test_sorted_pairs()

def reachable(Adj, s, t):
    """
    Adj is adjacency list rep of graph
    Return True if edges in Adj have directed path from s to t.

    Note that this routine is one of the most-used and most time-consuming
    of this whole procedure, which is why it is passed an adjacency list
    rep rather than a list of vertices and edges, since the adjacency list
    rep is easy to update when a new edge is committed to in RP.
    """
    # search for path
    Q = [ s ]         # vertices to expand
    R = set([s])      # reachable
    while Q:
        i = Q.pop()
        for j in Adj[i]:
            if j == t:
                return True
            if j not in R:
                R.add(j)
                Q.append(j)
    return False

def test_reachable():
    V = range(6)
    E = [ (1,2), (1,3), (2, 3), (3, 2), (3,4), (4,3), (4, 1), (4,5), (0,5) ]
    assert reachable(V, E, 1, 5)
    assert not reachable(V, E, 1, 6)

# test_reachable()  ### NO LONGER GOOD TEST ROUTINE GIVEN CHANGE TO REACHABLE INTERFACE

def RP(A):
    """
    Ranked-pairs algorithm.
    Input A is m x m preference matrix.
    Output is ordered list of candidates. (Most favored first)
    Labels assumed to be from range(m)
    """
    m = len(A)
    V = range(m)
    E = sorted_pairs(A)
    CE = [ ]                      # committed edges
    Adj = { i:[] for i in V }     # adj list for committed edges
    for (i,j) in E:
        if not reachable(Adj, j, i):
            CE.append((i,j))
            Adj[i].append(j)
    beats = { i:0 for i in V }    # number that i beats
    for (i,j) in CE:
        beats[i] += 1
    L = [ (beats[i], i) for i in V ]
    L = sorted(L, reverse=True)
    return [ i for (c, i) in L ]

def test_RP():
    A = [ [ 0, 6, 9 ], \
          [ 7, 0, 11 ], \
          [ 13, 12, 0 ]]
    assert RP(A) == [2, 1, 0]

#test_RP()

##############################################################################
## end of ranked-pairs (RP) implementation
##############################################################################

##############################################################################
## generate profile of size n of ballots that is similar in terms of
## preferences represented by a pairwise preference matrix A
##############################################################################
def generate_tweaked_profile(A, n, printing_wanted=True):
    """
    Input: A is a pairwise preference matrix where A[i][j] is the number of voters
           that prefer candidate i to j.
           n is desired number of ballots to generate and return.
    Output: list S of n ballots that are "like" those in B,
            in the sense that matrix of prefs for S is close to
            (percentage-wise) those in B.
            (Some variations on prefs are deliberately added for variability.)
    """
    if printing_wanted:
        print "Preference matrix A of provided ballots (before tweaking):"
        for row in A:
            print row
    A = sn_matrix(A, n)    # make a noisy version of A
    generate_profile(A, n, printing_wanted)

def generate_profile(A, n, printing_wanted=True):
    m = len(A[0])
    if printing_wanted:
        print "Preference matrix A of provided ballots:"
        for row in A:
            print row

    S = []            # list of generated ballots
    d = dict()        # maps generated ballots to counts

    A2 = [[0 for j in range(m)] for i in range(m)]  # prefs for generated ballots

    needs = [ [ A[i][j] \
                for j in range(m) ] for i in range(m) ]

    target = copy.deepcopy(needs)

    if printing_wanted:
        print "target profile matrix for ballots to be generated:"
        for i, row in enumerate(needs):
            print "%2d: "%i,
            for item in row:
                print "%6d "%int(item),
            print

    while len(S) < n:
        # generate p as new ballot using RP
        p = RP(needs)
        S.append(p)

        # update counts in d, if m is not too large
        if m <= 12:
            pt = tuple(p)
            d[pt] = d.get(pt,0) + 1

        # now update prefs and needs
        for i in range(m):
            a = p[i]
            for j in range(i+1, m):
                b = p[j]
                A2[a][b] += 1
                needs[a][b] -= 1

    if printing_wanted:
        print "actual preference matrix for ballots generated:"
        for i, row in enumerate(A2):
            print "%2d: "%i,
            for c in row:
                print "%6d "%c,
            print
    if printing_wanted:
        print "differences in matrix entries from desired matrix:"
    difference_matrix = []
    for x in xrange(len(A2)):
        a2_row = A2[x]
        target_row = target[x]
        difference_matrix.append([])
        if printing_wanted:
            print "%2d: " %x,
        for c1, c2 in zip(a2_row, target_row):
            difference_matrix[x].append(abs(c1-c2))
            if printing_wanted:
                print "%6d " %(c1-c2),
        if printing_wanted:
            print
    deviations = sum(map(sum, difference_matrix))
    if printing_wanted:
        print "sum of absolute values of deviations:"
        print deviations
    return deviations

    # if m>12:
    #     return
    #if printing_wanted:
       # print "ballots generated with multiplicities:"
        #for b in sorted(d.keys()):
        #    print b, d[b]
       # print

##############################################################################
## generate profile of size n of ballots that is similar in terms of
## preferences to a given sample B of ballots
##############################################################################

def sample(B, n, partial_ballots=True, printing_wanted=True):
    """
    Input: B is list of ballots (over candidates range(m)).
           n is desired number of ballots to generate and return.
           partial_ballots is True if partial ballots may be present on input
                 and if they are OK to output
    Output: list S of n ballots that are "like" those in B,
            in the sense that matrix of prefs for S is close to
            (percentage-wise) those in B.
            (Some variations on prefs are deliberately added for variability.)

    Notes: Procedure is randomized; likely to return different S each time.
           Preference matrix for B is used as template, but:
              scaled up so for each i,j:  A[i,j]+A[j,i] = n
              Given preferences A[i,j],A[j,i] only used a parameters for
                 a beta distribution to determine final A[i,j],A[j,i]
           Tideman's ranked-pairs method used repeatedly to construct a
           a ballot that best fits remaining marginals, until you have n ballots.
    """

    if printing_wanted:
        print "number of ballots desired = ", n
        print "Profile of ballots provided:"
        for ballot in B:
            print ballot

    A = prefs(B, partial_ballots)
    generate_tweaked_profile(A, n, printing_wanted)

def test_sample():
    sample(B1, 100)
    sample(B2, 100)
    sample(B3, 100)
    sample(B4, 100)

# test_sample()

def test_sample_2(m):
    print "test_sample_2: generating 10**d ballots"
    for d in range(1,6):
        print "d=",d,
        t0 = time.time()
        B = []
        for t in range(200):
            ballot = range(m)
            random.shuffle(ballot)
            B.append(ballot)
        sample(B, 10**d, printing_wanted=False)
        t1 = time.time()
        print "done in %d seconds."%(int(t1-t0))

test_sample_2(100)

##############################################################################
## end of profile-generating code
##############################################################################


text:
package org.springframework.cloud.gcp.data.spanner.core;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

import com.google.cloud.spanner.Key;
import com.google.cloud.spanner.KeySet;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.Mutation.Op;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.cloud.gcp.data.spanner.core.admin.SpannerSchemaUtils;
import org.springframework.cloud.gcp.data.spanner.core.convert.ConversionUtils;
import org.springframework.cloud.gcp.data.spanner.core.convert.SpannerEntityProcessor;
import org.springframework.cloud.gcp.data.spanner.core.mapping.Column;
import org.springframework.cloud.gcp.data.spanner.core.mapping.Embedded;
import org.springframework.cloud.gcp.data.spanner.core.mapping.Interleaved;
import org.springframework.cloud.gcp.data.spanner.core.mapping.PrimaryKey;
import org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerDataException;
import org.springframework.cloud.gcp.data.spanner.core.mapping.SpannerMappingContext;
import org.springframework.cloud.gcp.data.spanner.core.mapping.Table;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

/**
 * Tests for the Spanner mutation factory implementation.
 *
 * @author Chengyuan Zhao
 */
public class SpannerMutationFactoryImplTests {

	/**
	 * used to check for exception messages and types.
	 */
	@Rule
	public ExpectedException expectedEx = ExpectedException.none();

	private SpannerMappingContext mappingContext;

	private SpannerEntityProcessor objectMapper;

	private SpannerSchemaUtils spannerSchemaUtils;

	private SpannerMutationFactoryImpl spannerMutationFactory;

	@Before
	public void setUp() {
		this.mappingContext = new SpannerMappingContext();
		this.objectMapper = mock(SpannerEntityProcessor.class);
		this.spannerSchemaUtils = new SpannerSchemaUtils(this.mappingContext,
				this.objectMapper, true);
		this.spannerMutationFactory = new SpannerMutationFactoryImpl(this.objectMapper,
				this.mappingContext, this.spannerSchemaUtils);
	}

	private void executeWriteTest(Function<TestEntity, List<Mutation>> writeFunc,
			Op writeMethod) {
		TestEntity t = new TestEntity();
		List<Mutation> mutations = writeFunc.apply(t);
		t.id = "a";
		Mutation parentMutation = mutations.get(0);
		assertThat(mutations).hasSize(1);
		assertThat(parentMutation.getTable()).isEqualTo("custom_test_table");
		assertThat(parentMutation.getOperation()).isEqualTo(writeMethod);
		ChildEntity c1 = new ChildEntity();
		c1.keyComponents = new EmbeddedKeyComponents();
		c1.keyComponents.id = t.id;
		c1.keyComponents.id2 = "c2";
		ChildEntity c2 = new ChildEntity();
		c2.keyComponents = new EmbeddedKeyComponents();
		c2.keyComponents.id = t.id;
		c2.keyComponents.id2 = "c3";
		t.childEntities = Arrays.asList(c1, c2);
		mutations = writeFunc.apply(t);
		parentMutation = mutations.get(0);
		assertThat(mutations).hasSize(3);
		List<Mutation> childMutations = mutations.subList(1, mutations.size());
		assertThat(parentMutation.getTable()).isEqualTo("custom_test_table");
		assertThat(parentMutation.getOperation()).isEqualTo(writeMethod);
		for (Mutation childMutation : childMutations) {
			assertThat(childMutation.getTable()).isEqualTo("child_test_table");
			assertThat(childMutation.getOperation()).isEqualTo(writeMethod);
		}
	}

	@Test
	public void lazyWriteTest() {
		TestEntity t = new TestEntity();
		t.id = "a";
		ChildEntity c1 = new ChildEntity();
		c1.keyComponents = new EmbeddedKeyComponents();
		c1.keyComponents.id = t.id;
		c1.keyComponents.id2 = "c2";
		ChildEntity c2 = new ChildEntity();
		c2.keyComponents = new EmbeddedKeyComponents();
		c2.keyComponents.id = t.id;
		c2.keyComponents.id2 = "c3";

		// intentionally setting it as an untouched-proxy
		t.childEntities = ConversionUtils.wrapSimpleLazyProxy(() -> Arrays.asList(c1, c2), List.class);

		List<Mutation> mutations = this.spannerMutationFactory.upsert(t, null);
		Mutation parentMutation = mutations.get(0);

		// The size is 1 because the child is an un-evaluated proxy.
		assertThat(mutations).hasSize(1);
		assertThat(parentMutation.getTable()).isEqualTo("custom_test_table");
		assertThat(parentMutation.getOperation()).isEqualTo(Op.INSERT_OR_UPDATE);

		t.childEntities.size();

		// mutations should now be generated since the child proxy has been touched.
		mutations = this.spannerMutationFactory.upsert(t, null);
		parentMutation = mutations.get(0);
		assertThat(mutations).hasSize(3);
		List<Mutation> childMutations = mutations.subList(1, mutations.size());
		assertThat(parentMutation.getTable()).isEqualTo("custom_test_table");
		assertThat(parentMutation.getOperation()).isEqualTo(Op.INSERT_OR_UPDATE);
		for (Mutation childMutation : childMutations) {
			assertThat(childMutation.getTable()).isEqualTo("child_test_table");
			assertThat(childMutation.getOperation()).isEqualTo(Op.INSERT_OR_UPDATE);
		}
	}

	@Test
	public void insertTest() {
		executeWriteTest((t) -> this.spannerMutationFactory.insert(t), Op.INSERT);
	}

	@Test
	public void insertChildrenMismatchIdTest() {

		this.expectedEx.expect(SpannerDataException.class);
		this.expectedEx.expectMessage("A child entity's common primary key parts with its parent must have " +
				"the same values. Primary key component 1 does not match for entities: " +
				"class org.springframework.cloud.gcp.data.spanner.core.SpannerMutationFactoryImplTests$TestEntity " +
				"class org.springframework.cloud.gcp.data.spanner.core.SpannerMutationFactoryImplTests$ChildEntity");

		TestEntity t = new TestEntity();
		t.id = "a";
		ChildEntity c1 = new ChildEntity();
		c1.keyComponents = new EmbeddedKeyComponents();
		c1.keyComponents.id = "b";
		c1.keyComponents.id2 = "c1";
		t.childEntities = Collections.singletonList(c1);
		// throws exception because child entity's id column does not match that of its
		// parent.
		this.spannerMutationFactory.insert(t);
	}

	@Test
	public void updateTest() {
		executeWriteTest((t) -> this.spannerMutationFactory.update(t, null), Op.UPDATE);
	}

	@Test
	public void upsertTest() {
		executeWriteTest((t) -> this.spannerMutationFactory.upsert(t, null),
				Op.INSERT_OR_UPDATE);
	}

	@Test
	public void deleteEntitiesTest() {
		TestEntity t1 = new TestEntity();
		t1.id = "key1";
		TestEntity t2 = new TestEntity();
		t2.id = "key2";

		Mutation mutation = this.spannerMutationFactory.delete(TestEntity.class,
				Arrays.asList(t1, t2));
		assertThat(mutation.getTable()).isEqualTo("custom_test_table");
		assertThat(mutation.getOperation()).isEqualTo(Op.DELETE);
		List<String> keys = new ArrayList<>();
		mutation.getKeySet().getKeys().forEach((key) -> {
			keys.add((String) (key.getParts().iterator().next()));
		});
		assertThat(keys).containsExactlyInAnyOrder(t1.id, t2.id);
	}

	@Test
	public void deleteEntityTest() {
		TestEntity t1 = new TestEntity();
		t1.id = "key1";

		Mutation mutation = this.spannerMutationFactory.delete(t1);
		assertThat(mutation.getTable()).isEqualTo("custom_test_table");
		assertThat(mutation.getOperation()).isEqualTo(Op.DELETE);
		List<String> keys = new ArrayList<>();
		mutation.getKeySet().getKeys().forEach((key) -> {
			keys.add((String) (key.getParts().iterator().next()));
		});
		assertThat(keys).containsExactlyInAnyOrder(t1.id);
	}

	@Test
	public void deleteKeysTest() {
		KeySet keySet = KeySet.newBuilder().addKey(Key.of("key1")).addKey(Key.of("key2"))
				.build();
		Mutation mutation = this.spannerMutationFactory.delete(TestEntity.class, keySet);
		assertThat(mutation.getTable()).isEqualTo("custom_test_table");
		assertThat(mutation.getOperation()).isEqualTo(Op.DELETE);
		List<String> keys = new ArrayList<>();
		mutation.getKeySet().getKeys().forEach((key) -> {
			keys.add((String) (key.getParts().iterator().next()));
		});
		assertThat(keys).containsExactlyInAnyOrder("key1", "key2");
	}

	@Test
	public void deleteKeyTest() {
		Key key = Key.of("key1");
		Mutation mutation = this.spannerMutationFactory.delete(TestEntity.class, key);
		assertThat(mutation.getTable()).isEqualTo("custom_test_table");
		assertThat(mutation.getOperation()).isEqualTo(Op.DELETE);
		List<String> keys = new ArrayList<>();
		mutation.getKeySet().getKeys().forEach((k) -> {
			keys.add((String) (k.getParts().iterator().next()));
		});
		assertThat(keys).containsExactlyInAnyOrder("key1");
	}

	@Table(name = "custom_test_table")
	private static class TestEntity {
		@PrimaryKey(keyOrder = 1)
		String id;

		@Column(name = "custom_col")
		String something;

		@Column(name = "")
		String other;

		@Interleaved
		List<ChildEntity> childEntities;
	}

	@Table(name = "child_test_table")
	private static class ChildEntity {
		@Embedded
		@PrimaryKey(keyOrder = 1)
		EmbeddedKeyComponents keyComponents;
	}

	private static class EmbeddedKeyComponents {
		@PrimaryKey(keyOrder = 1)
		String id;

		@PrimaryKey(keyOrder = 2)
		String id2;
	}
}


text:
```
  npm install
  cp config.js.example config.js
  <setup config.js>

  node .
```


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

<title>Uses of Package net.alexanderdev.lightdrive.input</title>
<meta name="date" content="2016-05-25">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
net.alexanderdev.lightdrive.input

Packages that use net.alexanderdev.lightdrive.input

Package
Description

net.alexanderdev.lightdrive.input

net.alexanderdev.lightdrive.state

Classes in net.alexanderdev.lightdrive.input used by net.alexanderdev.lightdrive.input

Class and Description

Controllable

An interface which combines all three input listeners into one.

Classes in net.alexanderdev.lightdrive.input used by net.alexanderdev.lightdrive.state

Class and Description

Controllable

An interface which combines all three input listeners into one.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package org.jkiss.dbeaver.runtime.jobs;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSInstance;
import org.jkiss.dbeaver.runtime.DBWorkbench;

import java.util.List;

/**
 * PingJob
 */
public class PingJob extends AbstractJob
{
    private static final Log log = Log.getLog(PingJob.class);

    private final DBPDataSource dataSource;

    public PingJob(DBPDataSource dataSource)
    {
        super("Connection ping");
        setUser(false);
        setSystem(true);
        this.dataSource = dataSource;
    }

    @Override
    protected IStatus run(DBRProgressMonitor monitor)
    {
        //log.debug("Ping connection " + dataSource.getContainer().getId());
        for (final DBSInstance instance : dataSource.getAvailableInstances()) {
            for (final DBCExecutionContext context : instance.getAllContexts()) {
                try {
                    context.checkContextAlive(monitor);
                } catch (Exception e) {
                    log.debug("Context [" + dataSource.getName() + "::" + context.getContextName() + "] check failed: " + e.getMessage());
                    if (e instanceof DBException) {
                        final List<InvalidateJob.ContextInvalidateResult> results = InvalidateJob.invalidateDataSource(monitor, dataSource, false,
                            () -> DBWorkbench.getPlatformUI().openConnectionEditor(dataSource.getContainer()));
                        log.debug("Connection invalidated: " + results);
                    }
                }
            }
        }
        return Status.OK_STATUS;
    }

}


text:
using SimpleXamarinFormsMVVM.Core.View.Models;
using SimpleXamarinFormsMVVM.Core.View.Services;
using Xamarin.Forms;

namespace SimpleXamarinFormsMVVM
{
    public class TestMasterViewModel : MasterViewModel
    {
        public TestMasterViewModel(INavigationService navigationService)
            : base(navigationService)
        {
            SelectPageCommand = new Command<string>(i =>
            {
                navigationService.ChangeDetailView<DetailViewModel>(d => d.Order = int.Parse(i));
            });
        }

        public Command<string> SelectPageCommand { get; }
    }
}


text:
<testcase name="ConflictResolution" description="" outpath="out">
	<variation name="_77572">
		<description>XSLT08004 : priority - null case</description>
		<data>
			<xml>books.xml</xml>
			<xsl>XSLT08004a.xsl</xsl>
		</data>
		<result expected="invalid">
		</result>
	</variation>
	<variation name="_77619">
		<description>XSLT08005 : priority - 0 case (span color green if 0 > -.5, red for failure)</description>
		<data>
			<xml>books.xml</xml>
			<xsl>XSLT08005.xsl</xsl>
		</data>
		<result expected="valid">77619.txt</result>
	</variation>
	<variation name="_77621">
		<description>XSLT08006 : priority
Author country: positive green, and negative red (.5)
Author last name: 1.222222222222222 green, 1.222222222222221 red
</description>
		<data>
			<xml>books.xml</xml>
			<xsl>XSLT08006a.xsl</xsl>
		</data>
		<result expected="valid">77621.txt</result>
	</variation>
	<variation name="_77622">
		<description>XSLT08007 : priority upper boundary cases, concatenates
Expected results: red on author country, red on author last name</description>
		<data>
			<xml>books.xml</xml>
			<xsl>XSLT08007.xsl</xsl>
		</data>
		<result expected="valid">77622.txt</result>
	</variation>
	<variation name="_77623">
		<description>XSLT08008 : priority contains text</description>
		<data>
			<xml>books.xml</xml>
			<xsl>XSLT08008.xsl</xsl>
		</data>
		<result expected="invalid">
		</result>
	</variation>
	<variation name="_77626">
		<description>XSLT08014 : priority contains text - hex notation</description>
		<data>
			<xml>books.xml</xml>
			<xsl>XSLT08014.xsl</xsl>
		</data>
		<result expected="invalid">
		</result>
	</variation>
	<variation name="_77746">
		<description>XSLT08112: default priority in attribute value template with x|y (bug 86835)</description>
		<data>
			<xml>xslt08112.XML</xml>
			<xsl>xslt08112.xsl</xsl>
		</data>
		<result expected="valid">77746.txt</result>
	</variation>
	<variation name="_77781">
		<description>XSLT09103: Conflict Resultion - priority .0 versus -.0, expect document order to break the tie</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09103.xsl</xsl>
		</data>
		<result expected="valid">77781.txt</result>
	</variation>
	<variation name="_77782">
		<description>XSLT09102: Conflict Resultion - priority 1 versus 1 expect document order to break the tie</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09102.xsl</xsl>
		</data>
		<result expected="valid">77782.txt</result>
	</variation>
	<variation name="_77783">
		<description>XSLT09104: Conflict Resultion - default priority n versus default priority n expect document order to break the tie</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09104.xsl</xsl>
		</data>
		<result expected="valid">77783.txt</result>
	</variation>
	<variation name="_77784">
		<description>Copy of 77783: XSLT09104: Conflict Resultion - default priority n versus default priority n expect document order to break the tie</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09105.xsl</xsl>
		</data>
		<result expected="valid">77784_output.txt</result>
	</variation>
	<variation name="_77802">
		<description>XSLT09000 : priority
Author country: positive green, and negative red (.5)
Author last name: 0.499999999999999 (15 digits) red vs .5 green
</description>
		<data>
			<xml>books.xml</xml>
			<xsl>XSLT09000.xsl</xsl>
		</data>
		<result expected="valid">77802.txt</result>
	</variation>
	<variation name="_77833">
		<description>XSLT08103 : pattern has the form processing-instruction(literal)</description>
		<data>
			<xml>plants01.xml</xml>
			<xsl>xslt08103.xsl</xsl>
		</data>
		<result expected="valid">77833.txt</result>
	</variation>
	<variation name="_77847">
		<description>XSLT08104: Conflict Resultion - Pattern has the form NCName:* - should have default priority of -0.25</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08104.xsl</xsl>
		</data>
		<result expected="valid">77847_output.txt</result>
	</variation>
	<variation name="_77870">
		<description>XSLT08101: Conflict Resultion - Pattern has the form Qname - should have default priority of 0</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08101.xsl</xsl>
		</data>
		<result expected="valid">77870_output.txt</result>
	</variation>
	<variation name="_77871">
		<description>XSLT08102: Conflict Resultion - Pattern has the form @Qname - should have default priority of 0</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08102.xsl</xsl>
		</data>
		<result expected="valid">77871.txt</result>
	</variation>
	<variation name="_77872">
		<description>XSLT08106: Conflict Resultion - specific match title[@style='foo'] - should have default priority of .5</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08106.xsl</xsl>
		</data>
		<result expected="valid">77872_output.txt</result>
	</variation>
	<variation name="_77874">
		<description>XSLT08100: Conflict Resultion - * (and @*) with no namespace where stylesheet has a default namespace - default priority of - .5</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08100.xsl</xsl>
		</data>
		<result expected="valid">77874_output.txt</result>
	</variation>
	<variation name="_77875">
		<description>XSLT08105: Conflict Resultion - pattern consists of just a NodeTest, just a processing-instruction, just a comment, just node()</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08105.xsl</xsl>
		</data>
		<result expected="valid">77875_output.txt</result>
	</variation>
	<variation name="_77876">
		<description>XSLT08107: Conflict Resultion -muliple alternatives separated by | : two equivalent priorities - a|b</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08107.xsl</xsl>
		</data>
		<result expected="valid">77876_output.txt</result>
	</variation>
	<variation name="_77877">
		<description>XSLT08110: Conflict Resultion -multiple alternates in a group : (a|a/b) a= 0, a/b = .5</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08110.xsl</xsl>
		</data>
		<result expected="valid">77877_output.txt</result>
	</variation>
	<variation name="_77878">
		<description>XSLT08109: Conflict Resultion -muliple alternatives : split priorities - a|a/b  specify a .25  c|c/d specify .6</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08109.xsl</xsl>
		</data>
		<result expected="valid">77878_output.txt</result>
	</variation>
	<variation name="_77879">
		<description>XSLT08113: Conflict Resultion -multiple alternates in a group : (a|a/b) both take highest priority</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08109.xsl</xsl>
		</data>
		<result expected="valid">77879_output.txt</result>
	</variation>
	<variation name="_77881">
		<description>XSLT08114: (Copy of 77878)  Conflict Resultion -muliple alternatives : split priorities - a|a/b  specify a .25  c|c/d specify .6
 with 17 template rules</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08114.xsl</xsl>
		</data>
		<result expected="valid">77881_output.txt</result>
	</variation>
	<variation name="_77882">
		<description>XSLT08108: muliple alternatives : a|b|a/b|c/d|c  -three splits > 17 template rules</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08108.xsl</xsl>
		</data>
		<result expected="valid">77882_output.txt</result>
	</variation>
	<variation name="_77883">
		<description>XSLT08111: mutliple alternatives including group:  a|c/d|(a/b|b) > 17 template rules</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt08111.xsl</xsl>
		</data>
		<result expected="invalid"></result>
	</variation>
	<variation name="_77884">
		<description>XSLT09001: default priority -0.5 versus specified priority -1</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09001.xsl</xsl>
		</data>
		<result expected="valid">77884_output.txt</result>
	</variation>
	<variation name="_77885">
		<description>XSLT09002:  Conflict Resolution: the same template rule over 16 times, mixed in with other templates</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09002.xsl</xsl>
		</data>
		<result expected="valid">77885.txt</result>
	</variation>
	<variation name="_77886">
		<description>XSLT09005:  Conflict Resolution: over 16 template rules all named, equivalent matches use document order</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09005.xsl</xsl>
		</data>
		<result expected="valid">77886_output.txt</result>
	</variation>
	<variation name="_77889">
		<description>XSLT09007:  Conflict Resolution: include (xsl into default ns), literal results(with my: ns and exclude-result-prefixes) , inter-mixed priorities</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09007.xsl</xsl>
		</data>
		<result expected="valid">77889_output.txt</result>
	</variation>
	<variation name="_77891">
		<description>XSLT09008:  Conflict Resolution: include, literal results, inter-mixed priorities, equivalent matches use document order</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09008.xsl</xsl>
		</data>
		<result expected="valid">77891_output.txt</result>
	</variation>
	<variation name="_77893">
		<description>XSLT09005:  Conflict Resolution:over 16 template rules all wildcard, equivalent matches use document order</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09005a.xsl</xsl>
		</data>
		<result expected="valid">77893_output.txt</result>
	</variation>
	<variation name="_77897">
		<description>XSLT09010:  Conflict Resolution:include literal result element, inter-mixed priorities with groups and |</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09010.xsl</xsl>
		</data>
		<result expected="valid">77897_output.txt</result>
	</variation>
	<variation name="_77898">
		<description>XSLT09011:  Conflict Resolution:include literal result element, inter-mixed priorities with groups and |,
 document order breaks tie.</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09011.xsl</xsl>
		</data>
		<result expected="valid">77898_output.txt</result>
	</variation>
	<variation name="_77902">
		<description>XSLT09009:  Conflict Resolution: specified priority in stylesheet versus higher default priority in included stylesheet</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09009.xsl</xsl>
		</data>
		<result expected="valid">77902_output.txt</result>
	</variation>
	<variation name="_77904">
		<description>XSLT09013: XSLT09014  Conflict Resolution: include, literal results, inter-mixed priorities...  groups and |  with Qnames</description>
		<data>
			<xml>books.xml</xml>
			<xsl>xslt09013.xsl</xsl>
		</data>
		<result expected="valid">77904_output.txt</result>
	</variation>
	<variation name="_84476">
		<description>Copy of 77871: XSLT08102: Conflict Resultion - Pattern has the form @Qname - should have default priority of 0</description>
		<data>
			<xml>84476.xml</xml>
			<xsl>84476.xsl</xsl>
		</data>
		<result expected="valid">84476.txt</result>
	</variation>
	<variation name="_84477">
		<description>Copy of 77878:  XSLT08109: Conflict Resultion -muliple alternatives : split priorities - a|a/b  specify a .25  c|c/d specify .6</description>
		<data>
			<xml>84477.xml</xml>
			<xsl>84477.xsl</xsl>
		</data>
		<result expected="valid">84477_output.txt</result>
	</variation>
	<variation name="_84478">
		<description>Copy of 77884: XSLT09001: default priority -0.5 versus specified priority -1</description>
		<data>
			<xml>84478.xml</xml>
			<xsl>84478.xsl</xsl>
		</data>
		<result expected="valid">84478_output.txt</result>
	</variation>
	<variation name="ConflictResBetweenStripSpaceAndPreserveSpace">
		<description>
		</description>
		<data>
			<xml>xslt_conflict_res_between_preservespace_and_strpspace.xml</xml>
			<xsl>xslt_conflict_res_between_preservespace_and_strpspace.xsl</xsl>
		</data>
		<result expected="valid">xslt_conflict_res_between_preservespace_and_strpspace.txt</result>
	</variation>
</testcase>


text:
<form name="editForm" role="form" novalidate ng-submit="vm.save()">

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"
                ng-click="vm.clear()">×</button>

Create or edit a Chapter

        <jhi-alert-error></jhi-alert-error>

            ID
            <input type="text" class="form-control" id="id" name="id"
                    ng-model="vm.chapter.id" readonly />

            Title
            <input type="text" class="form-control" name="title" id="field_title"
                    ng-model="vm.chapter.title"
                    />

            Content

            <textarea class="form-control" name="content" id="field_content" ng-model="vm.chapter.content">

            </textarea>

            Reference
            <select class="form-control" id="field_reference" name="reference" ng-model="vm.chapter.referenceId" ng-options="reference.id as reference.id for reference in vm.references"            >
                <option value=""></option>
            </select>

        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="vm.clear()">
             Cancel
        </button>
        <button type="submit" ng-disabled="editForm.$invalid || vm.isSaving" class="btn btn-primary">
             Save
        </button>

</form>