text:
var inherits = require('util').inherits
  , f = require('util').format
  , toError = require('./utils').toError
  , getSingleProperty = require('./utils').getSingleProperty
  , formattedOrderClause = require('./utils').formattedOrderClause
  , handleCallback = require('./utils').handleCallback
  , Logger = require('mongodb-core').Logger
  , EventEmitter = require('events').EventEmitter
  , ReadPreference = require('./read_preference')
  , MongoError = require('mongodb-core').MongoError
  , Readable = require('stream').Readable || require('readable-stream').Readable
  , CoreCursor = require('mongodb-core').Cursor
  , Query = require('mongodb-core').Query
  , CoreReadPreference = require('mongodb-core').ReadPreference;

/**
 * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB
 * allowing for iteration over the results returned from the underlying query. It supports
 * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X
 * or higher stream
 *
 * **CURSORS Cannot directly be instantiated**
 * @example
 * var MongoClient = require('mongodb').MongoClient,
 *   test = require('assert');
 * // Connection url
 * var url = 'mongodb://localhost:27017/test';
 * // Connect using MongoClient
 * MongoClient.connect(url, function(err, db) {
 *   // Create a collection we want to drop later
 *   var col = db.collection('createIndexExample1');
 *   // Insert a bunch of documents
 *   col.insert([{a:1, b:1}
 *     , {a:2, b:2}, {a:3, b:3}
 *     , {a:4, b:4}], {w:1}, function(err, result) {
 *     test.equal(null, err);
 *
 *     // Show that duplicate records got dropped
 *     col.find({}).toArray(function(err, items) {
 *       test.equal(null, err);
 *       test.equal(4, items.length);
 *       db.close();
 *     });
 *   });
 * });
 */

/**
 * Namespace provided by the mongodb-core and node.js
 * @external CoreCursor
 * @external Readable
 */

/**
 * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly)
 * @class
 * @extends external:CoreCursor
 * @extends external:Readable
 * @property {string} sortValue Cursor query sort setting.
 * @property {boolean} timeout Is Cursor able to time out.
 * @property {ReadPreference} readPreference Get cursor ReadPreference.
 * @property {number} cursorBatchSize The current cursorBatchSize for the cursor
 * @property {number} cursorLimit The current cursorLimit for the cursor
 * @property {number} cursorSkip The current cursorSkip for the cursor
 * @fires Cursor#data
 * @fires Cursor#end
 * @fires Cursor#close
 * @fires Cursor#readable
 * @return {Cursor} a Cursor instance.
 * @example
 * Some example
 */
var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) {
  CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
  var self = this;
  var state = Cursor.INIT;
  var streamOptions = {};

  // Tailable cursor options
  var numberOfRetries = options.numberOfRetries || 5;
  var tailableRetryInterval = options.tailableRetryInterval || 500;
  var currentNumberOfRetries = numberOfRetries;
  // MaxTimeMS
  var maxTimeMS = null;

  // Set up
  Readable.call(this, {objectMode: true});

  // Add a read Only property
  Object.defineProperty(this, 'sortValue', {
    enumerable:true,
    get: function() { return cmd.sort; }
  });

  // Add a read Only property
  Object.defineProperty(this, 'timeout', {
    enumerable:true,
    get: function() { return options.noCursorTimeout == true; }
  });

  // Get the read preferences
  Object.defineProperty(this, 'readPreference', {
    enumerable:true,
    get: function() { return options.readPreference; }
  });

  /**
   * Set the cursor query
   * @method
   * @param {object} filter The filter object used for the cursor.
   * @return {Cursor}
   */
  this.filter = function(filter) {
    if(state == Cursor.CLOSED || state == Cursor.OPEN || self.isDead()) throw new MongoError("Cursor is closed");
    cmd.query = filter;
    return this;
  }

  // Flags allowed for cursor
  var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial'];

  /**
   * Add a cursor flag to the cursor
   * @method
   * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial'].
   * @param {boolean} value The flag boolean value.
   * @throws {MongoError}
   * @return {Cursor}
   */
  this.addCursorFlag = function(flag, value) {
    if(state == Cursor.CLOSED || state == Cursor.OPEN || self.isDead()) throw new MongoError("Cursor is closed");
    if(flags.indexOf(flag) == -1) throw new MongoError(f("flag % not a supported flag %s", flag, flags));
    if(typeof value != 'boolean') throw new MongoError(f("flag % must be a boolean value", flag));
    options[flag] = value;
    return this;
  }

  /**
   * Add a query modifier to the cursor query
   * @method
   * @param {string} name The query modifier (must start with $, such as $orderby etc)
   * @param {boolean} value The flag boolean value.
   * @throws {MongoError}
   * @return {Cursor}
   */
  this.addQueryModifier = function(name, value) {
    if(state == Cursor.CLOSED || state == Cursor.OPEN || self.isDead()) throw new MongoError("Cursor is closed");
    if(name[0] != '$') throw new MongoError(f("%s is not a valid query modifier"));
    // Strip of the $
    var field = name.substr(1);
    // Set on the command
    cmd[field] = value;
    // Deal with the special case for sort
    if(field == 'orderby') cmd.sort = cmd[field];
    return this;
  }

  /**
   * Add a comment to the cursor query allowing for tracking the comment in the log.
   * @method
   * @param {string} value The comment attached to this query.
   * @throws {MongoError}
   * @return {Cursor}
   */
  this.comment = function(value) {
    if(state == Cursor.CLOSED || state == Cursor.OPEN || self.isDead()) throw new MongoError("Cursor is closed");
    cmd.comment = value;
    return this;
  }

  /**
   * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
   * @method
   * @param {number} value Number of milliseconds to wait before aborting the query.
   * @throws {MongoError}
   * @return {Cursor}
   */
  this.maxTimeMS = function(value) {
    if(typeof value != 'number') throw new MongoError("maxTimeMS must be a number");
    if(state == Cursor.CLOSED || state == Cursor.OPEN || self.isDead()) throw new MongoError("Cursor is closed");
    maxTimeMS = value;
    cmd.maxTimeMS = value;
    return self;
  }

  this.maxTimeMs = this.maxTimeMS;

  /**
   * Sets a field projection for the query.
   * @method
   * @param {object} value The field projection object.
   * @throws {MongoError}
   * @return {Cursor}
   */
  this.project = function(value) {
    if(state == Cursor.CLOSED || state == Cursor.OPEN || self.isDead()) throw new MongoError("Cursor is closed");
    cmd.fields = value;
    return this;
  }

  /**
   * Sets the sort order of the cursor query.
   * @method
   * @param {(string|array|object)} keyOrList The key or keys set for the sort.
   * @param {number} [direction] The direction of the sorting (1 or -1).
   * @throws {MongoError}
   * @return {Cursor}
   */
  this.sort = function(keyOrList, direction) {
    if(options.tailable) throw new MongoError("Tailable cursor doesn't support sorting");
    if(state == Cursor.CLOSED || state == Cursor.OPEN || self.isDead()) throw new MongoError("Cursor is closed");
    var order = keyOrList;

    if(direction != null) {
      order = [[keyOrList, direction]];
    }

    cmd.sort = order;
    return this;
  }

  /**
   * Set the batch size for the cursor.
   * @method
   * @param {number} value The batchSize for the cursor.
   * @throws {MongoError}
   * @return {Cursor}
   */
  this.batchSize = function(value) {
    if(options.tailable) throw new MongoError("Tailable cursor doesn't support limit");
    if(state == Cursor.CLOSED || self.isDead()) throw new MongoError("Cursor is closed");
    if(typeof value != 'number') throw new MongoError("batchSize requires an integer");
    cmd.batchSize = value;
    this.cursorBatchSize = value;
    return self;
  }

  /**
   * Set the limit for the cursor.
   * @method
   * @param {number} value The limit for the cursor query.
   * @throws {MongoError}
   * @return {Cursor}
   */
  this.limit = function(value) {
    if(options.tailable) throw new MongoError("Tailable cursor doesn't support limit");
    if(state == Cursor.OPEN || state == Cursor.CLOSED || self.isDead()) throw new MongoError("Cursor is closed");
    if(typeof value != 'number') throw new MongoError("limit requires an integer");
    cmd.limit = value;
    this.cursorLimit = value;
    return self;
  }

  /**
   * Set the skip for the cursor.
   * @method
   * @param {number} value The skip for the cursor query.
   * @throws {MongoError}
   * @return {Cursor}
   */
  this.skip = function(value) {
    if(options.tailable) throw new MongoError("Tailable cursor doesn't support skip");
    if(state == Cursor.OPEN || state == Cursor.CLOSED || self.isDead()) throw new MongoError("Cursor is closed");
    if(typeof value != 'number') throw new MongoError("skip requires an integer");
    cmd.skip = value;
    this.cursorSkip = value;
    return self;
  }

  /**
   * The callback format for results
   * @callback Cursor~resultCallback
   * @param {MongoError} error An error instance representing the error during the execution.
   * @param {(object|null)} result The result object if the command was executed successfully.
   */

  /**
   * Get the next available document from the cursor, returns null if no more documents are available.
   * @function external:CoreCursor#next
   * @param {Cursor~resultCallback} callback The result callback.
   * @throws {MongoError}
   * @return {null}
   */

  /**
   * Clone the cursor
   * @function external:CoreCursor#clone
   * @return {Cursor}
   */

  /**
   * Resets the cursor
   * @function external:CoreCursor#rewind
   * @return {null}
   */

  /**
   * Get the next available document from the cursor, returns null if no more documents are available.
   * @method
   * @param {Cursor~resultCallback} callback The result callback.
   * @throws {MongoError}
   * @deprecated
   * @return {null}
   */
  this.nextObject = function(callback) {
    if(state == Cursor.CLOSED || self.isDead()) return handleCallback(callback, new MongoError("Cursor is closed"));
    if(state == Cursor.INIT && cmd.sort) {
      try {
        cmd.sort = formattedOrderClause(cmd.sort);
      } catch(err) {
        return handleCallback(callback, err);
      }
    }

    // Get the next object
    self.next(function(err, doc) {
      if(err && err.tailable && currentNumberOfRetries == 0) return callback(err);
      if(err && err.tailable && currentNumberOfRetries > 0) {
        currentNumberOfRetries = currentNumberOfRetries - 1;
        return setTimeout(function() {
          self.nextObject(callback);
        }, tailableRetryInterval);
      }

      state = Cursor.OPEN;
      if(err) return handleCallback(callback, err);
      handleCallback(callback, null, doc);
    });
  }

  // Trampoline emptying the number of retrieved items
  // without incurring a nextTick operation
  var loop = function(self, callback) {
    // No more items we are done
    if(self.bufferedCount() == 0) return;
    // Get the next document
    self.next(callback);
    // Loop
    return loop;
  }

  /**
   * Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
   * not all of the elements will be iterated if this cursor had been previouly accessed.
   * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
   * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
   * at any given time if batch size is specified. Otherwise, the caller is responsible
   * for making sure that the entire result can fit the memory.
   * @method
   * @deprecated
   * @param {Cursor~resultCallback} callback The result callback.
   * @throws {MongoError}
   * @return {null}
   */
  this.each = function(callback) {
    // Rewind cursor state
    this.rewind();
    // Set current cursor to INIT
    state = Cursor.INIT;
    // Run the query
    _each(this, callback);
  };

  // Run the each loop
  var _each = function(self, callback) {
    if(!callback) throw new MongoError('callback is mandatory');
    if(self.isNotified()) return;
    if(state == Cursor.CLOSED || self.isDead()) {
      return handleCallback(callback, new MongoError("Cursor is closed"), null);
    }

    if(state == Cursor.INIT) state = Cursor.OPEN;
    // Trampoline all the entries
    if(self.bufferedCount() > 0) {
      while(fn = loop(self, callback)) fn(self, callback);
      _each(self, callback);
    } else {
      self.next(function(err, item) {
        if(err) return handleCallback(callback, err);
        if(item == null) {
          state = Cursor.CLOSED;
          return handleCallback(callback, null, null);
        }

        if(handleCallback(callback, null, item) == false) return;
        _each(self, callback);
      })
    }
  }

  /**
   * The callback format for the forEach iterator method
   * @callback Cursor~iteratorCallback
   * @param {Object} doc An emitted document for the iterator
   */

  /**
   * The callback error format for the forEach iterator method
   * @callback Cursor~endCallback
   * @param {MongoError} error An error instance representing the error during the execution.
   */

  /**
   * Iterates over all the documents for this cursor using the iterator, callback pattern.
   * @method
   * @param {Cursor~iteratorCallback} iterator The iteration callback.
   * @param {Cursor~endCallback} callback The end callback.
   * @throws {MongoError}
   * @return {null}
   */
  this.forEach = function(iterator, callback) {
    this.each(function(err, doc){
      if(err) { callback(err); return false; }
      if(doc != null) { iterator(doc); return true; }
      if(doc == null && callback) {
        var internalCallback = callback;
        callback = null;
        internalCallback(null);
        return false;
      }
    });
  }

  /**
   * Set the ReadPreference for the cursor.
   * @method
   * @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
   * @throws {MongoError}
   * @return {Cursor}
   */
  this.setReadPreference = function(r) {
    if(state != Cursor.INIT) throw new MongoError('cannot change cursor readPreference after cursor has been accessed');
    if(r instanceof ReadPreference) {
      options.readPreference = new CoreReadPreference(r.mode, r.tags);
    } else {
      options.readPreference = new CoreReadPreference(r);
    }

    return this;
  }

  /**
   * The callback format for results
   * @callback Cursor~toArrayResultCallback
   * @param {MongoError} error An error instance representing the error during the execution.
   * @param {object[]} documents All the documents the satisfy the cursor.
   */

  /**
   * Returns an array of documents. The caller is responsible for making sure that there
   * is enough memory to store the results. Note that the array only contain partial
   * results when this cursor had been previouly accessed. In that case,
   * cursor.rewind() can be used to reset the cursor.
   * @method
   * @param {Cursor~toArrayResultCallback} callback The result callback.
   * @throws {MongoError}
   * @return {null}
   */
  this.toArray = function(callback) {
    if(!callback) throw new MongoError('callback is mandatory');
    if(options.tailable) return handleCallback(callback, new MongoError("Tailable cursor cannot be converted to array"), null);
    var items = [];

    // Reset cursor
    this.rewind();
    this.state = Cursor.INIT;

    // Fetch all the documents
    var fetchDocs = function() {
      self.next(function(err, doc) {
        if(err) return handleCallback(callback, err);
        if(doc == null) {
          state = Cursor.CLOSED;
          return handleCallback(callback, null, items);
        }

        // Add doc to items
        items.push(doc)
        // Get all buffered objects
        if(self.bufferedCount() > 0) {
          var a = self.readBufferedDocuments(self.bufferedCount())
          items = items.concat(a);
        }

        // Attempt a fetch
        fetchDocs();
      })
    }

    fetchDocs();
  }

  /**
   * The callback format for results
   * @callback Cursor~countResultCallback
   * @param {MongoError} error An error instance representing the error during the execution.
   * @param {number} count The count of documents.
   */

  /**
   * Get the count of documents for this cursor
   * @method
   * @param {boolean} applySkipLimit Should the count command apply limit and skip settings on the cursor or in the passed in options.
   * @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
   * @param {object} [options=null] Optional settings.
   * @param {number} [options.skip=null] The number of documents to skip.
   * @param {number} [options.limit=null] The maximum amounts to count before aborting.
   * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
   * @param {string} [options.hint=null] An index name hint for the query.
   * @param {Cursor~countResultCallback} callback The result callback.
   * @return {null}
   */
  this.count = function(applySkipLimit, opts, callback) {
    if(typeof opts == 'function') callback = opts, opts = {};
    opts = opts || {};
    if(cmd.query == null) callback(new MongoError("count can only be used with find command"));
    if(typeof applySkipLimit == 'function') {
      callback = applySkipLimit;
      applySkipLimit = true;
    }

    var opts = {};
    if(applySkipLimit) {
      if(typeof this.cursorSkip == 'number') opts.skip = this.cursorSkip;
      if(typeof this.cursorLimit == 'number') opts.limit = this.cursorLimit;
    }

    // Command
    var command = {
      'count': ns.split('.').pop(), 'query': cmd.query
    }

    // If maxTimeMS set
    if(typeof maxTimeMS == 'number') {
      command.maxTimeMS = maxTimeMS;
    }

    // Get a server
    var server = topology.getServer(opts);
    // Get a connection
    var connection = topology.getConnection(opts);
    // Get the callbacks
    var callbacks = server.getCallbacks();

    // Merge in any options
    if(opts.skip) command.skip = opts.skip;
    if(opts.limit) command.limit = opts.limit;
    if(options.hint) command.hint = options.hint;

    // Build Query object
    var query = new Query(bson, f("%s.$cmd", ns.split('.').shift()), command, {
        numberToSkip: 0, numberToReturn: -1
      , checkKeys: false
    });

    // Set up callback
    callbacks.once(query.requestId, function(err, result) {
      if(err) return handleCallback(callback, err);
      if(result.documents.length == 1
        && (result.documents[0].errmsg
        || result.documents[0].err
        || result.documents[0]['$err'])) return callback(MongoError.create(result.documents[0]));
      handleCallback(callback, null, result.documents[0].n);
    });

    // Write the initial command out
    connection.write(query);
  };

  /**
   * Close the cursor, sending a KillCursor command and emitting close.
   * @method
   * @param {Cursor~resultCallback} [callback] The result callback.
   * @return {null}
   */
  this.close = function(callback) {
    state = Cursor.CLOSED;
    // Kill the cursor
    this.kill();
    // Emit the close event for the cursor
    this.emit('close');
    // Callback if provided
    if(callback) return handleCallback(callback, null, self);
  }

  /**
   * Is the cursor closed
   * @method
   * @return {boolean}
   */
  this.isClosed = function() {
    return this.isDead();
  }

  this.destroy = function(err) {
    this.pause();
    this.close();
    if(err) this.emit('error', err);
  }

  /**
   * Return a modified Readable stream including a possible transform method.
   * @method
   * @param {object} [options=null] Optional settings.
   * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream.
   * @return {Cursor}
   */
  this.stream = function(options) {
    streamOptions = options || {};
    return this;
  }

  /**
   * Execute the explain for the cursor
   * @method
   * @param {Cursor~resultCallback} [callback] The result callback.
   * @return {null}
   */
  this.explain = function(callback) {
    cmd.explain = true;
    self.next(callback);
  }

  this._read = function(n) {
    if(state == Cursor.CLOSED || self.isDead()) {
      // options.db.removeListener('close', closeListener);
      return self.push(null);
    }

    // Get the next item
    self.nextObject(function(err, result) {
      if(err) {
        if(!self.isDead()) self.destroy();
        return self.push(null);
      }

      // If we provided a transformation method
      if(typeof streamOptions.transform == 'function' && result != null) {
        return self.push(streamOptions.transform(result));
      }

      // Return the result
      self.push(result);
    });
  }

  /**
   * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.
   * @function external:Readable#read
   * @param {number} size Optional argument to specify how much data to read.
   * @return {(String | Buffer | null)}
   */

  /**
   * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
   * @function external:Readable#setEncoding
   * @param {string} encoding The encoding to use.
   * @return {null}
   */

  /**
   * This method will cause the readable stream to resume emitting data events.
   * @function external:Readable#resume
   * @return {null}
   */

  /**
   * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.
   * @function external:Readable#pause
   * @return {null}
   */

  /**
   * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
   * @function external:Readable#pipe
   * @param {Writable} destination The destination for writing data
   * @param {object} [options] Pipe options
   * @return {null}
   */

  /**
   * This method will remove the hooks set up for a previous pipe() call.
   * @function external:Readable#unpipe
   * @param {Writable} [destination] The destination for writing data
   * @return {null}
   */

  /**
   * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.
   * @function external:Readable#unshift
   * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue.
   * @return {null}
   */

  /**
   * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.)
   * @function external:Readable#wrap
   * @param {Stream} stream An "old style" readable stream.
   * @return {null}
   */
}

