text:
package org.ovirt.engine.core.common.businessentities.gluster;

import java.util.Objects;

import org.ovirt.engine.core.common.businessentities.IVdcQueryable;
import org.ovirt.engine.core.common.utils.ToStringBuilder;
import org.ovirt.engine.core.compat.Guid;

public class GlusterVolumeSnapshotConfig implements IVdcQueryable {
    private static final long serialVersionUID = 3432543544365L;
    private Guid clusterId;
    private Guid volumeId;
    private String paramName;
    private String paramValue;

    public GlusterVolumeSnapshotConfig() {
    }

    public GlusterVolumeSnapshotConfig(Guid clusterId, Guid volumeId, String paramName, String paramValue) {
        this.clusterId = clusterId;
        this.volumeId = volumeId;
        this.paramName = paramName;
        this.paramValue = paramValue;
    }

    public Guid getClusterId() {
        return this.clusterId;
    }

    public void setClusterId(Guid cid) {
        this.clusterId = cid;
    }

    public Guid getVolumeId() {
        return volumeId;
    }

    @Override
    public Object getQueryableId() {
        return getVolumeId();
    }

    public void setVolumeId(Guid volumeId) {
        this.volumeId = volumeId;
    }

    public String getParamName() {
        return paramName;
    }

    public void setParamName(String paramName) {
        this.paramName = paramName;
    }

    public String getParamValue() {
        return paramValue;
    }

    public void setParamValue(String paramValue) {
        this.paramValue = paramValue;
    }

    @Override
    public int hashCode() {
        return Objects.hash(
                clusterId,
                volumeId,
                paramName,
                paramValue
        );
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof GlusterVolumeSnapshotConfig)) {
            return false;
        }

        GlusterVolumeSnapshotConfig other = (GlusterVolumeSnapshotConfig) obj;
        return Objects.equals(clusterId, other.clusterId)
                && Objects.equals(volumeId, other.volumeId)
                && Objects.equals(paramName, other.paramName)
                && Objects.equals(paramValue, other.paramValue);
    }

    @Override
    public String toString() {
        return ToStringBuilder.forInstance(this)
                .append("clusterId", getClusterId())
                .append("volumeId", getVolumeId())
                .append("paramName", getParamName())
                .append("paramValue", getParamValue())
                .build();
    }
}


text:
from .texts.protestant import ProtestantCanon

# create an instance of the Protestant Canon to use as the default
pcanon=ProtestantCanon()

book_re = pcanon.book_re
scripture_re = pcanon.scripture_re

redpajama_set_name: RedPajamaGithub


text:
@interface PAPPhotoTimelineViewController : PFQueryTableViewController <PAPPhotoHeaderViewDelegate>

- (PAPPhotoHeaderView *)dequeueReusableSectionHeaderView;

@end


text:
import { customAttribute, inject, bindable } from 'aurelia-framework';

@inject(Element)
@customAttribute('scrollbar')
export class Scrollbar {

  value: 'vertical' | 'horizontal' | 'y' | 'x';

  constructor(private element: Element) {
    element.classList.add('sb');
    this.onWheel = this.onWheel.bind(this);
  }

  bind() {
    const element = this.element;
    const direction = this.value;
    const classList = element.classList;
    if (direction === 'horizontal' || direction === 'x') {
      classList.add('sb-x');
      classList.add('text-nowrap');
      element.addEventListener('wheel', this.onWheel, true);
    } else {
      classList.add('sb-y');
    }
  }

  unbind() {
    this.element.removeEventListener('wheel', this.onWheel, true);
  }

  onWheel(e: WheelEvent) {
    if (!e.shiftKey && e.deltaY !== 0) {
      (e.currentTarget as HTMLElement).scrollLeft += e.deltaY;
      e.stopImmediatePropagation();
      e.preventDefault();
    }
  }
}


text:
// This software is part of the Autofac IoC container
// Copyright © 2019 Autofac Contributors
// https://autofac.org
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

using System;
using Microsoft.Extensions.DependencyInjection;

namespace Autofac.Extensions.DependencyInjection
{
    /// <summary>
    /// A factory for creating a <see cref="IServiceProvider"/> that wraps a child <see cref="ILifetimeScope"/> created from an existing parent <see cref="ILifetimeScope"/>.
    /// </summary>
    public class AutofacChildLifetimeScopeServiceProviderFactory : IServiceProviderFactory<AutofacChildLifetimeScopeConfigurationAdapter>
    {
        private readonly Action<ContainerBuilder> _containerConfigurationAction;
        private readonly ILifetimeScope _rootLifetimeScope;
        private static readonly Action<ContainerBuilder> FallbackConfigurationAction = builder => { };

        /// <summary>
        /// Initializes a new instance of the <see cref="AutofacChildLifetimeScopeServiceProviderFactory"/> class.
        /// </summary>
        /// <param name="rootLifetimeScopeAccessor">A function to retrieve the root <see cref="ILifetimeScope"/> instance.</param>
        /// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/> that adds component registrations to the container.</param>
        public AutofacChildLifetimeScopeServiceProviderFactory(Func<ILifetimeScope> rootLifetimeScopeAccessor, Action<ContainerBuilder> configurationAction = null)
        {
            if (rootLifetimeScopeAccessor == null) throw new ArgumentNullException(nameof(rootLifetimeScopeAccessor));

            _rootLifetimeScope = rootLifetimeScopeAccessor();
            _containerConfigurationAction = configurationAction ?? FallbackConfigurationAction;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AutofacChildLifetimeScopeServiceProviderFactory"/> class.
        /// </summary>
        /// <param name="rootLifetimeScope">The root <see cref="ILifetimeScope"/> instance.</param>
        /// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/> that adds component registrations to the container.</param>
        public AutofacChildLifetimeScopeServiceProviderFactory(ILifetimeScope rootLifetimeScope, Action<ContainerBuilder> configurationAction = null)
        {
            _rootLifetimeScope = rootLifetimeScope ?? throw new ArgumentNullException(nameof(rootLifetimeScope));
            _containerConfigurationAction = configurationAction ?? FallbackConfigurationAction;
        }

        /// <summary>
        /// Creates a container builder from an <see cref="IServiceCollection" />.
        /// </summary>
        /// <param name="services">The collection of services.</param>
        /// <returns>A container builder that can be used to create an <see cref="IServiceProvider" />.</returns>
        public AutofacChildLifetimeScopeConfigurationAdapter CreateBuilder(IServiceCollection services)
        {
            var actions = new AutofacChildLifetimeScopeConfigurationAdapter();

            actions.Add(builder => builder.Populate(services));
            actions.Add(builder => _containerConfigurationAction(builder));

            return actions;
        }

        /// <summary>
        /// Creates an <see cref="IServiceProvider" /> from the container builder.
        /// </summary>
        /// <param name="configurationAdapter">The adapter holding configuration applied to <see cref="ContainerBuilder"/> creating the <see cref="IServiceProvider"/>.</param>
        /// <returns>An <see cref="IServiceProvider" />.</returns>
        public IServiceProvider CreateServiceProvider(AutofacChildLifetimeScopeConfigurationAdapter configurationAdapter)
        {
            if (configurationAdapter == null) throw new ArgumentNullException(nameof(configurationAdapter));

            var scope = _rootLifetimeScope.BeginLifetimeScope(scopeBuilder =>
            {
                foreach (var action in configurationAdapter.ConfigurationActions)
                {
                    action(scopeBuilder);
                }
            });

            return new AutofacServiceProvider(scope);
        }
    }
}


text:
package io.muoncore.transport.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.Environment;
import reactor.core.Dispatcher;
import reactor.core.dispatch.wait.AgileWaitingStrategy;
import reactor.core.dispatch.wait.WaitingMood;
import reactor.core.support.Assert;
import reactor.core.support.NamedDaemonThreadFactory;
import reactor.core.support.Recyclable;
import reactor.fn.Consumer;
import reactor.jarjar.com.lmax.disruptor.*;
import reactor.jarjar.com.lmax.disruptor.dsl.Disruptor;
import reactor.jarjar.com.lmax.disruptor.dsl.ProducerType;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Implementation of a {@link reactor.core.Dispatcher} that uses a
 * {@link RingBuffer} to queue tasks to execute.
 *
 * @author Jon Brisbin
 * @author Stephane Maldini
 */
public final class RingBufferLocalDispatcher implements Dispatcher, WaitingMood {

