text:
<!DOCTYPE html>

    <meta charset="utf-8" xmlns:th="http://www.w3.org/1999/xhtml"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta name="description" content=""/>
    <meta name="author" content=""/>
    <link rel="icon" href="img/favicon.ico"/>

    <title>Static Top Navbar Example for Bootstrap</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>

    <link href="http://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css" rel="stylesheet"/>

    <link href="css/navbar-static-top.css" rel="stylesheet"/>
    <link href="css/custom-styles.css" rel="stylesheet"/>

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
                    aria-expanded="false" aria-controls="navbar">
                Toggle navigation

            </button>
            Org.nized

Home

Attendance

Notes

Surveys

Announcements

                    Reports
                        (Officer Only)

People

Class Bonus

Advisor/Admin Only

Admin Page

Login

Notes

    Create

                Title
                Person
                Public to Person?
                The Note
                Actions

                Edit Delete

Dev Feedback and stuff.


text:
package fue.oot1.own_samples.l;

public class Dackel extends Lebewesen {

    public void bewegen() {
        System.out.println("Auf kurzen Beinen vorwärts wackeln");
    }

    public void bellen() {
        System.out.println("Wau wau wau");
    }

}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using log4net.Core;

namespace log4stash.LogEvent
{
    public interface ILoggingEventParser
    {
        void ParseBasicFields(LoggingEvent loggingEvent, Dictionary<string, object> resultDictionary);
        void ParseLocationInfo(LoggingEvent loggingEvent, Dictionary<string, object> resultDictionary);
        void ParseMessage(LoggingEvent loggingEvent, Dictionary<string, object> resultDictionary);
        void ParseException(LoggingEvent loggingEvent, Dictionary<string, object> resultDictionary);
        void ParseProperties(LoggingEvent loggingEvent, Dictionary<string, object> resultDictionary);
    }
}


text:
import {Injectable} from 'angular2/core';

@Injectable()
export class LanguagesService {
  get() {
    return ['en', 'es', 'fr'];
  }
}


text:
#ifndef		__FTTextureGlyph__
#define		__FTTextureGlyph__

#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H

#include "FTGL.h"
#include "FTGlyph.h"

/**
 * FTTextureGlyph is a specialisation of FTGlyph for creating texture
 * glyphs.
 *
 * @see FTGlyphContainer
 *
 */
class FTGL_EXPORT FTTextureGlyph : public FTGlyph
{
	public:
		/**
		 * Constructor
		 *
		 * @param glyph		The Freetype glyph to be processed
		 * @param id		The id the texture that this glyph will be
		 *					drawn in
		 * @param xOffset	The x offset into the parent texture to draw
		 *					this glyph
		 * @param yOffset	The y offset into the parent texture to draw
		 *					this glyph
		 * @param width		The width of the parent texture
		 * @param height	The height (number of rows) of the parent texture
		 */
		FTTextureGlyph( FT_Glyph glyph, int id, int xOffset, int yOffset, GLsizei width, GLsizei height);

		/**
		 * Destructor
		 */
		virtual ~FTTextureGlyph();

		/**
		 * Renders this glyph at the current pen position.
		 *
		 * @param pen	The current pen position.
		 * @return		The advance distance for this glyph.
		 */
		virtual float Render( const FT_Vector& pen);

	private:
		/**
		 * Pointer to the 'image' data
		 */
		unsigned char* data;

		/**
		 * The width of the glyph 'image'
		 */
		int destWidth;

		/**
		 * The height of the glyph 'image'
		 */
		int destHeight;

		/**
		 * The number of greys or bit depth of the image
		 */
		int numGreys;

		/**
		 * A structure to hold the uv co-ords.
		 */
		struct FTPoint
		{
			float x;
			float y;
		};

		/**
		 * The texture co-ords of this glyph within the texture.
		 */
		FTPoint uv[2];

		/**
		 * The texture index that this glyph is contained in.
		 */
		int glTextureID;

		/**
		 * The texture index of the currently active texture
		 *
		 * We call glGetIntegerv( GL_TEXTURE_2D_BINDING, activeTextureID);
		 * to get the currently active texture to try to reduce the number
		 * of texture bind operations
		 */
		GLint activeTextureID;

};

#endif	//	__FTTextureGlyph__


text:
package Lab8;

public class Invoice implements Payable
{
   private String partNumber;
   private String partDescription;
   private int quantity;
   private double pricePerItem;

   // four-argument constructor
   public Invoice( String part, String description, int count,
                   double price )
   {
      partNumber = part;
      partDescription = description;
      setQuantity( count ); // validate and store quantity
      setPricePerItem( price ); // validate and store price per item
   } // end four-argument Invoice constructor

   // set part number
   public void setPartNumber( String part )
   {
      partNumber = part;
   } // end method setPartNumber

   // get part number
   public String getPartNumber()
   {
      return partNumber;
   } // end method getPartNumber

   // set description
   public void setPartDescription( String description )
   {
      partDescription = description;
   } // end method setPartDescription

   // get description
   public String getPartDescription()
   {
      return partDescription;
   } // end method getPartDescription

   // set quantity
   public void setQuantity( int count )
   {
      quantity = ( count < 0 ) ? 0 : count; // quantity cannot be negative
   } // end method setQuantity

   // get quantity
   public int getQuantity()
   {
      return quantity;
   } // end method getQuantity

   // set price per item
   public void setPricePerItem( double price )
   {
      pricePerItem = ( price < 0.0 ) ? 0.0 : price; // validate price
   } // end method setPricePerItem

   // get price per item
   public double getPricePerItem()
   {
      return pricePerItem;
   } // end method getPricePerItem

   // return String representation of Invoice object
   public String toString()
   {
      return String.format( "%s: \n%s: %s (%s) \n%s: %d \n%s: $%,.2f",
              "invoice", "part number", getPartNumber(), getPartDescription(),
              "quantity", getQuantity(), "price per item", getPricePerItem() );
   } // end method toString

   // method required to carry out contract with interface Payable
   public double getPaymentAmount()
   {
      return getQuantity() * getPricePerItem(); // calculate total cost
   } // end method getPaymentAmount
} // end class Invoice


text:
<?php

namespace app\modules\contratacao\models;

use Yii;

/**
 * This is the model class for table "edital".
 *
 * @property integer $id
 * @property string $edital
 * @property integer $processo_id
 *
 * @property Processo $processo
 */
class Edital extends \yii\db\ActiveRecord
{
    public $file;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'edital';
    }

    /**
     * @return \yii\db\Connection the database connection used by this AR class.
     */
    public static function getDb()
    {
        return Yii::$app->get('db_processos');
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['processo_id'], 'required'],
            [['processo_id'], 'integer'],
            [['edital'], 'string', 'max' => 165]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'edital' => 'Edital',
            'processo_id' => 'Processo ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProcesso()
    {
        return $this->hasOne(Processo::className(), ['id' => 'processo_id']);
    }
}


text:
/**
 * @file
 * @brief
 *
 * @date 27.03.2012
 * @author Andrey Gazukin
 */

#include <errno.h>
#include <unistd.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

#include <fs/kfsop.h>
#include <fs/fs_driver.h>
#include <drivers/block_dev/ramdisk/ramdisk.h>

#include <mem/page.h>

#include <util/err.h>

#define MKFS_CREATE_RAMDISK 0x00000001
#define MKFS_FORMAT_DEV     0x00000002

#define MIN_ARGS_OF_MKFS 3 /* <mkfs -q /dev/ram0> must create ramdisk*/
#define DEFAULT_BLOCK_QTTY  0x20
#define DEFAULT_FS_NAME  "vfat"
#define DEFAULT_FS_TYPE  12

static int mkfs_do_operation(size_t blocks, char *path, const char *fs_name,
		unsigned int fs_type, unsigned int operation_flag);

static void print_usage(void) {
	printf("Usage: mkfs [ -t type ] file [ blocks ]\n");
}

static int check_invalid(int min_argc, int argc, char **argv) {
	if (min_argc > argc){
		printf("Invalid option `-%c' `%s'\n", optind, argv[optind]);
		print_usage();
		return EINVAL;
	} else {
		return 0;
	}
}

static int mkfs_create_ramdisk(char *path, int blocks) {
	return err(ramdisk_create(path, blocks * PAGE_SIZE()));
}

int main(int argc, char **argv) {
	int opt;
	int min_argc;
	unsigned int operation_flag;
	int       blocks;
	char         *path;
	const char   *fs_name;
	unsigned int fs_type;

	min_argc = MIN_ARGS_OF_MKFS;

	operation_flag = 0;
	fs_name = DEFAULT_FS_NAME;
	fs_type = DEFAULT_FS_TYPE;
	blocks = DEFAULT_BLOCK_QTTY;

	getopt_init();
	while (-1 != (opt = getopt(argc, argv, "ht:q:"))) {
		switch (opt) {
		case 't':
			min_argc = 4;
			fs_name = optarg;
			operation_flag |= MKFS_FORMAT_DEV;
			break;
		case 'q':
			if (argc < 4) {
				/*mkfs -q /dev/xxx blocks*/
				return -EINVAL;
			}

			path = argv[argc - 2];

			if (0 >= sscanf(argv[argc - 1], "%d", &blocks)){
				print_usage();
				return -EINVAL;
			}

			return mkfs_create_ramdisk(path, blocks);
		case '?':
		case 'h':
			print_usage();
			return 0;
		default:
			return 0;
		}
		if (check_invalid(min_argc, argc, argv)) {
			return -EINVAL;
		}
	}

	if (argc > 1) {
		if (argc > min_argc) {/** last arg should be block quantity*/
			if (0 >= sscanf(argv[argc - 1], "%d", &blocks)){
				print_usage();
				return -EINVAL;
			}
			path = argv[argc - 2];
		} else {/** last arg should be diskname*/
			path = argv[argc - 1];
		}

		return mkfs_do_operation(blocks, path,
				                 fs_name, fs_type, operation_flag);
	}
	return 0;
}

static int mkfs_do_operation(size_t blocks, char *path, const char *fs_name,
		unsigned int fs_type, unsigned int operation_flag) {
	int rezult;

	if (operation_flag & MKFS_CREATE_RAMDISK) {
		if (0 == (err(ramdisk_create(path, blocks * PAGE_SIZE())))) {
			return -errno;
		}
	}

	if (operation_flag & MKFS_FORMAT_DEV) {
		if (0 != (rezult = kformat(path, fs_name))) {
			return rezult;
		}
	}
	return 0;
}


text:
package edu.gatech.cs2340.trydent;

import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import edu.gatech.cs2340.trydent.internal.JavaFXManager;
import edu.gatech.cs2340.trydent.internal.SwingManager;
import edu.gatech.cs2340.trydent.log.Log;

/**
 * Main class that kicks off the TrydentEngine.
 *
 * As a developer using the TrydentEngine, all you have to do is call
 * TrydentEngine.start() to get started.
 *
 * @author Garrett Malmquist
 * */
public class TrydentEngine {

    private static TrydentEngine instance;

    private final Object mainLock = new Object();

    private volatile boolean doQuit = false;

    private volatile long frameNumber;

    private volatile boolean superCalledFlag = false;

    private Set<ContinuousEvent> continuousEvents, continuousEventsToAdd, continuousEventsToRemove;

