text:
.class Landroid/support/v4/app/bs;
.super Landroid/support/v4/app/bz;

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Landroid/support/v4/app/bz;-><init>()V

    return-void
.end method

# virtual methods
.method public a(Landroid/support/v4/app/bo;Landroid/support/v4/app/bp;)Landroid/app/Notification;
    .locals 26

    new-instance v2, Landroid/support/v4/app/cc;

    move-object/from16 v0, p1

    iget-object v3, v0, Landroid/support/v4/app/bo;->a:Landroid/content/Context;

    move-object/from16 v0, p1

    iget-object v4, v0, Landroid/support/v4/app/bo;->B:Landroid/app/Notification;

    move-object/from16 v0, p1

    iget-object v5, v0, Landroid/support/v4/app/bo;->b:Ljava/lang/CharSequence;

    move-object/from16 v0, p1

    iget-object v6, v0, Landroid/support/v4/app/bo;->c:Ljava/lang/CharSequence;

    move-object/from16 v0, p1

    iget-object v7, v0, Landroid/support/v4/app/bo;->h:Ljava/lang/CharSequence;

    move-object/from16 v0, p1

    iget-object v8, v0, Landroid/support/v4/app/bo;->f:Landroid/widget/RemoteViews;

    move-object/from16 v0, p1

    iget v9, v0, Landroid/support/v4/app/bo;->i:I

    move-object/from16 v0, p1

    iget-object v10, v0, Landroid/support/v4/app/bo;->d:Landroid/app/PendingIntent;

    move-object/from16 v0, p1

    iget-object v11, v0, Landroid/support/v4/app/bo;->e:Landroid/app/PendingIntent;

    move-object/from16 v0, p1

    iget-object v12, v0, Landroid/support/v4/app/bo;->g:Landroid/graphics/Bitmap;

    move-object/from16 v0, p1

    iget v13, v0, Landroid/support/v4/app/bo;->o:I

    move-object/from16 v0, p1

    iget v14, v0, Landroid/support/v4/app/bo;->p:I

    move-object/from16 v0, p1

    iget-boolean v15, v0, Landroid/support/v4/app/bo;->q:Z

    move-object/from16 v0, p1

    iget-boolean v0, v0, Landroid/support/v4/app/bo;->k:Z

    move/from16 v16, v0

    move-object/from16 v0, p1

    iget-boolean v0, v0, Landroid/support/v4/app/bo;->l:Z

    move/from16 v17, v0

    move-object/from16 v0, p1

    iget v0, v0, Landroid/support/v4/app/bo;->j:I

    move/from16 v18, v0

    move-object/from16 v0, p1

    iget-object v0, v0, Landroid/support/v4/app/bo;->n:Ljava/lang/CharSequence;

    move-object/from16 v19, v0

    move-object/from16 v0, p1

    iget-boolean v0, v0, Landroid/support/v4/app/bo;->v:Z

    move/from16 v20, v0

    move-object/from16 v0, p1

    iget-object v0, v0, Landroid/support/v4/app/bo;->C:Ljava/util/ArrayList;

    move-object/from16 v21, v0

    move-object/from16 v0, p1

    iget-object v0, v0, Landroid/support/v4/app/bo;->x:Landroid/os/Bundle;

    move-object/from16 v22, v0

    move-object/from16 v0, p1

    iget-object v0, v0, Landroid/support/v4/app/bo;->r:Ljava/lang/String;

    move-object/from16 v23, v0

    move-object/from16 v0, p1

    iget-boolean v0, v0, Landroid/support/v4/app/bo;->s:Z

    move/from16 v24, v0

    move-object/from16 v0, p1

    iget-object v0, v0, Landroid/support/v4/app/bo;->t:Ljava/lang/String;

    move-object/from16 v25, v0

    invoke-direct/range {v2 .. v25}, Landroid/support/v4/app/cc;-><init>(Landroid/content/Context;Landroid/app/Notification;Ljava/lang/CharSequence;Ljava/lang/CharSequence;Ljava/lang/CharSequence;Landroid/widget/RemoteViews;ILandroid/app/PendingIntent;Landroid/app/PendingIntent;Landroid/graphics/Bitmap;IIZZZILjava/lang/CharSequence;ZLjava/util/ArrayList;Landroid/os/Bundle;Ljava/lang/String;ZLjava/lang/String;)V

    move-object/from16 v0, p1

    iget-object v3, v0, Landroid/support/v4/app/bo;->u:Ljava/util/ArrayList;

    invoke-static {v2, v3}, Landroid/support/v4/app/bj;->a(Landroid/support/v4/app/bh;Ljava/util/ArrayList;)V

    move-object/from16 v0, p1

    iget-object v3, v0, Landroid/support/v4/app/bo;->m:Landroid/support/v4/app/ca;

    invoke-static {v2, v3}, Landroid/support/v4/app/bj;->a(Landroid/support/v4/app/bi;Landroid/support/v4/app/ca;)V

    move-object/from16 v0, p2

    move-object/from16 v1, p1

    invoke-virtual {v0, v1, v2}, Landroid/support/v4/app/bp;->a(Landroid/support/v4/app/bo;Landroid/support/v4/app/bi;)Landroid/app/Notification;

    move-result-object v2

    return-object v2
.end method


text:
package org.apache.camel.itest.springboot.arquillian.container;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.camel.itest.springboot.arquillian.container.jmx.CustomJMXProtocol;
import org.apache.camel.itest.springboot.arquillian.container.util.Await;
import org.apache.camel.itest.springboot.arquillian.container.util.FileDeploymentUtils;
import org.jboss.arquillian.container.se.api.ClassPath;
import org.jboss.arquillian.container.se.api.ClassPathDirectory;
import org.jboss.arquillian.container.spi.client.container.DeployableContainer;
import org.jboss.arquillian.container.spi.client.container.DeploymentException;
import org.jboss.arquillian.container.spi.client.container.LifecycleException;
import org.jboss.arquillian.container.spi.client.protocol.ProtocolDescription;
import org.jboss.arquillian.container.spi.client.protocol.metadata.JMXContext;
import org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData;
import org.jboss.arquillian.protocol.jmx.JMXTestRunnerMBean;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.Node;
import org.jboss.shrinkwrap.api.asset.ArchiveAsset;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.asset.ClassAsset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.descriptor.api.Descriptor;

public class ManagedSEDeployableContainer implements DeployableContainer<ManagedSEContainerConfiguration> {

    private static final Logger LOGGER = Logger.getLogger(ManagedSEDeployableContainer.class.getName());
    private static final String SYSPROP_KEY_JAVA_HOME = "java.home";
    private static final String DEBUG_AGENT_STRING = "-agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=y";
    private static final String TARGET = "target";
    private static final String SERVER_MAIN_CLASS_FQN = "org.jboss.arquillian.container.se.server.Main";
    private static final String SYSTEM_PROPERTY_SWITCH = "-D";
    private static final String EQUALS = "=";

    private boolean debugModeEnabled;
    private boolean keepDeploymentArchives;
    private Process process;
    private List<File> materializedFiles;
    private List<File> classpathDependencies;
    private String host;
    private int port;
    private String librariesPath;
    private List<String> additionalJavaOpts;
    private int waitTime;

    @Override
    public Class<ManagedSEContainerConfiguration> getConfigurationClass() {
        return ManagedSEContainerConfiguration.class;
    }

    public void setup(ManagedSEContainerConfiguration configuration) {
        debugModeEnabled = configuration.isDebug();
        host = configuration.getHost();
        port = configuration.getPort();
        materializedFiles = new ArrayList<>();
        classpathDependencies = new ArrayList<>();
        librariesPath = configuration.getLibrariesPath();
        keepDeploymentArchives = configuration.isKeepDeploymentArchives();
        additionalJavaOpts = initAdditionalJavaOpts(configuration.getAdditionalJavaOpts());
        configureLogging(configuration);
        waitTime = configuration.getWaitTime() > 0 ? configuration.getWaitTime() : 10;
    }

    private List<String> initAdditionalJavaOpts(String opts) {
        if (opts == null || opts.isEmpty()) {
            return Collections.emptyList();
        }
        List<String> additionalOpts = new ArrayList<>();

        for (String option : opts.split("\\s+")) {
            additionalOpts.add(option);
        }
        return additionalOpts;
    }

    private void configureLogging(ManagedSEContainerConfiguration configuration) {
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setLevel(configuration.getLogLevel());
        LOGGER.setUseParentHandlers(false);
        LOGGER.addHandler(consoleHandler);
        LOGGER.setLevel(configuration.getLogLevel());
    }

    @Override
    public void start() throws LifecycleException {
    }

    @Override
    public void stop() throws LifecycleException {
    }

    @Override
    public ProtocolDescription getDefaultProtocol() {
        return new ProtocolDescription(CustomJMXProtocol.NAME);
    }

    @Override
    public void deploy(Descriptor descriptor) throws DeploymentException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void undeploy(Descriptor descriptor) throws DeploymentException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void undeploy(Archive<?> archive) throws DeploymentException {
        LOGGER.info("Undeploying " + archive.getName());
        if (!keepDeploymentArchives) {
            for (File materializedFile : materializedFiles) {
                if (materializedFile.isDirectory()) {
                    try {
                        FileDeploymentUtils.deleteRecursively(materializedFile.toPath());
                    } catch (IOException e) {
                        LOGGER.warning("Could not delete materialized directory: " + materializedFile);
                    }
                } else {
                    materializedFile.delete();
                }
            }
        }
        // Kill the subprocess (test JVM)
        if (process != null) {
            process.destroy();
            try {
                process.waitFor();
            } catch (final InterruptedException e) {
                Thread.interrupted();
                throw new RuntimeException("Interrupted while awaiting server daemon process termination", e);
            }
        }
    }

    @Override
    public ProtocolMetaData deploy(final Archive<?> archive) throws DeploymentException {
        LOGGER.info("Deploying " + archive.getName());

        // First of all clear the list of previously materialized deployments - otherwise the class path would grow indefinitely
        materializedFiles.clear();

        // Create a new classpath
        classpathDependencies.clear();

        if (ClassPath.isRepresentedBy(archive)) {
            for (Node child : archive.get(ClassPath.ROOT_ARCHIVE_PATH).getChildren()) {
                Asset asset = child.getAsset();
                if (asset instanceof ArchiveAsset) {
                    Archive<?> assetArchive = ((ArchiveAsset) asset).getArchive();
                    if (ClassPathDirectory.isRepresentedBy(assetArchive)) {
                        materializeDirectory(assetArchive);
                    } else {
                        materializeArchive(assetArchive);
                    }
                }
            }
        } else {
            materializeArchive(archive);
        }

        Properties systemProperties = getSystemProperties(archive);
        readJarFilesFromDirectory();
        addTestResourcesDirectory(systemProperties);

        List<String> processCommand = buildProcessCommand(systemProperties);
        logExecutedCommand(processCommand);
        // Launch the process
        final ProcessBuilder processBuilder = new ProcessBuilder(processCommand);

        String path = systemProperties.getProperty("container.user.dir");
        if (path != null) {
            processBuilder.directory(new File(path));
        }

        processBuilder.environment().put("JAVA_HOME", new File(System.getProperty(SYSPROP_KEY_JAVA_HOME)).getAbsolutePath());

        processBuilder.redirectErrorStream(true);
        processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);