	private final Logger log = LoggerFactory.getLogger(getClass());
	private final ExecutorService executor;
	private final Disruptor<RingBufferTask> disruptor;
	private final RingBuffer<RingBufferTask> ringBuffer;
	private final WaitingMood waitingMood;
	protected final List<Task> tailRecursionPile = new ArrayList<Task>();
	protected final int backlog;

	protected int tailRecurseSeq = -1;
	protected int tailRecursionPileSize = 0;

	/**
	 * Creates a new {@code RingBufferDispatcher} with the given {@code name}.
	 * It will use a RingBuffer with 1024 slots, configured with a producer type
	 * of {@link ProducerType#MULTI MULTI} and a {@link BlockingWaitStrategy
	 * blocking wait strategy}.
	 *
	 * @param name
	 *            The name of the dispatcher.
	 */
	public RingBufferLocalDispatcher(String name) {
		this(name, 32768, null, ProducerType.MULTI, new AgileWaitingStrategy());
		// this(name, DEFAULT_BUFFER_SIZE);
	}

	/**
	 * Creates a new {@code RingBufferDispatcher} with the given {@code name}
	 * {@link ProducerType#MULTI MULTI} and a {@link BlockingWaitStrategy
	 * blocking wait strategy}.
	 *
	 * @param name
	 *            The name of the dispatcher
	 * @param bufferSize
	 *            The size to configure the ring buffer with
	 */
	public RingBufferLocalDispatcher(String name, int bufferSize) {
		this(name, bufferSize, null, ProducerType.MULTI, new AgileWaitingStrategy());
	}

	/**
	 * Creates a new {@literal RingBufferDispatcher} with the given {@code name}
	 * . It will use a {@link RingBuffer} with {@code bufferSize} slots,
	 * configured with a producer type of {@link ProducerType#MULTI MULTI} and a
	 * {@link BlockingWaitStrategy blocking wait. A given @param
	 * uncaughtExceptionHandler} will catch anything not handled e.g. by the
	 * owning {@code reactor.bus.EventBus} or {@code reactor.rx.Stream}.
	 *
	 * @param name
	 *            The name of the dispatcher
	 * @param bufferSize
	 *            The size to configure the ring buffer with
	 * @param uncaughtExceptionHandler
	 *            The last resort exception handler
	 */
	public RingBufferLocalDispatcher(String name, int bufferSize, final Consumer<Throwable> uncaughtExceptionHandler) {
		this(name, bufferSize, uncaughtExceptionHandler, ProducerType.MULTI, new BlockingWaitStrategy());

	}

	/**
	 * Creates a new {@literal RingBufferDispatcher} with the given {@code name}
	 * . It will use a {@link RingBuffer} with {@code bufferSize} slots,
	 * configured with the given {@code producerType},
	 * exceptions.
	 *
	 * @param name
	 *            The name of the dispatcher
	 * @param bufferSize
	 *            The size to configure the ring buffer with
	 * @param producerType
	 *            The producer type to configure the ring buffer with
	 * @param waitStrategy
	 *            The wait strategy to configure the ring buffer with
	 * @param uncaughtExceptionHandler
	 *            The last resort exception handler
	 */
	@SuppressWarnings({ "unchecked" })
	public RingBufferLocalDispatcher(String name, int bufferSize, final Consumer<Throwable> uncaughtExceptionHandler,
			ProducerType producerType, WaitStrategy waitStrategy) {
		this.backlog = bufferSize;
		expandTailRecursionPile(backlog);

		if (WaitingMood.class.isAssignableFrom(waitStrategy.getClass())) {
			this.waitingMood = (WaitingMood) waitStrategy;
		} else {
			this.waitingMood = null;
		}

		this.executor = Executors.newSingleThreadExecutor(new NamedDaemonThreadFactory(name, getContext()));
		this.disruptor = new Disruptor<RingBufferTask>(new EventFactory<RingBufferTask>() {
			@Override
			public RingBufferTask newInstance() {
				return new RingBufferTask();
			}
		}, bufferSize, executor, producerType, waitStrategy);

		this.disruptor.handleExceptionsWith(new ExceptionHandler<Object>() {
			@Override
			public void handleEventException(Throwable ex, long sequence, Object event) {
				handleOnStartException(ex);
			}

			@Override
			public void handleOnStartException(Throwable ex) {
				if (null != uncaughtExceptionHandler) {
					uncaughtExceptionHandler.accept(ex);
				} else {
					log.error(ex.getMessage(), ex);
				}
			}

			@Override
			public void handleOnShutdownException(Throwable ex) {
				handleOnStartException(ex);
			}
		});
		this.disruptor.handleEventsWith(new EventHandler<RingBufferTask>() {
			@Override
			public void onEvent(RingBufferTask task, long sequence, boolean endOfBatch) throws Exception {
				task.run();
			}
		});

		this.ringBuffer = disruptor.start();
	}

	public boolean awaitAndShutdown(long timeout, TimeUnit timeUnit) {
		boolean alive = alive();
		shutdown();
		try {
			executor.awaitTermination(timeout, timeUnit);
			if (alive) {
				disruptor.shutdown();
			}
		} catch (InterruptedException e) {
			return false;
		}
		return true;
	}

	public void shutdown() {
		executor.shutdown();
		disruptor.shutdown();
		alive.compareAndSet(true, false);
	}

	public void forceShutdown() {
		executor.shutdownNow();
		disruptor.halt();
		alive.compareAndSet(true, false);
	}

	public long remainingSlots() {
		return ringBuffer.remainingCapacity();
	}

	@Override
	public void nervous() {
		if (waitingMood != null) {
			execute(new Runnable() {
				@Override
				public void run() {
					waitingMood.nervous();
				}
			});
		}
	}

	@Override
	public void calm() {
		if (waitingMood != null) {
			execute(new Runnable() {
				@Override
				public void run() {
					waitingMood.calm();
				}
			});

		}
	}