    private Map<Runnable, ContinuousEvent> continuousRunnables;

    private JavaFXManager fxManager;

    private TrydentEngine() {
        continuousEvents = new HashSet<>();
        continuousEventsToAdd = new HashSet<>();
        continuousEventsToRemove = new HashSet<>();
        continuousRunnables = new HashMap<>();

        fxManager = new SwingManager();
    }

    private void mainUpdate() {
        if (frameNumber == 0)
            Time.startTheDawnOfTime();

        if (!doQuit) {
            try {
                updateContinuousEvents();
            } catch (Exception ex) {
                Log.error(String.valueOf(ex));
                ex.printStackTrace();
                quit();
            }
            Time.updateTime();
        } else {
            cleanup();
        }

        frameNumber++;
    }

    private void updateContinuousEvents() {
        continuousEvents.addAll(continuousEventsToAdd);
        continuousEventsToAdd.clear();

        // Removing events is uglier than creating events, because
        // we need to make sure we handle the case where users
        // remove additional events in an events onStop() method.
        while (!continuousEventsToRemove.isEmpty()) {
            ContinuousEvent next = null;
            for (ContinuousEvent event : continuousEventsToRemove) {
                next = event;
                break;
            }
            next.doStop();
            continuousEvents.remove(next);
            continuousEventsToRemove.remove(next);
        }

        for (ContinuousEvent event : continuousEvents) {
            clearSuperCalledFlag();
            event.onPreUpdate();
            if (!superCalledFlag) {
                throw new TrydentException("ContinuousEvent " + event
                        + " overloaded onPreUpdate() but failed to call super method!");
            }
            event.doUpdate();
        }
    }

    private void cleanup() {
        // Stop any remaining events.
        ContinuousEvent[] toStop = new ContinuousEvent[continuousEvents.size()];
        continuousEvents.toArray(toStop);
        for (ContinuousEvent event : toStop) {
            event.doStop();
        }

        continuousEvents.clear();
        continuousEventsToRemove.clear();
        continuousEventsToAdd.clear();

        fxManager.stopJavaFX();
    }

    private static TrydentEngine getInstance() {
        if (instance == null)
            instance = new TrydentEngine();
        return instance;
    }

    /** For internal engine use only. */
    static void clearSuperCalledFlag() {
        getInstance().superCalledFlag = false;
    }

    /** For internal engine use only. */
    static void setSuperCalledFlag() {
        getInstance().superCalledFlag = true;
    }

    /**
     * Adds a continuous event -- an event that the engine will invoke once
     * every frame.
     *
     * @param event
     *            - A ContinuousEvent whose onUpdate() method will be invoked
     *            every frame.
     */
    static void addContinuousEvent(ContinuousEvent event) {
        getInstance().continuousEventsToAdd.add(event);
    }

    /**
     * Stops running the given continuous event.
     *
     * @param event
     */
    static void removeContinuousEvent(ContinuousEvent event) {
        getInstance().continuousEventsToRemove.add(event);
    }

    static Group getRootNode() {
        return getInstance().fxManager.getBackground();
    }

    /**
     * Replaces the current foreground layout node
     *
     * @param resource
     *            the url of the new JavaFX node
     * @return the previous foreground JavaFX node, if none, returns null
     */
    public static Node setForeground(InputStream resource) {
        Node previous = null;
        try {
            FXMLLoader myLoader = new FXMLLoader();
            Node node = myLoader.load(resource);
            previous = getInstance().fxManager.setForeground(node);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return previous;
    }

    /**
     * Starts the TrydentEngine and JavaFX.
     */
    public static void start() {
        final TrydentEngine engine = getInstance();
        synchronized (engine.mainLock) {
            if (engine.fxManager.isRunning()) {
                Log.warn("Engine has already been started.");
                return; // Nothing to do.
            }
            engine.doQuit = false;
            engine.frameNumber = 0;
            engine.fxManager.setUpdateAction(new Runnable() {
                @Override
                public void run() {
                    engine.mainUpdate();
                }
            });
            // Could pass command-line args here maybe
            // JavaFXFacade.main(args);
            engine.fxManager.startJavaFX();
        }
    }

    public static void quit() {
        getInstance().doQuit = true;
    }

    /**
     * Hangs the current thread until the TrydentEngine stops running.
     *
     * @throws InterruptedException
     *             if this thread is interrupted while waiting
     */
    public static void waitUntilEngineStops() throws InterruptedException {
        // We don't have our own thread, because we rely on JavaFX
        // to invoke the engine's update method, so we have to busy-wait.
        while (getInstance().fxManager.isRunning()) {
            try {
                // Wait 100 ms and try again.
                Thread.sleep(100);
            } catch (InterruptedException ex) {

            }
        }
    }

    /**
     * Returns true if the TrydentEngine has been started, and hasn't been
     * stopped.
     *
     * @return whether the engine is running
     */
    public static boolean isRunning() {
        return getInstance().fxManager.isRunning();
    }

    /**
     * Stops the runnable that was previously executed with
     * {@link #runContinuously(Runnable)}.
     *

     * Depending on when this method is called, the runnable might be run one
     * more time before stopping permanently. For more controlled behavior, use
     * the {@link edu.gatech.cs2340.trydent.ContinuousEvent} class instead of
     * {@link #runContinuously(Runnable)}.
     *
     * @param runnable
     *            the runnable to stop executing every frame
     * @return true if the runnable was stopped, false if it was already stopped
     *         or not run in the first place.
     */
    public static boolean stopRunnable(Runnable runnable) {
        if (getInstance().continuousRunnables.containsKey(runnable)) {
            getInstance().continuousRunnables.get(runnable).stop();
            return true;
        }
        return false;
    }

    /**
     * Tells the TrydentEngine to run the given runnable continuously (once per
     * frame), starting on the next frame.
     *

     * For more sophisticated behavior, such as triggering actions when the
     * runnable starts or finishes, see
     * {@link edu.gatech.cs2340.trydent.ContinuousEvent}.
     *

     * To stop the runnable, use {@link #stopRunnable(Runnable)}.
     *
     * @param runnable
     *            action to run
     */
    public static void runContinuously(final Runnable runnable) {
        getInstance().continuousRunnables.put(runnable, new ContinuousEvent() {
            @Override
            public void onUpdate() {
                runnable.run();
            }
        });
    }

    /**
     * Tells the TrydentEngine to run the given runnable on the next frame.
     *

     * To run something every frame, use {@link #runContinuously(Runnable)} or
     * {@link edu.gatech.cs2340.trydent.ContinuousEvent} instead.
     *
     * @param runnable
     *            action to run
     */
    public static void runOnce(final Runnable runnable) {
        new ContinuousEvent() {
            @Override
            public void onStart() {
                runnable.run();
                this.stop();
            }

            @Override
            public void onUpdate() {
            }
        };
    }

    /**
     * Sets the window title string for the TrydentEngine singleton.
     * @param title the title of the window.
     */
    public static void setWindowTitle(String title) {
        getInstance().fxManager.setWindowTitle(title);
    }

    /**
     * Sets the window dimensions for the TrydentEngine singleton.
     * @param width the width of the window
     * @param height the height of the window
     */
    public static void setWindowSize(int width, int height) {
        getInstance().fxManager.setWindowSize(width, height);
    }

    /**
     * Sets the window background color for the TrydentEngine singleton.
     * @param color the background color.
     */
    public static void setBackgroundColor(Color color) {
        getInstance().fxManager.setBackgroundColor(color);
    }

}


text:
namespace BiDictionaryImplementation
{
    public class Student
    {
        public Student(string firstName, string lastName)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
        }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public override string ToString()
        {
            return this.FirstName + " " + this.LastName;
        }
    }
}


text:
@foreach(config('crudui.sections') as $key => $section)
    <li class="<% (isset($page_name) && $page_name == $section['page_name']) ? ' active' : '' %>">
        <a href="<% $section['route_url'] %>/items"><% $section['menu_title'] %>

@endforeach


text:
package org.mmtk.utility.options;

/**
 * Should we print verbose fragmentation statistics for the free list allocator?
 */
public final class VerboseFragmentationStats extends org.vmutil.options.BooleanOption {
  /**
   * Create the option.
   */
  public VerboseFragmentationStats() {
    super(Options.set, "Verbose Fragmentation Stats",
        "Should we print verbose fragmentation statistics for the free list allocator?",
        false);
  }
}


text:
from google.cloud import pubsub_v1
import json

def create_preprocessing_task(origin, chunk_dims):
    args = {}
    args['inlayer'] = 'gs://neuroglancer/pinky100_v0/image'
    args['outlayer'] = 'gs://neuroglancer/pinky100_v0/image_corrected'
    args['contrastlayer'] = 'gs://neuroglancer/pinky100_v0/contrast'
    args['masklayer'] = 'gs://neuroglancer/pinky100_v0/edge_mask'
    args['orderlayer'] = 'gs://neuroglancer/pinky100_v0/z_order_corrected'
    args['x_slice'] = [origin[0], origin[0]+chunk_dims[0]]
    args['y_slice'] = [origin[1], origin[1]+chunk_dims[1]]
    args['z_slice'] = [origin[2], origin[2]+chunk_dims[2]]
    return json.dumps(args)

def publish_messages(project, topic_name):
	"""Publishes multiple messages to a Pub/Sub topic."""
	publisher = pubsub_v1.PublisherClient()
	topic_path = publisher.topic_path(project, topic_name)
	chunk_dims = [1024,1024,64]
	x_start = 35840
	x_stop = 35840+100352 - chunk_dims[0]
	y_start = 26624
	y_stop = 26624+62464 - chunk_dims[1]
	z_start = 1
	z_stop = 1+2240 - chunk_dims[2]

	# 64 x 36 x 36

	n = 1
	for x in range(x_start, x_stop, chunk_dims[0]):
	    for y in range(y_start, y_stop, chunk_dims[1]):
	        for z in range(z_start, z_stop, chunk_dims[2]):
		        data = create_preprocessing_task([x,y,z], chunk_dims)
		        # Data must be a bytestring
		        data = data.encode('utf-8')
		        publisher.publish(topic_path, data=data)

	print('Published messages.')

def main():
	project = 'neuromancer-seung-import'
	topic_name = 'alembic_preprocessing'
	publish_messages(project, topic_name)

if __name__ == "__main__":
	main()


text:
<?php
mb_internal_encoding( "UTF-8" );
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
ini_set( 'display_startup_errors', 1 );
require( '../include/templateLib.php' );
require( '../include/db.class.php' );
require( '../include/functions.php' );

$puede_ver = isset( $_SESSION['user']['id'] );
$puede_editar = isset( $_SESSION['user']['estado'] ) && $_SESSION['user']['estado'] === 2;

/* Configuraciones globales  */
$t_colegio = array( 'Municipal', 'Subvencionado', 'Particular' );