        try {
            process = processBuilder.start();
        } catch (final IOException e) {
            throw new DeploymentException("Could not start process", e);
        }

        int finalWaitTime = debugModeEnabled ? (3 * waitTime) : waitTime;

        // Wait for socket connection
        if (!isServerStarted(host, port, finalWaitTime)) {
            throw new DeploymentException("Child JVM process failed to start within " + finalWaitTime + " seconds.");
        }
        if (!isJMXTestRunnerMBeanRegistered(host, port, finalWaitTime)) {
            throw new DeploymentException("JMXTestRunnerMBean not registered within " + finalWaitTime + " seconds.");
        }

        ProtocolMetaData protocolMetaData = new ProtocolMetaData();
        protocolMetaData.addContext(new JMXContext(host, port));
        return protocolMetaData;
    }

    private Properties getSystemProperties(final Archive<?> archive) throws DeploymentException {
        Node systemPropertiesNode = archive.get(ClassPath.SYSTEM_PROPERTIES_ARCHIVE_PATH);
        if (systemPropertiesNode != null) {
            try (InputStream in = systemPropertiesNode.getAsset().openStream()) {
                Properties systemProperties = new Properties();
                systemProperties.load(in);
                return systemProperties;
            } catch (IOException e) {
                throw new DeploymentException("Could not load system properties", e);
            }
        }
        return null;
    }

    private boolean isServerStarted(final String host, final int port, int waitTime) {
        return new Await(waitTime, new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                try (Socket ignored = new Socket(host, port)) {
                    return true;
                }
            }
        }).start();
    }

    private boolean isJMXTestRunnerMBeanRegistered(final String host, final int port, int waitTime) throws DeploymentException {
        // Taken from org.jboss.arquillian.container.spi.client.protocol.metadata.JMXContext
        final String jmxServiceUrl = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
        try (JMXConnector jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxServiceUrl), null)) {
            final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
            return new Await(waitTime, new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    mbsc.getObjectInstance(new ObjectName(JMXTestRunnerMBean.OBJECT_NAME));
                    LOGGER.fine("JMXTestRunnerMBean registered with the remote MBean server at: " + jmxServiceUrl);
                    return true;
                }
            }).start();
        } catch (IOException e) {
            throw new DeploymentException("Could not verify JMXTestRunnerMBean registration", e);
        }
    }

    private void materializeArchive(Archive<?> archive) {
        File deploymentFile = new File(TARGET.concat(File.separator).concat(archive.getName()));
        archive.as(ZipExporter.class).exportTo(deploymentFile, true);
        materializedFiles.add(deploymentFile);
    }

    private void materializeDirectory(Archive<?> archive) throws DeploymentException {
        if (archive.getContent().isEmpty()) {
            // Do not materialize an empty directory
            return;
        }
        File entryDirectory = new File(TARGET.concat(File.separator).concat(archive.getName()));
        try {
            if (entryDirectory.exists()) {
                // Always delete previous content
                FileDeploymentUtils.deleteContent(entryDirectory.toPath());
            } else {
                if (!entryDirectory.mkdirs()) {
                    throw new DeploymentException("Could not create class path directory: " + entryDirectory);
                }
            }
            for (Node child : archive.get(ClassPath.ROOT_ARCHIVE_PATH).getChildren()) {
                Asset asset = child.getAsset();
                if (asset instanceof ClassAsset) {
                    FileDeploymentUtils.materializeClass(entryDirectory, (ClassAsset) asset);
                } else if (asset == null) {
                    FileDeploymentUtils.materializeSubdirectories(entryDirectory, child);
                }
            }
        } catch (IOException e) {
            throw new DeploymentException("Could not materialize class path directory: " + archive.getName(), e);
        }
        materializedFiles.add(entryDirectory);
    }

    private List<String> buildProcessCommand(Properties properties) {
        final List<String> command = new ArrayList<>();
        final File javaHome = new File(System.getProperty(SYSPROP_KEY_JAVA_HOME));
        command.add(javaHome.getAbsolutePath() + File.separator + "bin" + File.separator + "java");
        if (getJavaMajorVersion() >= 9) {
            command.add("--add-modules");
            command.add("java.sql");
        }
        command.add("-cp");
        StringBuilder builder = new StringBuilder();
        Set<File> classPathEntries = new HashSet<>(materializedFiles);
        classPathEntries.addAll(classpathDependencies);
        for (Iterator<File> iterator = classPathEntries.iterator(); iterator.hasNext();) {
            builder.append(iterator.next().getPath());
            if (iterator.hasNext()) {
                builder.append(File.pathSeparator);
            }
        }
        command.add(builder.toString());
        command.add("-Dcom.sun.management.jmxremote");
        command.add("-Dcom.sun.management.jmxremote.port=" + port);
        command.add("-Dcom.sun.management.jmxremote.authenticate=false");
        command.add("-Dcom.sun.management.jmxremote.ssl=false");

        if (debugModeEnabled) {
            command.add(DEBUG_AGENT_STRING);
        }
        for (String option : additionalJavaOpts) {
            command.add(option);
        }
        if (properties != null) {
            for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                addSystemProperty(command, entry.getKey().toString(), entry.getValue().toString());
            }
        }
        command.add(SERVER_MAIN_CLASS_FQN);
        return command;
    }

    private void addSystemProperty(List<String> command, String key, String value) {
        command.add(SYSTEM_PROPERTY_SWITCH + key + EQUALS + value);
    }

    private void readJarFilesFromDirectory() throws DeploymentException {
        if (librariesPath == null) {
            return;
        }
        File lib = new File(librariesPath);
        if (!lib.exists() || lib.isFile()) {
            throw new DeploymentException("Cannot read files from " + librariesPath);
        }

        File[] dep = lib.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".jar");
            }
        });
        classpathDependencies.addAll(Arrays.asList(dep));

    }

    private void addTestResourcesDirectory(Properties properties) throws DeploymentException {
        String testResources = properties.getProperty("container.test.resources.dir");
        if (testResources != null) {
            File testDir = new File(testResources);
            if (testDir.exists() && testDir.isDirectory()) {
                classpathDependencies.add(testDir);
            }
        }
    }

    private void logExecutedCommand(List<String> processCommand) {
        if (LOGGER.isLoggable(Level.FINE)) {
            StringBuilder builder = new StringBuilder();
            for (String s : processCommand) {
                builder.append(s);
                builder.append(" ");
            }
            LOGGER.log(Level.FINE, "Executing command: " + builder);
        }
    }

    private static int getJavaMajorVersion() {
        String javaSpecVersion = System.getProperty("java.specification.version");
        if (javaSpecVersion.contains(".")) { //before jdk 9
            return Integer.parseInt(javaSpecVersion.split("\\.")[1]);
        } else {
            return Integer.parseInt(javaSpecVersion);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: tag
tag: work
---


text:
from    ubuntu:14.04
run     locale-gen en_US.UTF-8
env     LANG en_US.UTF-8
env     LANGUAGE en_US:en
env     LC_ALL en_US.UTF-8
run     apt-get update
run     apt-get install wget curl apt-transport-https -y --force-yes
run     wget http://github.com/leandrosouza/basebuilder/tarball/master -O basebuilder.tar.gz --no-check-certificate
run     mkdir /var/lib/tsuru
run     tar -xvf basebuilder.tar.gz -C /var/lib/tsuru --strip 1
run     cp /var/lib/tsuru/static/deploy /var/lib/tsuru
run     cp /var/lib/tsuru/base/start /var/lib/tsuru
run     curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash -
run     apt-get update
run     apt-get install ruby-full -y --force-yes
run     apt-get install nodejs -y --force-yes
run	apt-get install build-essential -y --force-yes
run     gem install sass compass
run     npm install gulp
run     /var/lib/tsuru/static/install


text:
class TabelaController < ApplicationController

	def index
	end

	def elemento
		#@curiosidade = Array.new
		@elemento = Elemento.find_by nome: params['element']
		@massa = @elemento.num_protons + @elemento.num_neutrons

	#	@where = 'nome = '+params['element']
#		@join =  ' JOIN curiosidade ON elementos.id = curiosidades.elemento'
	#	@curiosidade= Curiosidade.joins(@join).where(@where).select('texto as field_one').first
	end
end


text:
using System;
using System.Linq;
using System.Text;

namespace Berp
{
    class CallStackItem
    {
        private readonly CallStackItem parent;
        private readonly Rule rule;
        private readonly int position;

        public CallStackItem Parent
        {
            get { return parent; }
        }

        public CallStackItem(CallStackItem parent, Rule rule, int position = 0)
        {
            if (rule == null) throw new ArgumentNullException("rule");
            this.parent = parent;
            this.rule = rule;
            this.position = position;
        }

        public Rule Rule
        {
            get { return rule; }
        }

        public int Position
        {
            get { return position; }
        }

        public override string ToString()
        {
            var result = new StringBuilder();
            if (parent != null)
                result.AppendFormat("{0}>", parent);
            result.AppendFormat("{0}:{1}", rule.Name, position);
            return result.ToString();
        }

        protected bool Equals(CallStackItem other)
        {
            return Equals(parent, other.parent) && Equals(rule, other.rule) && position == other.position;
        }

        public static bool PositionAgnosticEquals(CallStackItem x, CallStackItem y)
        {
            return ((x.parent == null && y.parent == null) ||
                    (x.parent != null && y.parent != null && PositionAgnosticEquals(x.parent, y.parent))) &&
                    Equals(x.rule, y.rule);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != GetType()) return false;
            return Equals((CallStackItem) obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = (parent != null ? parent.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ (rule != null ? rule.GetHashCode() : 0);
                hashCode = (hashCode*397) ^ position;
                return hashCode;
            }
        }
    }
}


text:
AccessTest
====
C#からAccessファイル(*.accdb)をSQL文で操作するメモ

このプログラムを実行する場合はあらかじめ「Microsoft Access データベース エンジン 2010 再頒布可能コンポーネント」をインストールしておくこと。

- Download Microsoft Access データベース エンジン 2010 再頒布可能コンポーネント from Official Microsoft Download Center
    - https://www.microsoft.com/ja-jp/download/details.aspx?id=13255

Copyright and license
----
Copyright (c) 2015 yoggy

Released under the [MIT license](LICENSE.txt)


text:
/*
 * Beigesoft ™
 *
 * Licensed under the Apache License, Version 2.0
 *
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package org.beigesoft.uml.controller;

import org.beigesoft.uml.diagram.assembly.IAsmDiagramClassInteractive;

/**
 * Abstraction of a interactive class diagram maker
 *
 * @author Yury Demidenko
 */
public interface IControllerDiagramClass<ADUML extends IAsmDiagramClassInteractive<?, ?, ?, ?, PRI, ?>, PRI> extends IControllerDiagramUml<ADUML, PRI> {

  public void newDiagramFromJavaSource();

  public void addClassFromJavaSource();

  public void rearrange();

  public void adjustRelationsFor90Degree();

  public int evalCountClasses();

  public int evalCountRelationshipsBinaryClass();
}


text:
/* eslint-disable */

var webpack = require('webpack');
var webpackConfig = require('./make-webpack-config.js')({
  sourcemaps: true,
});

module.exports = function(config) {
  var browsers = [process.env.DEBUG ? 'Chrome' : 'PhantomJS'];

  config.set({
    autoWatch: true,
    browsers: browsers,
    singleRun: false,
    frameworks: ['mocha', 'chai-things', 'chai'],
    preprocessors: {
      'tests.webpack.js': ['webpack', 'sourcemap'],
    },
    files: [
      'node_modules/phantomjs-polyfill/bind-polyfill.js',
      'tests.webpack.js',
    ],
    reporters: ['dots'],
    webpack: webpackConfig,
    webpackServer: {
      noInfo: true,
    },
  });
};


text:
import {AUTO_STYLE, AnimationOptions, AnimationPlayer, NoopAnimationPlayer, ɵPRE_STYLE as PRE_STYLE, ɵStyleData} from '@angular/animations';

import {AnimationTimelineInstruction} from '../dsl/animation_timeline_instruction';
import {AnimationTransitionFactory} from '../dsl/animation_transition_factory';
import {AnimationTransitionInstruction} from '../dsl/animation_transition_instruction';
import {AnimationTrigger} from '../dsl/animation_trigger';
import {ElementInstructionMap} from '../dsl/element_instruction_map';
import {AnimationStyleNormalizer} from '../dsl/style_normalization/animation_style_normalizer';
import {ENTER_CLASSNAME, LEAVE_CLASSNAME, NG_ANIMATING_CLASSNAME, NG_ANIMATING_SELECTOR, NG_TRIGGER_CLASSNAME, NG_TRIGGER_SELECTOR, copyObj, eraseStyles, setStyles} from '../util';

import {AnimationDriver} from './animation_driver';
import {getOrSetAsInMap, listenOnPlayer, makeAnimationEvent, normalizeKeyframes, optimizeGroupPlayer} from './shared';

const QUEUED_CLASSNAME = 'ng-animate-queued';
const QUEUED_SELECTOR = '.ng-animate-queued';
const DISABLED_CLASSNAME = 'ng-animate-disabled';
const DISABLED_SELECTOR = '.ng-animate-disabled';

const EMPTY_PLAYER_ARRAY: TransitionAnimationPlayer[] = [];
const NULL_REMOVAL_STATE: ElementAnimationState = {
  namespaceId: '',
  setForRemoval: null,
  hasAnimation: false,
  removedBeforeQueried: false
};
const NULL_REMOVED_QUERIED_STATE: ElementAnimationState = {
  namespaceId: '',
  setForRemoval: null,
  hasAnimation: false,
  removedBeforeQueried: true
};

interface TriggerListener {
  name: string;
  phase: string;
  callback: (event: any) => any;
}

export interface QueueInstruction {
  element: any;
  triggerName: string;
  fromState: StateValue;
  toState: StateValue;
  transition: AnimationTransitionFactory;
  player: TransitionAnimationPlayer;
  isFallbackTransition: boolean;
}

export const REMOVAL_FLAG = '__ng_removed';

export interface ElementAnimationState {
  setForRemoval: any;
  hasAnimation: boolean;
  namespaceId: string;
  removedBeforeQueried: boolean;
}

export class StateValue {
  public value: string;
  public options: AnimationOptions;

  constructor(input: any) {
    const isObj = input && input.hasOwnProperty('value');
    const value = isObj ? input['value'] : input;
    this.value = normalizeTriggerValue(value);
    if (isObj) {
      const options = copyObj(input as any);
      delete options['value'];
      this.options = options as AnimationOptions;
    } else {
      this.options = {};
    }
    if (!this.options.params) {
      this.options.params = {};
    }
  }

  absorbOptions(options: AnimationOptions) {
    const newParams = options.params;
    if (newParams) {
      const oldParams = this.options.params !;
      Object.keys(newParams).forEach(prop => {
        if (oldParams[prop] == null) {
          oldParams[prop] = newParams[prop];
        }
      });
    }
  }
}

export const VOID_VALUE = 'void';
export const DEFAULT_STATE_VALUE = new StateValue(VOID_VALUE);
export const DELETED_STATE_VALUE = new StateValue('DELETED');

export class AnimationTransitionNamespace {
  public players: TransitionAnimationPlayer[] = [];

  private _triggers: {[triggerName: string]: AnimationTrigger} = {};
  private _queue: QueueInstruction[] = [];

  private _elementListeners = new Map<any, TriggerListener[]>();

  private _hostClassName: string;

  constructor(
      public id: string, public hostElement: any, private _engine: TransitionAnimationEngine) {
    this._hostClassName = 'ng-tns-' + id;
    addClass(hostElement, this._hostClassName);
  }

  listen(element: any, name: string, phase: string, callback: (event: any) => boolean): () => any {
    if (!this._triggers.hasOwnProperty(name)) {
      throw new Error(
          `Unable to listen on the animation trigger event "${phase}" because the animation trigger "${name}" doesn\'t exist!`);
    }

    if (phase == null || phase.length == 0) {
      throw new Error(
          `Unable to listen on the animation trigger "${name}" because the provided event is undefined!`);
    }

    if (!isTriggerEventValid(phase)) {
      throw new Error(
          `The provided animation trigger event "${phase}" for the animation trigger "${name}" is not supported!`);
    }

    const listeners = getOrSetAsInMap(this._elementListeners, element, []);
    const data = {name, phase, callback};
    listeners.push(data);

    const triggersWithStates = getOrSetAsInMap(this._engine.statesByElement, element, {});
    if (!triggersWithStates.hasOwnProperty(name)) {
      addClass(element, NG_TRIGGER_CLASSNAME);
      addClass(element, NG_TRIGGER_CLASSNAME + '-' + name);
      triggersWithStates[name] = null;
    }

    return () => {
      // the event listener is removed AFTER the flush has occurred such
      // that leave animations callbacks can fire (otherwise if the node
      // is removed in between then the listeners would be deregistered)
      this._engine.afterFlush(() => {
        const index = listeners.indexOf(data);
        if (index >= 0) {
          listeners.splice(index, 1);
        }

        if (!this._triggers[name]) {
          delete triggersWithStates[name];
        }
      });
    };
  }

  register(name: string, ast: AnimationTrigger): boolean {
    if (this._triggers[name]) {
      // throw
      return false;
    } else {
      this._triggers[name] = ast;
      return true;
    }
  }

  private _getTrigger(name: string) {
    const trigger = this._triggers[name];
    if (!trigger) {
      throw new Error(`The provided animation trigger "${name}" has not been registered!`);
    }
    return trigger;
  }

  trigger(element: any, triggerName: string, value: any, defaultToFallback: boolean = true):
      TransitionAnimationPlayer|undefined {
    const trigger = this._getTrigger(triggerName);
    const player = new TransitionAnimationPlayer(this.id, triggerName, element);

    let triggersWithStates = this._engine.statesByElement.get(element);
    if (!triggersWithStates) {
      addClass(element, NG_TRIGGER_CLASSNAME);
      addClass(element, NG_TRIGGER_CLASSNAME + '-' + triggerName);
      this._engine.statesByElement.set(element, triggersWithStates = {});
    }

    let fromState = triggersWithStates[triggerName];
    const toState = new StateValue(value);

    const isObj = value && value.hasOwnProperty('value');
    if (!isObj && fromState) {
      toState.absorbOptions(fromState.options);
    }

    triggersWithStates[triggerName] = toState;

    if (!fromState) {
      fromState = DEFAULT_STATE_VALUE;
    } else if (fromState === DELETED_STATE_VALUE) {
      return player;
    }

    const isRemoval = toState.value === VOID_VALUE;

    // normally this isn't reached by here, however, if an object expression
    // is passed in then it may be a new object each time. Comparing the value
    // is important since that will stay the same despite there being a new object.
    // The removal arc here is special cased because the same element is triggered
    // twice in the event that it contains animations on the outer/inner portions
    // of the host container
    if (!isRemoval && fromState.value === toState.value) return;

    const playersOnElement: TransitionAnimationPlayer[] =
        getOrSetAsInMap(this._engine.playersByElement, element, []);
    playersOnElement.forEach(player => {
      // only remove the player if it is queued on the EXACT same trigger/namespace
      // we only also deal with queued players here because if the animation has
      // started then we want to keep the player alive until the flush happens
      // (which is where the previousPlayers are passed into the new palyer)
      if (player.namespaceId == this.id && player.triggerName == triggerName && player.queued) {
        player.destroy();
      }
    });

    let transition = trigger.matchTransition(fromState.value, toState.value);
    let isFallbackTransition = false;
    if (!transition) {
      if (!defaultToFallback) return;
      transition = trigger.fallbackTransition;
      isFallbackTransition = true;
    }

    this._engine.totalQueuedPlayers++;
    this._queue.push(
        {element, triggerName, transition, fromState, toState, player, isFallbackTransition});

    if (!isFallbackTransition) {
      addClass(element, QUEUED_CLASSNAME);
      player.onStart(() => { removeClass(element, QUEUED_CLASSNAME); });
    }

    player.onDone(() => {
      let index = this.players.indexOf(player);
      if (index >= 0) {
        this.players.splice(index, 1);
      }

      const players = this._engine.playersByElement.get(element);
      if (players) {
        let index = players.indexOf(player);
        if (index >= 0) {
          players.splice(index, 1);
        }
      }
    });

    this.players.push(player);
    playersOnElement.push(player);

    return player;
  }

  deregister(name: string) {
    delete this._triggers[name];

    this._engine.statesByElement.forEach((stateMap, element) => { delete stateMap[name]; });

    this._elementListeners.forEach((listeners, element) => {
      this._elementListeners.set(
          element, listeners.filter(entry => { return entry.name != name; }));
    });
  }

  clearElementCache(element: any) {
    this._engine.statesByElement.delete(element);
    this._elementListeners.delete(element);
    const elementPlayers = this._engine.playersByElement.get(element);
    if (elementPlayers) {
      elementPlayers.forEach(player => player.destroy());
      this._engine.playersByElement.delete(element);
    }
  }

  private _destroyInnerNodes(rootElement: any, context: any, animate: boolean = false) {
    this._engine.driver.query(rootElement, NG_TRIGGER_SELECTOR, true).forEach(elm => {
      if (animate && containsClass(elm, this._hostClassName)) {
        const innerNs = this._engine.namespacesByHostElement.get(elm);

        // special case for a host element with animations on the same element
        if (innerNs) {
          innerNs.removeNode(elm, context, true);
        }

        this.removeNode(elm, context, true);
      } else {
        this.clearElementCache(elm);
      }
    });
  }

  removeNode(element: any, context: any, doNotRecurse?: boolean): void {
    const engine = this._engine;

    if (!doNotRecurse && element.childElementCount) {
      this._destroyInnerNodes(element, context, true);
    }

    const triggerStates = engine.statesByElement.get(element);
    if (triggerStates) {
      const players: TransitionAnimationPlayer[] = [];
      Object.keys(triggerStates).forEach(triggerName => {
        // this check is here in the event that an element is removed
        // twice (both on the host level and the component level)
        if (this._triggers[triggerName]) {
          const player = this.trigger(element, triggerName, VOID_VALUE, false);
          if (player) {
            players.push(player);
          }
        }
      });

      if (players.length) {
        engine.markElementAsRemoved(this.id, element, true, context);
        optimizeGroupPlayer(players).onDone(() => engine.processLeaveNode(element));
        return;
      }
    }

    // find the player that is animating and make sure that the
    // removal is delayed until that player has completed
    let containsPotentialParentTransition = false;
    if (engine.totalAnimations) {
      const currentPlayers =
          engine.players.length ? engine.playersByQueriedElement.get(element) : [];

      // when this `if statement` does not continue forward it means that
      // a previous animation query has selected the current element and
      // is animating it. In this situation want to continue fowards and
      // allow the element to be queued up for animation later.
      if (currentPlayers && currentPlayers.length) {
        containsPotentialParentTransition = true;
      } else {
        let parent = element;
        while (parent = parent.parentNode) {
          const triggers = engine.statesByElement.get(parent);
          if (triggers) {
            containsPotentialParentTransition = true;
            break;
          }
        }
      }
    }

    // at this stage we know that the element will either get removed
    // during flush or will be picked up by a parent query. Either way
    // we need to fire the listeners for this element when it DOES get
    // removed (once the query parent animation is done or after flush)
    const listeners = this._elementListeners.get(element);
    if (listeners) {
      const visitedTriggers = new Set<string>();
      listeners.forEach(listener => {
        const triggerName = listener.name;
        if (visitedTriggers.has(triggerName)) return;
        visitedTriggers.add(triggerName);

        const trigger = this._triggers[triggerName];
        const transition = trigger.fallbackTransition;
        const elementStates = engine.statesByElement.get(element) !;
        const fromState = elementStates[triggerName] || DEFAULT_STATE_VALUE;
        const toState = new StateValue(VOID_VALUE);
        const player = new TransitionAnimationPlayer(this.id, triggerName, element);

        this._engine.totalQueuedPlayers++;
        this._queue.push({
          element,
          triggerName,
          transition,
          fromState,
          toState,
          player,
          isFallbackTransition: true
        });
      });
    }

    // whether or not a parent has an animation we need to delay the deferral of the leave
    // operation until we have more information (which we do after flush() has been called)
    if (containsPotentialParentTransition) {
      engine.markElementAsRemoved(this.id, element, false, context);
    } else {
      // we do this after the flush has occurred such
      // that the callbacks can be fired
      engine.afterFlush(() => this.clearElementCache(element));
      engine.destroyInnerAnimations(element);
      engine._onRemovalComplete(element, context);
    }
  }

  insertNode(element: any, parent: any): void { addClass(element, this._hostClassName); }

  drainQueuedTransitions(microtaskId: number): QueueInstruction[] {
    const instructions: QueueInstruction[] = [];
    this._queue.forEach(entry => {
      const player = entry.player;
      if (player.destroyed) return;

      const element = entry.element;
      const listeners = this._elementListeners.get(element);
      if (listeners) {
        listeners.forEach((listener: TriggerListener) => {
          if (listener.name == entry.triggerName) {
            const baseEvent = makeAnimationEvent(
                element, entry.triggerName, entry.fromState.value, entry.toState.value);
            (baseEvent as any)['_data'] = microtaskId;
            listenOnPlayer(entry.player, listener.phase, baseEvent, listener.callback);
          }
        });
      }

      if (player.markedForDestroy) {
        this._engine.afterFlush(() => {
          // now we can destroy the element properly since the event listeners have
          // been bound to the player
          player.destroy();
        });
      } else {
        instructions.push(entry);
      }
    });

    this._queue = [];

    return instructions.sort((a, b) => {
      // if depCount == 0 them move to front
      // otherwise if a contains b then move back
      const d0 = a.transition.ast.depCount;
      const d1 = b.transition.ast.depCount;
      if (d0 == 0 || d1 == 0) {
        return d0 - d1;
      }
      return this._engine.driver.containsElement(a.element, b.element) ? 1 : -1;
    });
  }

  destroy(context: any) {
    this.players.forEach(p => p.destroy());
    this._destroyInnerNodes(this.hostElement, context);
  }

  elementContainsData(element: any): boolean {
    let containsData = false;
    if (this._elementListeners.has(element)) containsData = true;
    containsData =
        (this._queue.find(entry => entry.element === element) ? true : false) || containsData;
    return containsData;
  }
}

export interface QueuedTransition {
  element: any;
  instruction: AnimationTransitionInstruction;
  player: TransitionAnimationPlayer;
}

export class TransitionAnimationEngine {
  public players: TransitionAnimationPlayer[] = [];
  public newHostElements = new Map<any, AnimationTransitionNamespace>();
  public playersByElement = new Map<any, TransitionAnimationPlayer[]>();
  public playersByQueriedElement = new Map<any, TransitionAnimationPlayer[]>();
  public statesByElement = new Map<any, {[triggerName: string]: StateValue}>();
  public disabledNodes = new Set<any>();

  public totalAnimations = 0;
  public totalQueuedPlayers = 0;

  private _namespaceLookup: {[id: string]: AnimationTransitionNamespace} = {};
  private _namespaceList: AnimationTransitionNamespace[] = [];
  private _flushFns: (() => any)[] = [];
  private _whenQuietFns: (() => any)[] = [];

  public namespacesByHostElement = new Map<any, AnimationTransitionNamespace>();
  public collectedEnterElements: any[] = [];
  public collectedLeaveElements: any[] = [];

  // this method is designed to be overridden by the code that uses this engine
  public onRemovalComplete = (element: any, context: any) => {};

  _onRemovalComplete(element: any, context: any) { this.onRemovalComplete(element, context); }

  constructor(public driver: AnimationDriver, private _normalizer: AnimationStyleNormalizer) {}

  get queuedPlayers(): TransitionAnimationPlayer[] {
    const players: TransitionAnimationPlayer[] = [];
    this._namespaceList.forEach(ns => {
      ns.players.forEach(player => {
        if (player.queued) {
          players.push(player);
        }
      });
    });
    return players;
  }

  createNamespace(namespaceId: string, hostElement: any) {
    const ns = new AnimationTransitionNamespace(namespaceId, hostElement, this);
    if (hostElement.parentNode) {
      this._balanceNamespaceList(ns, hostElement);
    } else {
      // defer this later until flush during when the host element has
      // been inserted so that we know exactly where to place it in
      // the namespace list
      this.newHostElements.set(hostElement, ns);

      // given that this host element is apart of the animation code, it
      // may or may not be inserted by a parent node that is an of an
      // animation renderer type. If this happens then we can still have
      // access to this item when we query for :enter nodes. If the parent
      // is a renderer then the set data-structure will normalize the entry
      this.collectEnterElement(hostElement);
    }
    return this._namespaceLookup[namespaceId] = ns;
  }

  private _balanceNamespaceList(ns: AnimationTransitionNamespace, hostElement: any) {
    const limit = this._namespaceList.length - 1;
    if (limit >= 0) {
      let found = false;
      for (let i = limit; i >= 0; i--) {
        const nextNamespace = this._namespaceList[i];
        if (this.driver.containsElement(nextNamespace.hostElement, hostElement)) {
          this._namespaceList.splice(i + 1, 0, ns);
          found = true;
          break;
        }
      }
      if (!found) {
        this._namespaceList.splice(0, 0, ns);
      }
    } else {
      this._namespaceList.push(ns);
    }

    this.namespacesByHostElement.set(hostElement, ns);
    return ns;
  }

  register(namespaceId: string, hostElement: any) {
    let ns = this._namespaceLookup[namespaceId];
    if (!ns) {
      ns = this.createNamespace(namespaceId, hostElement);
    }
    return ns;
  }

  registerTrigger(namespaceId: string, name: string, trigger: AnimationTrigger) {
    let ns = this._namespaceLookup[namespaceId];
    if (ns && ns.register(name, trigger)) {
      this.totalAnimations++;
    }
  }

  destroy(namespaceId: string, context: any) {
    if (!namespaceId) return;

    const ns = this._fetchNamespace(namespaceId);

    this.afterFlush(() => {
      this.namespacesByHostElement.delete(ns.hostElement);
      delete this._namespaceLookup[namespaceId];
      const index = this._namespaceList.indexOf(ns);
      if (index >= 0) {
        this._namespaceList.splice(index, 1);
      }
    });

    this.afterFlushAnimationsDone(() => ns.destroy(context));
  }

  private _fetchNamespace(id: string) { return this._namespaceLookup[id]; }

  trigger(namespaceId: string, element: any, name: string, value: any): boolean {
    if (isElementNode(element)) {
      this._fetchNamespace(namespaceId).trigger(element, name, value);
      return true;
    }
    return false;
  }

  insertNode(namespaceId: string, element: any, parent: any, insertBefore: boolean): void {
    if (!isElementNode(element)) return;

    // special case for when an element is removed and reinserted (move operation)
    // when this occurs we do not want to use the element for deletion later
    const details = element[REMOVAL_FLAG] as ElementAnimationState;
    if (details && details.setForRemoval) {
      details.setForRemoval = false;
    }

    // in the event that the namespaceId is blank then the caller
    // code does not contain any animation code in it, but it is
    // just being called so that the node is marked as being inserted
    if (namespaceId) {
      this._fetchNamespace(namespaceId).insertNode(element, parent);
    }

    // only *directives and host elements are inserted before
    if (insertBefore) {
      this.collectEnterElement(element);
    }
  }

  collectEnterElement(element: any) { this.collectedEnterElements.push(element); }

  markElementAsDisabled(element: any, value: boolean) {
    if (value) {
      if (!this.disabledNodes.has(element)) {
        this.disabledNodes.add(element);
        addClass(element, DISABLED_CLASSNAME);
      }
    } else if (this.disabledNodes.has(element)) {
      this.disabledNodes.delete(element);
      removeClass(element, DISABLED_CLASSNAME);
    }
  }

  removeNode(namespaceId: string, element: any, context: any, doNotRecurse?: boolean): void {
    if (!isElementNode(element)) {
      this._onRemovalComplete(element, context);
      return;
    }

    const ns = namespaceId ? this._fetchNamespace(namespaceId) : null;
    if (ns) {
      ns.removeNode(element, context, doNotRecurse);
    } else {
      this.markElementAsRemoved(namespaceId, element, false, context);
    }
  }

  markElementAsRemoved(namespaceId: string, element: any, hasAnimation?: boolean, context?: any) {
    this.collectedLeaveElements.push(element);
    element[REMOVAL_FLAG] = {
      namespaceId,
      setForRemoval: context, hasAnimation,
      removedBeforeQueried: false
    };
  }

  listen(
      namespaceId: string, element: any, name: string, phase: string,
      callback: (event: any) => boolean): () => any {
    if (isElementNode(element)) {
      return this._fetchNamespace(namespaceId).listen(element, name, phase, callback);
    }
    return () => {};
  }

  private _buildInstruction(entry: QueueInstruction, subTimelines: ElementInstructionMap) {
    return entry.transition.build(
        this.driver, entry.element, entry.fromState.value, entry.toState.value,
        entry.toState.options, subTimelines);
  }

  destroyInnerAnimations(containerElement: any) {
    let elements = this.driver.query(containerElement, NG_TRIGGER_SELECTOR, true);
    elements.forEach(element => {
      const players = this.playersByElement.get(element);
      if (players) {
        players.forEach(player => {
          // special case for when an element is set for destruction, but hasn't started.
          // in this situation we want to delay the destruction until the flush occurs
          // so that any event listeners attached to the player are triggered.
          if (player.queued) {
            player.markedForDestroy = true;
          } else {
            player.destroy();
          }
        });
      }
      const stateMap = this.statesByElement.get(element);
      if (stateMap) {
        Object.keys(stateMap).forEach(triggerName => stateMap[triggerName] = DELETED_STATE_VALUE);
      }
    });

    if (this.playersByQueriedElement.size == 0) return;

    elements = this.driver.query(containerElement, NG_ANIMATING_SELECTOR, true);
    if (elements.length) {
      elements.forEach(element => {
        const players = this.playersByQueriedElement.get(element);
        if (players) {
          players.forEach(player => player.finish());
        }
      });
    }
  }

  whenRenderingDone(): Promise<any> {
    return new Promise(resolve => {
      if (this.players.length) {
        return optimizeGroupPlayer(this.players).onDone(() => resolve());
      } else {
        resolve();
      }
    });
  }

  processLeaveNode(element: any) {
    const details = element[REMOVAL_FLAG] as ElementAnimationState;
    if (details && details.setForRemoval) {
      // this will prevent it from removing it twice
      element[REMOVAL_FLAG] = NULL_REMOVAL_STATE;
      if (details.namespaceId) {
        this.destroyInnerAnimations(element);
        const ns = this._fetchNamespace(details.namespaceId);
        if (ns) {
          ns.clearElementCache(element);
        }
      }
      this._onRemovalComplete(element, details.setForRemoval);
    }

    if (this.driver.matchesElement(element, DISABLED_SELECTOR)) {
      this.markElementAsDisabled(element, false);
    }

    this.driver.query(element, DISABLED_SELECTOR, true).forEach(node => {
      this.markElementAsDisabled(element, false);
    });
  }

  flush(microtaskId: number = -1) {
    let players: AnimationPlayer[] = [];
    if (this.newHostElements.size) {
      this.newHostElements.forEach((ns, element) => this._balanceNamespaceList(ns, element));
      this.newHostElements.clear();
    }

    if (this._namespaceList.length &&
        (this.totalQueuedPlayers || this.collectedLeaveElements.length)) {
      const cleanupFns: Function[] = [];
      try {
        players = this._flushAnimations(cleanupFns, microtaskId);
      } finally {
        for (let i = 0; i < cleanupFns.length; i++) {
          cleanupFns[i]();
        }
      }
    } else {
      for (let i = 0; i < this.collectedLeaveElements.length; i++) {
        const element = this.collectedLeaveElements[i];
        this.processLeaveNode(element);
      }
    }

    this.totalQueuedPlayers = 0;
    this.collectedEnterElements.length = 0;
    this.collectedLeaveElements.length = 0;
    this._flushFns.forEach(fn => fn());
    this._flushFns = [];

    if (this._whenQuietFns.length) {
      // we move these over to a variable so that
      // if any new callbacks are registered in another
      // flush they do not populate the existing set
      const quietFns = this._whenQuietFns;
      this._whenQuietFns = [];

      if (players.length) {
        optimizeGroupPlayer(players).onDone(() => { quietFns.forEach(fn => fn()); });
      } else {
        quietFns.forEach(fn => fn());
      }
    }
  }

  private _flushAnimations(cleanupFns: Function[], microtaskId: number):
      TransitionAnimationPlayer[] {
    const subTimelines = new ElementInstructionMap();
    const skippedPlayers: TransitionAnimationPlayer[] = [];
    const skippedPlayersMap = new Map<any, AnimationPlayer[]>();
    const queuedInstructions: QueuedTransition[] = [];
    const queriedElements = new Map<any, TransitionAnimationPlayer[]>();
    const allPreStyleElements = new Map<any, Set<string>>();
    const allPostStyleElements = new Map<any, Set<string>>();

    const disabledElementsSet = new Set<any>();
    this.disabledNodes.forEach(node => {
      const nodesThatAreDisabled = this.driver.query(node, QUEUED_SELECTOR, true);
      for (let i = 0; i < nodesThatAreDisabled.length; i++) {
        disabledElementsSet.add(nodesThatAreDisabled[i]);
      }
    });

    const bodyNode = getBodyNode();
    const allEnterNodes: any[] = this.collectedEnterElements.length ?
        this.collectedEnterElements.filter(createIsRootFilterFn(this.collectedEnterElements)) :
        [];

    // this must occur before the instructions are built below such that
    // the :enter queries match the elements (since the timeline queries
    // are fired during instruction building).
    for (let i = 0; i < allEnterNodes.length; i++) {
      addClass(allEnterNodes[i], ENTER_CLASSNAME);
    }

    const allLeaveNodes: any[] = [];
    const leaveNodesWithoutAnimations: any[] = [];
    for (let i = 0; i < this.collectedLeaveElements.length; i++) {
      const element = this.collectedLeaveElements[i];
      const details = element[REMOVAL_FLAG] as ElementAnimationState;
      if (details && details.setForRemoval) {
        addClass(element, LEAVE_CLASSNAME);
        allLeaveNodes.push(element);
        if (!details.hasAnimation) {
          leaveNodesWithoutAnimations.push(element);
        }
      }
    }

    cleanupFns.push(() => {
      allEnterNodes.forEach(element => removeClass(element, ENTER_CLASSNAME));
      allLeaveNodes.forEach(element => {
        removeClass(element, LEAVE_CLASSNAME);
        this.processLeaveNode(element);
      });
    });

    const allPlayers: TransitionAnimationPlayer[] = [];
    const erroneousTransitions: AnimationTransitionInstruction[] = [];
    for (let i = this._namespaceList.length - 1; i >= 0; i--) {
      const ns = this._namespaceList[i];
      ns.drainQueuedTransitions(microtaskId).forEach(entry => {
        const player = entry.player;
        allPlayers.push(player);

        const element = entry.element;
        if (!bodyNode || !this.driver.containsElement(bodyNode, element)) {
          player.destroy();
          return;
        }

        const instruction = this._buildInstruction(entry, subTimelines) !;
        if (instruction.errors && instruction.errors.length) {
          erroneousTransitions.push(instruction);
          return;
        }

        // if a unmatched transition is queued to go then it SHOULD NOT render
        // an animation and cancel the previously running animations.
        if (entry.isFallbackTransition) {
          player.onStart(() => eraseStyles(element, instruction.fromStyles));
          player.onDestroy(() => setStyles(element, instruction.toStyles));
          skippedPlayers.push(player);
          return;
        }

        // this means that if a parent animation uses this animation as a sub trigger
        // then it will instruct the timeline builder to not add a player delay, but
        // instead stretch the first keyframe gap up until the animation starts. The
        // reason this is important is to prevent extra initialization styles from being
        // required by the user in the animation.
        instruction.timelines.forEach(tl => tl.stretchStartingKeyframe = true);

        subTimelines.append(element, instruction.timelines);

        const tuple = {instruction, player, element};

        queuedInstructions.push(tuple);

        instruction.queriedElements.forEach(
            element => getOrSetAsInMap(queriedElements, element, []).push(player));

        instruction.preStyleProps.forEach((stringMap, element) => {
          const props = Object.keys(stringMap);
          if (props.length) {
            let setVal: Set<string> = allPreStyleElements.get(element) !;
            if (!setVal) {
              allPreStyleElements.set(element, setVal = new Set<string>());
            }
            props.forEach(prop => setVal.add(prop));
          }
        });

        instruction.postStyleProps.forEach((stringMap, element) => {
          const props = Object.keys(stringMap);
          let setVal: Set<string> = allPostStyleElements.get(element) !;
          if (!setVal) {
            allPostStyleElements.set(element, setVal = new Set<string>());
          }
          props.forEach(prop => setVal.add(prop));
        });
      });
    }

    if (erroneousTransitions.length) {
      let msg = `Unable to process animations due to the following failed trigger transitions\n`;
      erroneousTransitions.forEach(instruction => {
        msg += `@${instruction.triggerName} has failed due to:\n`;
        instruction.errors !.forEach(error => { msg += `- ${error}\n`; });
      });

      allPlayers.forEach(player => player.destroy());
      throw new Error(msg);
    }

    // these can only be detected here since we have a map of all the elements
    // that have animations attached to them...
    const enterNodesWithoutAnimations: any[] = [];
    for (let i = 0; i < allEnterNodes.length; i++) {
      const element = allEnterNodes[i];
      if (!subTimelines.has(element)) {
        enterNodesWithoutAnimations.push(element);
      }
    }

    const allPreviousPlayersMap = new Map<any, TransitionAnimationPlayer[]>();
    let sortedParentElements: any[] = [];
    queuedInstructions.forEach(entry => {
      const element = entry.element;
      if (subTimelines.has(element)) {
        sortedParentElements.unshift(element);
        this._beforeAnimationBuild(
            entry.player.namespaceId, entry.instruction, allPreviousPlayersMap);
      }
    });

    skippedPlayers.forEach(player => {
      const element = player.element;
      const previousPlayers =
          this._getPreviousPlayers(element, false, player.namespaceId, player.triggerName, null);
      previousPlayers.forEach(
          prevPlayer => { getOrSetAsInMap(allPreviousPlayersMap, element, []).push(prevPlayer); });
    });

    allPreviousPlayersMap.forEach(players => players.forEach(player => player.destroy()));

    // PRE STAGE: fill the ! styles
    const preStylesMap = allPreStyleElements.size ?
        cloakAndComputeStyles(
            this.driver, enterNodesWithoutAnimations, allPreStyleElements, PRE_STYLE) :
        new Map<any, ɵStyleData>();

    // POST STAGE: fill the * styles
    const postStylesMap = cloakAndComputeStyles(
        this.driver, leaveNodesWithoutAnimations, allPostStyleElements, AUTO_STYLE);

    const rootPlayers: TransitionAnimationPlayer[] = [];
    const subPlayers: TransitionAnimationPlayer[] = [];
    queuedInstructions.forEach(entry => {
      const {element, player, instruction} = entry;
      // this means that it was never consumed by a parent animation which
      // means that it is independent and therefore should be set for animation
      if (subTimelines.has(element)) {
        if (disabledElementsSet.has(element)) {
          skippedPlayers.push(player);
          return;
        }

        const innerPlayer = this._buildAnimation(
            player.namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap,
            postStylesMap);
        player.setRealPlayer(innerPlayer);

        let parentHasPriority: any = null;
        for (let i = 0; i < sortedParentElements.length; i++) {
          const parent = sortedParentElements[i];
          if (parent === element) break;
          if (this.driver.containsElement(parent, element)) {
            parentHasPriority = parent;
            break;
          }
        }

        if (parentHasPriority) {
          const parentPlayers = this.playersByElement.get(parentHasPriority);
          if (parentPlayers && parentPlayers.length) {
            player.parentPlayer = optimizeGroupPlayer(parentPlayers);
          }
          skippedPlayers.push(player);
        } else {
          rootPlayers.push(player);
        }
      } else {
        eraseStyles(element, instruction.fromStyles);
        player.onDestroy(() => setStyles(element, instruction.toStyles));
        subPlayers.push(player);
      }
    });

    subPlayers.forEach(player => {
      const playersForElement = skippedPlayersMap.get(player.element);
      if (playersForElement && playersForElement.length) {
        const innerPlayer = optimizeGroupPlayer(playersForElement);
        player.setRealPlayer(innerPlayer);
      }
    });

    // the reason why we don't actually play the animation is
    // because all that a skipped player is designed to do is to
    // fire the start/done transition callback events
    skippedPlayers.forEach(player => {
      if (player.parentPlayer) {
        player.parentPlayer.onDestroy(() => player.destroy());
      } else {
        player.destroy();
      }
    });

    // run through all of the queued removals and see if they
    // were picked up by a query. If not then perform the removal
    // operation right away unless a parent animation is ongoing.
    for (let i = 0; i < allLeaveNodes.length; i++) {
      const element = allLeaveNodes[i];
      const details = element[REMOVAL_FLAG] as ElementAnimationState;
      removeClass(element, LEAVE_CLASSNAME);

      // this means the element has a removal animation that is being
      // taken care of and therefore the inner elements will hang around
      // until that animation is over (or the parent queried animation)
      if (details && details.hasAnimation) continue;

      let players: AnimationPlayer[] = [];

      // if this element is queried or if it contains queried children
      // then we want for the element not to be removed from the page
      // until the queried animations have finished
      if (queriedElements.size) {
        let queriedPlayerResults = queriedElements.get(element);
        if (queriedPlayerResults && queriedPlayerResults.length) {
          players.push(...queriedPlayerResults);
        }

        let queriedInnerElements = this.driver.query(element, NG_ANIMATING_SELECTOR, true);
        for (let j = 0; j < queriedInnerElements.length; j++) {
          let queriedPlayers = queriedElements.get(queriedInnerElements[j]);
          if (queriedPlayers && queriedPlayers.length) {
            players.push(...queriedPlayers);
          }
        }
      }
      if (players.length) {
        removeNodesAfterAnimationDone(this, element, players);
      } else {
        this.processLeaveNode(element);
      }
    }

    // this is required so the cleanup method doesn't remove them
    allLeaveNodes.length = 0;

    rootPlayers.forEach(player => {
      this.players.push(player);
      player.onDone(() => {
        player.destroy();

        const index = this.players.indexOf(player);
        this.players.splice(index, 1);
      });
      player.play();
    });

    return rootPlayers;
  }

  elementContainsData(namespaceId: string, element: any) {
    let containsData = false;
    const details = element[REMOVAL_FLAG] as ElementAnimationState;
    if (details && details.setForRemoval) containsData = true;
    if (this.playersByElement.has(element)) containsData = true;
    if (this.playersByQueriedElement.has(element)) containsData = true;
    if (this.statesByElement.has(element)) containsData = true;
    return this._fetchNamespace(namespaceId).elementContainsData(element) || containsData;
  }

  afterFlush(callback: () => any) { this._flushFns.push(callback); }

  afterFlushAnimationsDone(callback: () => any) { this._whenQuietFns.push(callback); }

  private _getPreviousPlayers(
      element: string, isQueriedElement: boolean, namespaceId?: string, triggerName?: string,
      toStateValue?: any): TransitionAnimationPlayer[] {
    let players: TransitionAnimationPlayer[] = [];
    if (isQueriedElement) {
      const queriedElementPlayers = this.playersByQueriedElement.get(element);
      if (queriedElementPlayers) {
        players = queriedElementPlayers;
      }
    } else {
      const elementPlayers = this.playersByElement.get(element);
      if (elementPlayers) {
        const isRemovalAnimation = !toStateValue || toStateValue == VOID_VALUE;
        elementPlayers.forEach(player => {
          if (player.queued) return;
          if (!isRemovalAnimation && player.triggerName != triggerName) return;
          players.push(player);
        });
      }
    }
    if (namespaceId || triggerName) {
      players = players.filter(player => {
        if (namespaceId && namespaceId != player.namespaceId) return false;
        if (triggerName && triggerName != player.triggerName) return false;
        return true;
      });
    }
    return players;
  }

  private _beforeAnimationBuild(
      namespaceId: string, instruction: AnimationTransitionInstruction,
      allPreviousPlayersMap: Map<any, TransitionAnimationPlayer[]>) {
    // it's important to do this step before destroying the players
    // so that the onDone callback below won't fire before this
    eraseStyles(instruction.element, instruction.fromStyles);

    const triggerName = instruction.triggerName;
    const rootElement = instruction.element;

    // when a removal animation occurs, ALL previous players are collected
    // and destroyed (even if they are outside of the current namespace)
    const targetNameSpaceId: string|undefined =
        instruction.isRemovalTransition ? undefined : namespaceId;
    const targetTriggerName: string|undefined =
        instruction.isRemovalTransition ? undefined : triggerName;

    instruction.timelines.map(timelineInstruction => {
      const element = timelineInstruction.element;
      const isQueriedElement = element !== rootElement;
      const players = getOrSetAsInMap(allPreviousPlayersMap, element, []);
      const previousPlayers = this._getPreviousPlayers(
          element, isQueriedElement, targetNameSpaceId, targetTriggerName, instruction.toState);
      previousPlayers.forEach(player => {
        const realPlayer = player.getRealPlayer() as any;
        if (realPlayer.beforeDestroy) {
          realPlayer.beforeDestroy();
        }
        players.push(player);
      });
    });
  }

  private _buildAnimation(
      namespaceId: string, instruction: AnimationTransitionInstruction,
      allPreviousPlayersMap: Map<any, TransitionAnimationPlayer[]>,
      skippedPlayersMap: Map<any, AnimationPlayer[]>, preStylesMap: Map<any, ɵStyleData>,
      postStylesMap: Map<any, ɵStyleData>): AnimationPlayer {
    const triggerName = instruction.triggerName;
    const rootElement = instruction.element;

    // we first run this so that the previous animation player
    // data can be passed into the successive animation players
    const allQueriedPlayers: TransitionAnimationPlayer[] = [];
    const allConsumedElements = new Set<any>();
    const allSubElements = new Set<any>();
    const allNewPlayers = instruction.timelines.map(timelineInstruction => {
      const element = timelineInstruction.element;
      allConsumedElements.add(element);

      // FIXME (matsko): make sure to-be-removed animations are removed properly
      const details = element[REMOVAL_FLAG];
      if (details && details.removedBeforeQueried) return new NoopAnimationPlayer();

      const isQueriedElement = element !== rootElement;
      const previousPlayers =
          (allPreviousPlayersMap.get(element) || EMPTY_PLAYER_ARRAY).map(p => p.getRealPlayer());

      const preStyles = preStylesMap.get(element);
      const postStyles = postStylesMap.get(element);
      const keyframes = normalizeKeyframes(
          this.driver, this._normalizer, element, timelineInstruction.keyframes, preStyles,
          postStyles);
      const player = this._buildPlayer(timelineInstruction, keyframes, previousPlayers);

      // this means that this particular player belongs to a sub trigger. It is
      // important that we match this player up with the corresponding (@trigger.listener)
      if (timelineInstruction.subTimeline && skippedPlayersMap) {
        allSubElements.add(element);
      }

      if (isQueriedElement) {
        const wrappedPlayer = new TransitionAnimationPlayer(namespaceId, triggerName, element);
        wrappedPlayer.setRealPlayer(player);
        allQueriedPlayers.push(wrappedPlayer);
      }

      return player;
    });

    allQueriedPlayers.forEach(player => {
      getOrSetAsInMap(this.playersByQueriedElement, player.element, []).push(player);
      player.onDone(() => deleteOrUnsetInMap(this.playersByQueriedElement, player.element, player));
    });

    allConsumedElements.forEach(element => addClass(element, NG_ANIMATING_CLASSNAME));
    const player = optimizeGroupPlayer(allNewPlayers);
    player.onDestroy(() => {
      allConsumedElements.forEach(element => removeClass(element, NG_ANIMATING_CLASSNAME));
      setStyles(rootElement, instruction.toStyles);
    });

    // this basically makes all of the callbacks for sub element animations
    // be dependent on the upper players for when they finish
    allSubElements.forEach(
        element => { getOrSetAsInMap(skippedPlayersMap, element, []).push(player); });

    return player;
  }

  private _buildPlayer(
      instruction: AnimationTimelineInstruction, keyframes: ɵStyleData[],
      previousPlayers: AnimationPlayer[]): AnimationPlayer {
    if (keyframes.length > 0) {
      return this.driver.animate(
          instruction.element, keyframes, instruction.duration, instruction.delay,
          instruction.easing, previousPlayers);
    }

    // special case for when an empty transition|definition is provided
    // ... there is no point in rendering an empty animation
    return new NoopAnimationPlayer();
  }
}

export class TransitionAnimationPlayer implements AnimationPlayer {
  private _player: AnimationPlayer = new NoopAnimationPlayer();
  private _containsRealPlayer = false;

  private _queuedCallbacks: {[name: string]: (() => any)[]} = {};
  private _destroyed = false;
  public parentPlayer: AnimationPlayer;

  public markedForDestroy: boolean = false;

  constructor(public namespaceId: string, public triggerName: string, public element: any) {}

  get queued() { return this._containsRealPlayer == false; }

  get destroyed() { return this._destroyed; }

  setRealPlayer(player: AnimationPlayer) {
    if (this._containsRealPlayer) return;

    this._player = player;
    Object.keys(this._queuedCallbacks).forEach(phase => {
      this._queuedCallbacks[phase].forEach(
          callback => listenOnPlayer(player, phase, undefined, callback));
    });
    this._queuedCallbacks = {};
    this._containsRealPlayer = true;
  }

  getRealPlayer() { return this._player; }

  private _queueEvent(name: string, callback: (event: any) => any): void {
    getOrSetAsInMap(this._queuedCallbacks, name, []).push(callback);
  }

  onDone(fn: () => void): void {
    if (this.queued) {
      this._queueEvent('done', fn);
    }
    this._player.onDone(fn);
  }

  onStart(fn: () => void): void {
    if (this.queued) {
      this._queueEvent('start', fn);
    }
    this._player.onStart(fn);
  }

  onDestroy(fn: () => void): void {
    if (this.queued) {
      this._queueEvent('destroy', fn);
    }
    this._player.onDestroy(fn);
  }

  init(): void { this._player.init(); }

  hasStarted(): boolean { return this.queued ? false : this._player.hasStarted(); }

  play(): void { !this.queued && this._player.play(); }

  pause(): void { !this.queued && this._player.pause(); }

  restart(): void { !this.queued && this._player.restart(); }

  finish(): void { this._player.finish(); }

  destroy(): void {
    this._destroyed = true;
    this._player.destroy();
  }

  reset(): void { !this.queued && this._player.reset(); }

  setPosition(p: any): void {
    if (!this.queued) {
      this._player.setPosition(p);
    }
  }

  getPosition(): number { return this.queued ? 0 : this._player.getPosition(); }

  get totalTime(): number { return this._player.totalTime; }
}

function deleteOrUnsetInMap(map: Map<any, any[]>| {[key: string]: any}, key: any, value: any) {
  let currentValues: any[]|null|undefined;
  if (map instanceof Map) {
    currentValues = map.get(key);
    if (currentValues) {
      if (currentValues.length) {
        const index = currentValues.indexOf(value);
        currentValues.splice(index, 1);
      }
      if (currentValues.length == 0) {
        map.delete(key);
      }
    }
  } else {
    currentValues = map[key];
    if (currentValues) {
      if (currentValues.length) {
        const index = currentValues.indexOf(value);
        currentValues.splice(index, 1);
      }
      if (currentValues.length == 0) {
        delete map[key];
      }
    }
  }
  return currentValues;
}

function normalizeTriggerValue(value: any): string {
  switch (typeof value) {
    case 'boolean':
      return value ? '1' : '0';
    default:
      return value != null ? value.toString() : null;
  }
}

function isElementNode(node: any) {
  return node && node['nodeType'] === 1;
}

function isTriggerEventValid(eventName: string): boolean {
  return eventName == 'start' || eventName == 'done';
}

function cloakElement(element: any, value?: string) {
  const oldValue = element.style.display;
  element.style.display = value != null ? value : 'none';
  return oldValue;
}

function cloakAndComputeStyles(
    driver: AnimationDriver, elements: any[], elementPropsMap: Map<any, Set<string>>,
    defaultStyle: string): Map<any, ɵStyleData> {
  const cloakVals = elements.map(element => cloakElement(element));
  const valuesMap = new Map<any, ɵStyleData>();

  elementPropsMap.forEach((props: Set<string>, element: any) => {
    const styles: ɵStyleData = {};
    props.forEach(prop => {
      const value = styles[prop] = driver.computeStyle(element, prop, defaultStyle);

      // there is no easy way to detect this because a sub element could be removed
      // by a parent animation element being detached.
      if (!value || value.length == 0) {
        element[REMOVAL_FLAG] = NULL_REMOVED_QUERIED_STATE;
      }
    });
    valuesMap.set(element, styles);
  });

  elements.forEach((element, i) => cloakElement(element, cloakVals[i]));
  return valuesMap;
}

/*
Since the Angular renderer code will return a collection of inserted
nodes in all areas of a DOM tree, it's up to this algorithm to figure
out which nodes are roots.

By placing all nodes into a set and traversing upwards to the edge,
the recursive code can figure out if a clean path from the DOM node
to the edge container is clear. If no other node is detected in the
set then it is a root element.

This algorithm also keeps track of all nodes along the path so that
if other sibling nodes are also tracked then the lookup process can
skip a lot of steps in between and avoid traversing the entire tree
multiple times to the edge.
 */
function createIsRootFilterFn(nodes: any): (node: any) => boolean {
  const nodeSet = new Set(nodes);
  const knownRootContainer = new Set();
  let isRoot: (node: any) => boolean;
  isRoot = node => {
    if (!node) return true;
    if (nodeSet.has(node.parentNode)) return false;
    if (knownRootContainer.has(node.parentNode)) return true;
    if (isRoot(node.parentNode)) {
      knownRootContainer.add(node);
      return true;
    }
    return false;
  };
  return isRoot;
}

const CLASSES_CACHE_KEY = '$$classes';
function containsClass(element: any, className: string): boolean {
  if (element.classList) {
    return element.classList.contains(className);
  } else {
    const classes = element[CLASSES_CACHE_KEY];
    return classes && classes[className];
  }
}

function addClass(element: any, className: string) {
  if (element.classList) {
    element.classList.add(className);
  } else {
    let classes: {[className: string]: boolean} = element[CLASSES_CACHE_KEY];
    if (!classes) {
      classes = element[CLASSES_CACHE_KEY] = {};
    }
    classes[className] = true;
  }
}

function removeClass(element: any, className: string) {
  if (element.classList) {
    element.classList.remove(className);
  } else {
    let classes: {[className: string]: boolean} = element[CLASSES_CACHE_KEY];
    if (classes) {
      delete classes[className];
    }
  }
}

function getBodyNode(): any|null {
  if (typeof document != 'undefined') {
    return document.body;
  }
  return null;
}

function removeNodesAfterAnimationDone(
    engine: TransitionAnimationEngine, element: any, players: AnimationPlayer[]) {
  optimizeGroupPlayer(players).onDone(() => engine.processLeaveNode(element));
}


text:
using System;
using System.Threading.Tasks;
using Nimbus.StressTests.ThroughputTests.EventHandlers;
using Nimbus.StressTests.ThroughputTests.MessageContracts;
using NUnit.Framework;

namespace Nimbus.StressTests.ThroughputTests
{
    [TestFixture]
    public class WhenSendingManyRequestsOfTheSameType : ThroughputSpecificationForBus
    {
        public override async Task SendMessages(IBus bus, Func<bool> shouldKeepSending)
        {
            while (shouldKeepSending())
            {
                var response = await bus.Request(new FooRequest(), TimeSpan.FromSeconds(TimeoutSeconds));
                StressTestMessageHandler.RecordResponseMessageReceipt(response);
                IncrementExpectedMessageCount();
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<meta id="meta.mount" label="CONF_MESSAGE[FS Mount]" description="CONF_MESSAGE[Mount a remote location on the file system before accessing the repository]" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="file:../core.ajaxplorer/ajxp_registry.xsd" mixins="credentials_consumer">
    <class_definition filename="plugins/meta.mount/class.FilesystemMounter.php" classname="FilesystemMounter"/>
    <server_settings>
   		<param name="FILESYSTEM_TYPE" type="string" label="CONF_MESSAGE[FS Type]" description="CONF_MESSAGE[Filesystem Type, will be used for the -t option of the mount command]" mandatory="true" default="cifs"/>
   		<param name="MOUNT_SUDO" type="boolean" label="CONF_MESSAGE[Sudo]" description="CONF_MESSAGE[Call the mount/umount commands through sudo, must be configured on the server]" mandatory="true" default="yes"/>
   		<param name="UNC_PATH" type="string" label="CONF_MESSAGE[Remote Path]" description="CONF_MESSAGE[Path to the remote share to mount, use //123.456.789.654/path you can use AJXP_USER]" mandatory="true" default=""/>
   		<param name="MOUNT_POINT" type="string" label="CONF_MESSAGE[Mount Point]" description="CONF_MESSAGE[Mount Path, use AJXP_USER]" mandatory="true" default=""/>
   		<param name="MOUNT_OPTIONS" type="string" label="CONF_MESSAGE[Mount Options]" description="CONF_MESSAGE[Used with the -o command option, use AJXP_USER, AJXP_PASS, AJXP_SERVER_UID, AJXP_SERVER_GID]" mandatory="false" default="user=AJXP_USER,pass=AJXP_PASS,uid=AJXP_SERVER_UID,gid=AJXP_SERVER_GID"/>
    </server_settings>
   	<client_settings>
   		<resources>
   			<i18n namespace="meta.mount" path="plugins/meta.mount/i18n" />
   		</resources>
   	</client_settings>
   	<registry_contributions>
           <actions>
               <action name="logout">
                   <pre_processing>
                       <serverCallback methodName="umountFS"/>
                   </pre_processing>
               </action>
               <action name="switch_repository">
                   <pre_processing>
                       <serverCallback methodName="umountFS"/>
                   </pre_processing>
               </action>
           </actions>
    </registry_contributions>
</meta>


text:
/**
 * Common service provider interfaces and useful base implementations.
 */
package org.eclipse.emf.cdo.spi.common;


text:
module TrafficSpy

  class Event
    extend ModelHelper

    def self.table
      DB.from(:events)
    end

    def self.sorted_events_by(identifier)
      combined_db = DB.from(:sources).join(:payloads, :source_id => :id).join(:events, :id => :eventName_id)
      filtered_db = combined_db.filter(:source_id => identifier_id(identifier))
      filtered_db.order(Sequel.desc(:event)).select(:event).to_a.uniq
    end

    # def self.create(attributes, source_id)
    #   table.insert(
    #   :event => attributes["eventName"],
    #   :source_id => source_id
    #   )
    # end

    def self.exist?(event)
      table.where(
      :event => event
      ).count > 0
    end

    def self.return_id(event)
      if exist?(event)
        table.select(:id).where(:event => event)
      else
        table.insert(
        :event => event
        )
        table.select(:id).to_a.last[:id]

      end
    end

    def self.hours_and_frequency(identifier, eventname)
      combined_db = DB.from(:sources).join(:payloads, :source_id => :id).join(:events, :id => :eventName_id)
      filtered_db = combined_db.filter(:source_id => identifier_id(identifier))

      #filtered_db.inject(Hash.new(0)) {|hash, ele| hash[DateTime.parse("#{ele[:requestedAt]}").strftime('%H')] += 1; hash}
      filtered_db.inject(Hash.new(0)) do |hash, ele|
        hash["#{ele[:requestedAt]}".split[1].split(':').first] += 1; hash
      end
    end

    def self.total_sum(identifier, eventname)
      hours_and_frequency(identifier, eventname).values.reduce(:+)
    end

  end
end


text:
"""Streaming HTTP uploads module.

This module extends the standard httplib and urllib2 objects so that
iterable objects can be used in the body of HTTP requests.

In most cases all one should have to do is call :func:`register_openers()`
to register the new streaming http handlers which will take priority over
the default handlers, and then you can use iterable objects in the body
of HTTP requests.

**N.B.** You must specify a Content-Length header if using an iterable object
since there is no way to determine in advance the total size that will be
yielded, and there is no way to reset an interator.

Example usage:

>>> from StringIO import StringIO
>>> import urllib2, poster.streaminghttp

>>> opener = poster.streaminghttp.register_openers()

>>> s = "Test file data"
>>> f = StringIO(s)

>>> req = urllib2.Request("http://localhost:5000", f,
...                       {'Content-Length': str(len(s))})
"""

from __future__ import division

import httplib, urllib2, socket
from httplib import NotConnected

__all__ = ['StreamingHTTPConnection', 'StreamingHTTPRedirectHandler',
        'StreamingHTTPHandler', 'register_openers']

if hasattr(httplib, 'HTTPS'):
    __all__.extend(['StreamingHTTPSHandler', 'StreamingHTTPSConnection'])

class _StreamingHTTPMixin(object):
    """Mixin class for HTTP and HTTPS connections that implements a streaming
    send method."""
    def send(self, value):
        """Send ``value`` to the server.

        ``value`` can be a string object, a file-like object that supports
        a .read() method, or an iterable object that supports a .next()
        method.
        """
        # Based on python 2.6's httplib.HTTPConnection.send()
        if self.sock is None:
            if self.auto_open:
                self.connect()
            else:
                raise NotConnected()

        # send the data to the server. if we get a broken pipe, then close
        # the socket. we want to reconnect when somebody tries to send again.
        #
        # NOTE: we DO propagate the error, though, because we cannot simply
        #       ignore the error... the caller will know if they can retry.
        if self.debuglevel > 0:
            print "send:", repr(value)
        try:
            blocksize = 8192
            if hasattr(value, 'read') :
                if hasattr(value, 'seek'):
                    value.seek(0)
                if self.debuglevel > 0:
                    print "sendIng a read()able"
                data = value.read(blocksize)
                while data:
                    self.sock.sendall(data)
                    data = value.read(blocksize)
            elif hasattr(value, 'next'):
                if hasattr(value, 'reset'):
                    value.reset()
                if self.debuglevel > 0:
                    print "sendIng an iterable"
                for data in value:
                    self.sock.sendall(data)
            else:
                self.sock.sendall(value)
        except socket.error, v:
            if v[0] == 32:      # Broken pipe
                self.close()
            raise

class StreamingHTTPConnection(_StreamingHTTPMixin, httplib.HTTPConnection):
    """Subclass of `httplib.HTTPConnection` that overrides the `send()` method
    to support iterable body objects"""

class StreamingHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
    """Subclass of `urllib2.HTTPRedirectHandler` that overrides the
    `redirect_request` method to properly handle redirected POST requests

    This class is required because python 2.5's HTTPRedirectHandler does
    not remove the Content-Type or Content-Length headers when requesting
    the new resource, but the body of the original request is not preserved.
    """

    handler_order = urllib2.HTTPRedirectHandler.handler_order - 1

    # From python2.6 urllib2's HTTPRedirectHandler
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        """Return a Request or None in response to a redirect.

        This is called by the http_error_30x methods when a
        redirection response is received.  If a redirection should
        take place, return a new Request to allow http_error_30x to
        perform the redirect.  Otherwise, raise HTTPError if no-one
        else should try to handle this url.  Return None if you can't
        but another Handler might.
        """
        m = req.get_method()
        if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
            or code in (301, 302, 303) and m == "POST"):
            # Strictly (according to RFC 2616), 301 or 302 in response
            # to a POST MUST NOT cause a redirection without confirmation
            # from the user (of urllib2, in this case).  In practice,
            # essentially all clients do redirect in this case, so we
            # do the same.
            # be conciliant with URIs containing a space
            newurl = newurl.replace(' ', '%20')
            newheaders = dict((k, v) for k, v in req.headers.items()
                              if k.lower() not in (
                                  "content-length", "content-type")
                             )
            return urllib2.Request(newurl,
                           headers=newheaders,
                           origin_req_host=req.get_origin_req_host(),
                           unverifiable=True)
        else:
            raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)

class StreamingHTTPHandler(urllib2.HTTPHandler):
    """Subclass of `urllib2.HTTPHandler` that uses
    StreamingHTTPConnection as its http connection class."""

    handler_order = urllib2.HTTPHandler.handler_order - 1

    def http_open(self, req):
        """Open a StreamingHTTPConnection for the given request"""
        return self.do_open(StreamingHTTPConnection, req)

    def http_request(self, req):
        """Handle a HTTP request.  Make sure that Content-Length is specified
        if we're using an interable value"""
        # Make sure that if we're using an iterable object as the request
        # body, that we've also specified Content-Length
        if req.has_data():
            data = req.get_data()
            if hasattr(data, 'read') or hasattr(data, 'next'):
                if not req.has_header('Content-length'):
                    raise ValueError(
                            "No Content-Length specified for iterable body")
        return urllib2.HTTPHandler.do_request_(self, req)

if hasattr(httplib, 'HTTPS'):
    class StreamingHTTPSConnection(_StreamingHTTPMixin,
            httplib.HTTPSConnection):
        """Subclass of `httplib.HTTSConnection` that overrides the `send()`
        method to support iterable body objects"""

    class StreamingHTTPSHandler(urllib2.HTTPSHandler):
        """Subclass of `urllib2.HTTPSHandler` that uses
        StreamingHTTPSConnection as its http connection class."""

        handler_order = urllib2.HTTPSHandler.handler_order - 1

        def https_open(self, req):
            return self.do_open(StreamingHTTPSConnection, req)

        def https_request(self, req):
            # Make sure that if we're using an iterable object as the request
            # body, that we've also specified Content-Length
            if req.has_data():
                data = req.get_data()
                if hasattr(data, 'read') or hasattr(data, 'next'):
                    if not req.has_header('Content-length'):
                        raise ValueError(
                                "No Content-Length specified for iterable body")
            return urllib2.HTTPSHandler.do_request_(self, req)

def register_openers(cookiejar=None):
    """Register the streaming http handlers in the global urllib2 default
    opener object.

    Returns the created OpenerDirector object."""
    handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]
    if hasattr(httplib, "HTTPS"):
        handlers.append(StreamingHTTPSHandler)

    if cookiejar:
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar), *handlers)
    else:
        opener = urllib2.build_opener(*handlers)

    urllib2.install_opener(opener)

    return opener


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-792
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.01.08 at 10:45:27 PM MEZ
//

package de.unistuttgart.iaas.chor.messages;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="choreographyModelID" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="processModels" type="{http://www.example.org/choreography_deployment_message}processBundleResultType" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "choreographyModelID",
    "processModels"
})
@XmlRootElement(name = "ChorUndeploymentMessage", namespace = "http://www.example.org/choreography_deployment_message")
public class ChorUndeploymentMessage {