/**
 * Cursor stream data event, fired for each document in the cursor.
 *
 * @event Cursor#data
 * @type {object}
 */

/**
 * Cursor stream end event
 *
 * @event Cursor#end
 * @type {null}
 */

/**
 * Cursor stream close event
 *
 * @event Cursor#close
 * @type {null}
 */

/**
 * Cursor stream readable event
 *
 * @event Cursor#readable
 * @type {null}
 */

// Extend the Cursor
inherits(Cursor, CoreCursor);

// Inherit from Readable
inherits(Cursor, Readable);

Cursor.INIT = 0;
Cursor.OPEN = 1;
Cursor.CLOSED = 2;
Cursor.GET_MORE = 3;

module.exports = Cursor;


text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"net/url"
	"os"
	"time"

	"github.com/flynn/flynn/Godeps/_workspace/src/github.com/mattn/go-colorable"
	"github.com/flynn/flynn/Godeps/_workspace/src/gopkg.in/inconshreveable/log15.v2"
	"github.com/flynn/flynn/controller/client"
	ct "github.com/flynn/flynn/controller/types"
	"github.com/flynn/flynn/discoverd/client"
	"github.com/flynn/flynn/updater/types"
)

var slugbuilderURI, slugrunnerURI string

// use a flag to determine whether to use a TTY log formatter because actually
// assigning a TTY to the job causes reading images via stdin to fail.
var isTTY = flag.Bool("tty", false, "use a TTY log formatter")

func main() {
	flag.Parse()
	if err := run(); err != nil {
		os.Exit(1)
	}
}

func run() error {
	log := log15.New()
	if *isTTY {
		log.SetHandler(log15.StreamHandler(colorable.NewColorableStdout(), log15.TerminalFormat()))
	}

	var images map[string]string
	if err := json.NewDecoder(os.Stdin).Decode(&images); err != nil {
		log.Error("error decoding images", "err", err)
		return err
	}

	instances, err := discoverd.GetInstances("flynn-controller", 10*time.Second)
	if err != nil {
		log.Error("error looking up controller in service discovery", "err", err)
		return err
	}
	client, err := controller.NewClient("", instances[0].Meta["AUTH_KEY"])
	if err != nil {
		log.Error("error creating controller client", "err", err)
		return err
	}

	log.Info("validating images")
	uris := make(map[string]string, len(updater.SystemApps)+2)
	for _, name := range append(updater.SystemApps, "slugbuilder", "slugrunner") {
		image := "flynn/" + name
		if name == "gitreceive" {
			image = "flynn/receiver"
		} else if name == "postgres" {
			image = "flynn/postgresql"
		}
		uri, ok := images[image]
		if !ok {
			err := fmt.Errorf("missing image: %s", image)
			log.Error(err.Error())
			return err
		}
		uris[name] = uri
	}
	slugbuilderURI = uris["slugbuilder"]
	slugrunnerURI = uris["slugrunner"]

	// deploy system apps in order first
	for _, name := range updater.SystemApps {
		log := log.New("name", name)
		log.Info("starting deploy of system app")

		app, err := client.GetApp(name)
		if err != nil {
			log.Error("error getting app", "err", err)
			return err
		}
		if err := deployApp(client, app, uris[name], log); err != nil {
			if e, ok := err.(errDeploySkipped); ok {
				log.Info("skipped deploy of system app", "reason", e.reason)
				continue
			}
			return err
		}
		log.Info("finished deploy of system app")
	}

	// deploy all other apps
	apps, err := client.AppList()
	if err != nil {
		log.Error("error getting apps", "err", err)
		return err
	}
	for _, app := range apps {
		if app.System() {
			continue
		}
		log := log.New("name", app.Name)
		log.Info("starting deploy of app to update slugrunner")
		if err := deployApp(client, app, slugrunnerURI, log); err != nil {
			if e, ok := err.(errDeploySkipped); ok {
				log.Info("skipped deploy of app", "reason", e.reason)
				continue
			}
			return err
		}
		log.Info("finished deploy of app")
	}
	return nil
}