	protected Task tryAllocateTask() throws InsufficientCapacityException {
		try {
			long seqId = ringBuffer.tryNext();
			return ringBuffer.get(seqId).setSequenceId(seqId);
		} catch (reactor.jarjar.com.lmax.disruptor.InsufficientCapacityException e) {
			throw InsufficientCapacityException.INSTANCE;
		}
	}

	protected Task allocateTask() {
		long seqId = ringBuffer.next();
		return ringBuffer.get(seqId).setSequenceId(seqId);
	}

	protected void execute(Task task) {
		ringBuffer.publish(((RingBufferTask) task).getSequenceId());
	}

	private class RingBufferTask extends SingleThreadTask {
		private long sequenceId;

		public long getSequenceId() {
			return sequenceId;
		}

		public RingBufferTask setSequenceId(long sequenceId) {
			this.sequenceId = sequenceId;
			return this;
		}
	}

	public boolean supportsOrdering() {
		return true;
	}

	public long backlogSize() {
		return backlog;
	}

	public int getTailRecursionPileSize() {
		return tailRecursionPileSize;
	}

	protected void expandTailRecursionPile(int amount) {
		int toAdd = amount * 2;
		for (int i = 0; i < toAdd; i++) {
			tailRecursionPile.add(new SingleThreadTask());
		}
		this.tailRecursionPileSize += toAdd;
	}

	protected Task allocateRecursiveTask() {
		int next = ++tailRecurseSeq;
		if (next == tailRecursionPileSize) {
			expandTailRecursionPile(backlog);
		}
		Task elem = tailRecursionPile.get(next);
		return elem;
	}

	protected class SingleThreadTask extends Task {

		@Override
		public void run() {
			route(this);

			// Process any recursive tasks
			if (tailRecurseSeq < 0) {
				return;
			}
			int next = -1;
			while (next < tailRecurseSeq) {
				route(tailRecursionPile.get(++next));
			}

			// clean up extra tasks
			next = tailRecurseSeq;
			int max = backlog * 2;
			while (next >= max) {
				tailRecursionPile.remove(next--);
			}
			tailRecursionPileSize = max;
			tailRecurseSeq = -1;
		}
	}

	protected static final int DEFAULT_BUFFER_SIZE = 1024;

	private final AtomicBoolean alive = new AtomicBoolean(true);
	public final ClassLoader context = new ClassLoader(Thread.currentThread().getContextClassLoader()) {
	};

	public boolean alive() {
		return alive.get();
	}

	public boolean awaitAndShutdown() {
		return awaitAndShutdown(Integer.MAX_VALUE, TimeUnit.SECONDS);
	}

	/**
	 * Dispatchers can be traced through a {@code contextClassLoader} to let
	 * producers adapting their dispatching strategy
	 *
	 * @return boolean true if the programs is already run by this dispatcher
	 */
	public boolean inContext() {
		// FIX: Commenting this should fix the errors from muon-clojure
		// return context == Thread.currentThread().getContextClassLoader();
		return false;
	}

	protected final ClassLoader getContext() {
		return context;
	}

	public final <E> void tryDispatch(E event, Consumer<E> eventConsumer, Consumer<Throwable> errorConsumer) {
		Assert.isTrue(alive(), "This Dispatcher has been shut down.");
		boolean isInContext = inContext();
		Task task;
		if (isInContext) {
			task = allocateRecursiveTask();
		} else {
			try {
				task = tryAllocateTask();
			} catch (InsufficientCapacityException e) {
				throw new IllegalStateException("Error in task allocation");
			}
		}

		task.setData(event).setErrorConsumer(errorConsumer).setEventConsumer(eventConsumer);

		if (!isInContext) {
			execute(task);
		}
	}

	public final <E> void dispatch(E event, Consumer<E> eventConsumer, Consumer<Throwable> errorConsumer) {

		Assert.isTrue(alive(), "This Dispatcher has been shut down.");
		Assert.isTrue(eventConsumer != null, "The signal consumer has not been passed.");
		boolean isInContext = inContext();
		Task task;
		if (isInContext) {
			task = allocateRecursiveTask();
		} else {
			task = allocateTask();
		}

		task.setData(event).setErrorConsumer(errorConsumer).setEventConsumer(eventConsumer);

		if (!isInContext) {
			execute(task);
		}
	}

	public void execute(final Runnable command) {
		dispatch(null, new Consumer<Object>() {
			@Override
			public void accept(Object ev) {
				command.run();
			}
		}, null);
	}

	@SuppressWarnings("unchecked")
	protected static void route(Task task) {
		try {
			if (task.eventConsumer == null)
				return;

			task.eventConsumer.accept(task.data);

		} catch (Exception e) {
			if (task.errorConsumer != null) {

				task.errorConsumer.accept(e);

			} else if (Environment.alive()) {

				Environment.get().routeError(e);

			}
		} finally {
			task.recycle();
		}
	}

	public String toString() {
		return getClass().getSimpleName().replaceAll("Dispatcher", "");
	}

	public abstract class Task implements Runnable, Recyclable {
		protected volatile Object data;
		@SuppressWarnings("rawtypes")
		protected volatile Consumer eventConsumer;
		protected volatile Consumer<Throwable> errorConsumer;

		public Task setData(Object data) {
			this.data = data;
			return this;
		}

		public Task setEventConsumer(Consumer<?> eventConsumer) {
			this.eventConsumer = eventConsumer;
			return this;
		}

		public Task setErrorConsumer(Consumer<Throwable> errorConsumer) {
			this.errorConsumer = errorConsumer;
			return this;
		}