text:
define(["require", "exports", './FlumpTexture', '../../../createts/util/Promise'], function (require, exports, FlumpTexture, Promise) {
    var FlumpTextureGroupAtlas = (function () {
        function FlumpTextureGroupAtlas(renderTexture, json) {
            this.flumpTextures = {};
            this.renderTexture = renderTexture;
            var textures = json.textures;
            for (var i = 0; i < textures.length; i++) {
                var texture = textures[i];
                this.flumpTextures[texture.symbol] = new FlumpTexture(renderTexture, texture);
            }
        }
        FlumpTextureGroupAtlas.load = function (flumpLibrary, json) {
            var file = json.file;
            var url = flumpLibrary.url + '/' + file;
            return new Promise(function (resolve, reject) {
                var img = document.createElement('img');
                img.onload = function () {
                    resolve(img);
                };
                img.onerror = function () {
                    reject();
                };
                img.src = url;
            }).then(function (data) {
                return new FlumpTextureGroupAtlas(data, json);
            });
        };
        return FlumpTextureGroupAtlas;
    })();
    return FlumpTextureGroupAtlas;
});


text: extern MifareTag tag;


text:
/*
 * This file is part of Evo2DSim.
 *
 * Evo2DSim is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Evo2DSim is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Evo2DSim.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.vastness.evo2dsim.core.simulator

import org.jbox2d.common.Vec2
import org.apache.commons.math3.util.FastMath
import org.vastness.evo2dsim.core.utils.LinearMapping
import org.vastness.evo2dsim.core.neuro._
import scala.Some

class Motor extends LinearMapping {
  var agentOption: Option[Agent] = None
  val UPPER_OUTPUT_LIMIT = 0.15 // m/s  taken from Cooperative Hole Avoidance in a Swarm-bot
  val LOWER_OUTPUT_LIMIT = -0.15

  val UPPER_INPUT_LIMIT = 1.0
  val LOWER_INPUT_LIMIT = -1.0

  private var leftMotorVelocity: Float = 0.0f
  private var rightMotorVelocity: Float = 0.0f

  def setLeftMotorVelocity(x: NumberT) {
    leftMotorVelocity = transform(x).toFloat
  }

  def setRightMotorVelocity(x: NumberT) {
    rightMotorVelocity = transform(x).toFloat
  }

  //taken from enki speed control
  def forwardVelocity = (rightMotorVelocity + leftMotorVelocity) / 2
  def velocity(agent: Agent) = new Vec2((forwardVelocity * FastMath.cos(agent.body.getAngle)).toFloat, (forwardVelocity * FastMath.sin(agent.body.getAngle)).toFloat)
  def angularVelocity(agent: Agent): Float = (rightMotorVelocity-leftMotorVelocity)/(4*agent.radius) // 2* wheel distants

  def attachToAgent(agent: Agent) {
    agentOption = Some(agent)
  }

  //TODO: Check if velocities or forces are better..
  def step() {
    agentOption match {
      case Some(agent) => {
        agent.setLinearVelocity(velocity(agent))
        agent.setAngularVelocity(angularVelocity(agent))
      }
      case None => {}
    }

  }
}


text:
package org.apache.calcite.rel.rules;

import org.apache.calcite.plan.RelOptRule;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.rel.RelCollation;
import org.apache.calcite.rel.core.Filter;
import org.apache.calcite.rel.logical.LogicalCalc;
import org.apache.calcite.rel.logical.LogicalFilter;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexProgram;
import org.apache.calcite.rex.RexProgramBuilder;

import java.util.Collections;

/**
 * Planner rule that merges a
 * {@link org.apache.calcite.rel.logical.LogicalFilter} and a
 * {@link org.apache.calcite.rel.logical.LogicalCalc}. The
 * result is a {@link org.apache.calcite.rel.logical.LogicalCalc}
 * whose filter condition is the logical AND of the two.
 *
 * @see FilterMergeRule
 */
public class FilterCalcMergeRule extends RelOptRule {
  //~ Static fields/initializers ---------------------------------------------

  public static final FilterCalcMergeRule INSTANCE =
      new FilterCalcMergeRule();

  //~ Constructors -----------------------------------------------------------

  private FilterCalcMergeRule() {
    super(
        operand(
            Filter.class,
            operand(LogicalCalc.class, any())));
  }

  //~ Methods ----------------------------------------------------------------

  public void onMatch(RelOptRuleCall call) {
    final LogicalFilter filter = call.rel(0);
    final LogicalCalc calc = call.rel(1);

    // Don't merge a filter onto a calc which contains windowed aggregates.
    // That would effectively be pushing a multiset down through a filter.
    // We'll have chance to merge later, when the over is expanded.
    if (calc.getProgram().containsAggs()) {
      return;
    }

    // Create a program containing the filter.
    final RexBuilder rexBuilder = filter.getCluster().getRexBuilder();
    final RexProgramBuilder progBuilder =
        new RexProgramBuilder(
            calc.getRowType(),
            rexBuilder);
    progBuilder.addIdentity();
    progBuilder.addCondition(filter.getCondition());
    RexProgram topProgram = progBuilder.getProgram();
    RexProgram bottomProgram = calc.getProgram();

    // Merge the programs together.
    RexProgram mergedProgram =
        RexProgramBuilder.mergePrograms(
            topProgram,
            bottomProgram,
            rexBuilder);
    final LogicalCalc newCalc =
        new LogicalCalc(
            calc.getCluster(),
            calc.getTraitSet(),
            calc.getInput(),
            mergedProgram,
            Collections.<RelCollation>emptyList());
    call.transformTo(newCalc);
  }
}

// End FilterCalcMergeRule.java


text:
/**
 * Carrier.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201509.cm;

/**
 * Represents a Carrier Criterion.
 *
A criterion of this type can only be created using
 * an ID.
 *             This is enabled for
 * AdX.
 */
public class Carrier  extends com.google.api.ads.adwords.axis.v201509.cm.Criterion  implements java.io.Serializable {
    /* This field is read only and
     * will be ignored when sent to the API. */
    private java.lang.String name;

    /* This field is read only and
     * will be ignored when sent to the API. */
    private java.lang.String countryCode;

    public Carrier() {
    }

    public Carrier(
           java.lang.Long id,
           com.google.api.ads.adwords.axis.v201509.cm.CriterionType type,
           java.lang.String criterionType,
           java.lang.String name,
           java.lang.String countryCode) {
        super(
            id,
            type,
            criterionType);
        this.name = name;
        this.countryCode = countryCode;
    }

    /**
     * Gets the name value for this Carrier.
     *
     * @return name   * This field is read only and
     * will be ignored when sent to the API.
     */
    public java.lang.String getName() {
        return name;
    }

    /**
     * Sets the name value for this Carrier.
     *
     * @param name   * This field is read only and
     * will be ignored when sent to the API.
     */
    public void setName(java.lang.String name) {
        this.name = name;
    }

    /**
     * Gets the countryCode value for this Carrier.
     *
     * @return countryCode   * This field is read only and
     * will be ignored when sent to the API.
     */
    public java.lang.String getCountryCode() {
        return countryCode;
    }