type errDeploySkipped struct {
	reason string
}

func (e errDeploySkipped) Error() string {
	return e.reason
}

func deployApp(client *controller.Client, app *ct.App, uri string, log log15.Logger) error {
	release, err := client.GetAppRelease(app.ID)
	if err != nil {
		log.Error("error getting release", "err", err)
		return err
	}
	artifact, err := client.GetArtifact(release.ArtifactID)
	if err != nil {
		log.Error("error getting release artifact", "err", err)
		return err
	}
	if !app.System() {
		u, err := url.Parse(artifact.URI)
		if err != nil {
			return err
		}
		if u.Query().Get("name") != "flynn/slugrunner" {
			return errDeploySkipped{"app not using slugrunner image"}
		}
	}
	skipDeploy := artifact.URI == uri
	// deploy the gitreceive / taffy apps if builder / runner images have changed
	switch app.Name {
	case "taffy", "gitreceive":
		if updateSlugURIs(release.Env) {
			skipDeploy = false
		}
	}
	if skipDeploy {
		return errDeploySkipped{"app is already using latest images"}
	}
	artifact.ID = ""
	artifact.URI = uri
	if err := client.CreateArtifact(artifact); err != nil {
		log.Error("error creating artifact", "err", err)
		return err
	}
	release.ID = ""
	release.ArtifactID = artifact.ID
	if err := client.CreateRelease(release); err != nil {
		log.Error("error creating new release", "err", err)
		return err
	}
	if err := client.DeployAppRelease(app.ID, release.ID); err != nil {
		log.Error("error deploying app", "err", err)
		return err
	}
	return nil
}