    @XmlElement(namespace = "http://www.example.org/choreography_deployment_message", required = true)
    protected String choreographyModelID;
    @XmlElement(namespace = "http://www.example.org/choreography_deployment_message")
    protected List<ProcessBundleResultType> processModels;

    /**
     * Gets the value of the choreographyModelID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getChoreographyModelID() {
        return choreographyModelID;
    }

    /**
     * Sets the value of the choreographyModelID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setChoreographyModelID(String value) {
        this.choreographyModelID = value;
    }

    /**
     * Gets the value of the processModels property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the processModels property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getProcessModels().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ProcessBundleResultType }
     *
     *
     */
    public List<ProcessBundleResultType> getProcessModels() {
        if (processModels == null) {
            processModels = new ArrayList<ProcessBundleResultType>();
        }
        return this.processModels;
    }

}


text:
package models;

import java.util.*;

import javax.persistence.*;

import com.avaje.ebean.annotation.Where;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Expr;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;

import controllers.*;

import com.fasterxml.jackson.annotation.*;

import play.data.*;
import play.data.validation.Constraints.*;
import play.data.validation.ValidationError;
import com.avaje.ebean.Model;
import static play.libs.F.*;

@Entity
public class Section extends Model {
    @Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "section_id_seq")
    public Integer id;

    public String title = "";
	public String num = "";

    @OneToMany(mappedBy="section")
    @OrderBy("num ASC")
	@Where(clause = "${ta}.deleted = false")
    @JsonIgnore
    public List<Entry> entries;

    @ManyToOne()
    public Chapter chapter;

	public Boolean deleted;

    public static Finder<Integer,Section> find = new Finder<Integer,Section>(
        Section.class
    );

    public static Section findById(int id) {
        return find.where().eq("chapter.organization", Organization.getByHost())
            .eq("id", id).findUnique();
    }

    public String getNumber() {
        return chapter.num + num;
    }

	public void updateFromForm(Form<Section> form) {
		title = form.field("title").value();
		num = form.field("num").value();
		chapter = Chapter.find.byId(Integer.parseInt(form.field("chapter.id").value()));
		String deleted_val = form.field("deleted").value();
		deleted = deleted_val != null && deleted_val.equals("true");
		save();
	}

	public static Section create(Form<Section> form) {
		Section result = form.get();
		result.updateFromForm(form);
		result.save();
		return result;
	}
}


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("profiles", "0001_initial"),
    ]

    operations = [
        migrations.AlterField(
            model_name="profile",
            name="created_by",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=models.deletion.SET_NULL,
                related_name="created_profile_set",
                to=settings.AUTH_USER_MODEL,
                verbose_name="Created By",
            ),
        ),
        migrations.AlterField(
            model_name="profile",
            name="modified_by",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=models.deletion.SET_NULL,
                related_name="updated_profile_set",
                to=settings.AUTH_USER_MODEL,
                verbose_name="Modified By",
            ),
        ),
    ]