    /**
     * Sets the countryCode value for this Carrier.
     *
     * @param countryCode   * This field is read only and
     * will be ignored when sent to the API.
     */
    public void setCountryCode(java.lang.String countryCode) {
        this.countryCode = countryCode;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof Carrier)) return false;
        Carrier other = (Carrier) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = super.equals(obj) &&
            ((this.name==null && other.getName()==null) ||
             (this.name!=null &&
              this.name.equals(other.getName()))) &&
            ((this.countryCode==null && other.getCountryCode()==null) ||
             (this.countryCode!=null &&
              this.countryCode.equals(other.getCountryCode())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = super.hashCode();
        if (getName() != null) {
            _hashCode += getName().hashCode();
        }
        if (getCountryCode() != null) {
            _hashCode += getCountryCode().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(Carrier.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201509", "Carrier"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("name");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201509", "name"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("countryCode");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201509", "countryCode"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
      <groupId>\${groupId}</groupId>
      <artifactId>\${artifactId}-pom</artifactId>
      <version>\${version}</version>
    </parent>
    <artifactId>\${artifactId}-shared</artifactId>
    <packaging>bundle</packaging>
    <name>\${artifactId} Shared Client Server Data Structures</name>
    <dependencies>
        <dependency>
            <groupId>org.netbeans.html</groupId>
            <artifactId>net.java.html.json</artifactId>
            <version>\${net.java.html.version}</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>2.4.0</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Export-Package>${package}.shared</Export-Package>
                        <Bundle-SymbolicName>${package}.shared</Bundle-SymbolicName>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
<!DOCTYPE html>

beforefootnote


text:
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var RateLimiter = require('limiter').RateLimiter;
var q = require('q');
const grApi = require('./gr-api.js');
const AccountManager = require('./accountmanager.js');

var sessionStore     = require('express-session'),
	passportSocketIo = require("passport.socketio");

var io = null;
var dbConn = null;
var config = null;
var goodreads = null;
var limiter = new RateLimiter(1, 1000);
var goodreadsAccountManager = null;

module.exports = function initIoServer(cfg, server) {
	config = cfg;

	goodreads = new grApi({
		apiKeys: config.goodreads,
	});

	goodreadsAccountManager = new AccountManager(config.userData.providers.goodreads);
	goodreadsAccountManager.init();

	io = require('socket.io').listen(server);
	// dbConn = new Connection(config.database);

	// dbConn.on('connect', function(err) {
	// 	console.log('Connected to MySQL');
	// });

	io.on('connection', socketIoConnected);

	//With Socket.io >= 1.0
	io.use(passportSocketIo.authorize({
		// cookieParser: cookieParser,       // the same middleware you registrer in express
		key:          config.session.key,       // the name of the cookie where express/connect stores its session_id
		secret:       config.session.secret,    // the session_secret to parse the cookie
		store:        config.session.store,        // we NEED to use a sessionstore. no memorystore please
		success:      onAuthorizeSuccess,  // *optional* callback on success - read more below
		fail:         onAuthorizeFail,     // *optional* callback on fail/error - read more below
	}));
}

function socketIoConnected(socket) {
	socket.on('addIsbn', addIsbn);
	socket.on('getClientInfo', getClientInfo);
	socket.on('userHideWelcomePrompt', userHideWelcomePrompt);
	socket.on('setEntryKey', setUserEntryKey);
}

function addIsbn(data) {
	var socket = this;
	var bookId = null;
	var addBookRequest = {
		bookId: null,
	};

	if (typeof data.condition === 'number') {
		addBookRequest.condition = data.condition;
	}

	if (typeof data.isbn !== 'string' || null !== data.isbn.match(/\A([0-9]{10}|[0-9]{13})\Z/)) {
		this.emit('apperror', { type: 'application', msg: 'No ISBN given in request' });
		return;
	}

	console.log('Request for isbn: ', data.isbn);

	function doRequest(requestNo) {
		goodreads.bookShowByIsbn(data.isbn)
			.then(
				function(book) {
					addBookRequest.bookId = book.book.id;

					socket.emit('isbnIdentified', {
						isbn: data.isbn,
						books: [ book.book ],
					});

					return goodreads.addUserOwnedBook(addBookRequest, userOauthInfo(socket));
				},
				function(err) {
					if (err.response.statusCode !== 404 && requestNo < config.goodreads.maxRetries) {
						doRequest(requestNo + 1);
					} else {
						socket.emit('apperror', { type: 'application', method: 'addIsbn', msg: 'Error looking up book', data: err, searchIsbn: data.isbn, requestNo: requestNo, });
					}
				})
			.then(
				function(addResponse) {
					console.log('User book added: ', addResponse);
					socket.emit('bookAdded', {
						isbn: data.isbn,
						data: addResponse,
						request: addBookRequest,
					});
				},
				function (err) {
					if (requestNo < config.goodreads.maxRetries) {
						doRequest(requestNo + 1);
					} else {
						socket.emit('apperror', { type: 'application', method: 'addIsbn', msg: 'Error adding user owned book', data: err, searchIsbn: data.isbn, requestNo: requestNo, });
					}
				});
	}

	doRequest(0);
}

function userHideWelcomePrompt(hide) {
	var socket = this;
	var showWelcomePrompt = hide ? false : true;

	if (typeof this.request.user.clientInfo !== 'undefined') {
		this.request.user.clientInfo.showWelcomePrompt = showWelcomePrompt;
	}

	goodreadsAccountManager.setAccountProperties(socket.request.user.id, { 'showWelcomePrompt': showWelcomePrompt })
		.then(function (clientInfo) {
			socket.emit('clientInfo', clientInfo);
		})
		.catch(function (err) {
			socket.emit('apperror', { type: 'application', method: 'userHideWelcomePrompt', msg: 'Error updating user showWelcomePrompt', data: err });
		});
}

function setUserEntryKey(key) {
	var socket = this;
	var entryKeyString = typeof key === 'string' ? key : 'Enter';

	if (entryKeyString.length > 50) {
		console.error('Entry key string too long!');
		socket.emit('apperror', { type: 'application', method: 'setUserEntryKey', msg: 'Error setting entry key string: string too long' });
		return;
	}

	if (typeof this.request.user.clientInfo !== 'undefined') {
		this.request.user.clientInfo.entryKey = entryKeyString;
	}

	goodreadsAccountManager.setAccountProperties(socket.request.user.id, { 'entryKey': entryKeyString })
		.then(function (clientInfo) {
			socket.emit('clientInfo', clientInfo);
		})
		.catch(function (err) {
			socket.emit('apperror', { type: 'application', method: 'setUserEntryKey', msg: 'Error updating user entryKey', data: err });
		});
}

function userOauthInfo(socket) {
	return {
		key: socket.request.user.grToken,
		secret: socket.request.user.grTokenSecret
	};
}

function onAuthorizeSuccess(data, accept) {
	var _this = this;
	goodreads.getUserShelves(data.user.id)
		.then(function (shelves) {
			data.user.shelves = shelves.shelves.user_shelf;
			accept(null, true);
		})
		.catch(function (err) {
			console.error('Get user shelves error: ', err);
			accept(null, false);
		});
}

function onAuthorizeFail(data, message, error, accept){
	// if(error) {
	// 	throw new Error(message);
	// }

	console.log('failed connection to socket.io:', message);

	// We use this callback to log all of our failed connections.
	accept(null, false);
}

function getGRClient(socket, cb) {
	if (typeof socket.grClient !== 'undefined') {
		cb(socket.grClient);
	}

}

function wrapApi(thisArg, f) {
	var Q = q.defer();

	var args = Array.prototype.slice.call(arguments);
	args.splice(0, 2);

	limiter.removeTokens(1, function (err, remaining) {
		if (err) {
			throw err;
		}

		Q.resolve(f.apply(thisArg, args));
	});

	return Q.promise;
}

function wrapFnCall($this, method) {
    return function () {
        return method.apply($this, arguments);
    }
}

function getClientInfo() {
	var socket = this;
	goodreadsAccountManager.loadAccount(socket.request.user.id)
		.then(function(clientInfo) {
			socket.emit('clientInfo', clientInfo);
		});
}


text:
require 'simplecov'
SimpleCov.start

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'em/gserver'
require 'easy_sockets'

TEST_LOGS_PATH = "test_logs"

def clean_logs
    FileUtils.rm_rf TEST_LOGS_PATH if File.exist? TEST_LOGS_PATH
end

def check_log_dir
    FileUtils.mkdir TEST_LOGS_PATH unless File.exist? TEST_LOGS_PATH
end

RSpec.configure do |config|
    config.before(:all) do
        clean_logs
        check_log_dir
    end
end


text:
<?php
header("Access-Control-Allow-Origin: *");
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'PHPMailer/PHPMailerAutoload.php';

if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputPhone']) && isset($_POST['inputMessage'])) {

    //check if any of the inputs are empty
    if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputPhone']) || empty($_POST['inputMessage'])) {
        $data = array('success' => false, 'message' => 'Por favor complete todos los campos');
        echo json_encode($data);
        exit;
    }

    //create an instance of PHPMailer
    $mail = new PHPMailer();
    // incluimos los datos de conexión
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'usuario@gmail.com';                 // SMTP username
    $mail->Password = 'password';                           // SMTP password
    $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 465;
    //datos para el envio
    $mail->From = $_POST['inputEmail'];
    $mail->FromName = $_POST['inputName'];
    $mail->AddAddress('usuario@gmail.com'); //recipient
    $mail->Subject = "Reporte de Incidentes - Vía addons para firefox";
    $mail->Body = "Nombre: " . $_POST['inputName'] . "\r\n\r\nDescripción: " . stripslashes($_POST['inputMessage']). "\r\n\r\nTeléfono: " .$_POST['inputPhone']. "\r\n\r\nCorreo: " .$_POST['inputEmail'];
    if (isset($_POST['ref'])) {
        $mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
    }

    if(!$mail->send()) {
        $data = array('success' => false, 'message' => 'Su mensaje no pudo ser enviado. ' . $mail->ErrorInfo);
        echo json_encode($data);
        exit;
    }

    $data = array('success' => true, 'message' => 'Muchas gracias. Hemos recibido su mensaje');
    echo json_encode($data);

} else {

    $data = array('success' => false, 'message' => 'POr favor rellene todos los campos correctamente;
    echo json_encode($data);

}


text:
All notable changes to this project will be documented in this file, in reverse chronological order by release.

## 2.7.0 - 2016-02-22

### Added

- Nothing.

### Deprecated

- Nothing.

### Removed

- Nothing.

### Fixed

- [#85](https://github.com/zendframework/zend-db/pull/85) and
  [#87](https://github.com/zendframework/zend-db/pull/87) update the code base
  to be forwards compatible with:
  - zend-eventmanager v3
  - zend-hydrator v2.1
  - zend-servicemanager v3
  - zend-stdlib v3

## 2.6.2 - 2015-12-09

### Added

- [#49](https://github.com/zendframework/zend-db/pull/49) Add docbook
  documentation.

### Deprecated

- Nothing.

### Removed

- Nothing.

### Fixed

- [#55](https://github.com/zendframework/zend-db/pull/55) Implement FeatureSet
  canCallMagicCall and callMagicCall methods
- [#56](https://github.com/zendframework/zend-db/pull/56)
  AbstractResultSet::current now does validation to ensure an array.
- [#58](https://github.com/zendframework/zend-db/pull/58) Fix unbuffered result
  on MySQLi.
- [#59](https://github.com/zendframework/zend-db/pull/59) Allow unix_socket
  parameter

## 2.6.1 - 2015-10-14

### Added

- Nothing.

### Deprecated

- Nothing.

### Removed

- Nothing.

### Fixed

- [#31](https://github.com/zendframework/zend-db/pull/31) fixes table gateway
  update when there is a table alias utilized.

## 2.6.1 - 2015-10-14

### Added

- Nothing.

### Deprecated

- Nothing.

### Removed

- Nothing.

### Fixed

- [#43](https://github.com/zendframework/zend-db/pull/43) unset and get during
  an insert operation would throw an InvalidArgumentException during an insert.

## 2.6.0 - 2015-09-22

### Added

- [#42](https://github.com/zendframework/zend-db/pull/42) updates the component
  to use zend-hydrator for hydrator functionality; this provides forward
  compatibility with zend-hydrator, and backwards compatibility with
  hydrators from older versions of zend-stdlib.
- [#15](https://github.com/zendframework/zend-db/pull/15) adds a new predicate,
  `Zend\Db\Sql\Predicate\NotBetween`, which can be invoked via `Sql`
  instances: `$sql->notBetween($field, $min, $max)`.
- [#22](https://github.com/zendframework/zend-db/pull/22) extracts a factory,
  `Zend\Db\Metadata\Source\Factory`, from `Zend\Db\Metadata\Metadata`,
  removing the (non-public) `createSourceFromAdapter()` method from that
  class. Additionally, it extracts `Zend\Db\Metadata\MetadataInterface`, to
  allow creating alternate implementations.

### Deprecated

- [#27](https://github.com/zendframework/zend-db/pull/27) deprecates the
  constants `JOIN_OUTER_LEFT` and `JOIN_OUTER_RIGHT` in favor of
  `JOIN_LEFT_OUTER` and `JOIN_RIGHT_OUTER`.

### Removed

- Nothing.

### Fixed

- Nothing.

## 2.5.2 - 2015-09-22

### Added

- Nothing.

### Deprecated

- Nothing.

### Removed

- [#29](https://github.com/zendframework/zend-db/pull/29) removes the required
  second argument to `Zend\Db\Predicate\Predicate::expression()`, allowing it to
  be nullable, and mirroring the constructor of `Zend\Db\Predicate\Expression`.

### Fixed

- [#40](https://github.com/zendframework/zend-db/pull/40) updates the
  zend-stdlib dependency to reference `>=2.5.0,<2.7.0` to ensure hydrators
  will work as expected following extraction of hydrators to the zend-hydrator
  repository.
- [#34](https://github.com/zendframework/zend-db/pull/34) fixes retrieval of
  constraint metadata in the Oracle adapter.
- [#41](https://github.com/zendframework/zend-db/pull/41) removes hard dependency
  on EventManager in AbstractTableGateway.
- [#17](https://github.com/zendframework/zend-db/pull/17) removes an executable
  bit on a regular file.
- [#3](https://github.com/zendframework/zend-db/pull/3) updates the code to use
  closure binding (now that we're on 5.5+, this is possible).
- [#9](https://github.com/zendframework/zend-db/pull/9) thoroughly audits the
  OCI8 (Oracle) driver, ensuring it provides feature parity with other drivers,
  and fixes issues with subselects, limits, and offsets.


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;

import java.util.List;

/**
 * @author Simon Thoresen Hult
 */
abstract public class PredicateOperator extends Predicate {

    public abstract List<Predicate> getOperands();

}


text:
package test.org.apache.skywalking.apm.testcase.inherit;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/inherit/child")
public class ChildController extends ParentController {

}


text:
package edu.cmu.hcii.citrus.views;

import edu.cmu.hcii.citrus.*;

//
// @author Andrew J. Ko
//
public class AnimateSetProperty extends AnimationStatement {

	public static final Dec<Property> property = new Dec<Property>();
	public static final Dec<Element> value = new Dec<Element>();
	public static final Dec<Transition> transition = new Dec<Transition>();

	// Runtime state
	private Property<?> propertyAnimating = null;

	public AnimateSetProperty() {}
	public AnimateSetProperty(Namespace subType, ArgumentList args) { super(subType, args); }

	public boolean startAnimating(Element context) {

		// Get the property, value, and transition
		Property p = get(property);
		Element v = get(value);
		Transition t = get(transition);
		if(t == null) t = App.getGlobalStyle().getQuickerTransition();
		t.reset();
		p.set(v, t);

		// If the property animating is visible, set it.
		propertyAnimating = p;

		return false;

	}

	public boolean doneAnimating(Element context) {

		// Is the property done transitioning?
		return propertyAnimating == null || propertyAnimating.isDoneTransitioning();

	}

	public String toString() {

		return "set " + propertyAnimating.getName();

	}

}


text:
module load apps/R/3.3.2/intel-17.0-sequential

Rscript ./../../../summary_rds.r > intel_r_sequential_summary.txt


text:
var ran = false;

async function test() {
  try {
    let [namespace1, namespace2] = await Promise.all([
      import('modules-skip-1.js'),
      import('modules-skip-3.js')
    ]);

    let life = namespace1.life();
    let stringlife = namespace2.stringlife;
    assertEquals(42, life);
    assertEquals("42", stringlife);
    ran = true;
  } catch(e) {
    %AbortJS("failure: " + e);
  }
}

test();

%PerformMicrotaskCheckpoint();
assertTrue(ran);


text:
#import <UIKit/UIKit.h>
#import "BZFoursquare.h"

#ifndef __has_feature
#define __has_feature(x) 0
#endif

#if __has_feature(objc_arc)
#error This file does not support Objective-C Automatic Reference Counting (ARC)
#endif

#define kAuthorizeBaseURL       @"https://foursquare.com/oauth2/authorize"

@interface BZFoursquare ()
@property(nonatomic,copy,readwrite) NSString *clientID;
@property(nonatomic,copy,readwrite) NSString *callbackURL;
@end

@implementation BZFoursquare

@synthesize clientID = clientID_;
@synthesize callbackURL = callbackURL_;
@synthesize version = version_;
@synthesize locale = locale_;
@synthesize sessionDelegate = sessionDelegate_;
@synthesize accessToken = accessToken_;

- (id)initWithClientID:(NSString *)clientID callbackURL:(NSString *)callbackURL {
    NSParameterAssert(clientID != nil && callbackURL != nil);
    self = [super init];
    if (self) {
        self.clientID = clientID;
        self.callbackURL = callbackURL;
    }
    return self;
}

- (void)dealloc {
    self.clientID = nil;
    self.callbackURL = nil;
    self.version = nil;
    self.locale = nil;
    self.sessionDelegate = nil;
    self.accessToken = nil;
    [super dealloc];
}

- (BOOL)startAuthorization {
    NSMutableArray *pairs = [NSMutableArray array];
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:clientID_, @"client_id", @"token", @"response_type", callbackURL_, @"redirect_uri", nil];
    for (NSString *key in parameters) {
        NSString *value = [parameters objectForKey:key];
        CFStringRef escapedValue = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)value, NULL, CFSTR("%:/?#[]@!$&'()*+,;="), kCFStringEncodingUTF8);
        NSMutableString *pair = [[key mutableCopy] autorelease];
        [pair appendString:@"="];
        [pair appendString:(NSString *)escapedValue];
        [pairs addObject:pair];
        CFRelease(escapedValue);
    }
    NSString *URLString = kAuthorizeBaseURL;
    NSMutableString *mURLString = [[URLString mutableCopy] autorelease];
    [mURLString appendString:@"?"];
    [mURLString appendString:[pairs componentsJoinedByString:@"&"]];
    NSURL *URL = [NSURL URLWithString:mURLString];
    BOOL result = [[UIApplication sharedApplication] openURL:URL];
    if (!result) {
        NSLog(@"*** %s: cannot open url \"%@\"", __PRETTY_FUNCTION__, URL);
    }
    return result;
}

- (BOOL)handleOpenURL:(NSURL *)url {
    if (![[url absoluteString] hasPrefix:callbackURL_]) {
        return NO;
    }
    NSString *fragment = [url fragment];
    NSArray *pairs = [fragment componentsSeparatedByString:@"&"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    for (NSString *pair in pairs) {
        NSArray *kv = [pair componentsSeparatedByString:@"="];
        NSString *key = [kv objectAtIndex:0];
        NSString *val = [[kv objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [parameters setObject:val forKey:key];
    }
    self.accessToken = [parameters objectForKey:@"access_token"];
    if (accessToken_) {
        if ([sessionDelegate_ respondsToSelector:@selector(foursquareDidAuthorize:)]) {
            [sessionDelegate_ foursquareDidAuthorize:self];
        }
    } else {
        if ([sessionDelegate_ respondsToSelector:@selector(foursquareDidNotAuthorize:error:)]) {
            [sessionDelegate_ foursquareDidNotAuthorize:self error:parameters];
        }
    }
    return YES;
}

- (void)invalidateSession {
    self.accessToken = nil;
}

- (BOOL)isSessionValid {
    return (accessToken_ != nil);
}

- (BZFoursquareRequest *)requestWithPath:(NSString *)path HTTPMethod:(NSString *)HTTPMethod parameters:(NSDictionary *)parameters delegate:(id<BZFoursquareRequestDelegate>)delegate {
    NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithDictionary:parameters];
    if ([self isSessionValid]) {
        [mDict setObject:accessToken_ forKey:@"oauth_token"];
    }
    if (version_) {
        [mDict setObject:version_ forKey:@"v"];
    }
    if (locale_) {
        [mDict setObject:locale_ forKey:@"locale"];
    }
    return [[[BZFoursquareRequest alloc] initWithPath:path HTTPMethod:HTTPMethod parameters:mDict delegate:delegate] autorelease];
}

@end


text:
package com.zimbra.qa.unittest;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.util.SharedByteArrayInputStream;

import junit.framework.Assert;

import org.junit.runner.JUnitCore;

import com.google.common.io.Closeables;
import com.zimbra.client.ZContact;
import com.zimbra.client.ZDataSource;
import com.zimbra.client.ZDateTime;
import com.zimbra.client.ZDocument;
import com.zimbra.client.ZEmailAddress;
import com.zimbra.client.ZFilterRule;
import com.zimbra.client.ZFolder;
import com.zimbra.client.ZGetInfoResult;
import com.zimbra.client.ZGetMessageParams;
import com.zimbra.client.ZGrant.GranteeType;
import com.zimbra.client.ZIdentity;
import com.zimbra.client.ZInvite;
import com.zimbra.client.ZInvite.ZAttendee;
import com.zimbra.client.ZInvite.ZClass;
import com.zimbra.client.ZInvite.ZComponent;
import com.zimbra.client.ZInvite.ZOrganizer;
import com.zimbra.client.ZInvite.ZParticipantStatus;
import com.zimbra.client.ZInvite.ZRole;
import com.zimbra.client.ZInvite.ZStatus;
import com.zimbra.client.ZInvite.ZTransparency;
import com.zimbra.client.ZMailbox;
import com.zimbra.client.ZMailbox.ContactSortBy;
import com.zimbra.client.ZMailbox.OwnerBy;
import com.zimbra.client.ZMailbox.SharedItemBy;
import com.zimbra.client.ZMailbox.ZAppointmentResult;
import com.zimbra.client.ZMailbox.ZImportStatus;
import com.zimbra.client.ZMailbox.ZOutgoingMessage;
import com.zimbra.client.ZMailbox.ZOutgoingMessage.AttachedMessagePart;
import com.zimbra.client.ZMailbox.ZOutgoingMessage.MessagePart;
import com.zimbra.client.ZMessage;
import com.zimbra.client.ZMessage.ZMimePart;
import com.zimbra.client.ZMountpoint;
import com.zimbra.client.ZSearchHit;
import com.zimbra.client.ZSearchParams;
import com.zimbra.client.ZTag;
import com.zimbra.common.account.Key;
import com.zimbra.common.account.Key.AccountBy;
import com.zimbra.common.auth.ZAuthToken;
import com.zimbra.common.lmtp.LmtpClient;
import com.zimbra.common.localconfig.LC;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.soap.AccountConstants;
import com.zimbra.common.soap.AdminConstants;
import com.zimbra.common.soap.Element;
import com.zimbra.common.soap.Element.Attribute;
import com.zimbra.common.soap.Element.XMLElement;
import com.zimbra.common.soap.SoapFaultException;
import com.zimbra.common.soap.SoapHttpTransport;
import com.zimbra.common.soap.SoapTransport;
import com.zimbra.common.util.ByteUtil;
import com.zimbra.common.util.CliUtil;
import com.zimbra.common.util.StringUtil;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.common.zmime.ZMimeMessage;
import com.zimbra.cs.account.Account;
import com.zimbra.cs.account.Config;
import com.zimbra.cs.account.DataSource;
import com.zimbra.cs.account.Domain;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.Server;
import com.zimbra.cs.account.soap.SoapProvisioning;
import com.zimbra.cs.client.LmcSession;
import com.zimbra.cs.client.soap.LmcAdminAuthRequest;
import com.zimbra.cs.client.soap.LmcAdminAuthResponse;
import com.zimbra.cs.client.soap.LmcAuthRequest;
import com.zimbra.cs.client.soap.LmcAuthResponse;
import com.zimbra.cs.client.soap.LmcSoapClientException;
import com.zimbra.cs.index.SortBy;
import com.zimbra.cs.index.ZimbraHit;
import com.zimbra.cs.index.ZimbraQueryResults;
import com.zimbra.cs.mailbox.DeliveryOptions;
import com.zimbra.cs.mailbox.Flag;
import com.zimbra.cs.mailbox.Folder;
import com.zimbra.cs.mailbox.MailItem;
import com.zimbra.cs.mailbox.MailServiceException;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.Message;
import com.zimbra.cs.mailbox.OperationContext;
import com.zimbra.cs.mime.ParsedMessage;
import com.zimbra.cs.store.StoreManager;
import com.zimbra.cs.store.file.FileBlobStore;
import com.zimbra.cs.util.BuildInfo;
import com.zimbra.cs.util.JMSession;

/**
 * @author bburtin
 */
public class TestUtil
extends Assert {

    public static final String DEFAULT_PASSWORD = "test123";

    public static boolean accountExists(String userName)
    throws ServiceException {
        return AccountTestUtil.accountExists(userName);
    }

    public static Account getAccount(String userName)
    throws ServiceException {
        return AccountTestUtil.getAccount(userName);
    }

    public static String getDomain()
    throws ServiceException {
        return AccountTestUtil.getDomain();
    }

    public static Mailbox getMailbox(String userName)
    throws ServiceException {
        return AccountTestUtil.getMailbox(userName);
    }

    public static String getAddress(String userName)
    throws ServiceException {
        return AccountTestUtil.getAddress(userName);
    }

    public static String getAddress(String userName, String domainName) {
        return AccountTestUtil.getAddress(userName, domainName);
    }

    public static String getSoapUrl() {
        try {
            return getBaseUrl() + AccountConstants.USER_SERVICE_URI;
        } catch (ServiceException e) {
            ZimbraLog.test.error("Unable to determine SOAP URL", e);
        }
        return null;
    }

    public static String getBaseUrl()
    throws ServiceException {
        String scheme;
        int port;
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraMailPort, 0);
        if (port > 0) {
            scheme = "http";
        } else {
            port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraMailSSLPort, 0);
            scheme = "https";
        }
        return scheme + "://localhost:" + port;
    }

    public static String getAdminSoapUrl() {
        int port;
        try {
            port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
        } catch (ServiceException e) {
            ZimbraLog.test.error("Unable to get admin SOAP port", e);
            port = LC.zimbra_admin_service_port.intValue();
        }
        return "https://localhost:" + port + AdminConstants.ADMIN_SERVICE_URI;
    }

    public static LmcSession getSoapSession(String userName)
    throws ServiceException, LmcSoapClientException, IOException, SoapFaultException
    {
        LmcAuthRequest auth = new LmcAuthRequest();
        auth.setUsername(getAddress(userName));
        auth.setPassword(DEFAULT_PASSWORD);
        LmcAuthResponse authResp = (LmcAuthResponse) auth.invoke(getSoapUrl());
        return authResp.getSession();
    }

    public static LmcSession getAdminSoapSession()
    throws Exception
    {
        // Authenticate
        LmcAdminAuthRequest auth = new LmcAdminAuthRequest();
        auth.setUsername(LC.zimbra_ldap_user.value());
        auth.setPassword(LC.zimbra_ldap_password.value());
        LmcAdminAuthResponse authResp = (LmcAdminAuthResponse) auth.invoke(getAdminSoapUrl());
        return authResp.getSession();
    }

    public static Message addMessage(Mailbox mbox, String subject)
    throws Exception {
        return addMessage(mbox, Mailbox.ID_FOLDER_INBOX, subject, System.currentTimeMillis());
    }

    public static Message addMessage(Mailbox mbox, int folderId, String subject, long timestamp)
    throws Exception {
        String message = getTestMessage(subject, null, null, new Date(timestamp));
        ParsedMessage pm = new ParsedMessage(message.getBytes(), timestamp, false);
        DeliveryOptions dopt = new DeliveryOptions().setFolderId(folderId).setFlags(Flag.BITMASK_UNREAD);
        return mbox.addMessage(null, pm, dopt, null);
    }

    public static String getTestMessage(String subject)
    throws ServiceException, MessagingException, IOException {
        return new MessageBuilder().withSubject(subject).create();
    }

    public static String getTestMessage(String subject, String recipient, String sender, Date date)
    throws ServiceException, MessagingException, IOException {
        return new MessageBuilder().withSubject(subject).withToRecipient(recipient)
            .withFrom(sender).withDate(date).create();
    }

    static String addDomainIfNecessary(String user)
    throws ServiceException {
        if (StringUtil.isNullOrEmpty(user) || user.contains("@")) {
            return user;
        }
        return String.format("%s@%s", user, getDomain());
    }

    public static boolean addMessageLmtp(String subject, String recipient, String sender)
    throws Exception {
        return addMessageLmtp(subject, new String[] { recipient }, sender);
    }

    public static boolean addMessageLmtp(String subject, String[] recipients, String sender)
    throws Exception {
        String message = getTestMessage(subject, recipients[0], sender, null);
        return addMessageLmtp(recipients, sender, message);
    }

    public static boolean addMessageLmtp(String[] recipients, String sender, String message)
    throws Exception {
        String[] recipWithDomain = new String[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            recipWithDomain[i] = addDomainIfNecessary(recipients[i]);
        }
        Provisioning prov = Provisioning.getInstance();
        LmtpClient lmtp = new LmtpClient("localhost", prov.getLocalServer().getIntAttr(Provisioning.A_zimbraLmtpBindPort, 7025));
        byte[] data = message.getBytes();
        String senderAddress = "";
        if (!StringUtil.isNullOrEmpty(sender)) {
            senderAddress = addDomainIfNecessary(sender);
        }
        boolean success = lmtp.sendMessage(new ByteArrayInputStream(data), recipWithDomain, senderAddress, "TestUtil", (long) data.length);
        lmtp.close();
        return success;
    }

    public static String addMessage(ZMailbox mbox, String subject)
    throws ServiceException, IOException, MessagingException {
        return addMessage(mbox, subject, Integer.toString(Mailbox.ID_FOLDER_INBOX));
    }

    public static String addMessage(ZMailbox mbox, String subject, String folderId)
    throws ServiceException, IOException, MessagingException {
        String message = getTestMessage(subject);
        return mbox.addMessage(folderId, null, null, 0, message, true);
    }

    public static String addMessage(ZMailbox mbox, String subject, String folderId, String flags)
    throws ServiceException, IOException, MessagingException {
        String message = getTestMessage(subject);
        return mbox.addMessage(folderId, flags, null, 0, message, true);
    }

    public static String addRawMessage(ZMailbox mbox, String rawMessage)
    throws ServiceException {
        return mbox.addMessage(Integer.toString(Mailbox.ID_FOLDER_INBOX), null, null, 0, rawMessage, true);
    }

    public static void sendMessage(ZMailbox senderMbox, String recipientName, String subject)
    throws Exception {
        String body = getTestMessage(subject);
        sendMessage(senderMbox, recipientName, subject, body);
    }

    public static void sendMessage(ZMailbox senderMbox, String recipientName, String subject, String body)
    throws Exception {
        sendMessage(senderMbox, recipientName, subject, body, null);
    }

    public static void sendMessage(ZMailbox senderMbox, String recipientName, String subject, String body, String attachmentUploadId)
    throws Exception {
        ZOutgoingMessage msg = getOutgoingMessage(recipientName, subject, body, attachmentUploadId);
        senderMbox.sendMessage(msg, null, false);
    }

    public static void saveDraftAndSendMessage(ZMailbox senderMbox, String recipient, String subject, String body, String attachmentUploadId)
    throws ServiceException {
        ZOutgoingMessage outgoingDraft = getOutgoingMessage(recipient, subject, body, attachmentUploadId);
        ZMessage draft = senderMbox.saveDraft(outgoingDraft, null, Integer.toString(Mailbox.ID_FOLDER_DRAFTS));

        ZOutgoingMessage outgoing = getOutgoingMessage(recipient, subject, body, null);
        if (attachmentUploadId != null) {
            AttachedMessagePart part = new AttachedMessagePart(draft.getId(), "2", null);
            outgoing.setMessagePartsToAttach(Arrays.asList(part));
        }
        senderMbox.sendMessage(outgoing, null, false);
    }

    public static ZOutgoingMessage getOutgoingMessage(String recipient, String subject, String body, String attachmentUploadId)
    throws ServiceException {
        ZOutgoingMessage msg = new ZOutgoingMessage();
        List<ZEmailAddress> addresses = new ArrayList<ZEmailAddress>();
        addresses.add(new ZEmailAddress(addDomainIfNecessary(recipient),
            null, null, ZEmailAddress.EMAIL_TYPE_TO));
        msg.setAddresses(addresses);
        msg.setSubject(subject);
        msg.setMessagePart(new MessagePart("text/plain", body));
        msg.setAttachmentUploadId(attachmentUploadId);
        return msg;
    }

    /**
     * Searches a mailbox and returns the id's of all matching items.
     */
    public static List<Integer> search(Mailbox mbox, String query, MailItem.Type type) throws ServiceException {
        return search(mbox, query, Collections.singleton(type));
    }

    /**
     * Searches a mailbox and returns the id's of all matching items.
     */
    public static List<Integer> search(Mailbox mbox, String query, Set<MailItem.Type> types) throws ServiceException {
        List<Integer> ids = new ArrayList<Integer>();
        ZimbraQueryResults r = mbox.index.search(new OperationContext(mbox), query, types, SortBy.DATE_DESC, 100);
        while (r.hasNext()) {
            ZimbraHit hit = r.getNext();
            ids.add(new Integer(hit.getItemId()));
        }
        Closeables.closeQuietly(r);
        return ids;
    }

    public static List<String> search(ZMailbox mbox, String query, String type)
    throws ServiceException {
        List<String> ids = new ArrayList<String>();
        ZSearchParams params = new ZSearchParams(query);
        params.setTypes(type);
        for (ZSearchHit hit : mbox.search(params).getHits()) {
            ids.add(hit.getId());
        }
        return ids;
    }

    public static List<ZMessage> search(ZMailbox mbox, String query)
    throws ServiceException {
        List<ZMessage> msgs = new ArrayList<ZMessage>();
        ZSearchParams params = new ZSearchParams(query);
        params.setTypes(ZSearchParams.TYPE_MESSAGE);

        for (ZSearchHit hit : mbox.search(params).getHits()) {
            ZGetMessageParams msgParams = new ZGetMessageParams();
            msgParams.setId(hit.getId());
            msgs.add(mbox.getMessage(msgParams));
        }
        return msgs;
    }

    /**
     * Gets the raw content of a message.
     */
    public static String getContent(ZMailbox mbox, String msgId)
    throws ServiceException {
        ZGetMessageParams msgParams = new ZGetMessageParams();
        msgParams.setId(msgId);
        msgParams.setRawContent(true);
        ZMessage msg = mbox.getMessage(msgParams);
        return msg.getContent();
    }

    public static byte[] getContent(ZMailbox mbox, String msgId, String name)
    throws ServiceException, IOException {
        ZMessage msg = mbox.getMessageById(msgId);
        ZMimePart part = getPart(msg, name);
        if (part == null) {
            return null;
        }
        return ByteUtil.getContent(mbox.getRESTResource("?id=" + msgId + "&part=" + part.getPartName()), 1024);
    }

    /**
     * Returns the mime part with a matching name, part name, or filename.
     */
    public static ZMimePart getPart(ZMessage msg, String name) {
        return getPart(msg.getMimeStructure(), name);
    }

    private static ZMimePart getPart(ZMimePart mimeStructure, String name) {
        for (ZMimePart child : mimeStructure.getChildren()) {
            ZMimePart part = getPart(child, name);
            if (part != null) {
                return part;
            }
        }
        if (StringUtil.equalIgnoreCase(mimeStructure.getName(), name) ||
            StringUtil.equalIgnoreCase(mimeStructure.getFileName(), name) ||
            StringUtil.equalIgnoreCase(mimeStructure.getPartName(), name)) {
            return mimeStructure;
        }
        return null;
    }

    public static ZMessage waitForMessage(ZMailbox mbox, String query)
    throws Exception {
        for (int i = 1; i <= 20; i++) {
            List<ZMessage> msgs = search(mbox, query);
            if (msgs.size() == 1) {
                return msgs.get(0);
            }
            if (msgs.size() > 1) {
                Assert.fail("Unexpected number of messages (" + msgs.size() + ") returned by query '" + query + "'");
            }
            Thread.sleep(500);
        }
        Assert.fail("Message for query '" + query + "' never arrived.  Either the MTA is not running or the test failed.");
        return null;
    }

    /**
     * Returns a folder with the given path, or null if the folder
     * doesn't exist.
     */
    public static Folder getFolderByPath(Mailbox mbox, String path)
    throws Exception {
        Folder folder = null;
        try {
            folder = mbox.getFolderByPath(null, path);
        } catch (MailServiceException e) {
            if (e.getCode() != MailServiceException.NO_SUCH_FOLDER) {
                throw e;
            }
        }
        return folder;
    }

    /**
     * Delete all messages, tags and folders in the user's mailbox
     * whose subjects contain the given substring.  For messages, the
     * subject must contain subjectString as a separate word.  Tags
     * and folders can have the string anywhere in the name.
     */
    public static void deleteTestData(String userName, String subjectSubstring)
    throws ServiceException {
        ZMailbox mbox = getZMailbox(userName);

        deleteMessages(mbox, "is:anywhere " + subjectSubstring);

        // Workaround for bug 15160 (is:anywhere is busted)
        deleteMessages(mbox, "in:trash " + subjectSubstring);
        deleteMessages(mbox, "in:junk " + subjectSubstring);
        deleteMessages(mbox, "in:sent " + subjectSubstring);

        // Workaround for bug 31370
        deleteMessages(mbox, "subject: " + subjectSubstring);

        // Delete tags
        for (ZTag tag : mbox.getAllTags()) {
            if (tag.getName().contains(subjectSubstring)) {
                mbox.deleteTag(tag.getId());
            }
        }

        // Delete folders
        for (ZFolder folder : mbox.getAllFolders()) {
            if (folder.getName().contains(subjectSubstring)) {
                mbox.deleteFolder(folder.getId());
            }
        }

        // Delete contacts
        for (ZContact contact : mbox.getAllContacts(null, ContactSortBy.nameAsc, false, null)) {
            String fullName = contact.getAttrs().get("fullName");
            if (fullName != null && fullName.contains(subjectSubstring)) {
                mbox.deleteContact(contact.getId());
            }
        }

        // Delete data sources
        List<ZDataSource> dataSources = mbox.getAllDataSources();
        for (ZDataSource ds : dataSources) {
            if (ds.getName().contains(subjectSubstring)) {
                mbox.deleteDataSource(ds);
            }
        }

        // Delete appointments
        List<String> ids = search(mbox, subjectSubstring, ZSearchParams.TYPE_APPOINTMENT);
        if (!ids.isEmpty()) {
            mbox.deleteItem(StringUtil.join(",", ids), null);
        }

        // Delete documents
        ids = search(mbox, subjectSubstring, ZSearchParams.TYPE_DOCUMENT);
        if (!ids.isEmpty()) {
            mbox.deleteItem(StringUtil.join(",", ids), null);
        }

        ZMailbox adminMbox = getZMailboxAsAdmin(userName);
        adminMbox.emptyDumpster();
    }

    private static void deleteMessages(ZMailbox mbox, String query)
    throws ServiceException {
        // Delete messages
        ZSearchParams params = new ZSearchParams(query);
        params.setTypes(ZSearchParams.TYPE_MESSAGE);
        List<ZSearchHit> hits = mbox.search(params).getHits();
        if (hits.size() > 0) {
            List<String> ids = new ArrayList<String>();
            for (ZSearchHit hit : hits) {
                ids.add(hit.getId());
            }
            mbox.deleteMessage(StringUtil.join(",", ids));
        }
    }

    private static boolean sIsCliInitialized = false;

    /**
     * Sets up the environment for command-line unit tests.
     */
    public static void cliSetup()
    throws ServiceException {
        if (!sIsCliInitialized) {
            CliUtil.toolSetup();
            Provisioning.setInstance(newSoapProvisioning());
            SoapTransport.setDefaultUserAgent("Zimbra Unit Tests", BuildInfo.VERSION);
            sIsCliInitialized = true;
        }
    }

    public static SoapProvisioning newSoapProvisioning()
    throws ServiceException {
        SoapProvisioning sp = new SoapProvisioning();
        sp.soapSetURI("https://localhost:7071" + AdminConstants.ADMIN_SERVICE_URI);
        sp.soapZimbraAdminAuthenticate();
        return sp;
    }

    public static void runTest(Class<?> testClass) {
        JUnitCore junit = new JUnitCore();
        junit.addListener(new TestLogger());
        ZimbraLog.test.info("Starting unit test %s.", testClass.getName());
        junit.run(testClass);
    }

    public static ZMailbox getZMailbox(String username)
    throws ServiceException {
        ZMailbox.Options options = new ZMailbox.Options();
        options.setAccount(getAddress(username));
        options.setAccountBy(AccountBy.name);
        options.setPassword(DEFAULT_PASSWORD);
        options.setUri(getSoapUrl());
        return ZMailbox.getMailbox(options);
    }

    public static ZMailbox getZMailboxAsAdmin(String username)
    throws ServiceException {
        ZAuthToken adminAuthToken = newSoapProvisioning().getAuthToken();
        ZMailbox.Options options = new ZMailbox.Options(adminAuthToken, getSoapUrl());
        options.setTargetAccount(getAddress(username));
        options.setTargetAccountBy(AccountBy.name);
        return ZMailbox.getMailbox(options);
    }

    /**
     * Creates an account for the given username, with
     * password set to {@link #DEFAULT_PASSWORD}.
     */
    public static Account createAccount(String username)
    throws ServiceException {
        Provisioning prov = Provisioning.getInstance();
        String address = getAddress(username);
        return prov.createAccount(address, DEFAULT_PASSWORD, null);
    }

    /**
     * Deletes the account for the given username.
     */
    public static void deleteAccount(String username)
    throws ServiceException {
        Provisioning prov = Provisioning.getInstance();

        // If this code is running on the server, call SoapProvisioning explicitly
        // so that both the account and mailbox are deleted.
        if (!(prov instanceof SoapProvisioning)) {
            prov = newSoapProvisioning();
        }
        Account account = prov.get(AccountBy.name, getAddress(username));
        if (account != null) {
            prov.deleteAccount(account.getId());
        }
    }

    public static String getServerAttr(String attrName)
    throws ServiceException {
        Provisioning prov = Provisioning.getInstance();
        Server server = prov.getLocalServer();
        return server.getAttr(attrName, null);
    }

    public static void setServerAttr(String attrName, String attrValue)
    throws ServiceException {
        Provisioning prov = Provisioning.getInstance();
        Server server = prov.getLocalServer();
        Map<String, Object> attrs = new HashMap<String, Object>();
        attrs.put(attrName, attrValue);
        prov.modifyAttrs(server, attrs);
    }

    public static String getAccountAttr(String userName, String attrName)
    throws ServiceException {
        String accountName = getAddress(userName);
        Account account = Provisioning.getInstance().getAccount(accountName);
        return account.getAttr(attrName);
    }

    public static String[] getAccountMultiAttr(String userName, String attrName)
    throws ServiceException {
        String accountName = getAddress(userName);
        Account account = Provisioning.getInstance().getAccount(accountName);
        return account.getMultiAttr(attrName);
    }

    public static void setAccountAttr(String userName, String attrName, String attrValue)
    throws ServiceException {
        Provisioning prov = Provisioning.getInstance();
        Account account = prov.get(AccountBy.name, getAddress(userName));
        Map<String, Object> attrs = new HashMap<String, Object>();
        attrs.put(attrName, attrValue);
        prov.modifyAttrs(account, attrs);
    }

    public static void setAccountAttr(String userName, String attrName, String[] attrValues)
    throws ServiceException {
        Provisioning prov = Provisioning.getInstance();
        Account account = prov.get(AccountBy.name, getAddress(userName));
        Map<String, Object> attrs = new HashMap<String, Object>();
        attrs.put(attrName, attrValues);
        prov.modifyAttrs(account, attrs);
    }

    public static String getConfigAttr(String attrName)
    throws ServiceException {
        return Provisioning.getInstance().getConfig().getAttr(attrName, "");
    }

    public static void setConfigAttr(String attrName, String attrValue)
    throws ServiceException {
        Provisioning prov = Provisioning.getInstance();
        Config config = prov.getConfig();
        Map<String, Object> attrs = new HashMap<String, Object>();
        attrs.put(attrName, attrValue);
        prov.modifyAttrs(config, attrs);
    }

    public static String getDomainAttr(String userName, String attrName)
    throws ServiceException {
        Account account = getAccount(userName);
        return Provisioning.getInstance().getDomain(account).getAttr(attrName);
    }

    public static void setDomainAttr(String userName, String attrName, Object attrValue)
    throws ServiceException {
        Account account = getAccount(userName);
        Domain domain = Provisioning.getInstance().getDomain(account);
        Map<String, Object> attrs = new HashMap<String, Object>();
        attrs.put(attrName, attrValue);
        Provisioning.getInstance().modifyAttrs(domain, attrs);
    }

    public static void setDataSourceAttr(String userName, String dataSourceName, String attrName, String attrValue)
    throws ServiceException {
        Provisioning prov = Provisioning.getInstance();
        Account account = getAccount(userName);
        DataSource ds = prov.get(account, Key.DataSourceBy.name, dataSourceName);
        Map<String, Object> attrs = new HashMap<String, Object>();
        attrs.put(attrName, attrValue);
        prov.modifyAttrs(ds, attrs);
    }

    /**
     * Verifies that a message is tagged.
     */
    public static void verifyTag(ZMailbox mbox, ZMessage msg, String tagName)
    throws Exception {
        List<ZTag> tags = mbox.getTags(msg.getTagIds());
        for (ZTag tag : tags) {
            if (tag.getName().equals(tagName)) {
                return;
            }
        }
        Assert.fail("Message not tagged with " + tagName);
    }

    public static ZMessage getMessage(ZMailbox mbox, String query)
    throws Exception {
        List<ZMessage> results = search(mbox, query);
        String errorMsg = String.format("Unexpected number of messages returned by query '%s'", query);
        Assert.assertEquals(errorMsg, 1, results.size());
        return results.get(0);
    }

    /**
     * Verifies that a message is flagged.
     */
    public static void verifyFlag(ZMailbox mbox, ZMessage msg, ZMessage.Flag flag) {
        String flags = msg.getFlags();
        String errorMsg = String.format("Flag %s not found in %s", flag.getFlagChar(), msg.getFlags());
        Assert.assertTrue(errorMsg, flags.indexOf(flag.getFlagChar()) >= 0);
    }

    public static ZFolder createFolder(ZMailbox mbox, String path)
    throws ServiceException {
        String parentId = Integer.toString(Mailbox.ID_FOLDER_USER_ROOT);
        String name = null;
        int idxLastSlash = path.lastIndexOf('/');

        if (idxLastSlash < 0) {
            name = path;
        } else if (idxLastSlash == 0) {
            name = path.substring(1);
        } else {
            String parentPath = path.substring(0, idxLastSlash);
            name = path.substring(idxLastSlash + 1);
            ZFolder parent = mbox.getFolderByPath(parentPath);
            if (parent == null) {
                String msg = String.format("Creating folder %s: parent %s does not exist", name, parentPath);
                throw ServiceException.FAILURE(msg, null);
            }
            parentId = parent.getId();
        }

        return mbox.createFolder(parentId, name, ZFolder.View.message, null, null, null);
    }

    public static ZFolder createFolder(ZMailbox mbox, String parentId, String folderName)
    throws ServiceException {
        return mbox.createFolder(parentId, folderName, ZFolder.View.message, null, null, null);
    }

    /**
     * Creates a mountpoint between two mailboxes.  The mountpoint gives the
     * "to" user full rights on the folder.
     *
     * @param remoteMbox remote mailbox
     * @param remotePath remote folder path.  Folder is created if it doesn't exist.
     * @param localMbox local mailbox
     * @param mountpointName the name of the mountpoint folder.  The folder is created
     * directly under the user root.
     */
    public static ZMountpoint createMountpoint(ZMailbox remoteMbox, String remotePath,
                                               ZMailbox localMbox, String mountpointName)
    throws ServiceException {
        ZFolder remoteFolder = remoteMbox.getFolderByPath(remotePath);
        if (remoteFolder == null) {
            remoteFolder = createFolder(remoteMbox, remotePath);
        }
        ZGetInfoResult remoteInfo = remoteMbox.getAccountInfo(true);
        remoteMbox.modifyFolderGrant(
            remoteFolder.getId(), GranteeType.all, null, "rwidx", null);
        return localMbox.createMountpoint(Integer.toString(Mailbox.ID_FOLDER_USER_ROOT),
            mountpointName, null, null, null,
            OwnerBy.BY_ID, remoteInfo.getId(), SharedItemBy.BY_ID, remoteFolder.getId(), false);
    }

    /**
     * Returns the data source with the given name.
     */
    public static ZDataSource getDataSource(ZMailbox mbox, String name)
    throws ServiceException {
        for (ZDataSource ds : mbox.getAllDataSources()) {
            if (ds.getName().equals(name)) {
                return ds;
            }
        }
        return null;
    }

    /**
     * Imports data from the given data source and updates state on both the local
     * and remote mailboxes.
     */
    public static void importDataSource(ZDataSource dataSource, ZMailbox localMbox, ZMailbox remoteMbox)
    throws Exception {
        importDataSource(dataSource, localMbox, remoteMbox, true);
    }

    /**
     * Imports data from the given data source and updates state on both the local
     * and remote mailboxes.
     */
    public static void importDataSource(ZDataSource dataSource, ZMailbox localMbox, ZMailbox remoteMbox, boolean expectedSuccess)
    throws Exception {
        List<ZDataSource> dataSources = new ArrayList<ZDataSource>();
        dataSources.add(dataSource);
        localMbox.importData(dataSources);
        String type = dataSource.getType().toString();

        // Wait for import to complete
        ZImportStatus status;
        while (true) {
            Thread.sleep(500);

            status = null;
            for (ZImportStatus iter : localMbox.getImportStatus()) {
                if (iter.getId().equals(dataSource.getId())) {
                    status = iter;
                }
            }
            assertNotNull("No import status returned for data source " + dataSource.getName(), status);
            assertEquals("Unexpected data source type", type, status.getType());
            if (!status.isRunning()) {
                break;
            }
        }
        assertEquals(expectedSuccess, status.getSuccess());
        if (!expectedSuccess) {
            assertNotNull(status.getError());
        }

        // Get any state changes from the server
        localMbox.noOp();
        if (remoteMbox != null) {
            remoteMbox.noOp();
        }
    }

    /**
     * Returns an authenticated transport for the <tt>zimbra</tt> account.
     */
    public static SoapTransport getAdminSoapTransport()
    throws SoapFaultException, IOException, ServiceException {
        SoapHttpTransport transport = new SoapHttpTransport(getAdminSoapUrl());

        // Create auth element
        Element auth = new XMLElement(AdminConstants.AUTH_REQUEST);
        auth.addElement(AdminConstants.E_NAME).setText(LC.zimbra_ldap_user.value());
        auth.addElement(AdminConstants.E_PASSWORD).setText(LC.zimbra_ldap_password.value());

        // Authenticate and get auth token
        Element response = transport.invoke(auth);
        String authToken = response.getElement(AccountConstants.E_AUTH_TOKEN).getText();
        transport.setAuthToken(authToken);
        return transport;
    }

    /**
     * Assert the message contains the given sub-message, ignoring newlines.  Used
     * for comparing equality of two messages, when one had <tt>Return-Path</tt> or
     * other headers prepended.
     */
    public static void assertMessageContains(String message, String subMessage)
    throws IOException {
        BufferedReader msgReader = new BufferedReader(new StringReader(message));
        BufferedReader subReader = new BufferedReader(new StringReader(subMessage));
        String firstLine = subReader.readLine();
        String line;
        boolean foundFirstLine = false;

        while ((line = msgReader.readLine()) != null) {
            if (line.equals(firstLine)) {
                foundFirstLine = true;
                break;
            }
        }

        String context = String.format("Could not find '%s' in message:\n", firstLine, message);
        assertTrue(context, foundFirstLine);

        while(true) {
            line = msgReader.readLine();
            String subLine = subReader.readLine();
            if (line == null || subLine == null) {
                break;
            }
            assertEquals(subLine, line);
        }

    }

    /**
     * Asserts that two elements and all children in their hierarchy are equal.
     */
    public static void assertEquals(Element expected, Element actual) {
        assertEquals(expected, actual, expected.prettyPrint(), actual.prettyPrint());
    }

    private static void assertEquals(Element expected, Element actual, String expectedDump, String actualDump) {
        assertEquals(expected.getName(), actual.getName());
        List<Element> expectedChildren = expected.listElements();
        List<Element> actualChildren = actual.listElements();
        String context = String.format("Element %s, expected:\n%s\nactual:\n%s", expected.getName(), expectedDump, actualDump);
        assertEquals(context + " children", getElementNames(expectedChildren), getElementNames(actualChildren));

        // Compare child elements
        for (int i = 0; i < expectedChildren.size(); i++) {
            assertEquals(expectedChildren.get(i), actualChildren.get(i), expectedDump, actualDump);
        }

        // Compare text
        assertEquals(expected.getTextTrim(), actual.getTextTrim());

        // Compare attributes
        Set<Attribute> expectedAttrs = expected.listAttributes();
        Set<Attribute> actualAttrs = actual.listAttributes();
        assertEquals(context + " attributes", getAttributesAsString(expectedAttrs), getAttributesAsString(actualAttrs));
    }

    /**
     * Asserts that two byte arrays are equal.
     */
    public static void assertEquals(byte[] expected, byte[] actual) {
        if (expected == null && actual == null) {
            return;
        }
        if (expected == null) {
            Assert.fail("expected was null but actual was not.");
        }
        if (actual == null) {
            Assert.fail("expected was not null but actual was.");
        }
        assertEquals("Arrays have different length.", expected.length, actual.length);
        for (int i = 0; i < expected.length; i++) {
            assertEquals("Data mismatch at byte " + i, expected[i], actual[i]);
        }
    }

    private static String getElementNames(List<Element> elements) {
        StringBuilder buf = new StringBuilder();
        for (Element e : elements) {
            if (buf.length() > 0) {
                buf.append(",");
            }
            buf.append(e.getName());
        }
        return buf.toString();
    }

    private static String getAttributesAsString(Set<Attribute> attrs) {
        Set<String> attrStrings = new TreeSet<String>();
        for (Attribute attr : attrs) {
            attrStrings.add(String.format("%s=%s", attr.getKey(), attr.getValue()));
        }
        return StringUtil.join(",", attrStrings);
    }

    public static String getHeaderValue(ZMailbox mbox, ZMessage msg, String headerName)
    throws Exception {
        String content = msg.getContent();
        if (content == null) {
            content = getContent(mbox, msg.getId());
        }
        assertNotNull("Content was not fetched from the server", content);
        MimeMessage mimeMsg = new ZMimeMessage(JMSession.getSession(), new SharedByteArrayInputStream(content.getBytes()));
        return mimeMsg.getHeader(headerName, null);
    }

    public static ZAppointmentResult createAppointment(ZMailbox mailbox, String subject, String attendee, Date startDate, Date endDate)
    throws ServiceException {
        ZInvite invite = new ZInvite();
        ZInvite.ZComponent comp = new ZComponent();

        comp.setStatus(ZStatus.CONF);
        comp.setClassProp(ZClass.PUB);
        comp.setTransparency(ZTransparency.O);

        comp.setStart(new ZDateTime(startDate.getTime(), false, mailbox.getPrefs().getTimeZone()));
        comp.setEnd(new ZDateTime(endDate.getTime(), false, mailbox.getPrefs().getTimeZone()));
        comp.setName(subject);
        comp.setOrganizer(new ZOrganizer(mailbox.getName()));

        if (attendee != null) {
            attendee = addDomainIfNecessary(attendee);
            ZAttendee zattendee = new ZAttendee();
            zattendee.setAddress(attendee);
            zattendee.setRole(ZRole.REQ);
            zattendee.setParticipantStatus(ZParticipantStatus.NE);
            zattendee.setRSVP(true);
            comp.getAttendees().add(zattendee);
        }

        invite.getComponents().add(comp);

        ZOutgoingMessage m = null;
        if (attendee != null) {
            m = getOutgoingMessage(attendee, subject, "Test appointment", null);
        }

        return mailbox.createAppointment(ZFolder.ID_CALENDAR, null, m, invite, null);
    }

    public static void sendInviteReply(ZMailbox mbox, String inviteId, String organizer, String subject, ZMailbox.ReplyVerb replyVerb)
    throws ServiceException {
        organizer = addDomainIfNecessary(organizer);
        ZOutgoingMessage msg = getOutgoingMessage(organizer, subject, "Reply to appointment " + inviteId, null);
        mbox.sendInviteReply(inviteId, "0", replyVerb, true, null, null, msg);
    }

    public static ZFilterRule getFilterRule(ZMailbox mbox, String ruleName)
    throws ServiceException {
        for (ZFilterRule rule : mbox.getIncomingFilterRules(true).getRules()) {
            if (rule.getName().equals(ruleName)) {
                return rule;
            }
        }
        return null;
    }

    public static ZDocument createDocument(ZMailbox mbox, String folderId, String name, String contentType, byte[] content)
    throws ServiceException {
        return createDocument(mbox, folderId, name, contentType, content, false);
    }

    public static ZDocument createDocument(ZMailbox mbox, String folderId, String name,
                                           String contentType, byte[] content, boolean isNote)
    throws ServiceException {
        String attachId = mbox.uploadAttachment(name, content, contentType, 0);
        String docId = mbox.createDocument(folderId, name, attachId, isNote);
        return mbox.getDocument(docId);
    }

    public static ZIdentity getDefaultIdentity(ZMailbox mbox)
    throws ServiceException {
        for (ZIdentity ident : mbox.getIdentities()) {
            if (ident.getName().equalsIgnoreCase("DEFAULT")) {
                return ident;
            }
        }
        Assert.fail("Could not find default identity for " + mbox.getName());
        return null;
    }

    public static boolean checkLocalBlobs() {
        //some tests check disk for blob files. these tests only work with FileBlobStore
        return StoreManager.getInstance() instanceof FileBlobStore;
    }

    public static byte[] readInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        while ((i = is.read()) >= 0) {
            baos.write(i);
        }
        return baos.toByteArray();
    }

    public static boolean bytesEqual(byte[] b1, InputStream is) throws IOException {
        return bytesEqual(b1, readInputStream(is));
    }

    public static boolean bytesEqual(byte[] b1, byte[] b2) {
        if (b1.length != b2.length) {
            return false;
        } else {
            for (int i = 0; i < b1.length; i++) {
                if (b1[i] != b2[i]) {
                    return false;
                }
            }
            return true;
        }
    }
}


text:
const readModelConnector = () => ({})

export default readModelConnector