		@Override
		public void recycle() {
			data = null;
			errorConsumer = null;
			eventConsumer = null;
		}
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//
// This include file determines how VARSET_TP is implemented.
//
#ifndef _VARSET_INCLUDED_
#define _VARSET_INCLUDED_ 1

// A VARSET_TP is a set of (small) integers representing local variables.
// We implement varsets using the BitSet abstraction, which supports
// several different implementations.
//
// The set of tracked variables may change during a compilation, and variables may be
// re-sorted, so the tracked variable index of a variable is decidedly *not* stable.  The
// bitset abstraction supports labeling of bitsets with "epochs", and supports a
// debugging mode in which live bitsets must have the current epoch.  To use this feature,
// divide a compilation up into epochs, during which tracked variable indices are
// stable.

// Some implementations of BitSet may use a level of indirection.  Therefore, we
// must be careful about about assignment and initialization.  We often want to
// reason about VARSET_TP as immutable values, and just copying the contents would
// introduce sharing in the indirect case, which is usually not what's desired.  On
// the other hand, there are many cases in which the RHS value has just been
// created functionally, and the intialization/assignment is obviously its last
// use.  In these cases, allocating a new indirect representation for the lhs (if
// it does not already have one) would be unnecessary and wasteful.  Thus, for both
// initialization and assignment, we have normal versions, which do make copies to
// prevent sharing and definitely preserve value semantics, and "NOCOPY" versions,
// which do not.  Obviously, the latter should be used with care.

#include "bitset.h"
#include "compilerbitsettraits.h"

const unsigned UInt64Bits = sizeof(UINT64) * 8;

// This #define chooses the BitSet representation used for VARSET.
// The choices are defined in "bitset.h"; they currently include
// BSUInt64, BSShortLong, and BSUInt64Class.
#define VARSET_REP BSShortLong

#if VARSET_REP == BSUInt64

#include "bitsetasuint64.h"

typedef BitSetOps</*BitSetType*/ UINT64,
                  /*Brand*/ VARSET_REP,
                  /*Env*/ Compiler*,
                  /*BitSetTraits*/ TrackedVarBitSetTraits>
    VarSetOpsRaw;

typedef UINT64 VARSET_TP;

const unsigned lclMAX_TRACKED = UInt64Bits;

#define VARSET_REP_IS_CLASS 0

#elif VARSET_REP == BSShortLong

#include "bitsetasshortlong.h"

typedef BitSetOps</*BitSetType*/ BitSetShortLongRep,
                  /*Brand*/ VARSET_REP,
                  /*Env*/ Compiler*,
                  /*BitSetTraits*/ TrackedVarBitSetTraits>
    VarSetOpsRaw;

typedef BitSetShortLongRep VARSET_TP;

// Tested various sizes for max tracked locals. The largest value for which no throughput regression
// could be measured was 512. Going to 1024 showed the first throughput regressions.
// We anticipate the larger size will be needed to support better inlining.
// There were a number of failures when 512 was used for legacy, so we just retain the 128 value
// for legacy backend.

#if !defined(LEGACY_BACKEND)
const unsigned       lclMAX_TRACKED = 512;
#else
const unsigned lclMAX_TRACKED = 128;
#endif

#define VARSET_REP_IS_CLASS 0

#elif VARSET_REP == BSUInt64Class

#include "bitsetasuint64inclass.h"

typedef BitSetOps</*BitSetType*/ BitSetUint64<Compiler*, TrackedVarBitSetTraits>,
                  /*Brand*/ VARSET_REP,
                  /*Env*/ Compiler*,
                  /*BitSetTraits*/ TrackedVarBitSetTraits>
    VarSetOpsRaw;

typedef BitSetUint64<Compiler*, TrackedVarBitSetTraits> VARSET_TP;

const unsigned lclMAX_TRACKED = UInt64Bits;

#define VARSET_REP_IS_CLASS 1

#else

#error "Unrecognized BitSet implemention for VarSet."

#endif

// These types should be used as the types for VARSET_TP arguments and return values, respectively.
// Arg type represent the read only argument type, that can't be modified.
typedef VarSetOpsRaw::ValArgType VARSET_VALARG_TP;
typedef VarSetOpsRaw::RetValType VARSET_VALRET_TP;

#define VARSET_COUNTOPS 0
#if VARSET_COUNTOPS
typedef BitSetOpsWithCounter<VARSET_TP,
                             VARSET_REP,
                             Compiler*,
                             TrackedVarBitSetTraits,
                             VARSET_VALARG_TP,
                             VARSET_VALRET_TP,
                             VarSetOpsRaw::Iter>
    VarSetOps;
#else
typedef VarSetOpsRaw VarSetOps;
#endif

#define ALLVARSET_REP BSUInt64

#if ALLVARSET_REP == BSUInt64

#include "bitsetasuint64.h"

typedef BitSetOps</*BitSetType*/ UINT64,
                  /*Brand*/ ALLVARSET_REP,
                  /*Env*/ Compiler*,
                  /*BitSetTraits*/ AllVarBitSetTraits>
    AllVarSetOps;

typedef UINT64 ALLVARSET_TP;

const unsigned lclMAX_ALLSET_TRACKED = UInt64Bits;

#define ALLVARSET_REP_IS_CLASS 0

#elif ALLVARSET_REP == BSShortLong

#include "bitsetasshortlong.h"

typedef BitSetOps</*BitSetType*/ BitSetShortLongRep,
                  /*Brand*/ ALLVARSET_REP,
                  /*Env*/ Compiler*,
                  /*BitSetTraits*/ AllVarBitSetTraits>
    AllVarSetOps;

typedef BitSetShortLongRep ALLVARSET_TP;

const unsigned lclMAX_ALLSET_TRACKED = lclMAX_TRACKED;

#define ALLVARSET_REP_IS_CLASS 0

#elif ALLVARSET_REP == BSUInt64Class

#include "bitsetasuint64inclass.h"

typedef BitSetOps</*BitSetType*/ BitSetUint64<Compiler*, AllVarBitSetTraits>,
                  /*Brand*/ ALLVARSET_REP,
                  /*Env*/ Compiler*,
                  /*BitSetTraits*/ AllVarBitSetTraits>
    AllVarSetOps;

typedef BitSetUint64<Compiler*, AllVarBitSetTraits> ALLVARSET_TP;

const unsigned lclMAX_ALLSET_TRACKED = UInt64Bits;

#define ALLVARSET_REP_IS_CLASS 1

#else
#error "Unrecognized BitSet implemention for AllVarSet."
#endif

// These types should be used as the types for ALLVARSET_TP arguments and return values, respectively.
typedef AllVarSetOps::ValArgType ALLVARSET_VALARG_TP;
typedef AllVarSetOps::RetValType ALLVARSET_VALRET_TP;

// The iterator pattern.

// Use this to initialize an iterator "iterName" to iterate over a VARSET_TP "vs".
// "varIndex" will be an unsigned variable to which we assign the elements of "vs".
#define VARSET_ITER_INIT(comp, iterName, vs, varIndex)                                                                 \
    unsigned        varIndex = 0;                                                                                \
    VarSetOps::Iter iterName(comp, vs)

#endif // _VARSET_INCLUDED_


text:
using System;
using System.Collections.Generic;
using Orchard.Messaging.Services;
using Orchard.Tests.Stubs;

namespace Orchard.Messaging.Tests {
    public class StubMessageChannel : IMessageChannel {
        public const string ChannelName = "stub";
        private readonly TimeSpan _simulatedProcessingTime;
        private readonly StubClock _clock;

        public StubMessageChannel(TimeSpan simulatedProcessingTime, StubClock clock) {
            _simulatedProcessingTime = simulatedProcessingTime;
            _clock = clock;
        }

        public void Dispose() {
        }