text:
package str

// StringMap is custom wrapper for golang map
// It provides additional capabilities like list of keys, list of values, Empty
type StringMap map[string]string

// AddMap adds all key/value pairs from map m to StringMap
// If key already exists, it will be overwritten by new value
func (sm StringMap) AddMap(m map[string]string) {
	if sm.Size() == 0 {
		sm = m
	} else {
		for k, v := range m {
			sm[k] = v
		}
	}
}

// RemoveAll deletes all key/value pairs from map
func (sm StringMap) RemoveAll() {
	sm = map[string]string{}
}

// Size return number of key/value pairs
func (sm StringMap) Size() int {
	return len(sm)
}

// Empty checks if map contains any key/value pair
func (sm StringMap) Empty() bool {
	return len(sm) == 0
}

// Keys returns slice of map keys
func (sm StringMap) Keys() []string {
	keys := []string{}
	for k := range sm {
		keys = append(keys, k)
	}
	return keys
}

// Values returns slice of map values
func (sm StringMap) Values() []string {
	values := []string{}
	for _, v := range sm {
		values = append(values, v)
	}
	return values
}

// HasKey checks if key exists in map
func (sm StringMap) HasKey(key string) bool {
	_, found := sm[key]
	return found
}


text:
layout: post-no-feature
title: Steamworld Dig
category: articles
tags: [3DS, platform, digger]
---