func updateSlugURIs(env map[string]string) bool {
	updated := false
	if env["SLUGBUILDER_IMAGE_URI"] != slugbuilderURI {
		env["SLUGBUILDER_IMAGE_URI"] = slugbuilderURI
		updated = true
	}
	if env["SLUGRUNNER_IMAGE_URI"] != slugrunnerURI {
		env["SLUGRUNNER_IMAGE_URI"] = slugrunnerURI
		updated = true
	}
	return updated
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 37: 373 (1939)

#### Original name
Mycosphaerella verecunda Syd.

### Remarks
null


text:
namespace DTS
{
   class BrushMesh : public Mesh
   {
      public:

         //! Creates an standard mesh by default
         BrushMesh() : Mesh(T_Standard) {}

         //! Creates (or recreates) the mesh
         virtual void construct() = 0 ;

      protected:

         //! Create a new vertex with convenient (altough arbitrary) normal/texture data
         void addVertex (float, float, float) ;
   };

   class CylinderMesh : public BrushMesh
   {
      public:

         //! Create a standard mesh as a cylinder (the box is used for the center and Z range)
         CylinderMesh (Box &, float radius, float complexity = 0.25f) ;

         //! Creates (or recreates) the mesh
         virtual void construct() ;

      private:

         float complexity ;
   };

   class BoxMesh : public BrushMesh
   {
      public:

         //! Create a standard mesh as a box
         BoxMesh (Box &) ;

         //! Creates (or recreates) the mesh
         virtual void construct() ;
   };
}

#endif


text:
// Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.server.index.group;

import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.replication.ReplicatedAccountIndexer;

import java.io.IOException;

public interface GroupIndexer extends ReplicatedAccountIndexer {

  /**
   * Synchronously index a group.
   *
   * @param uuid group UUID to index.
   */
  void index(AccountGroup.UUID uuid) throws IOException;

  /**
   * Synchronously reindex a group if it is stale.
   *
   * @param uuid group UUID to index.
   * @return whether the group was reindexed
   */
  boolean reindexIfStale(AccountGroup.UUID uuid) throws IOException;
}


text:
;(function(exports) {
  var Coquette = function(game, canvasId, width, height, backgroundColor, autoFocus) {
    var canvas = document.getElementById(canvasId);
    this.renderer = new Coquette.Renderer(this, game, canvas, width, height, backgroundColor);
    this.inputter = new Coquette.Inputter(this, canvas, autoFocus);
    this.entities = new Coquette.Entities(this, game);
    this.runner = new Coquette.Runner(this);
    this.collider = new Coquette.Collider(this);

    var self = this;
    this.ticker = new Coquette.Ticker(this, function(interval) {
      self.runner.update(interval);
      if (game.update !== undefined) {
        game.update(interval);
      }

      self.entities.update(interval)
      self.collider.update(interval);
      self.renderer.update(interval);
      self.inputter.update();
    });
  };

  exports.Coquette = Coquette;
})(this);

;(function(exports) {
  var Collider = function(coquette) {
    this.c = coquette;
  };

  var isSetupForCollisions = function(obj) {
    return obj.center !== undefined && obj.size !== undefined;
  };

  Collider.prototype = {
    _currentCollisionPairs: [],

    update: function() {
      this._currentCollisionPairs = [];

      // get all entity pairs to test for collision
      var ent = this.c.entities.all();
      for (var i = 0, len = ent.length; i < len; i++) {
        for (var j = i + 1; j < len; j++) {
          this._currentCollisionPairs.push([ent[i], ent[j]]);
        }
      }

      // test collisions
      while (this._currentCollisionPairs.length > 0) {
        var pair = this._currentCollisionPairs.shift();
        if (this.isColliding(pair[0], pair[1])) {
          this.collision(pair[0], pair[1]);
        }
      }
    },

    collision: function(entity1, entity2) {
      notifyEntityOfCollision(entity1, entity2);
      notifyEntityOfCollision(entity2, entity1);
    },

    createEntity: function(entity) {
      var ent = this.c.entities.all();
      for (var i = 0, len = ent.length; i < len; i++) {
        if (ent[i] !== entity) { // decouple from when c.entities adds to _entities
          this._currentCollisionPairs.push([ent[i], entity]);
        }
      }
    },

    destroyEntity: function(entity) {
      // if coll detection happening, remove any pairs that include entity
      for(var i = this._currentCollisionPairs.length - 1; i >= 0; i--){
        if (this._currentCollisionPairs[i][0] === entity ||
           this._currentCollisionPairs[i][1] === entity) {
          this._currentCollisionPairs.splice(i, 1);
        }
      }
    },

    isColliding: function(obj1, obj2) {
      return obj1 !== obj2 &&
        isSetupForCollisions(obj1) &&
        isSetupForCollisions(obj2) &&
        this.isIntersecting(obj1, obj2);
    },

    isIntersecting: function(obj1, obj2) {
      var obj1BoundingBox = getBoundingBox(obj1);
      var obj2BoundingBox = getBoundingBox(obj2);

      if (obj1BoundingBox === this.RECTANGLE && obj2BoundingBox === this.RECTANGLE) {
        return Maths.rectanglesIntersecting(obj1, obj2);
      } else if (obj1BoundingBox === this.CIRCLE && obj2BoundingBox === this.RECTANGLE) {
        return Maths.circleAndRectangleIntersecting(obj1, obj2);
      } else if (obj1BoundingBox === this.RECTANGLE && obj2BoundingBox === this.CIRCLE) {
        return Maths.circleAndRectangleIntersecting(obj2, obj1);
      } else if (obj1BoundingBox === this.CIRCLE && obj2BoundingBox === this.CIRCLE) {
        return Maths.circlesIntersecting(obj1, obj2);
      } else {
        throw "Objects being collision tested have unsupported bounding box types."
      }
    },

    RECTANGLE: 0,
    CIRCLE: 1
  };

  var getBoundingBox = function(obj) {
    return obj.boundingBox || Collider.prototype.RECTANGLE;
  };

  var notifyEntityOfCollision = function(entity, other) {
    if (entity.collision !== undefined) {
      entity.collision(other);
    }
  };

  var rotated = function(obj) {
    return obj.angle !== undefined && obj.angle !== 0;
  };

  var getAngle = function(obj) {
    return obj.angle === undefined ? 0 : obj.angle;
  };

  var Maths = {
    circlesIntersecting: function(obj1, obj2) {
      return Maths.distance(obj1.center, obj2.center) <
        obj1.size.x / 2 + obj2.size.x / 2;
    },

    rectanglesIntersecting: function(obj1, obj2) {
      if (!rotated(obj1) && !rotated(obj2)) {
        return this.unrotatedRectanglesIntersecting(obj1, obj2); // faster
      } else {
        return this.rotatedRectanglesIntersecting(obj1, obj2); // slower
      }
    },

    circleAndRectangleIntersecting: function(circleObj, rectangleObj) {
      var rectangleObjAngleRad = -getAngle(rectangleObj) * Maths.RADIANS_TO_DEGREES;

      var unrotatedCircleCenter = {
        x: Math.cos(rectangleObjAngleRad) *
          (circleObj.center.x - rectangleObj.center.x) -
          Math.sin(rectangleObjAngleRad) *
          (circleObj.center.y - rectangleObj.center.y) + rectangleObj.center.x,
        y: Math.sin(rectangleObjAngleRad) *
          (circleObj.center.x - rectangleObj.center.x) +
          Math.cos(rectangleObjAngleRad) *
          (circleObj.center.y - rectangleObj.center.y) + rectangleObj.center.y
      };

      var closest = { x: 0, y: 0 };

      if (unrotatedCircleCenter.x < rectangleObj.center.x - rectangleObj.size.x / 2) {
        closest.x = rectangleObj.center.x - rectangleObj.size.x / 2;
      } else if (unrotatedCircleCenter.x > rectangleObj.center.x + rectangleObj.size.x / 2) {
        closest.x = rectangleObj.center.x + rectangleObj.size.x / 2;
      } else {
        closest.x = unrotatedCircleCenter.x;
      }

      if (unrotatedCircleCenter.y < rectangleObj.center.y - rectangleObj.size.y / 2) {
        closest.y = rectangleObj.center.y - rectangleObj.size.y / 2;
      } else if (unrotatedCircleCenter.y > rectangleObj.center.y + rectangleObj.size.y / 2) {
        closest.y = rectangleObj.center.y + rectangleObj.size.y / 2;
      } else {
        closest.y = unrotatedCircleCenter.y;
      }

      return this.distance(unrotatedCircleCenter, closest) < circleObj.size.x / 2;
    },

    unrotatedRectanglesIntersecting: function(obj1, obj2) {
      if(obj1.center.x + obj1.size.x / 2 < obj2.center.x - obj2.size.x / 2) {
        return false;
      } else if(obj1.center.x - obj1.size.x / 2 > obj2.center.x + obj2.size.x / 2) {
        return false;
      } else if(obj1.center.y - obj1.size.y / 2 > obj2.center.y + obj2.size.y / 2) {
        return false;
      } else if(obj1.center.y + obj1.size.y / 2 < obj2.center.y - obj2.size.y / 2) {
        return false
      } else {
        return true;
      }
    },

    rotatedRectanglesIntersecting: function(obj1, obj2) {
      var obj1Normals = this.rectanglePerpendicularNormals(obj1);
      var obj2Normals = this.rectanglePerpendicularNormals(obj2);

      var obj1Corners = this.rectangleCorners(obj1);
      var obj2Corners = this.rectangleCorners(obj2);

      if (this.projectionsSeparate(
        this.getMinMaxProjection(obj1Corners, obj1Normals[1]),
        this.getMinMaxProjection(obj2Corners, obj1Normals[1]))) {
        return false;
      } else if (this.projectionsSeparate(
        this.getMinMaxProjection(obj1Corners, obj1Normals[0]),
        this.getMinMaxProjection(obj2Corners, obj1Normals[0]))) {
        return false;
      } else if (this.projectionsSeparate(
        this.getMinMaxProjection(obj1Corners, obj2Normals[1]),
        this.getMinMaxProjection(obj2Corners, obj2Normals[1]))) {
        return false;
      } else if (this.projectionsSeparate(
        this.getMinMaxProjection(obj1Corners, obj2Normals[0]),
        this.getMinMaxProjection(obj2Corners, obj2Normals[0]))) {
        return false;
      } else {
        return true;
      }
    },

    pointInsideObj: function(point, obj) {
      var objBoundingBox = getBoundingBox(obj);

      if (objBoundingBox === Collider.prototype.RECTANGLE) {
        return this.pointInsideRectangle(point, obj);
      } else if (objBoundingBox === Collider.prototype.CIRCLE) {
        return this.pointInsideCircle(point, obj);
      } else {
        throw "Tried to see if point inside object with unsupported bounding box.";
      }
    },

    pointInsideRectangle: function(point, obj) {
      var c = Math.cos(-getAngle(obj) * Maths.RADIANS_TO_DEGREES);
      var s = Math.sin(-getAngle(obj) * Maths.RADIANS_TO_DEGREES);

      var rotatedX = obj.center.x + c *
          (point.x - obj.center.x) - s * (point.y - obj.center.y);
      var rotatedY = obj.center.y + s *
          (point.x - obj.center.x) + c * (point.y - obj.center.y);

      var leftX = obj.center.x - obj.size.x / 2;
      var rightX = obj.center.x + obj.size.x / 2;
      var topY = obj.center.y - obj.size.y / 2;
      var bottomY = obj.center.y + obj.size.y / 2;

      return leftX <= rotatedX && rotatedX <= rightX &&
        topY <= rotatedY && rotatedY <= bottomY;
    },

    pointInsideCircle: function(point, obj) {
      return this.distance(point, obj.center) <= obj.size.x / 2;
    },

    distance: function(point1, point2) {
      var x = point1.x - point2.x;
      var y = point1.y - point2.y;
      return Math.sqrt((x * x) + (y * y));
    },

    vectorTo: function(start, end) {
      return {
        x: end.x - start.x,
        y: end.y - start.y
      };
    },

    magnitude: function(vector) {
      return Math.sqrt(vector.x * vector.x + vector.y * vector.y);
    },

    leftNormalizedNormal: function(vector) {
      return {
        x: -vector.y,
        y: vector.x
      };
    },

    dotProduct: function(vector1, vector2) {
      return vector1.x * vector2.x + vector1.y * vector2.y;
    },

    unitVector: function(vector) {
      return {
        x: vector.x / Maths.magnitude(vector),
        y: vector.y / Maths.magnitude(vector)
      };
    },

    projectionsSeparate: function(proj1, proj2) {
      return proj1.max < proj2.min || proj2.max < proj1.min;
    },

    getMinMaxProjection: function(objCorners, normal) {
      var min = Maths.dotProduct(objCorners[0], normal);
      var max = Maths.dotProduct(objCorners[0], normal);

      for (var i = 1; i < objCorners.length; i++) {
        var current = Maths.dotProduct(objCorners[i], normal);
        if (min > current) {
          min = current;
        }

        if (current > max) {
          max = current;
        }
      }

      return { min: min, max: max };
    },

    rectangleCorners: function(obj) {
      var corners = [ // unrotated
        { x:obj.center.x - obj.size.x / 2, y: obj.center.y - obj.size.y / 2 },
        { x:obj.center.x + obj.size.x / 2, y: obj.center.y - obj.size.y / 2 },
        { x:obj.center.x + obj.size.x / 2, y: obj.center.y + obj.size.y / 2 },
        { x:obj.center.x - obj.size.x / 2, y: obj.center.y + obj.size.y / 2 }
      ];

      var angle = getAngle(obj) * Maths.RADIANS_TO_DEGREES;

			for (var i = 0; i < corners.length; i++) {
				var xOffset = corners[i].x - obj.center.x;
				var yOffset = corners[i].y - obj.center.y;
				corners[i].x = obj.center.x +
          xOffset * Math.cos(angle) - yOffset * Math.sin(angle);
				corners[i].y = obj.center.y +
          xOffset * Math.sin(angle) + yOffset * Math.cos(angle);
			}

      return corners;
    },

    rectangleSideVectors: function(obj) {
      var corners = this.rectangleCorners(obj);
      return [
        { x: corners[0].x - corners[1].x, y: corners[0].y - corners[1].y },
        { x: corners[1].x - corners[2].x, y: corners[1].y - corners[2].y },
        { x: corners[2].x - corners[3].x, y: corners[2].y - corners[3].y },
        { x: corners[3].x - corners[0].x, y: corners[3].y - corners[0].y }
      ];
    },

    rectanglePerpendicularNormals: function(obj) {
      var sides = this.rectangleSideVectors(obj);
      return [
        Maths.leftNormalizedNormal(sides[0]),
        Maths.leftNormalizedNormal(sides[1])
      ];
    },

    RADIANS_TO_DEGREES: 0.01745
  };

  exports.Collider = Collider;
  exports.Collider.Maths = Maths;
})(typeof exports === 'undefined' ? this.Coquette : exports);

;(function(exports) {
  var Inputter = function(coquette, canvas, autoFocus) {
    var keyboardReceiver = autoFocus === false ? canvas : window;
    connectReceiverToKeyboard(keyboardReceiver, window, autoFocus);

    this._buttonListener = new ButtonListener(canvas, keyboardReceiver);
    this._mouseMoveListener = new MouseMoveListener(canvas);
  };

  Inputter.prototype = {
    update: function() {
      this._buttonListener.update();
    },

    // Returns true if passed button currently down
    isDown: function(button) {
      return this._buttonListener.isDown(button);
    },

    // Returns true if passed button just gone down. true once per keypress.
    isPressed: function(button) {
      return this._buttonListener.isPressed(button);
    },

    getMousePosition: function() {
      return this._mouseMoveListener.getMousePosition();
    },

    // Returns true if passed button currently down
    bindMouseMove: function(fn) {
      return this._mouseMoveListener.bind(fn);
    },

    // Stops calling passed fn on mouse move
    unbindMouseMove: function(fn) {
      return this._mouseMoveListener.unbind(fn);
    },

    LEFT_MOUSE: "LEFT_MOUSE",
    RIGHT_MOUSE: "RIGHT_MOUSE",

    BACKSPACE: 8,
    TAB: 9,
    ENTER: 13,
    SHIFT: 16,
    CTRL: 17,
    ALT: 18,
    PAUSE: 19,
    CAPS_LOCK: 20,
    ESC: 27,
    SPACE: 32,
    PAGE_UP: 33,
    PAGE_DOWN: 34,
    END: 35,
    HOME: 36,
    LEFT_ARROW: 37,
    UP_ARROW: 38,
    RIGHT_ARROW: 39,
    DOWN_ARROW: 40,
    INSERT: 45,
    DELETE: 46,
    ZERO: 48,
    ONE: 49,
    TWO: 50,
    THREE: 51,
    FOUR: 52,
    FIVE: 53,
    SIX: 54,
    SEVEN: 55,
    EIGHT: 56,
    NINE: 57,
    A: 65,
    B: 66,
    C: 67,
    D: 68,
    E: 69,
    F: 70,
    G: 71,
    H: 72,
    I: 73,
    J: 74,
    K: 75,
    L: 76,
    M: 77,
    N: 78,
    O: 79,
    P: 80,
    Q: 81,
    R: 82,
    S: 83,
    T: 84,
    U: 85,
    V: 86,
    W: 87,
    X: 88,
    Y: 89,
    Z: 90,
    F1: 112,
    F2: 113,
    F3: 114,
    F4: 115,
    F5: 116,
    F6: 117,
    F7: 118,
    F8: 119,
    F9: 120,
    F10: 121,
    F11: 122,
    F12: 123,
    NUM_LOCK: 144,
    SCROLL_LOCK: 145,
    SEMI_COLON: 186,
    EQUALS: 187,
    COMMA: 188,
    DASH: 189,
    PERIOD: 190,
    FORWARD_SLASH: 191,
    GRAVE_ACCENT: 192,
    OPEN_SQUARE_BRACKET: 219,
    BACK_SLASH: 220,
    CLOSE_SQUARE_BRACKET: 221,
    SINGLE_QUOTE: 222
  };

  var ButtonListener = function(canvas, keyboardReceiver) {
    var self = this;
    this._buttonDownState = {};
    this._buttonPressedState = {};

    keyboardReceiver.addEventListener('keydown', function(e) {
      self._down(e.keyCode);
    }, false);

    keyboardReceiver.addEventListener('keyup', function(e) {
      self._up(e.keyCode);
    }, false);

    canvas.addEventListener('mousedown', function(e) {
      self._down(self._getMouseButton(e));
    }, false);

    canvas.addEventListener('mouseup', function(e) {
      self._up(self._getMouseButton(e));
    }, false);
  };

  ButtonListener.prototype = {
    update: function() {
      for (var i in this._buttonPressedState) {
        if (this._buttonPressedState[i] === true) { // tick passed and press event in progress
          this._buttonPressedState[i] = false; // end key press
        }
      }
    },

    _down: function(buttonId) {
      this._buttonDownState[buttonId] = true;
      if (this._buttonPressedState[buttonId] === undefined) { // start of new keypress
        this._buttonPressedState[buttonId] = true; // register keypress in progress
      }
    },

    _up: function(buttonId) {
      this._buttonDownState[buttonId] = false;
      if (this._buttonPressedState[buttonId] === false) { // prev keypress over
        this._buttonPressedState[buttonId] = undefined; // prep for keydown to start next press
      }
    },

    isDown: function(button) {
      return this._buttonDownState[button] || false;
    },

    isPressed: function(button) {
      return this._buttonPressedState[button] || false;
    },

    _getMouseButton: function(e) {
      if (e.which !== undefined || e.button !== undefined) {
        if (e.which === 3 || e.button === 2) {
          return Inputter.prototype.RIGHT_MOUSE;
        } else if (e.which === 1 || e.button === 0 || e.button === 1) {
          return Inputter.prototype.LEFT_MOUSE;
        }
      }

      throw "Cannot judge button pressed on passed mouse button event";
    }
  };

  var MouseMoveListener = function(canvas) {
    this._bindings = [];
    this._mousePosition;
    var self = this;

    canvas.addEventListener('mousemove', function(e) {
      var absoluteMousePosition = self._getAbsoluteMousePosition(e);
      var elementPosition = getElementPosition(canvas);
      self._mousePosition = {
        x: absoluteMousePosition.x - elementPosition.x,
        y: absoluteMousePosition.y - elementPosition.y
      };
    }, false);

    canvas.addEventListener('mousemove', function(e) {
      for (var i = 0; i < self._bindings.length; i++) {
        self._bindings[i](self.getMousePosition());
      }
    }, false);
  };

  MouseMoveListener.prototype = {
    bind: function(fn) {
      this._bindings.push(fn);
    },

    unbind: function(fn) {
      for (var i = 0; i < this._bindings.length; i++) {
        if (this._bindings[i] === fn) {
          this._bindings.splice(i, 1);
          return;
        }
      }

      throw "Function to unbind from mouse moves was never bound";
    },

    getMousePosition: function() {
      return this._mousePosition;
    },

    _getAbsoluteMousePosition: function(e) {
	    if (e.pageX) 	{
        return { x: e.pageX, y: e.pageY };
	    } else if (e.clientX) {
        return { x: e.clientX, y: e.clientY };
      }
    }
  };

  var getWindow = function(document) {
    return document.parentWindow || document.defaultView;
  };

  var getElementPosition = function(element) {
    var rect = element.getBoundingClientRect();
    var document = element.ownerDocument;
    var body = document.body;
    var window = getWindow(document);
    return {
      x: rect.left + (window.pageXOffset || body.scrollLeft) - (body.clientLeft || 0),
      y: rect.top + (window.pageYOffset || body.scrollTop) - (body.clientTop || 0)
    };
  };

  var connectReceiverToKeyboard = function(keyboardReceiver, window, autoFocus) {
    if (autoFocus === false) {
      keyboardReceiver.contentEditable = true; // lets canvas get focus and get key events
    } else {
      var suppressedKeys = [
        Inputter.prototype.SPACE,
        Inputter.prototype.LEFT_ARROW,
        Inputter.prototype.UP_ARROW,
        Inputter.prototype.RIGHT_ARROW,
        Inputter.prototype.DOWN_ARROW
      ];

      // suppress scrolling
      window.addEventListener("keydown", function(e) {
        for (var i = 0; i < suppressedKeys.length; i++) {
          if(suppressedKeys[i] === e.keyCode) {
            e.preventDefault();
            return;
          }
        }
      }, false);
    }
  };

  exports.Inputter = Inputter;
})(typeof exports === 'undefined' ? this.Coquette : exports);

;(function(exports) {
  function Runner(coquette) {
    this.c = coquette;
    this._runs = [];
  };

  Runner.prototype = {
    update: function() {
      this.run();
    },

    run: function() {
      while(this._runs.length > 0) {
        var run = this._runs.shift();
        run.fn(run.obj);
      }
    },

    add: function(obj, fn) {
      this._runs.push({
        obj: obj,
        fn: fn
      });
    }
  };

  exports.Runner = Runner;
})(typeof exports === 'undefined' ? this.Coquette : exports);

;(function(exports) {
  var interval = 16;

  function Ticker(coquette, gameLoop) {
    setupRequestAnimationFrame();

    var nextTickFn;
    this.stop = function() {
      nextTickFn = function() {};
    };

    this.start = function() {
      var prev = Date.now();
      var tick = function() {
        var now = Date.now();
        var interval = now - prev;
        prev = now;
        gameLoop(interval);
        requestAnimationFrame(nextTickFn);
      };

      nextTickFn = tick;
      requestAnimationFrame(nextTickFn);
    };

    this.start();
  };

  // From: https://gist.github.com/paulirish/1579671
  // Thanks Erik, Paul and Tino
  var setupRequestAnimationFrame = function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
      window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
      window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
        || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame) {
      window.requestAnimationFrame = function(callback, element) {
        var currTime = Date.now();
        var timeToCall = Math.max(0, interval - (currTime - lastTime));
        var id = window.setTimeout(function() { callback(currTime + timeToCall); },
                                   timeToCall);
        lastTime = currTime + timeToCall;
        return id;
      };
    }

    if (!window.cancelAnimationFrame) {
      window.cancelAnimationFrame = function(id) {
        clearTimeout(id);
      };
    }
  };

  exports.Ticker = Ticker;
})(typeof exports === 'undefined' ? this.Coquette : exports);