        public void Process(IDictionary<string ,object> parameters) {
            _clock.Advance(_simulatedProcessingTime);
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.integrations.v1alpha.model;

/**
 * Policy that defines the task retry logic and failure type. If no FailurePolicy is defined for a
 * task, all its dependent tasks will not be executed (i.e, a `retry_strategy` of NONE will be
 * applied).
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Application Integration API. For a detailed
 * explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudIntegrationsV1alphaFailurePolicy extends com.google.api.client.json.GenericJson {

  /**
   * Required if retry_strategy is FIXED_INTERVAL or
   * LINEAR/EXPONENTIAL_BACKOFF/RESTART_INTEGRATION_WITH_BACKOFF. Defines the initial interval in
   * seconds for backoff.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String intervalTime;

  /**
   * Required if retry_strategy is FIXED_INTERVAL or
   * LINEAR/EXPONENTIAL_BACKOFF/RESTART_INTEGRATION_WITH_BACKOFF. Defines the number of times the
   * task will be retried if failed.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer maxRetries;

  /**
   * Defines what happens to the task upon failure.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String retryStrategy;

  /**
   * Required if retry_strategy is FIXED_INTERVAL or
   * LINEAR/EXPONENTIAL_BACKOFF/RESTART_INTEGRATION_WITH_BACKOFF. Defines the initial interval in
   * seconds for backoff.
   * @return value or {@code null} for none
   */
  public String getIntervalTime() {
    return intervalTime;
  }

  /**
   * Required if retry_strategy is FIXED_INTERVAL or
   * LINEAR/EXPONENTIAL_BACKOFF/RESTART_INTEGRATION_WITH_BACKOFF. Defines the initial interval in
   * seconds for backoff.
   * @param intervalTime intervalTime or {@code null} for none
   */
  public GoogleCloudIntegrationsV1alphaFailurePolicy setIntervalTime(String intervalTime) {
    this.intervalTime = intervalTime;
    return this;
  }

  /**
   * Required if retry_strategy is FIXED_INTERVAL or
   * LINEAR/EXPONENTIAL_BACKOFF/RESTART_INTEGRATION_WITH_BACKOFF. Defines the number of times the
   * task will be retried if failed.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getMaxRetries() {
    return maxRetries;
  }

  /**
   * Required if retry_strategy is FIXED_INTERVAL or
   * LINEAR/EXPONENTIAL_BACKOFF/RESTART_INTEGRATION_WITH_BACKOFF. Defines the number of times the
   * task will be retried if failed.
   * @param maxRetries maxRetries or {@code null} for none
   */
  public GoogleCloudIntegrationsV1alphaFailurePolicy setMaxRetries(java.lang.Integer maxRetries) {
    this.maxRetries = maxRetries;
    return this;
  }

  /**
   * Defines what happens to the task upon failure.
   * @return value or {@code null} for none
   */
  public java.lang.String getRetryStrategy() {
    return retryStrategy;
  }

  /**
   * Defines what happens to the task upon failure.
   * @param retryStrategy retryStrategy or {@code null} for none
   */
  public GoogleCloudIntegrationsV1alphaFailurePolicy setRetryStrategy(java.lang.String retryStrategy) {
    this.retryStrategy = retryStrategy;
    return this;
  }

  @Override
  public GoogleCloudIntegrationsV1alphaFailurePolicy set(String fieldName, Object value) {
    return (GoogleCloudIntegrationsV1alphaFailurePolicy) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudIntegrationsV1alphaFailurePolicy clone() {
    return (GoogleCloudIntegrationsV1alphaFailurePolicy) super.clone();
  }

}


text:
namespace ImageSharp.Formats.Jpg
{
    using System;

    /// <summary>
    /// The missing ff00 exception.
    /// </summary>
    // ReSharper disable once InconsistentNaming
    internal class MissingFF00Exception : Exception
    {
    }
}


text:
from __future__ import print_function
import glob
import sys
import os
import re
from decimal import *
import urlparse, urllib
import argparse
import csv
import math
import time

# a global object id counter for the different objects for TrakEM2
global_oid_counter = 5

def read_bmp_dimensions(bmp_file):
    """ Taken from: http://runnable.com/UqJdRnCIohYmAAGP/reading-binary-files-in-python-for-io """
    import struct
    dims = None
    # When reading a binary file, always add a 'b' to the file open mode
    with open(bmp_file, 'rb') as f:
        # BMP files store their width and height statring at byte 18 (12h), so seek
        # to that position
        f.seek(18)

        # The width and height are 4 bytes each, so read 8 bytes to get both of them
        bytes = f.read(8)

        # Here, we decode the byte array from the last step. The width and height
        # are each unsigned, little endian, 4 byte integers, so they have the format
        # code '<II'. See http://docs.python.org/3/library/struct.html for more info
        # Our test showed that we needed to use 2's complement (so using 'i' instead of 'I', and taking absolute value)
        size = struct.unpack('<ii', bytes)
        size = [abs(size[0]), abs(size[1])]

        dims = [size[1], size[0]]
    return dims

def read_dimensions(img_file):
    if img_file.lower().endswith(".bmp"):
        return read_bmp_dimensions(img_file)
    else:
        import cv2
        im = cv2.imread(image_file, cv2.IMREAD_GRAYSCALE)
        if im is None:
            print('Cannot read tile image: {}'.format(image_file))
            sys.exit(1)
        return im.shape

def fetch_and_increase_oid():
    global global_oid_counter
    res = global_oid_counter
    global_oid_counter += 1
    return res

def write_pre_xml(out_data, xml_file_name, layer_width, layer_height, mipmap_threads):
    unuid="{}.1224689168.2106301".format(int(round(time.time() * 1000)))
    lines = """<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE trakem2_anything [
        <!ELEMENT trakem2 (project,t2_layer_set,t2_display)>
        <!ELEMENT project (anything)>
        <!ATTLIST project id NMTOKEN #REQUIRED>
        <!ATTLIST project unuid NMTOKEN #REQUIRED>
        <!ATTLIST project title NMTOKEN #REQUIRED>
        <!ATTLIST project preprocessor NMTOKEN #REQUIRED>
        <!ATTLIST project mipmaps_folder NMTOKEN #REQUIRED>
        <!ATTLIST project storage_folder NMTOKEN #REQUIRED>
        <!ATTLIST project n_mipmap_threads NMTOKEN #REQUIRED>
        <!ATTLIST project look_ahead_cache NMTOKEN #REQUIRED>
        <!ATTLIST project n_undo_steps NMTOKEN #REQUIRED>
        <!ELEMENT anything EMPTY>
        <!ATTLIST anything id NMTOKEN #REQUIRED>
        <!ATTLIST anything expanded NMTOKEN #REQUIRED>
        <!ELEMENT t2_layer (t2_patch,t2_label,t2_layer_set,t2_profile)>
        <!ATTLIST t2_layer oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer thickness NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer z NMTOKEN #REQUIRED>
        <!ELEMENT t2_layer_set (t2_prop,t2_linked_prop,t2_annot,t2_layer,t2_pipe,t2_ball,t2_area_list,t2_calibration,t2_stack,t2_treeline)>
        <!ATTLIST t2_layer_set oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set style NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set title NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set links NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set composite NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set layer_width NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set layer_height NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set rot_x NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set rot_y NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set rot_z NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set snapshots_quality NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set color_cues NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set area_color_cues NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set avoid_color_cue_colors NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set n_layers_color_cue NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set paint_arrows NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set paint_tags NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set paint_edge_confidence_boxes NMTOKEN #REQUIRED>
        <!ATTLIST t2_layer_set preload_ahead NMTOKEN #REQUIRED>
        <!ELEMENT t2_calibration EMPTY>
        <!ATTLIST t2_calibration pixelWidth NMTOKEN #REQUIRED>
        <!ATTLIST t2_calibration pixelHeight NMTOKEN #REQUIRED>
        <!ATTLIST t2_calibration pixelDepth NMTOKEN #REQUIRED>
        <!ATTLIST t2_calibration xOrigin NMTOKEN #REQUIRED>
        <!ATTLIST t2_calibration yOrigin NMTOKEN #REQUIRED>
        <!ATTLIST t2_calibration zOrigin NMTOKEN #REQUIRED>
        <!ATTLIST t2_calibration info NMTOKEN #REQUIRED>
        <!ATTLIST t2_calibration valueUnit NMTOKEN #REQUIRED>
        <!ATTLIST t2_calibration timeUnit NMTOKEN #REQUIRED>
        <!ATTLIST t2_calibration unit NMTOKEN #REQUIRED>
        <!ELEMENT t2_ball (t2_prop,t2_linked_prop,t2_annot,t2_ball_ob)>
        <!ATTLIST t2_ball oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball style NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball title NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball links NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball composite NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball fill NMTOKEN #REQUIRED>
        <!ELEMENT t2_ball_ob EMPTY>
        <!ATTLIST t2_ball_ob x NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball_ob y NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball_ob r NMTOKEN #REQUIRED>
        <!ATTLIST t2_ball_ob layer_id NMTOKEN #REQUIRED>
        <!ELEMENT t2_label (t2_prop,t2_linked_prop,t2_annot)>
        <!ATTLIST t2_label oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_label layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_label transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_label style NMTOKEN #REQUIRED>
        <!ATTLIST t2_label locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_label visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_label title NMTOKEN #REQUIRED>
        <!ATTLIST t2_label links NMTOKEN #REQUIRED>
        <!ATTLIST t2_label composite NMTOKEN #REQUIRED>
        <!ELEMENT t2_filter EMPTY>
        <!ELEMENT t2_patch (t2_prop,t2_linked_prop,t2_annot,ict_transform,ict_transform_list,t2_filter)>
        <!ATTLIST t2_patch oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch style NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch title NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch links NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch composite NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch file_path NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch original_path NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch type NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch false_color NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch ct NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch o_width NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch o_height NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch min NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch max NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch o_width NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch o_height NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch pps NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch mres NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch ct_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_patch alpha_mask_id NMTOKEN #REQUIRED>
        <!ELEMENT t2_pipe (t2_prop,t2_linked_prop,t2_annot)>
        <!ATTLIST t2_pipe oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_pipe layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_pipe transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_pipe style NMTOKEN #REQUIRED>
        <!ATTLIST t2_pipe locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_pipe visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_pipe title NMTOKEN #REQUIRED>
        <!ATTLIST t2_pipe links NMTOKEN #REQUIRED>
        <!ATTLIST t2_pipe composite NMTOKEN #REQUIRED>
        <!ATTLIST t2_pipe d NMTOKEN #REQUIRED>
        <!ATTLIST t2_pipe p_width NMTOKEN #REQUIRED>
        <!ATTLIST t2_pipe layer_ids NMTOKEN #REQUIRED>
        <!ELEMENT t2_polyline (t2_prop,t2_linked_prop,t2_annot)>
        <!ATTLIST t2_polyline oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_polyline layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_polyline transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_polyline style NMTOKEN #REQUIRED>
        <!ATTLIST t2_polyline locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_polyline visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_polyline title NMTOKEN #REQUIRED>
        <!ATTLIST t2_polyline links NMTOKEN #REQUIRED>
        <!ATTLIST t2_polyline composite NMTOKEN #REQUIRED>
        <!ATTLIST t2_polyline d NMTOKEN #REQUIRED>
        <!ELEMENT t2_profile (t2_prop,t2_linked_prop,t2_annot)>
        <!ATTLIST t2_profile oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_profile layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_profile transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_profile style NMTOKEN #REQUIRED>
        <!ATTLIST t2_profile locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_profile visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_profile title NMTOKEN #REQUIRED>
        <!ATTLIST t2_profile links NMTOKEN #REQUIRED>
        <!ATTLIST t2_profile composite NMTOKEN #REQUIRED>
        <!ATTLIST t2_profile d NMTOKEN #REQUIRED>
        <!ELEMENT t2_area_list (t2_prop,t2_linked_prop,t2_annot,t2_area)>
        <!ATTLIST t2_area_list oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_area_list layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_area_list transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_area_list style NMTOKEN #REQUIRED>
        <!ATTLIST t2_area_list locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_area_list visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_area_list title NMTOKEN #REQUIRED>
        <!ATTLIST t2_area_list links NMTOKEN #REQUIRED>
        <!ATTLIST t2_area_list composite NMTOKEN #REQUIRED>
        <!ATTLIST t2_area_list fill_paint NMTOKEN #REQUIRED>
        <!ELEMENT t2_area (t2_path)>
        <!ATTLIST t2_area layer_id NMTOKEN #REQUIRED>
        <!ELEMENT t2_path EMPTY>
        <!ATTLIST t2_path d NMTOKEN #REQUIRED>
        <!ELEMENT t2_dissector (t2_prop,t2_linked_prop,t2_annot,t2_dd_item)>
        <!ATTLIST t2_dissector oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_dissector layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_dissector transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_dissector style NMTOKEN #REQUIRED>
        <!ATTLIST t2_dissector locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_dissector visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_dissector title NMTOKEN #REQUIRED>
        <!ATTLIST t2_dissector links NMTOKEN #REQUIRED>
        <!ATTLIST t2_dissector composite NMTOKEN #REQUIRED>
        <!ELEMENT t2_dd_item EMPTY>
        <!ATTLIST t2_dd_item radius NMTOKEN #REQUIRED>
        <!ATTLIST t2_dd_item tag NMTOKEN #REQUIRED>
        <!ATTLIST t2_dd_item points NMTOKEN #REQUIRED>
        <!ELEMENT t2_stack (t2_prop,t2_linked_prop,t2_annot,(iict_transform|iict_transform_list)?)>
        <!ATTLIST t2_stack oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_stack layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_stack transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_stack style NMTOKEN #REQUIRED>
        <!ATTLIST t2_stack locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_stack visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_stack title NMTOKEN #REQUIRED>
        <!ATTLIST t2_stack links NMTOKEN #REQUIRED>
        <!ATTLIST t2_stack composite NMTOKEN #REQUIRED>
        <!ATTLIST t2_stack file_path CDATA #REQUIRED>
        <!ATTLIST t2_stack depth CDATA #REQUIRED>
        <!ELEMENT t2_tag EMPTY>
        <!ATTLIST t2_tag name NMTOKEN #REQUIRED>
        <!ATTLIST t2_tag key NMTOKEN #REQUIRED>
        <!ELEMENT t2_node (t2_area*,t2_tag*)>
        <!ATTLIST t2_node x NMTOKEN #REQUIRED>
        <!ATTLIST t2_node y NMTOKEN #REQUIRED>
        <!ATTLIST t2_node lid NMTOKEN #REQUIRED>
        <!ATTLIST t2_node c NMTOKEN #REQUIRED>
        <!ATTLIST t2_node r NMTOKEN #IMPLIED>
        <!ELEMENT t2_treeline (t2_node*,t2_prop,t2_linked_prop,t2_annot)>
        <!ATTLIST t2_treeline oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_treeline layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_treeline transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_treeline style NMTOKEN #REQUIRED>
        <!ATTLIST t2_treeline locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_treeline visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_treeline title NMTOKEN #REQUIRED>
        <!ATTLIST t2_treeline links NMTOKEN #REQUIRED>
        <!ATTLIST t2_treeline composite NMTOKEN #REQUIRED>
        <!ELEMENT t2_areatree (t2_node*,t2_prop,t2_linked_prop,t2_annot)>
        <!ATTLIST t2_areatree oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_areatree layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_areatree transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_areatree style NMTOKEN #REQUIRED>
        <!ATTLIST t2_areatree locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_areatree visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_areatree title NMTOKEN #REQUIRED>
        <!ATTLIST t2_areatree links NMTOKEN #REQUIRED>
        <!ATTLIST t2_areatree composite NMTOKEN #REQUIRED>
        <!ELEMENT t2_connector (t2_node*,t2_prop,t2_linked_prop,t2_annot)>
        <!ATTLIST t2_connector oid NMTOKEN #REQUIRED>
        <!ATTLIST t2_connector layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_connector transform NMTOKEN #REQUIRED>
        <!ATTLIST t2_connector style NMTOKEN #REQUIRED>
        <!ATTLIST t2_connector locked NMTOKEN #REQUIRED>
        <!ATTLIST t2_connector visible NMTOKEN #REQUIRED>
        <!ATTLIST t2_connector title NMTOKEN #REQUIRED>
        <!ATTLIST t2_connector links NMTOKEN #REQUIRED>
        <!ATTLIST t2_connector composite NMTOKEN #REQUIRED>
        <!ELEMENT t2_prop EMPTY>
        <!ATTLIST t2_prop key NMTOKEN #REQUIRED>
        <!ATTLIST t2_prop value NMTOKEN #REQUIRED>
        <!ELEMENT t2_linked_prop EMPTY>
        <!ATTLIST t2_linked_prop target_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_linked_prop key NMTOKEN #REQUIRED>
        <!ATTLIST t2_linked_prop value NMTOKEN #REQUIRED>
        <!ELEMENT t2_annot EMPTY>
        <!ELEMENT t2_display EMPTY>
        <!ATTLIST t2_display id NMTOKEN #REQUIRED>
        <!ATTLIST t2_display layer_id NMTOKEN #REQUIRED>
        <!ATTLIST t2_display x NMTOKEN #REQUIRED>
        <!ATTLIST t2_display y NMTOKEN #REQUIRED>
        <!ATTLIST t2_display magnification NMTOKEN #REQUIRED>
        <!ATTLIST t2_display srcrect_x NMTOKEN #REQUIRED>
        <!ATTLIST t2_display srcrect_y NMTOKEN #REQUIRED>
        <!ATTLIST t2_display srcrect_width NMTOKEN #REQUIRED>
        <!ATTLIST t2_display srcrect_height NMTOKEN #REQUIRED>
        <!ATTLIST t2_display scroll_step NMTOKEN #REQUIRED>
        <!ATTLIST t2_display c_alphas NMTOKEN #REQUIRED>
        <!ATTLIST t2_display c_alphas_state NMTOKEN #REQUIRED>
        <!ATTLIST t2_display filter_enabled NMTOKEN #REQUIRED>
        <!ATTLIST t2_display filter_min_max_enabled NMTOKEN #REQUIRED>
        <!ATTLIST t2_display filter_min NMTOKEN #REQUIRED>
        <!ATTLIST t2_display filter_max NMTOKEN #REQUIRED>
        <!ATTLIST t2_display filter_invert NMTOKEN #REQUIRED>
        <!ATTLIST t2_display filter_clahe_enabled NMTOKEN #REQUIRED>
        <!ATTLIST t2_display filter_clahe_block_size NMTOKEN #REQUIRED>
        <!ATTLIST t2_display filter_clahe_histogram_bins NMTOKEN #REQUIRED>
        <!ATTLIST t2_display filter_clahe_max_slope NMTOKEN #REQUIRED>
        <!ELEMENT ict_transform EMPTY>
        <!ATTLIST ict_transform class CDATA #REQUIRED>
        <!ATTLIST ict_transform data CDATA #REQUIRED>
        <!ELEMENT iict_transform EMPTY>
        <!ATTLIST iict_transform class CDATA #REQUIRED>
        <!ATTLIST iict_transform data CDATA #REQUIRED>
        <!ELEMENT ict_transform_list (ict_transform|iict_transform)*>
        <!ELEMENT iict_transform_list (iict_transform*)>
] >

<trakem2>
        <project
                id="0"
                title=""" + '"' + xml_file_name + '"' + """
                """ + 'unuid="{}"'.format(unuid) + """
                """ + 'mipmaps_folder="trakem2.{}/trakem2.mipmaps/"'.format(unuid) + """
                storage_folder=""
                mipmaps_format="4"
                image_resizing_mode="Area downsampling"
                """ + 'n_mipmap_threads="{}"'.format(mipmap_threads) + """
                n_undo_steps="32"
                look_ahead_cache="0"
        >
        </project>
        <t2_layer_set
                oid="3"
                width="20.0"
                height="20.0"
                transform="matrix(1.0,0.0,0.0,1.0,0.0,0.0)"
                title="Top Level"
                links=""
                """ + 'layer_width="{}"'.format(float(layer_width)) + """
                """ + 'layer_height="{}"'.format(float(layer_height)) + """
                rot_x="0.0"
                rot_y="0.0"
                rot_z="0.0"
                snapshots_quality="true"
                snapshots_mode="Full"
                color_cues="true"
                area_color_cues="true"
                avoid_color_cue_colors="false"
                n_layers_color_cue="0"
                paint_arrows="true"
                paint_tags="true"
                paint_edge_confidence_boxes="true"
                prepaint="false"
                preload_ahead="0"
        >
                <t2_calibration
                        pixelWidth="4.0"
                        pixelHeight="4.0"
                        pixelDepth="30.0"
                        xOrigin="0.0"
                        yOrigin="0.0"
                        zOrigin="0.0"
                        info="null"
                        valueUnit="Gray Value"
                        timeUnit="sec"
                        unit="nm"
                />
                """
    out_data.writelines(lines)

def write_post_xml(out_data, layer_width, layer_height):
    lines = """</t2_layer_set>
            """ + '<t2_display id="{}"'.format(fetch_and_increase_oid()) + """
                layer_id="1"
                c_alphas="-1"
                c_alphas_state="-1"
                x="0"
                y="0"
                magnification="0.013888888888888888"
                srcrect_x="0"
                srcrect_y="0"
                """ + 'srcrect_width="{}"'.format(layer_width) + """
                """ + 'srcrect_height="{}"'.format(layer_height) + """
                scroll_step="1"
                filter_enabled="false"
                filter_min_max_enabled="false"
                filter_min="0"
                filter_max="255"
                filter_invert="false"
                filter_clahe_enabled="false"
                filter_clahe_block_size="127"
                filter_clahe_histogram_bins="256"
                filter_clahe_max_slope="3.0"
        />
</trakem2>
    """
    out_data.writelines(lines)

def write_layer(out_data, layer, layer_patches):
    pre_layer = '<t2_layer oid="{}"'.format(fetch_and_increase_oid()) + """
                         """ + 'thickness="7.5"' + """
                         """ + 'z="{}.0"'.format(layer) + """
                         title=""
                >
"""
    post_layer = "</t2_layer>\n"

    out_data.writelines(pre_layer)
    for tile in layer_patches:
        write_patch(out_data, tile)
    out_data.writelines(post_layer)

def write_patch(out_data, tile):
    patch_lines = \
"""                        <t2_patch
                                """ + 'oid="{}"'.format(fetch_and_increase_oid()) + """
                                """ + 'width="{}.0"'.format(tile["width"]) + """
                                """ + 'height="{}.0"'.format(tile["height"]) + """
                                """ + 'transform="matrix(1.0,0.0,0.0,1.0,{},{})"'.format(float(tile["tx"]), float(tile["ty"])) + """
                                """ + 'title="{}"'.format(tile["file_base_name"]) + """
                                links=""
                                type="0"
                                """ + 'file_path="{}"'.format(tile["file_full_path"]) + """
                                style="fill-opacity:1.0;stroke:#ffff00;"
                                """ + 'o_width="{}"'.format(tile["width"]) + """
                                """ + 'o_height="{}"'.format(tile["height"]) + """
                                min="0.0"
                                max="255.0"
                                mres="32"
                        >
                        </t2_patch>
"""
    out_data.writelines(patch_lines)

def parse_layer(base_dir, images, x, y):
    '''Writes the tilespec for a single section'''
    tiles = []
    layer_size = [0, 0]
    image_size = None

    for i, img in enumerate(images):
        # If not using windows, change the folder separator
        if os.name == "posix":
            img = img.replace('\\', '/')

        image_file = os.path.join(base_dir, img)
        tile = {}
        if image_size is None:
            image_size = read_dimensions(image_file)
        tile["file_full_path"] = os.path.abspath(image_file)
        tile["file_base_name"] = os.path.basename(tile["file_full_path"])
        tile["width"] = image_size[1]
        tile["height"] = image_size[0]
        tile["tx"] = x[i]
        tile["ty"] = y[i]
        tiles.append(tile)
        layer_size[0] = max(layer_size[0], image_size[0] + tile["ty"])
        layer_size[1] = max(layer_size[1], image_size[1] + tile["tx"])

    # if len(tiles) > 0:
    #     write_layer(out_data, layer, tiles)
    # else:
    #     print('Nothing to write from directory {}'.format(subdir))
    if len(tiles) == 0:
        print('Nothing to write from directory {}'.format(base_dir))
    layer_data = {}
    layer_data["height"] = layer_size[0]
    layer_data["width"] = layer_size[1]
    layer_data["tiles"] = tiles
    return layer_data

def parse_coordinates_file(input_file):
    images_dict = {}
    images = []
    x = []
    y = []
    with open(input_file, 'r') as csvfile:
        data_reader = csv.reader(csvfile, delimiter='\t')
        for row in data_reader:
            img_fname = row[0]
            img_sec_mfov_beam = '_'.join(img_fname.split('\\')[-1].split('_')[:3])
            # Make sure that no duplicates appear
            if img_sec_mfov_beam not in images_dict.keys():
                images.append(img_fname)
                images_dict[img_sec_mfov_beam] = img_fname
                cur_x = float(row[1])
                cur_y = float(row[2])
                x.append(cur_x)
                y.append(cur_y)
            else:
                # Either the image is duplicated, or a newer version was taken,
                # so make sure that the newer version is used
                prev_img = images_dict[img_sec_mfov_beam]
                prev_img_date = prev_img.split('\\')[-1].split('_')[-1]
                curr_img_date = img_fname.split('\\')[-1].split('_')[-1]
                if curr_img_date > prev_img_date:
                    idx = images.index(prev_img)
                    images[idx] = img_fname
                    images_dict[img_sec_mfov_beam] = img_fname

    return images, x, y

def offset_list(lst):
    m = min(lst)
    return [item - m for item in lst]

if __name__ == '__main__':

    # Command line parser
    parser = argparse.ArgumentParser(description='Creates the TrakEM2 xml file for images that were acquired using the multiebeam EM.')
    parser.add_argument('input_folder', metavar='input_folder', type=str,
                    help='a directory that contains sections subdirectories in which a full_coordinates txt file per section')
    parser.add_argument('-t', '--mipmap_threads', type=int,
                    help='number of mipmap threads that should be used (default: 8)',
                    default=8)
    parser.add_argument('-o', '--output_xml', type=str,
                    help='the xml file where all the tiles will be stored (default: ./output.xml)',
                    default='./output.xml')
    # parser.add_argument('-v', '--overlap', type=float,
    #                 help='the overlap fraction between the tiles (default: 0.06)', # 0.06 from Alyssa's data
    #                 default=0.06)

    args = parser.parse_args()

    xml_file_name = os.path.basename(args.output_xml)

    print("Parsing all subsections from folder: {}".format(args.input_folder))
    all_sub_folders = sorted(glob.glob(os.path.join(args.input_folder, '*')))

    max_layer_width = 0
    max_layer_height = 0

    all_layers = []

    for sub_folder in all_sub_folders:
        if os.path.isdir(sub_folder):
            print("Parsing subfolder: {}".format(sub_folder))
            coords_file = os.path.join(sub_folder, "full_image_coordinates.txt")
            if os.path.exists(coords_file):
                images, x, y = parse_coordinates_file(coords_file)
                x = offset_list(x)
                y = offset_list(y)
                cur_layer = parse_layer(sub_folder, images, x, y)
                max_layer_width = max(max_layer_width, cur_layer["width"])
                max_layer_height = max(max_layer_height, cur_layer["height"])
                layer = int(sub_folder.split(os.path.sep)[-1])
                cur_layer["layer_num"] = layer
                all_layers.append(cur_layer)
            else:
                print("Could not find full_image_coordinates.txt, skipping subfolder")

    max_layer_width = int(math.ceil(max_layer_width))
    max_layer_height = int(math.ceil(max_layer_height))

    print("Done parsing, writing xml file")

    # Create the output file and write the first lines of the xml
    out_data = open(args.output_xml, "w")
    write_pre_xml(out_data, xml_file_name, max_layer_width, max_layer_height, args.mipmap_threads)
    # write the tiles per layer
    for cur_layer in all_layers:
        write_layer(out_data, cur_layer["layer_num"], cur_layer["tiles"])

    # write the last lines of the xml
    write_post_xml(out_data, max_layer_width, max_layer_height)
    out_data.close()


text:
var system = require('system'),
	webPage = require('webpage').create();// Require the library: webpage

if(system.args.length < 1) {
	console.log('Usage: loadwebpage.js <some URL>');
	phantom.exit();// Stop PhantomJS
}

var url = system.args[1];// Get the URL From the input arguments

var start = Date.now();// Get the starttime sinds 1970
webPage.viewPort = {width: 480, height: 800};
webPage.clipRect = {
	top: 0,
	left: 0,
	width: 480,
	height: 800
}
webPage.open(url, function(result) {
	if(result !== 'success') {
		console.log('Failed to load the webpage: ' + url);
	} else {
		var end =  Date.now();
		var diff = end - start;

		console.log('Time to load the webpage: ' + url + ' -> ' + diff + 'ms');

		var title = webPage.evaluate(function() {
			return document.title;
		});

		console.log('Title of the webpage: ' + title + '.');

		var fileName = end + '.png';

		webPage.render(fileName);

	}
	phantom.exit();// Stop PhantomJS
});