![Rusty the robot from Steamworld](/images/rusty.png)

* The mix of Wild West and slightly Steampunk robots is great. Characters are well written and the mining theme fits well.
* Mining is *fun*. Well balanced progress and upgrades. Controls work well for directional mining.
* Enemies are a bit meh. Don't really add anything.

[Steamworld Dig](http://steamworldgames.com/dig/)


text:
package com.voxela.gov.players.primeminister;

import java.util.HashMap;
import java.util.Set;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import com.voxela.gov.Main;

import net.md_5.bungee.api.ChatColor;

public class CandidatePlayer {

	public static HashMap<Player, Integer> candidateMap = new HashMap<Player, Integer>();

	public static Set<Player> getCandidates() { return candidateMap.keySet(); }

	public static void addCandidate(Player player) {
		Bukkit.broadcastMessage(Main.gamePrefix + ChatColor.GOLD + player.getName() + ChatColor.GREEN + " is running for Prime Minister!");
		candidateMap.put(player, 0);
	}

	public static void resetCandidates() { candidateMap.clear(); }

	public static void addVote(Player player) {

		Integer votes = candidateMap.get(player);
		int newVotes = new Integer(votes.intValue() + 1);
		candidateMap.put(player, newVotes);
	}

	public static int getVotes(Player player) { return candidateMap.get(player); }

	public static Player getWinner() {

		Integer largestVoteCount = 0;
		Player winner = null;

		for (Player player : candidateMap.keySet()) {

			Integer votes = candidateMap.get(player);
			if (votes > largestVoteCount) {
				largestVoteCount = votes;
				winner = player;
			}
		}

		System.out.print(Main.consolePrefix + "Election winner: " + winner.getName());
        return winner;
	}

}