;(function(exports) {
  var Maths;
  if(typeof module !== 'undefined' && module.exports) { // node
    Maths = require('./collider').Collider.Maths;
  } else { // browser
    Maths = Coquette.Collider.Maths;
  }

  var Renderer = function(coquette, game, canvas, wView, hView, backgroundColor) {
    this.c = coquette;
    this.game = game;
    canvas.style.outline = "none"; // stop browser outlining canvas when it has focus
    canvas.style.cursor = "default"; // keep pointer normal when hovering over canvas
    this._ctx = canvas.getContext('2d');
    this._backgroundColor = backgroundColor;

    canvas.width = wView;
    canvas.height = hView;
    this._viewSize = { x:wView, y:hView };
    this._viewCenter = { x: this._viewSize.x / 2, y: this._viewSize.y / 2 };
  };

  Renderer.prototype = {
    getCtx: function() {
      return this._ctx;
    },

    getViewSize: function() {
      return this._viewSize;
    },

    getViewCenter: function() {
      return this._viewCenter;
    },

    setViewCenter: function(pos) {
      this._viewCenter = { x:pos.x, y:pos.y };
    },

    setBackground: function(color) {
      this._backgroundColor = color;
    },

    update: function(interval) {
      var ctx = this.getCtx();
      var viewTranslate = viewOffset(this._viewCenter, this._viewSize);

      ctx.translate(viewTranslate.x, viewTranslate.y);

      // draw background
      var viewArgs = [
            this._viewCenter.x - this._viewSize.x / 2,
            this._viewCenter.y - this._viewSize.y / 2,
            this._viewSize.x,
            this._viewSize.y
      ]
      if (this._backgroundColor !== undefined) {
          ctx.fillStyle = this._backgroundColor;
          ctx.fillRect.apply(ctx, viewArgs);
      } else {
          ctx.clearRect.apply(ctx, viewArgs);
      }

      // draw game and entities
      var drawables = [this.game]
        .concat(this.c.entities.all().sort(zindexSort));
      for (var i = 0, len = drawables.length; i < len; i++) {
        if (drawables[i].draw !== undefined) {
          var drawable = drawables[i];

          ctx.save();

          if (drawable.center !== undefined && drawable.angle !== undefined) {
            ctx.translate(drawable.center.x, drawable.center.y);
            ctx.rotate(drawable.angle * Maths.RADIANS_TO_DEGREES);
            ctx.translate(-drawable.center.x, -drawable.center.y);
          }

          drawables[i].draw(ctx);

          ctx.restore();
        }
      }

      ctx.translate(-viewTranslate.x, -viewTranslate.y);
    },

    onScreen: function(obj) {
      return Maths.rectanglesIntersecting(obj, {
        size: this._viewSize,
        center: {
          x: this._viewCenter.x,
          y: this._viewCenter.y
        }
      });
    }
  };

  var viewOffset = function(viewCenter, viewSize) {
    return {
      x: -(viewCenter.x - viewSize.x / 2),
      y: -(viewCenter.y - viewSize.y / 2)
    }
  };

  // sorts passed array by zindex
  // elements with a higher zindex are drawn on top of those with a lower zindex
  var zindexSort = function(a, b) {
    return (a.zindex || 0) < (b.zindex || 0) ? -1 : 1;
  };

  exports.Renderer = Renderer;
})(typeof exports === 'undefined' ? this.Coquette : exports);

;(function(exports) {
  function Entities(coquette, game) {
    this.c = coquette;
    this.game = game;
    this._entities = [];
  };

  Entities.prototype = {
    update: function(interval) {
      var entities = this.all();
      for (var i = 0, len = entities.length; i < len; i++) {
        if (entities[i].update !== undefined) {
          entities[i].update(interval);
        }
      }
    },

    all: function(Constructor) {
      if (Constructor === undefined) {
        return this._entities.slice(); // return shallow copy of array
      } else {
        var entities = [];
        for (var i = 0; i < this._entities.length; i++) {
          if (this._entities[i] instanceof Constructor) {
            entities.push(this._entities[i]);
          }
        }

        return entities;
      }
    },

    create: function(Constructor, settings) {
      var entity = new Constructor(this.game, settings || {});
      this.c.collider.createEntity(entity);
      this._entities.push(entity);
      return entity;
    },

    destroy: function(entity) {
      for(var i = 0; i < this._entities.length; i++) {
        if(this._entities[i] === entity) {
          this.c.collider.destroyEntity(entity);
          this._entities.splice(i, 1);
          break;
        }
      }
    }
  };

  exports.Entities = Entities;
})(typeof exports === 'undefined' ? this.Coquette : exports);


text:
using LookAndFeel.Components;
using LookAndFeel.Factories;
using LookAndFeelLibrary.Main.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LookAndFeel.Controls{
    /**
     *
     */
    public abstract class Button : MetroFramework.Controls.MetroButton, IControl {
        protected bool isHovered;
        protected bool isPressed;
        protected List<ClickHandler> clickHandlers = new List<ClickHandler>();
        protected ComponentInfo info;

        /**
         *
         */
        public Button() {
            info = new ComponentInfo();
        }

        public Button(ComponentInfo info)
        {
            // TODO: Complete member initialization
            this.info   = info.clone();
            this.Top    = info.Y;
            this.Left   = info.X;
            this.Name   = this.Text = info.Name;
            this.Width  = info.Width    != 0 ? info.Width   : this.Width;
            this.Height = info.Height   != 0 ? info.Height  : this.Height;
            info.Width  = info.Width    != 0 ? info.Width   : this.Width;
            info.Height = info.Height   != 0 ? info.Height  : this.Height;

        }

        /**
         * @return
         */
        public String getType() {
            return "Button";
        }

        /**
         * @return
         */
        public abstract IComponent clone(ComponentInfo info);

        /**
         * @param f
         * @return
         */
        public IComponent convert(ComponentFactory f) {
            return f.create(this.getType(), this.info);
        }

        public event ClickHandler ClickListener
        {
            add{
                this.clickHandlers.Add(value);
            }
            remove {
                this.clickHandlers.Remove(value);
            }
        }

        protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
        {
            base.OnMouseDown(e);
            isPressed = true;
        }

        protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e)
        {
            base.OnMouseUp(e);
            isPressed = false;
            Invalidate();
        }

        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);
            isHovered = true;
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            isHovered = false;
        }

        public override string Text
        {
            get
            {
                return base.Text;
            }
            set
            {
                this.Name = value;
                base.Text = value;
            }
        }

    }
}


text:
<?xml version="1.0"?>
<root>
	<tag><caret></tag><existenttag></existenttag>
</root>


text:
<?hh // strict

class :data extends :xhp:html-element {
  attribute Stringish value @required;
  category %flow, %phrase;
  children (%phrase*);
  protected string $tagName = 'data';
}


text:
package com.taobao.tddl.dbsync.binlog.event;

import com.taobao.tddl.dbsync.binlog.LogBuffer;
import com.taobao.tddl.dbsync.binlog.LogEvent;

/**
 * Start_log_event_v3 is the Start_log_event of binlog format 3 (MySQL 3.23 and
 * 4.x). Format_description_log_event derives from Start_log_event_v3; it is the
 * Start_log_event of binlog format 4 (MySQL 5.0), that is, the event that
 * describes the other events' Common-Header/Post-Header lengths. This event is
 * sent by MySQL 5.0 whenever it starts sending a new binlog if the requested
 * position is >4 (otherwise if ==4 the event will be sent naturally).
 *
 * @see mysql-5.1.60/sql/log_event.cc - Start_log_event_v3
 * @author Changyuan.lh
 * @version 1.0
 */
public class StartLogEventV3 extends LogEvent {

    /**
     * We could have used SERVER_VERSION_LENGTH, but this introduces an obscure
     * dependency - if somebody decided to change SERVER_VERSION_LENGTH this
     * would break the replication protocol
     */
    public static final int ST_SERVER_VER_LEN    = 50;

    /* start event post-header (for v3 and v4) */
    public static final int ST_BINLOG_VER_OFFSET = 0;
    public static final int ST_SERVER_VER_OFFSET = 2;

    protected int           binlogVersion;
    protected String        serverVersion;

    public StartLogEventV3(LogHeader header, LogBuffer buffer, FormatDescriptionLogEvent descriptionEvent){
        super(header);

        buffer.position(descriptionEvent.commonHeaderLen);
        binlogVersion = buffer.getUint16(); // ST_BINLOG_VER_OFFSET
        serverVersion = buffer.getFixName(ST_SERVER_VER_LEN); // ST_SERVER_VER_OFFSET
    }

    public StartLogEventV3(){
        super(new LogHeader(START_EVENT_V3));
    }

    public final String getServerVersion() {
        return serverVersion;
    }

    public final int getBinlogVersion() {
        return binlogVersion;
    }
}


text:
"""Provides services for a specific sustainability "resource" such as energy or water."""

from django.core.exceptions import ObjectDoesNotExist
from django.db.models.aggregates import Sum
from apps.managers.cache_mgr import cache_mgr
from apps.managers.challenge_mgr import challenge_mgr
from apps.managers.team_mgr.models import Team
from apps.managers.resource_mgr.models import EnergyUsage, WaterUsage, ResourceSetting, \
    WasteUsage, ResourceBlackoutDate
from django.template.defaultfilters import slugify
from apps.utils import utils

def get_resource_setting(name):
    """Returns the resource settings for the specified name."""
    resource_setting = cache_mgr.get_cache("resource_setting-%s" % name)
    if resource_setting is None:
        resource_setting = ResourceSetting.objects.get(name=name)
        cache_mgr.set_cache("resource_setting-%s" % name, resource_setting, 2592000)
    return resource_setting

def is_blackout(date):
    """Returns true if the date falls in the Resource Blackout dates."""
    return ResourceBlackoutDate.objects.filter(date=date).exists()

def team_resource_data(date, team, resource):
    """Returns the latest data for the specified resource on the current date."""

    if not is_blackout(date):
        usage = _get_resource_usage(resource)
        energy_data = usage.objects.filter(team=team, date=date)
        if energy_data:
            return energy_data[0]
        else:
            return None
    else:
        return None

def team_resource_usage(date, team, resource):
    """Returns the latest usage of the specified resource for the current date."""
    energy_data = team_resource_data(date, team, resource)
    if energy_data:
        return energy_data.usage
    else:
        return 0

def update_team_resource_usage(resource, session, date, team, storage):
    """update the latest energy usage for the team."""
    usage = storage.get_latest_resource_data(session, team, date)
    if usage:
        resource_usage = _get_resource_usage(resource)
        try:
            latest_usage = resource_usage.objects.get(team=team, date=date.date())
        except ObjectDoesNotExist:
            latest_usage = resource_usage(team=team, date=date.date())

        latest_usage.time = date.time()
        latest_usage.usage = usage
        latest_usage.save()
        print 'team %s energy usage from %s: %d at %s.' % (team, storage.name(), usage, date)

def get_history_resource_data(session, team, date, hour, storage):
    """Return the history energy usage of the team for the date and hour."""
    return storage.get_history_resource_data(session, team, date, hour)

def update_fake_water_usage(date):
    """update fake water usage."""
    for team in Team.objects.all():
        count = team.profile_set.count()
        if count:
            # assume the average water usage is 80 gallon per person per day
            average_usage = 80
            actual_usage = average_usage * 0.9
            water = WaterUsage.objects.filter(team=team, date=date.date())
            if water:
                water = water[0]
            else:
                water = WaterUsage(team=team, date=date.date())

            water.time = date.time()
            water.usage = actual_usage * count
            water.save()
            print 'team %s fake water usage updated at %s.' % (team, date)

def _get_resource_usage(name):
    """Returns the resource usage object by name, or None if not found."""
    if name == "energy":
        return EnergyUsage
    elif name == "water":
        return WaterUsage
    elif name == "waste":
        return WasteUsage
    else:
        return None

def resource_ranks(name, round_name=None):
    """Return the ranking of resource use for all teams."""

    cache_key = "%s_ranks-%s" % (name, slugify(round_name))
    ranks = cache_mgr.get_cache(cache_key)
    if ranks is None:
        resource_usage = _get_resource_usage(name)

        resource_setting = get_resource_setting(name)
        rate = resource_setting.conversion_rate
        if resource_setting.winning_order == "Ascending":
            ordering = "total"
        else:
            ordering = "-total"

        round_info = challenge_mgr.get_round_info(round_name)
        if not round_info:
            return None

        all_rounds_info = challenge_mgr.get_all_round_info()

        usage_ranks = resource_usage.objects.filter(
            date__lte=round_info["end"].date,
            date__gte=all_rounds_info["competition_start"]).values("team__name").annotate(
                total=Sum("usage")).order_by(ordering)

        ranks = []
        for rank in usage_ranks:
            ranks.append({"team__name": rank["team__name"],
                          "total": utils.format_usage(rank["total"], rate)})

        cache_mgr.set_cache(cache_key, ranks, 600)
    return ranks

def resource_team_rank_info(team, resource):
    """Get the overall rank for the team. Return a dict of the rank number and usage."""
    unit = get_resource_setting(resource).unit
    if team:
        ranks = resource_ranks(resource)
        if ranks:
            for idx, rank in enumerate(ranks):
                if rank["team__name"] == team.name:
                    return {"rank": idx + 1, "usage": rank["total"], "unit": unit, }
    else:
        return None

def resource_leader(name, round_name=None):
    """Returns the leader (team name) of the resource use."""
    ranks = resource_ranks(name, round_name)
    if ranks:
        return ranks[0]["team__name"]
    else:
        return None


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<groups>
  <group>[example] All Users</group>
  <group>[example] Authenticated Users</group>
  <group>[example] Local Admins</group>
  <group>[example] System Admins</group>
  <group>[example] Domain Admins</group>
  <group>[example] God</group>
  <group>[example] Viewers</group>
  <group>[example] Limited Access</group>
  <group>[example] Sales</group>
  <group>[example] Marketing</group>
  <group>[example] Upper Management</group>
  <group>[example] Owner</group>
  <group>[example] Legal</group>
  <group>[example] Ninjas</group>
</groups>


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file   Log_i.h
 *
 *  $Id: Log_i.h 935 2008-12-10 21:47:27Z mitza $
 *
 *  Implementation of the DsLogAdmin::Log interface.
 *
 *  @author Matthew Braun <mjb2@cs.wustl.edu>
 *  @author Pradeep Gore <pradeep@cs.wustl.edu>
 *  @author David A. Hanvey <d.hanvey@qub.ac.uk>
 */
//=============================================================================

#ifndef TAO_TLS_LOG_I_H
#define TAO_TLS_LOG_I_H

#include /**/ "ace/pre.h"

#include "orbsvcs/Log/LogRecordStore.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "orbsvcs/Log/Log_Compaction_Handler.h"
#include "orbsvcs/Log/Log_Flush_Handler.h"
#include "orbsvcs/Log/LogNotification.h"
#include "orbsvcs/Log/LogRecordStore.h"
#include "orbsvcs/DsLogAdminS.h"
#include "ace/Reactor.h"
#include "orbsvcs/Log/log_serv_export.h"

TAO_BEGIN_VERSIONED_NAMESPACE_DECL

class TAO_LogMgr_i;

/**
 * @class TAO_Log_i
 *
 * @brief Used to log events to a logging server
 *
 * This implementation attempts to conform to the telecom
 * logging specification.
 */
class TAO_Log_Serv_Export TAO_Log_i : public virtual POA_DsLogAdmin::Log
{

public:

  /// Constructor.
  TAO_Log_i (CORBA::ORB_ptr orb,
             TAO_LogMgr_i& logmgr_i,
             DsLogAdmin::LogMgr_ptr factory,
             DsLogAdmin::LogId id,
             TAO_LogNotification *log_notifier);

  /// Destructor.
  ~TAO_Log_i ();

  /// Initlialize the Log.
  void init (void);

  /**
   * @name DsLogAdmin::Log Methods
   *
   * DsLogAdmin::Log methods.
   */
  //@{
  /// Return the factory of the log.
  DsLogAdmin::LogMgr_ptr my_factory (void);

  /// Return the id of the log.
  DsLogAdmin::LogId id (void);

  /// Get the list of the QoS properties supported by the log.
  DsLogAdmin::QoSList*
  get_log_qos (void);

  /// Set the list of the QoS properties supported by the log.
  void set_log_qos (const DsLogAdmin::QoSList & qos);

  /// Get the record life in seconds (0 infinite).
  CORBA::ULong
  get_max_record_life (void);

  /// Set the record life in seconds (0 infinite).
  void
  set_max_record_life (CORBA::ULong life);

  /// Get the maximum size in octets.
  CORBA::ULongLong
  get_max_size (void);

  /// Set the maximum size in octets.
  void
  set_max_size (CORBA::ULongLong size);

  /// Get the current size of the log in octets.
  CORBA::ULongLong
  get_current_size (void);

  /// Return the number of records in the log.
  CORBA::ULongLong
  get_n_records (void);

  /// Get the action to be taken when the log reaches its maximum size.
  DsLogAdmin::LogFullActionType
  get_log_full_action (void);

  /// Set the action to be taken when the log reaches its maximum size.
  void
  set_log_full_action (DsLogAdmin::LogFullActionType action);

  /// Get the administrative state of the log.
  DsLogAdmin::AdministrativeState
  get_administrative_state (void);

  /// Set the administrative state of the log.
  void
  set_administrative_state (DsLogAdmin::AdministrativeState state);

  /// Get the forwarding state of the log.
  /// @@ Note: is it ok to make this method virtual?
  /// @@@ Of course!  get_forwarding_state() is virtual in the base
  ///     class dictated by the IDL!  -Ossama
  virtual DsLogAdmin::ForwardingState
  get_forwarding_state (void);

  /// Set the forwarding state of the log.
  /// @@ Note: is it ok to make this method virtual?
  void
    set_forwarding_state (DsLogAdmin::ForwardingState state);

  /// Get the operational state of the log.
  DsLogAdmin::OperationalState
  get_operational_state (void);

  /// Get the log duration
  DsLogAdmin::TimeInterval
  get_interval (void);

  /// Set the log duration.
  void
  set_interval (const DsLogAdmin::TimeInterval & interval);

  /// Get the availability status
  DsLogAdmin::AvailabilityStatus
  get_availability_status (void);

  /// Get the capacity alarm threshold
  DsLogAdmin::CapacityAlarmThresholdList*
    get_capacity_alarm_thresholds (void);

  /**
   * Set the capacity alarm threshold. Threshold values represent
   * percentage levels at which the log should emit events to signal
   * that a log full or log wrap condition is approaching. If the log
   * is set to wrap, the thresholds are relative to the log size
   * between wraps (after a wrap, the percentage full resets to
   * 0).
   */
  void
  set_capacity_alarm_thresholds
  (const DsLogAdmin::CapacityAlarmThresholdList & threshs);

  /// Get the weekly scheduling parameters
  DsLogAdmin::WeekMask*
  get_week_mask (void);

  /// Set the weekly scheduling parameters.
  void
  set_week_mask (const DsLogAdmin::WeekMask & masks);

  /// Returns all records in the log that match the given constraint
  /// <c>.
  DsLogAdmin::RecordList*
  query (const char * grammar,
         const char * c,
         DsLogAdmin::Iterator_out i);

  /// Retrieve <how_many> records from time <from_time> using iterator
  /// <i>.
  DsLogAdmin::RecordList*
  retrieve (DsLogAdmin::TimeT from_time,
            CORBA::Long how_many,
            DsLogAdmin::Iterator_out i);

  /// Returns the number of records matching constraint <c>.
  CORBA::ULong
  match (const char * grammar,
         const char * c);

  /// Delete records matching constraint <c>.
  CORBA::ULong
  delete_records (const char * grammar,
                  const char * c);

  /// Delete records matching ids in <ids>
  CORBA::ULong
  delete_records_by_id (const DsLogAdmin::RecordIdList & ids);

  /// Write records to the log storage.
  void
  write_records (const DsLogAdmin::Anys & records);

  /// Write a list of record ids to storage. Raises DsLogAdmin::LogFull
  /// and DsLogAdmin::LogLocked
  void
  write_recordlist (const DsLogAdmin::RecordList & list);

  /// Set single record attributes.
  void
  set_record_attribute (DsLogAdmin::RecordId id,
                        const DsLogAdmin::NVList & attr_list);

  /// Set the attributes of all records that matches the
  /// constraints with same attr_list.
  CORBA::ULong
  set_records_attribute (const char * grammar,
                         const char * c,
                         const DsLogAdmin::NVList & attr_list);

  /// Get the attributes of the record with id <id>. Raises
  /// DsLogAdmin::InvalidRecordId
  DsLogAdmin::NVList*
  get_record_attribute (DsLogAdmin::RecordId id);

  /// Causes all pending events to be written to storage. Raises
  /// DsLogAdmin::UnsupportedQos
  void
  flush (void);
  //@}

  /// Remove records that have exceeded max_record_life_.
  void remove_old_records (void);

protected:
  /// Get the availability status
  /// @note must be called with locks held
  DsLogAdmin::AvailabilityStatus
  get_availability_status_i (void);

  /// Tells if the Log is scheduled to run now.
  /// @note must be called with locks held
  CORBA::Boolean scheduled (void);

  /// Copy the attributes of the log being passed.
  void copy_attributes (DsLogAdmin::Log_ptr log);

  /// Check if threshold reached.
  void check_capacity_alarm_threshold (void);

  /// Reset capacity alarm threshold.
  void reset_capacity_alarm_threshold (void);

  /// Check that valid threshold values have been given.
  static CORBA::Boolean validate_capacity_alarm_thresholds (
    const DsLogAdmin::CapacityAlarmThresholdList & threshs);

  /// Reset Log QoS
  void reset_log_qos (const DsLogAdmin::QoSList& qos);

  /// Validate log QoS
  void validate_log_qos (const DsLogAdmin::QoSList& qos);

  /// Reset Week Mask
  ///
  /// Used to initialize internal data structures that represent the
  /// week mask list when the log service starts, and to reinitialize
  /// them when they are changed.
  ///
  void reset_week_mask (const DsLogAdmin::WeekMask& masks);

  /// Validate Week Mask
  ///
  /// Used to check whether week mask is valid.  If not, throws an
  /// InvalidTime, InvalidTimeInterval, or InvalidMask exception.
  ///
  void validate_week_mask (const DsLogAdmin::WeekMask& masks);

protected:
  /// Reference to the LogMgr servant
  TAO_LogMgr_i& logmgr_i_;

  /// The log's object reference
  DsLogAdmin::Log_var log_;

  /// The log's factory's object reference
  DsLogAdmin::LogMgr_var factory_;

  /// The log's id
  DsLogAdmin::LogId logid_;

  /// The log's operational state
  DsLogAdmin::OperationalState op_state_;

  /// The log's availability status
  DsLogAdmin::AvailabilityStatus avail_status_;

  /// The list of points at which the log should generate events
  /// indicating approaching full capacity
  DsLogAdmin::CapacityAlarmThresholdList thresholds_;

  /// The next capacity alarm threshold.
  CORBA::ULong current_threshold_;

  /// A Sequence of the weekly intervals when the log is in operation.
  DsLogAdmin::TimeIntervalSeq weekly_intervals_;

  /// The QoS type of the log
  DsLogAdmin::QoSType qostype_;

  /// The reactor used for timing (startup and shutdown), etc
  ACE_Reactor *reactor_;

  /// The storage for all the records
  TAO_LogRecordStore*   recordstore_;

  /// For sending Log Generated events.
  TAO_LogNotification*    notifier_;

  /// Log Compaction Handler
  TAO_Log_Compaction_Handler  log_compaction_handler_;

  /// Log Compaction Interval
  static const ACE_Time_Value log_compaction_interval_;

  /// Log Flush Handler
  TAO_Log_Flush_Handler   log_flush_handler_;

  /// Log Flush Interval
  static const ACE_Time_Value log_flush_interval_;
};

bool TAO_Log_Serv_Export
operator==(const DsLogAdmin::CapacityAlarmThresholdList& rhs,
           const DsLogAdmin::CapacityAlarmThresholdList& lhs);

bool TAO_Log_Serv_Export
operator!=(const DsLogAdmin::CapacityAlarmThresholdList& rhs,
           const DsLogAdmin::CapacityAlarmThresholdList& lhs);

bool TAO_Log_Serv_Export
operator==(const DsLogAdmin::IntervalsOfDay& rhs,
           const DsLogAdmin::IntervalsOfDay& lhs);

bool TAO_Log_Serv_Export
operator!=(const DsLogAdmin::IntervalsOfDay& rhs,
           const DsLogAdmin::IntervalsOfDay& lhs);

bool TAO_Log_Serv_Export
operator==(const DsLogAdmin::QoSList& rhs,
           const DsLogAdmin::QoSList& lhs);

bool TAO_Log_Serv_Export
operator!=(const DsLogAdmin::QoSList& rhs,
           const DsLogAdmin::QoSList& lhs);

bool TAO_Log_Serv_Export
operator==(const DsLogAdmin::Time24& rhs,
           const DsLogAdmin::Time24& lhs);

bool TAO_Log_Serv_Export
operator!=(const DsLogAdmin::Time24& rhs,
           const DsLogAdmin::Time24& lhs);

bool TAO_Log_Serv_Export
operator==(const DsLogAdmin::Time24Interval& rhs,
           const DsLogAdmin::Time24Interval& lhs);

bool TAO_Log_Serv_Export
operator!=(const DsLogAdmin::Time24Interval& rhs,
           const DsLogAdmin::Time24Interval& lhs);

bool TAO_Log_Serv_Export
operator==(const DsLogAdmin::TimeInterval& rhs,
           const DsLogAdmin::TimeInterval& lhs);

bool TAO_Log_Serv_Export
operator!=(const DsLogAdmin::TimeInterval& rhs,
           const DsLogAdmin::TimeInterval& lhs);

bool TAO_Log_Serv_Export
operator==(const DsLogAdmin::WeekMaskItem& rhs,
           const DsLogAdmin::WeekMaskItem& lhs);

bool TAO_Log_Serv_Export
operator!=(const DsLogAdmin::WeekMaskItem& rhs,
           const DsLogAdmin::WeekMaskItem& lhs);

bool TAO_Log_Serv_Export
operator==(const DsLogAdmin::WeekMask& rhs,
           const DsLogAdmin::WeekMask& lhs);

bool TAO_Log_Serv_Export
operator!=(const DsLogAdmin::WeekMask& rhs,
           const DsLogAdmin::WeekMask& lhs);

TAO_END_VERSIONED_NAMESPACE_DECL

#include /**/ "ace/post.h"

#endif  /* TAO_TLS_LOG_I_H */


text:
'use strict';

const expect = require('chai').expect;
const mockery = require('mockery');
const sinon = require('sinon');

describe('random-wrapper', () => {

    describe('real', () => {
        let randomWrapper;

        beforeEach(() => {
            mockery.enable({
                useCleanCache: true
            });

            sinon.stub(Math, 'random');

            mockery.registerAllowable('../../lib/random-wrapper.js');
            randomWrapper = require('../../lib/random-wrapper.js');
            randomWrapper.integer = {};

        });

        afterEach(() => {
            Math.random.restore();
            mockery.deregisterAll();
            mockery.disable();
        });

        it('should call Math.random once, without parameters', () => {
            randomWrapper.real();

            expect(Math.random.args).to.eql([[]]);
        });

        it('should return the result of Math.random', () => {
            Math.random.returns('result of random');

            const result = randomWrapper.real();

            expect(result).to.eql('result of random');
        });
    });

    describe('integer', () => {
        let randomWrapper;

        beforeEach(() => {
            mockery.enable({
                useCleanCache: true
            });

            sinon.stub(Math, 'random');
            sinon.stub(Math, 'floor');

            mockery.registerAllowable('../../lib/random-wrapper.js');
            randomWrapper = require('../../lib/random-wrapper.js');
            randomWrapper.real = {};
        });

        afterEach(() => {
            Math.random.restore();
            Math.floor.restore();
            mockery.deregisterAll();
            mockery.disable();
        });

        it('should call Math.random once, without parameters', () => {
            randomWrapper.integer();

            expect(Math.random.args).to.eql([[]]);
        });

        it('should call Math.floor once, with the result of Math.random * (max - min + 1) when min=1 and max=1', () => {
            Math.random.returns(1);

            randomWrapper.integer(1, 1);

            expect(Math.floor.args).to.eql([
                [1]
            ]);

        });

        it('should call Math.floor once, with the result of Math.random * (max - min + 1) when min=6 and max=20', () => {
            Math.random.returns(1);

            randomWrapper.integer(6, 20);

            expect(Math.floor.args).to.eql([
                [15]
            ]);
        });

        it('should return the result of Math.floor + min when min=3', () => {
            Math.floor.returns(94);

            const result = randomWrapper.integer(3, 49);

            expect(result).to.equal(94 + 3);
        });
    });
});


text:
package com.arcao.trackables.internal.di.module;

import android.app.Activity;
import com.arcao.trackables.internal.di.PerActivity;
import dagger.Module;
import dagger.Provides;

@Module
public class ActivityModule {
	private final Activity activity;

	public ActivityModule(Activity activity) {
		this.activity = activity;
	}

	@PerActivity
	@Provides
	public Activity provideActivity() {
		return activity;
	}
}


text:
import api from '../../api'

const LOADING = 'models/LOADING'
const LOADED = 'models/LOADED'
const ERROR = 'models/ERROR'

const initialState = {
  loading: false,
  loaded: false,
  data: [],
  error: null
}

const mutations = {
  [LOADING] (state) {
    state.loading = true
  },

  [LOADED] (state, models) {
    state.loading = false
    state.loaded = true
    state.data = models
  },

  [ERROR] (state, error) {
    state.loading = false
    state.error = error
  }
}

const actions = {
  loadModels ({ commit }) {
    commit(LOADING)
    api.allModels(
      (data) => commit(LOADED, data),
      (error) => commit(ERROR, error)
    )
  }
}

export default {
  state: initialState,
  mutations,
  actions
}


text:
'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var ArticleSchema = new Schema({
  name: String,
  info: String,
  active: Boolean,
  date: { type: Date, default: Date.now },
  author: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  }
});

ArticleSchema.statics = {
  loadRecent: function(req, cb) {
  if(req){
	this.find(req)
      .populate({path:'author', select: 'name'})
      .sort('-date')
      .limit(20)
      .exec(cb);
  }
  else{
    this.find({})
      .populate({path:'author', select: 'name'})
      .sort('-date')
      .limit(20)
      .exec(cb);
	}
  }
};

module.exports = mongoose.model('Article', ArticleSchema);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>mi-cho-coq: Error 🔥</title>
    <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
    <link href="../../../../../bootstrap.min.css" rel="stylesheet">
    <link href="../../../../../bootstrap-custom.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

             Coq bench

clean / extra-dev

dev / mi-cho-coq - 0.1

            « Up

              mi-cho-coq

                0.1
                Error 🔥

📅  (2022-05-10 21:30:59 UTC)

Context

# Packages matching: installed
# Name                # Installed # Synopsis
base-bigarray         base
base-threads          base
base-unix             base
conf-findutils        1           Virtual package relying on findutils
conf-gmp              4           Virtual package relying on a GMP lib system installation
coq                   dev         Formal proof management system
dune                  3.1.1       Fast, portable, and opinionated build system
ocaml                 4.13.1      The OCaml compiler (virtual package)
ocaml-base-compiler   4.13.1      Official release 4.13.1
ocaml-config          2           OCaml Switch Configuration
ocaml-options-vanilla 1           Ensure that OCaml is compiled with no special options enabled
ocamlfind             1.9.3       A library manager for OCaml
zarith                1.12        Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
synopsis: "A specification of Michelson in Coq to prove properties about smart contracts in Tezos"
maintainer: "raphael.cauderlier@nomadic-labs.com"
authors: [ "Raphaël Cauderlier" "Bruno Bernardo" "Julien Tesson" "Arvid Jakobsson" ]
homepage: "https://gitlab.com/nomadic-labs/mi-cho-coq/"
dev-repo: "git+https://gitlab.com/nomadic-labs/mi-cho-coq/"
bug-reports: "https://gitlab.com/nomadic-labs/mi-cho-coq/issues"
license: "MIT"
build: [
  ["./configure"]
  [make "-j%{jobs}%"]
]
install: [
  make "install"
]
depends: [
  "coq" {>= "8.8"}
  "coq-menhirlib" {>= "20190626"}
  "coq-ott" {>= "0.29"}
  "menhir"
  "ocaml" {>= "4.07.1"}
  "ocamlbuild"
  "ott" {build & >= "0.29"}
  "zarith"
]
description: """
Michelson is a language for writing smart contracts on the Tezos blockchain.
This package provides a Coq encoding of the syntax and semantics of Michelson,
automatically generated by the Ott tool. Also included is a framework called Mi-Cho-Coq
for reasoning about Michelson programs in Coq using a weakest precondition calculus."""
tags: [
  "category:Computer Science/Programming Languages/Formal Definitions and Theory"
  "date:2021-06-15"
  "keyword:cryptocurrency"
  "keyword:michelson"
  "keyword:semantics"
  "keyword:smart-contract"
  "keyword:tezos"
  "logpath:Michocoq"
  "logpath:Michocott"
]
url {
  http: "https://gitlab.com/nomadic-labs/mi-cho-coq/-/archive/version-0.1/mi-cho-coq-version-0.1.tar.gz"
  checksum: "521927e391d5529f652056d97fcdd261"
}

Lint

Command

true

Return code

0

Dry install 🏜

Dry install with the current Coq version:

Command

opam install -y --show-action coq-mi-cho-coq.0.1 coq.dev

Return code

0

Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:

Command

true

Return code

0

Install dependencies

Command

opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-mi-cho-coq.0.1 coq.dev

Return code

0

Duration

10 m 58 s

Install 🚀

Command

opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-mi-cho-coq.0.1 coq.dev

Return code

7936

Duration

25 s

Output

# Packages matching: installed
# Name                # Installed # Synopsis
base-bigarray         base
base-threads          base
base-unix             base
conf-findutils        1           Virtual package relying on findutils
conf-gmp              4           Virtual package relying on a GMP lib system installation
coq                   dev         Formal proof management system
coq-menhirlib         dev         A support library for verified Coq parsers produced by Menhir
coq-ott               dev         Auxiliary Coq library for Ott, a tool for writing definitions of programming languages and calculi
dune                  3.1.1       Fast, portable, and opinionated build system
menhir                dev         An LR(1) parser generator
menhirLib             dev         Runtime support library for parsers generated by Menhir
menhirSdk             dev         Compile-time library for auxiliary tools related to Menhir
ocaml                 4.13.1      The OCaml compiler (virtual package)
ocaml-base-compiler   4.13.1      Official release 4.13.1
ocaml-config          2           OCaml Switch Configuration
ocaml-options-vanilla 1           Ensure that OCaml is compiled with no special options enabled
ocamlbuild            0.14.1      OCamlbuild is a build system with builtin rules to easily build most OCaml projects
ocamlfind             1.9.3       A library manager for OCaml
ott                   0.32        A tool for writing definitions of programming languages and calculi
zarith                1.12        Implements arithmetic and logical operations over arbitrary-precision integers
[NOTE] Package coq is already installed (current version is dev).
The following actions will be performed:
  - install coq-mi-cho-coq 0.1
<><> Gathering sources ><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
Processing  1/1: [coq-mi-cho-coq.0.1: http]
[coq-mi-cho-coq.0.1] downloaded from https://gitlab.com/nomadic-labs/mi-cho-coq/-/archive/version-0.1/mi-cho-coq-version-0.1.tar.gz
Processing  1/1:
<><> Processing actions <><><><><><><><><><><><><><><><><><><><><><><><><><><><>
Processing  1/2: [coq-mi-cho-coq: ./configure]
+ /home/bench/.opam/opam-init/hooks/sandbox.sh "build" "./configure" (CWD=/home/bench/.opam/ocaml-base-compiler.4.13.1/.opam-switch/build/coq-mi-cho-coq.0.1)
- Generating the main Makefile
- Unknown option src
- Usage summary:
-
- coq_makefile .... [file.v] ... [file.ml[ig]?] ... [file.ml{lib,pack}]
-   ... [-I dir] ... [-R physicalpath logicalpath]
-   ... [-Q physicalpath logicalpath] ... [VARIABLE = value]
-   ... [-arg opt] ... [-docroot path] [-f file] [-o file]
-   ... [-generate-meta-for-package project-name]
-   [-h] [--help]
-
- Full list of options:
-
- [file.v]: Coq file to be compiled
- [file.ml[ig]?]: Objective Caml file to be compiled
- [file.ml{lib,pack}]: ocamlbuild-style file that describes a Objective Caml
-   library/module
- [-I dir]: look for Objective Caml dependencies in "dir"
- [-R physicalpath logicalpath]: look for Coq dependencies recursively
-   starting from "physicalpath". The logical path associated to the
-   physical path is "logicalpath".
- [-Q physicalpath logicalpath]: look for Coq dependencies starting from
-   "physicalpath". The logical path associated to the physical path
-   is "logicalpath".
- [VARIABLE = value]: Add the variable definition "VARIABLE=value"
- [-arg opt]: send option "opt" to coqc
- [-docroot path]: Install the documentation in this folder, relative to
-   "user-contrib".
- [-f file]: take the contents of file as arguments
- [-o file]: output should go in file file (recommended)
- 	Output file outside the current directory is forbidden.
- [-generate-meta-for-package project-name]: generate META.project-name.
- [-h]: print this usage summary
- [--help]: equivalent to [-h]
- fail while building main makefile
[ERROR] The compilation of coq-mi-cho-coq failed at "/home/bench/.opam/opam-init/hooks/sandbox.sh build ./configure".
#=== ERROR while compiling coq-mi-cho-coq.0.1 =================================#
# context              2.0.10 | linux/x86_64 | ocaml-base-compiler.4.13.1 | file:///home/bench/run/opam-coq-archive/released
# path                 ~/.opam/ocaml-base-compiler.4.13.1/.opam-switch/build/coq-mi-cho-coq.0.1
# command              ~/.opam/opam-init/hooks/sandbox.sh build ./configure
# exit-code            1
# env-file             ~/.opam/log/coq-mi-cho-coq-23599-865888.env
# output-file          ~/.opam/log/coq-mi-cho-coq-23599-865888.out
### output ###
# [-Q physicalpath logicalpath]: look for Coq dependencies starting from
# [...]
# [VARIABLE = value]: Add the variable definition "VARIABLE=value"
# [-arg opt]: send option "opt" to coqc
# [-docroot path]: Install the documentation in this folder, relative to
#   "user-contrib".
# [-f file]: take the contents of file as arguments
# [-o file]: output should go in file file (recommended)
# 	Output file outside the current directory is forbidden.
# [-generate-meta-for-package project-name]: generate META.project-name.
# [-h]: print this usage summary
# [--help]: equivalent to [-h]
# fail while building main makefile
<><> Error report <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
+- The following actions failed
| - build coq-mi-cho-coq 0.1
+-
- No changes have been performed
# Run eval $(opam env) to update the current shell environment
'opam install -y -v coq-mi-cho-coq.0.1 coq.dev' failed.

Installation size

No files were installed.

Uninstall 🧹

Command

true

Return code

0

Missing removes

                none

Wrong removes

                none

          Sources are on GitHub © Guillaume Claret 🐣


text:
package org.apache.felix.scr.annotations;

/**
 * Options for {@link Property#unbounded()} property.
 * @since 1.4
 */
public enum PropertyUnbounded {

    /** Property is not unbounded. This is the default. */
    DEFAULT,

    /** Property is an unbounded array. */
    ARRAY,

    /** Property is an unbounded vector. */
    VECTOR
}


text:
#include "honk.h"

#if !(defined(_WIN32))
#  error This file can only be used on Microsoft Windows systems.
#endif

#include <windows.h>

/**
 * Windows doesn't need a handle to the console,
 * so we just use an arbitrary value instead
 */
static const int default_handle = 42;

int
beep_open() {
    return default_handle;
    }

int
beep_do(int handle, double freq, double len) {
    /* Check the user passed in the same handle we gave them earlier */
    if (handle != default_handle)
        return -1;

    /* Perform the beep */
    Beep((DWORD) freq, (DWORD) (len * 1000));

    /* Return the handle */
    return handle;
    }

void
beep_close(int handle) {
    /* Turn off the speaker, if it is running */
    Beep(0, 0);
    }


text:
package ru.elazarev.bomberman.secondversion;

import ru.elazarev.bomberman.secondversion.board.Board;
import ru.elazarev.bomberman.secondversion.board.Cell;
import ru.elazarev.bomberman.secondversion.models.Hero;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Bobmerman game class.
 * @author Eugene Lazarev mailto(helycopternicht@rambler.ru)
 * @since 27.07.17
 */
public class Game {
    /**
     * Game board.
     */
    private Board board;
    /**
     * Pool of units threads.
     */
    private ExecutorService threadPool;
    /**
     * Count of monsters.
     */
    private int countOfMonsters;

    /**
     * Hero of game.
     */
    private Hero hero;

    /**
     * Constructor with board size.
     * @param fieldSize size of game board
     * @param countOfMonsters number of monsters to add on the game field
     */
    public Game(int fieldSize, int countOfMonsters) {
        this.board = new Board(fieldSize);
        this.countOfMonsters = countOfMonsters;
        this.threadPool = Executors.newFixedThreadPool(fieldSize);
    }

    /**
     * Start new game.
     */
    public void start() {
        placeUnitsOnTheBoard();
    }

    /**
     * Method places units on game board.
     */
    private void placeUnitsOnTheBoard() {
        hero = new Hero("Hero", board, new Cell(board.size() - 1, 0));
        threadPool.execute(hero);
        placeBariers();
        placeMonsters();
    }

    /**
     * Method places bariers on game board.
     */
    private void placeBariers() {
        //todo:
    }

    /**
     * Method places monsters on game board.
     */
    private void placeMonsters() {
        //todo:
    }

    /**
     * Main to test.
     * @param args args
     * @throws InterruptedException nop
     */
    public static void main(String[] args) throws InterruptedException {
        Game g = new Game(10, 10);
        g.start();
        g.hero.goBottom();
        Thread.sleep(1000);
        g.hero.goLeft();
        Thread.sleep(1000);
        g.hero.goRight();
        Thread.sleep(1000);
        g.hero.goTop();

    }
}