text:
package com.izforge.izpack.panels.process;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.junit.runner.RunWith;

import com.izforge.izpack.api.data.InstallData;
import com.izforge.izpack.api.handler.Prompt;
import com.izforge.izpack.api.rules.RulesEngine;
import com.izforge.izpack.core.resource.ResourceManager;
import com.izforge.izpack.panels.test.TestConsolePanelContainer;
import com.izforge.izpack.test.Container;
import com.izforge.izpack.test.junit.PicoRunner;
import com.izforge.izpack.test.util.TestConsole;
import com.izforge.izpack.util.PlatformModelMatcher;

/**
 * Tests the {@link ProcessConsolePanel} class.
 * TODO - this only covers a fraction of ProcessPanel functionality.
 *
 * @author Tim Anderson
 */
@RunWith(PicoRunner.class)
@Container(TestConsolePanelContainer.class)
public class ProcessConsolePanelTest
{

    /**
     * The installation data.
     */
    private final InstallData installData;

    /**
     * The rules.
     */
    private final RulesEngine rules;

    /**
     * The resources.
     */
    private final ResourceManager resources;

    /**
     * The prompt.
     */
    private final Prompt prompt;

    /**
     * The platform-model matcher.
     */
    private final PlatformModelMatcher matcher;

    /**
     * The console.
     */
    private final TestConsole console;

    /**
     * Constructs a {@code ProcessConsolePanelTest}.
     *
     * @param installData the installation data
     * @param rules       the rules
     * @param resources   the resources
     * @param prompt      the prompt
     * @param matcher     the platform-model matcher
     * @param console     the console
     */
    public ProcessConsolePanelTest(InstallData installData, RulesEngine rules, ResourceManager resources,
                                   Prompt prompt, PlatformModelMatcher matcher, TestConsole console)
    {
        this.installData = installData;
        this.rules = rules;
        this.resources = resources;
        this.prompt = prompt;
        this.matcher = matcher;
        this.console = console;
        resources.setResourceBasePath("/com/izforge/izpack/panels/process/");
    }

    /**
     * Tests a job with executeclass elements.
     */
    @Test
    public void testExecuteClass()
    {
        Executable.init();
        Executable.setReturn(true);

        ProcessConsolePanel panel = new ProcessConsolePanel(rules, resources, prompt, matcher, null);
        assertTrue(panel.run(installData, console));

        // verify Executable was run the expected no. of times, with the expected arguments
        assertEquals(2, Executable.getInvocations());
        assertArrayEquals(Executable.getArgs(0), new String[]{"run0"});
        assertArrayEquals(Executable.getArgs(1), new String[]{"run1", "somearg"});
    }

    /**
     * Verifies that an error is displayed if the specified executeclass throws an exception.
     *
     * @throws Exception for any error
     */
    @Test
    public void testExecuteClassException() throws Exception
    {
        Executable.init();
        Executable.setException(true);

        ProcessConsolePanel panel = new ProcessConsolePanel(rules, resources, prompt, matcher, null);
        assertFalse(panel.run(installData, console));

        assertEquals(4, console.getOutput().size());
        assertTrue(console.getOutput().get(3).equals(
                "Invocation Problem calling: com.izforge.izpack.panels.process.Executable, Executable exception"));

        // verify Executable was run the expected no. of times, with the expected arguments
        assertEquals(1, Executable.getInvocations());
        assertArrayEquals(Executable.getArgs(0), new String[]{"run0"});
    }

}


text:
<?php

namespace Amranidev\ScaffoldInterface\Tests;

use Orchestra\Testbench\TestCase as OrchestraTestCase;

abstract class TestCase extends OrchestraTestCase
{
    protected function getPackageProviders($app)
    {
        return ['Amranidev\ScaffoldInterface\ScaffoldInterfaceServiceProvider'];
    }

    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('amranidev.config.views', base_path().'/resources/views');
        $app['config']->set('amranidev.config.model', base_path().'/app');
        $app['config']->set('amranidev.config.controller', base_path().'/app');
        $app['config']->set('amranidev.config.migration', base_path().'/database/migrations');
        $app['config']->set('amranidev.config.routes', base_path().'/app/routes.php');
        $app['config']->set('amranidev.config.modelNameSpace', 'App');
        $app['config']->set('amranidev.config.migration', base_path().'/database/migrations');
        $app['config']->set('amranidev.config.controllerNameSpace', 'App\\Http\\Controllers');
        $app['config']->set('amranidev.config.prefixViews', null);
        $app['config']->set('amranidev.config.prefixRoutes', null);
    }
}

redpajama_set_name: RedPajamaGithub


text: <parent><?target data?></parent>


text:
#pragma once

#ifndef __BSPCONFIG__
#define	__BSPCONFIG__
#define	FIXEDTOCOLORCACHE(n)	((n+(1<<11))>>12)
#define	COLORLEVELONE	16
#define	COLORCACHESIZE	32
#endif


text:
var _ = require('underscore');
var amqp = require('amqp');
var events = require('events');
var util = require('util');

var log = require('oae-logger').logger('mq');
var OAE = require('./oae');
var OaeUtil = require('./util');

var connection = null;
var queueExchange = null;
var queues = {};

var initialized = false;

// Determines whether or not we should purge queues on first connect. Also ensures we only purge the
// first time it connects (i.e., on "startup"), however any disconnect / connects while the server is
// running will not repurge
var purgeQueuesOnStartup = false;
var startupPurgeStatus = {};

var numMessagesInProcessing = 0;
var messagesInProcessing = {};

var MAX_NUM_MESSAGES_IN_PROCESSING = 1000;
var NUM_MESSAGES_TO_DUMP = 10;

/**
 * ## RabbitMQ API
 *
 * ### Events
 *
 *  * `preSubmit(name, data)`                               - Invoked just before a task is submit to the task handler (in the same process tick).
 *  * `preHandle(name, data, headers, deliveryInfo)`        - Invoked just before a task handler is invoked with the task data (in the same process tick in which the task was received).
 *  * `postHandle(err, name, data, headers, deliveryInfo)`  - Invoked after the task handler finishes processing (or if an exception is thrown in the same process tick in which it is invoked).
 *  * `prePurge(name)`                                      - Invoked just before a queue is purged. All mesages which are not awaiting acknowledgement will be removed.
 *  * `postPurge(name, count)`                              - Invoked after the queue has been purged. `count` is the number of messages that are purged from the queue.
 *  * `idle`                                                - Invoked when all current tasks have been completed and the worker is no longer processing any tasks
 */
var MQ = module.exports = new events.EventEmitter();

/**
 * MQ constants.
 *
 *  {String}    DEFAULT_TASK_EXCHANGE_NAME          The name of the AMQP task exchange
 *  {Object}    DEFAULT_TASK_EXCHANGE_OPTS          The default options to specify when creating the AMQP task exchange
 *  {Object}    DEFAULT_TASK_QUEUE_OPTS             The default options to specify when creating the AMQP task queue
 *  {Object}    DEFAULT_TASK_QUEUE_PUBLISH_OPTS     The default options to specify when publishing tasks on the AMQP task queue
 *  {Object}    DEFAULT_TASK_QUEUE_SUBSCRIBE_OPTS   The default options to specify when subscribing to a task queue.
 */
var Constants = module.exports.Constants = {
    'DEFAULT_TASK_EXCHANGE_NAME': 'oae-taskexchange',
    'DEFAULT_TASK_EXCHANGE_OPTS': {
        'type': 'direct',
        'durable': true,
        'autoDelete': false
    },
    'DEFAULT_TASK_QUEUE_OPTS': {
        'durable': true,
        'autoDelete': false,
        'arguments': {
            // Additional information on highly available RabbitMQ queues can be found at http://www.rabbitmq.com/ha.html.
            // We use `all` as the policy: Queue is mirrored across all nodes in the cluster.
            // When a new node is added to the cluster, the queue will be mirrored to that node.
            'x-ha-policy': 'all'
        }
    },
    'DEFAULT_TASK_QUEUE_PUBLISH_OPTS': {
        'deliveryMode': 2                   // 2 indicates 'persistent'
    },
    'DEFAULT_TASK_QUEUE_SUBSCRIBE_OPTS': {
        'ack': true,
        'prefetchCount': 15
    }
};

var deferredTaskHandlers = {};
var ready = false;

OAE.on('ready', function() {
    ready = true;

    var numberToBind = _.keys(deferredTaskHandlers).length;
    var numberBound = 0;
    var returned = false;

    /*!
     * Monitors all the deferred task handlers that have been bound, emitting a 'ready' event
     * when all have been bound.
     */
    var _monitorBinding = function(err) {
        if (returned) {
            // Do nothing, we've called back
            return;
        } else if (err) {
            MQ.emit('ready', err);
            returned = true;
            return;
        }

        numberBound++;
        if (!returned && numberBound >= numberToBind) {
            MQ.emit('ready');
            returned = true;
        }
    };

    if (numberToBind > 0) {
        // Bind all the deferred task handlers now that the container is ready
        _.each(deferredTaskHandlers, function(handlerInfo, taskName) {
            bind(taskName, handlerInfo.listener, handlerInfo.options, _monitorBinding);
            delete deferredTaskHandlers[taskName];
        });
    } else {
        // No deferred task handlers, we're just immediately ready
        MQ.emit('ready');
    }
});

/**
 * Initialize the Message Queue system so that it can start sending and receiving messages.
 *
 * @param  {Object}    mqConfig        The MQ Configuration object
 * @param  {Function}  callback        Invoked when initialization completes
 * @param  {Object}    callback.err    An error that occurred, if any
 */
var init = module.exports.init = function(mqConfig, callback) {

    var taskConfig = mqConfig.tasks || {};

    if (!connection) {
        log().info('Initializing RabbitMQ connector.');

        connection = amqp.createConnection(mqConfig.connection);

        // We only honour the purge-queue setting if the environment is not production
        if (mqConfig.purgeQueuesOnStartup === true) {
            if (process.env['NODE_ENV'] !== 'production') {
                purgeQueuesOnStartup = true;
            } else {
                log().warn('Attempted to set config.mq.purgeQueuesOnStartup to true when in production mode. Ignoring and not purging queues.');
                purgeQueuesOnStartup = false;
            }
        }

        // When the connection drops away, we try to reconnect every second.
        connection.setImplOptions({'reconnect': true, 'reconnectBackoffTime': 1000});

        // Keeps track of whether or not the connection errored just before it closed. If so,
        // we let amqp do it's "backoff" retry thing as a result of the error. If it didn't
        // error (e.g., the server was killed), then we need to kick off a reconnect manually.
        var connectionError = false;

        connection.on('error', function(err) {
            connectionError = true;
            log().error({'err': err}, 'Error in the RabbitMQ connection. Reconnecting.');

            // Since this connection can error, retry, and become ready again, ensure we only continue the
            // initialization cycle once.
            if (!initialized) {
                initialized = true;
                return callback();
            }
        });

        connection.on('close', function() {
            if (connectionError) {
                // The connection closed because it had an error, since it's already retrying, just
                // set the error flag back to false so we can catch this again when if reconnect
                connectionError = false;
            } else {
                // The connection "closed" without an error. Since an AMQP connection inherits a stream
                // and not a connection, an unexpected closure (network issue) of an AMQP connection will
                // result in a simple "close". So if we did not get an explicit error above, then we'll
                // want to manually reconnect since AMQP won't do that for us in this scenario.
                log().warn('Closed connection to RabbitMQ. Reconnecting.');
                connection.reconnect();
            }
        });

        connection.on('ready', function() {
            log().info('Connection to RabbitMQ established.');

            // Initialize the exchange for the job queues

            // FIXME: Analyzing the debug output of amqp, it appears this exchange call here may be faulty in the context
            // of a "reconnect", as the original channel will remain open. This always seems to create duplicate channels
            // open to the exchange which go unused. The additional channel(s) (presumably one per reconnect) seem
            // more-or-less harmless and has been happening for quite some time, and at the moment is not worth doing the
            // testing needed to tighten this up

            connection.exchange(Constants.DEFAULT_TASK_EXCHANGE_NAME, Constants.DEFAULT_TASK_EXCHANGE_OPTS, function(exchange) {
                queueExchange = exchange;

                // Since this connection can error, retry, and become ready again, ensure we only continue the
                // initialization cycle once.
                if (!initialized) {
                    initialized = true;
                    return callback();
                }
            });
        });
    } else {
        log().warn('Attempted to initialize an existing RabbitMQ connector. Ignoring');
        return callback();
    }
};

/**
 * Safely shutdown the MQ service after all current tasks are completed.
 *
 * @param  {Function}   Invoked when shutdown is complete
 */
var destroy = module.exports.destroy = function(callback) {
    // Unbind all task queues so we don't receive new messages
    log().info('Unbinding all task queues for shut down...');
    _unbindAll(function() {
        // Give 15 seconds for mq tasks to complete processing
        log().info('Waiting until all processing tasks complete...');
        _waitUntilIdle(15000, callback);
    });
};

OAE.registerPreShutdownHandler('mq', null, destroy);

/**
 * Bind a function to listen for a particular type of task. When bound, the node effectively becomes a "worker" for that task,
 * meaning when it receives a particular job, no other node active in the cluster will receive it.
 *
 * @param  {String}    name                                The unique label that identifies the type of job this binding is listening to
 * @param  {Function}  listener                            The function that will handle tasks of the given type
 * @param  {Object}    listener.data                       The data that was sent in the job. This is different depending on the type of job
 * @param  {Object}    [options]                           A set of options that can override the default ones.
 * @param  {Object}    [options.queue]                     Holds the options that will override the `Constants.DEFAULT_TASK_QUEUE_OPTS` options.
 * @param  {Object}    [options.subscribe]                 Holds the options that will override the `Constants.DEFAULT_TASK_QUEUE_SUBSCRIBE_OPTS` options.
 * @param  {Number}    [options.subscribe.prefetchCount]   The maximum number of tasks that a listener should handle concurrently.
 * @param  {Function}  [callback]                          Invoked after the listener has been bound to the MQ
 * @param  {Object}    [callback.err]                      An error that occurred binding to the task queue, if any
 */
var bind = module.exports.bind = function(name, listener, options, callback) {
    callback = callback || function(err) { /* error is logged within the implementation */ };
    options = options || {};
    options.queue = options.queue || {};
    options.subscribe = options.subscribe || {};

    if (queues[name] || (!ready && deferredTaskHandlers[name])) {
        log().warn({
            'queueName': name,
            'listener': listener
        }, 'Attempted to bind duplicate listener for job queue. Aborting.');
        return callback();
    }

    // If the container is not ready to handle requests, defer the actual binding of these handlers until later
    if (!ready) {
        log().trace({'name': name}, 'Deferring registration of task handler until server is ready.');
        deferredTaskHandlers[name] = {'listener': listener, 'options': options};
        return callback();
    }

    // Create/get the queue.
    var queueOptions = _.defaults(options, Constants.DEFAULT_TASK_QUEUE_OPTS);
    connection.queue(name, queueOptions, function(queue) {
        log().info({'queueName': name}, 'Created/Retrieved a RabbitMQ task queue');
        queues[name] = {'queue': queue};

        // Bind the queue to the task exchange. The routing key is the same as the name of the job queue
        queue.bind(Constants.DEFAULT_TASK_EXCHANGE_NAME, name, function() {
            // Bind the listener to the queue, to handle all jobs of the given `name` type
            var subscribeOptions = _.defaults(options.subscribe, Constants.DEFAULT_TASK_QUEUE_SUBSCRIBE_OPTS);

            if (purgeQueuesOnStartup && !startupPurgeStatus[name]) {
                // Ensure this queue only gets purged the first time we connect
                startupPurgeStatus[name] = true;

                // Purge the queue before subscribing the handler to it if we are configured to do so.
                purge(name, function(err) {
                    if (err) {
                        return callback(err);
                    }

                    return _subscribe(queue, name, subscribeOptions, listener, callback);
                });
            } else {
                return _subscribe(queue, name, subscribeOptions, listener, callback);
            }
        });
    });
};

/**
 * Subscribe the given `listener` function to the provided queue.
 *
 * @param  {Queue}      queue               An AMQP Queue to which we'll subscribe the listener
 * @param  {String}     name                The name that the queue was created under
 * @param  {Object}     subscribeOptions    The options with which we wish to subscribe to the queue
 * @param  {Function}   listener            The function that will handle tasks delivered from the queue
 * @param  {Object}     listener.data       The data that was sent in the job. This is different depending on the type of job
 * @param  {Function}   callback            Invoked when the listener has been subscribed
 * @param  {Object}     callback.err        An error that occurred, if any
 * @api private
 */
var _subscribe = function(queue, name, subscribeOptions, listener, callback) {
    queue.subscribe(subscribeOptions, function(data, headers, deliveryInfo, message) {
        log().trace({
            'queueName': name,
            'data': data,
            'headers': headers,
            'deliveryInfo': deliveryInfo
        }, 'Received an MQ message.');

        var deliveryKey = util.format('%s:%s', deliveryInfo.queue, deliveryInfo.deliveryTag);

        // Indicate that this server has begun processing a new task
        _incrementProcessingTask(deliveryKey, data, deliveryInfo);
        MQ.emit('preHandle', name, data, headers, deliveryInfo);

        // Pass it to the listener.
        // We can only shift this element off the queue, once the listener has finished
        try {
            listener(data, function() {
                log().trace({
                    'queueName': name,
                    'data': data,
                    'headers': headers,
                    'deliveryInfo': deliveryInfo
                }, 'MQ message has been processed by the listener.');

                // Acknowledge that we've seen the message.
                // Note: We can't use queue.shift() as that only acknowledges the last message that the queue handed to us.
                // This message and the last message are not necessarily the same if the prefetchCount was higher than 1.
                message.acknowledge();

                // Indicate that this server has finished processing the task
                _decrementProcessingTask(deliveryKey, deliveryInfo);
                MQ.emit('postHandle', null, name, data, headers, deliveryInfo);

            });
        } catch (err) {
            log().error({
                'err': err,
                'queueName': name,
                'data': data
            }, 'Exception raised while handling job.');

            // Acknowledge that we've seen the message.
            message.acknowledge();

            // Indicate that this server has finished processing the task
            _decrementProcessingTask(deliveryKey, deliveryInfo);
            MQ.emit('postHandle', err, name, data, headers, deliveryInfo);
        }
    }).addCallback(function(ok) {
        if (!ok) {
            log().error({'err': err, 'queueName': name}, 'Error binding worker for task queue.');
            return _destroyQueue(name, function(err) {
                // Don't overwrite the original error with any binding errors
                return callback({'code': 500, 'msg': 'Error binding a worker for task queue'});
            });
        }

        // Keep the consumerTag so we can unsubscribe later.
        queues[name].consumerTag = ok.consumerTag;
        return callback();
    });
};

/**
 * Unbind this node as a worker for the specified type of task.
 *
 * @param  {String}    name            The name of the task to which to unbind this node
 * @param  {Function}  callback        Invoked when the task has been unbound
 * @param  {Object}    callback.err    An error that occurred, if any
 */
var unbind = module.exports.unbind = function(name, callback) {
    callback = callback || function(err) {
        if (err) {
            log().error({'err': err, 'queueName': name}, 'Error unbinding task queue handler.');
        }
    };
    _destroyQueue(name, callback);
};

/**
 * Submit a job to the task queue to be picked up by some arbitrary node in the cluster.
 *
 * @param  {String}     name                        The type of job to submit
 * @param  {Object}     data                        The data to send with the task. This will be received by the worker for this type of task
 * @param  {Function}   [callback]                  Invoked when the job has been submitted
 */
var submit = module.exports.submit = function(name, data, callback) {
    callback = callback || function() {};

    MQ.emit('preSubmit', name, data);
    queueExchange.publish(name, data, _.extend({}, Constants.DEFAULT_TASK_QUEUE_PUBLISH_OPTS));
    return callback();
};

/**
 * Get the names of all the task handlers that are bound to the service.
 *
 * @return {String[]}   A list of all the names of the bound task handlers
 */
var getTaskHandlerNames = module.exports.getTaskHandlerNames = function() {
    return _.keys(queues);
};

/**
 * Unbind all task handlers from the task queue.
 *
 * @param  {Function}   callback    Invoked when the handlers have been unbound
 * @api private
 */
var _unbindAll = function(callback) {
    var queueNames = getTaskHandlerNames();
    var queuesUnbound = 0;
    if (queueNames.length > 0) {
        _.each(queueNames, function(queueName) {
            log().info({'queueName': queueName}, 'Attempting to unbind a task queue.');
            _destroyQueue(queueName, function(err) {
                queuesUnbound++;

                if (!err) {
                    log().info({'queueName': queueName}, 'Successfully unbound a task queue.');
                }

                if (queuesUnbound === queueNames.length) {
                    return callback();
                }
            });
        });
    } else {
        return callback();
    }
};

/**
 * Wait until our set of pending tasks has drained. If it takes longer than `maxWaitMillis`, it will
 * dump the pending tasks in the log that are holding things up and force continue.
 *
 * @param  {Number}     maxWaitMillis   The maximum amount of time (in milliseconds) to wait for pending tasks to finish
 * @param  {Function}   callback        Invoked when processing has completed (or we've force-continued)
 * @api private
 */
var _waitUntilIdle = function(maxWaitMillis, callback) {
    if (numMessagesInProcessing <= 0) {
        log().info('Successfully entered into idle state.');
        return callback();
    }

    /*!
     * Gives at most `maxWaitMillis` time to finish. If it doesn't, we suspect we have leaked messages and
     * output a certain amount of them to the logs for inspection.
     */
    var forceContinueHandle = setTimeout(function() {
        _dumpProcessingMessages('Timed out ' + maxWaitMillis + 'ms while waiting for tasks to complete.');
        MQ.removeListener('idle', callback);
        return callback();
    }, maxWaitMillis);

    MQ.once('idle', function() {
        log().info('Successfully entered into idle state.');
        clearTimeout(forceContinueHandle);
        return callback();
    });
};

/**
 * Purge a queue.
 *
 * @param  {String}     name            The name of the queue to purge. This is the same name as the label you use to bind to a queue.
 * @param  {Function}   [callback]      Standard callback method
 * @param  {Object}     [callback.err]  An error that occurred purging the task queue, if any
 */
var purge = module.exports.purge = function(name, callback) {
    callback = callback || function(err) {
        if (err) {
            log().error({'err': err, 'queueName': name}, 'Error purging queue.');
        }
    };

    if (!queues[name]) {
        log().warn({'queueName': name}, 'Tried purging unknown queue.');
        return callback();
    }

    log().info({'queueName': name}, 'Purging queue.');
    MQ.emit('prePurge', name);
    queues[name].queue.purge().addCallback(function(data) {
        if (!data) {
            log().error({'err': err, 'queueName': name}, 'Error purging task queue.');
            return callback({'code': 500, 'msg': 'Error purging task queue: ' + name});
        }

        MQ.emit('postPurge', name, data.messageCount);

        return callback();
    });
};

/**
 * Purges all the known queues.
 * Note: This does *not* purge all the queues that are in RabbitMQ.
 * It only purges the queues that are known to the OAE system.
 *
 * @param  {Function}   [callback]      Standard callback method
 * @param  {Object}     [callback.err]  An error that occurred purging the task queue, if any
 */
var purgeAll = module.exports.purgeAll = function(callback) {
    callback = callback || function(err) {
        if (err) {
            log().error({'err': err}, 'Error purging all known queues.');
        }
    };

    // Get all the known queues we can purge.
    var toPurge = _.keys(queues);
    log().info({'queues': toPurge}, 'Purging all known queues.');

    /*!
     * Purges one of the known queues and calls the callback method when they are all purged (or when an error occurs.)
     *
     * @param  {Object}  err    Standard error object (if any.)
     * @api private
     */
    var doPurge = function(err) {
        if (err) {
            return callback(err);
        }

        if (toPurge.length === 0) {
            callback();
        } else {
            var queueToPurge = toPurge.pop();
            purge(queueToPurge, doPurge);
        }
    };

    // Start purging.
    doPurge();
};

/**
 * Destroy the managed task queue with the given name.
 *
 * @param  {String}    name            The type of the job message queue to destroy.
 * @param  {Function}  callback        Invoked when the process completes
 * @param  {Object}    callback.err    An error that occurred, if any
 * @api private
 */
var _destroyQueue = function(name, callback) {
    var queue = queues[name];
    if (!queue || !queue.queue) {
        log().warn({'queueName': name}, 'Attempted to unbind listener from non-existant job queue. Ignoring.');
        return callback();
    }
    var consumerTag = queue.consumerTag;
    queue = queue.queue;

    queue.unsubscribe(consumerTag).addCallback(function(ok) {
        delete queues[name];

        if (!ok) {
            log().error({'queueName': name}, 'An unknown error occurred unsubscribing a task queue.');
            return callback({'code': 500, 'msg': 'An unknown error occurred unsubscribing a task queue.'});
        }
        callback();
    });
};

/**
 * Record the fact that we have begun processing this task.
 *
 * @param  {String}     deliveryKey         A (locally) unique identifier for this message
 * @param  {Object}     data                The task data
 * @param  {Object}     deliveryInfo        The delivery info from RabbitMQ
 * @api private
 */
var _incrementProcessingTask = function(deliveryKey, data, deliveryInfo) {
    if (numMessagesInProcessing >= MAX_NUM_MESSAGES_IN_PROCESSING) {
        _dumpProcessingMessages('Reached maximum number of concurrent messages allowed in processing (' +
            MAX_NUM_MESSAGES_IN_PROCESSING + '), this probably means there were many tasks received that were never acknowledged.' +
            ' Clearing "messages in processing" to avoid a memory leak. Please analyze the set of task information (messages)' +
            ' dumped in this log and resolve the issue of tasks not being acknowledged.');

        messagesInProcessing = {};
        numMessagesInProcessing = 0;
    }

    messagesInProcessing[deliveryKey] = {'data': data, 'deliveryInfo': deliveryInfo};
    numMessagesInProcessing++;
};

/**
 * Record the fact that we have finished processing this task.
 *
 * @param  {String}     deliveryKey         A (locally) unique identifier for this message
 * @api private
 */
var _decrementProcessingTask = function(deliveryKey) {
    delete messagesInProcessing[deliveryKey];
    numMessagesInProcessing--;

    if (numMessagesInProcessing === 0) {
        MQ.emit('idle');
    } else if (numMessagesInProcessing < 0) {
        // In this case, what likely happened was we overflowed our concurrent tasks, flushed it to 0, then
        // some existing tasks completed. This is the best way I can think of handling it that will "self
        // recover" eventually. Concurrent tasks overflowing is a sign of a leak (i.e., a task is handled
        // but never acknowleged). When this happens there should be a dump of some tasks in the logs and
        // and they should be investigated and resolved.
        numMessagesInProcessing = 0;
    }
};

/**
 * Log a message with the in-processing messages in the log line. This will log at must `NUM_MESSAGES_TO_DUMP`
 * messages.
 *
 * @param  {String}     logMessage
 * @api private
 */
var _dumpProcessingMessages = function(logMessage) {
    log().warn({'messages':  _.values(messagesInProcessing).slice(0, NUM_MESSAGES_TO_DUMP)}, logMessage);
};


text:
use std::{
    io::{prelude::*, BufReader},
    mem,
    net::TcpStream,
    thread,
};

use crossbeam_channel::{Receiver, Sender};
use interface::{
    self,
    data::{MovementData, PlayerData},
    extract, text, InterfaceState, NetworkRequest,
};
use network_common::{
    error::{NetworkError, NetworkResult},
    NetworkEvent, PlayerId,
};

use crate::game::Game;

pub struct NetworkManager {
    pub socket: TcpStream,
    pub local_update_receiver: Receiver<NetworkEvent>,
    pub global_update_sender: Sender<NetworkEvent>,
}

pub fn handle_network(network_manager: NetworkManager) -> NetworkResult<PlayerId> {
    let mut receiver_socket = BufReader::new(network_manager.socket.try_clone()?);
    let mut data_buffer = String::new();

    receiver_socket.read_line(&mut data_buffer)?;
    let player_id = match serde_json::from_str(&data_buffer) {
        Ok(NetworkEvent::PlayerJoin(id)) => id,
        _ => return Err(NetworkError::DecodeError),
    };
    data_buffer.clear();

    let global_update_sender = network_manager.global_update_sender;
    thread::spawn(move || {
        loop {
            match receiver_socket.read_line(&mut data_buffer) {
                Ok(_) => {
                    let packet = serde_json::from_str(&data_buffer).unwrap();
                    // TODO: better error handling
                    let _ = global_update_sender.send(packet);
                }

                Err(e) => {
                    println!("Disconnected from server: {}", e);
                    break;
                }
            }
            data_buffer.clear();
        }
    });

    let local_update_receiver = network_manager.local_update_receiver;
    let mut sender_socket = network_manager.socket;
    thread::spawn(move || {
        loop {
            let packet = serde_json::to_vec(&local_update_receiver.recv().unwrap()).unwrap();

            // TODO: better error handling
            let _ = sender_socket.write(&packet);
            let _ = sender_socket.write(b"\n");
        }
    });

    Ok(player_id)
}

pub struct ClientManager {
    id: PlayerId,
    last_state: Option<PlayerData>,
    full_update: Option<PlayerData>,
    movement_update: Option<MovementData>,
    update_sender: Sender<NetworkEvent>,
    update_receiver: Receiver<NetworkEvent>,
}

impl ClientManager {
    pub fn new(
        id: PlayerId,
        update_sender: Sender<NetworkEvent>,
        update_receiver: Receiver<NetworkEvent>,
    ) -> ClientManager {
        ClientManager {
            id,
            last_state: None,
            full_update: None,
            movement_update: None,
            update_sender,
            update_receiver,
        }
    }

    pub fn update_player(&mut self, new_data: &PlayerData) {
        if let Some(ref last_state) = self.last_state {
            if last_state.movement_data != new_data.movement_data {
                self.movement_update = Some(new_data.movement_data);
            }
        }
        if self.last_state.as_ref() != Some(new_data) {
            self.last_state = Some(new_data.clone());
            self.full_update = Some(new_data.clone());
        }
    }

    pub fn send_update(&mut self, game: &mut Game) -> NetworkResult<()> {
        if self.movement_update.is_some() {
            let update_data = mem::replace(&mut self.movement_update, None).unwrap();
            self.update_sender
                .send(NetworkEvent::MovementUpdate(self.id, update_data))
                .map_err(|_| NetworkError::SendError)?;
        }

        if self.full_update.is_some() {
            let update_data = mem::replace(&mut self.full_update, None).unwrap();
            self.update_sender
                .send(NetworkEvent::FullUpdate(self.id, update_data))
                .map_err(|_| NetworkError::SendError)?;
        }

        if game.chat_box.message_ready {
            self.send_message(game)?;
        }

        match game.interface_data.borrow().network_request {
            NetworkRequest::None => {}
            NetworkRequest::Battle(id) => {
                println!("Requesting battle");
                self.update_sender
                    .send(NetworkEvent::BattleDataRequest(id, self.id))
                    .map_err(|_| NetworkError::SendError)?;
            }
        }

        game.interface_data.borrow_mut().network_request = NetworkRequest::None;
        Ok(())
    }

    pub fn recv_update(&mut self, game: &mut Game) -> NetworkResult<()> {
        let interface_data = &mut game.interface_data.borrow_mut();
        loop {
            match self.update_receiver.try_recv() {
                Ok(NetworkEvent::FullUpdate(id, update_data)) => {
                    interface_data.players.insert(id, update_data);
                }

                Ok(NetworkEvent::MovementUpdate(id, update_data)) => {
                    if let Some(player) = interface_data.players.get_mut(&id) {
                        player.movement_data = update_data;
                    }
                }

                Ok(NetworkEvent::PlayerQuit(id)) => {
                    println!("Player: {} quit.", id);
                    interface_data.players.remove(&id);
                }

                Ok(NetworkEvent::BattleDataRequest(_, id)) => {
                    println!("Responding to battle request");
                    let data = extract::battle_data(&game.emulator.mem);
                    self.update_sender
                        .send(NetworkEvent::BattleDataResponse(id, data))
                        .map_err(|_| NetworkError::SendError)?;
                }

                Ok(NetworkEvent::BattleDataResponse(_, battle_data)) => {
                    interface_data.state = InterfaceState::Normal;
                    let enemy_id = interface_data.last_interaction;
                    if let Some(enemy) = interface_data.players.get(&enemy_id) {
                        interface::set_battle(&mut game.emulator.mem, enemy, battle_data);
                    }
                }

                Ok(NetworkEvent::UpdateRequest) => {
                    println!("Responding to update request");
                    let update_data = game.player_data.clone();
                    self.update_sender
                        .send(NetworkEvent::FullUpdate(self.id, update_data))
                        .map_err(|_| NetworkError::SendError)?;
                }

                Ok(NetworkEvent::Chat(id, msg)) => {
                    let player_name = match interface_data.players.get(&id) {
                        Some(player) => player.name.clone(),
                        None => text::Encoder::new("UNKNOWN").collect(),
                    };
                    game.chat_box.add_message(player_name, text::Encoder::new(&*msg).collect());
                }

                Ok(_) => unimplemented!(),
                _ => break,
            }
        }

        Ok(())
    }

    pub fn send_message(&mut self, game: &mut Game) -> NetworkResult<()> {
        let msg = game.chat_box.get_message_buffer();
        let user_name = game.player_data.name.clone();

        game.chat_box.add_message(user_name, text::Encoder::new(&msg).collect());
        self.update_sender
            .send(NetworkEvent::Chat(self.id, msg))
            .map_err(|_| NetworkError::SendError)?;

        Ok(())
    }
}


text:
This directory contains files to build a docker image running the development version of the Annalist software.  The software itself is loaded from the git 'develop' branch.  It is intended to be used mainly for testing the docker deployment structure and framework.

# Build instructions

NOTE: the commands below should be run with an installed copy of the annalist version to be containerized.  (The makefile uses `annlist-manager version` to retieve the current software version tag.)

The line:

    echo "2015-12-29T15:30"

in `Dockerfile` should be updated when the github repository `develop` branch is updated to force a new Docker image to be created with the latest copy of the Git repository content.

To build a local docker image, named `annalist_dev`, use the command:

    make all

To push a copy of the current image to DockerHub as `gklyne/annalist_dev` (which can take some time on a slow network connection), use:

    make push

# Some other useful Docker commands

Some of the following adapted from [http://jimhoskins.com/2013/07/27/remove-untagged-docker-images.html]()

Remove all images:

    docker rmi `docker images -aq`

Remove old "dangling" docker images:

    docker rmi $(docker images -f "dangling=true" -q)

Remove all containers:

   docker rm `docker ps -aq`

Remove all stopped containers:

    docker rm $(docker ps -a -q)

This should not remove any running containers, and it will tell you it can't remove a running image.

Remove all untagged images:

    docker rm $(docker ps -a | grep -v 'annalist\|CONTAINER' | awk '{print $1}')

or

    docker rm $(docker ps -a |  awk '!/annalist|CONTAINER/ {print $1}')

Remove all images with given tag (along with tags):

    docker rmi -f $(docker images | grep "<tag>" | awk '{print $3}')


text:
package com.a9ski.gerrit.model;

public class User {
	private final String id;
	private final String firstName;
	private final String lastName;
	private final String fullName;
	private final String displayName;
	private final String email;
	private final String password;

	public User(final String id, final String firstName, final String lastName, final String email, final String password) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
		this.fullName = String.format("%s %s", firstName, lastName);
		this.displayName = this.fullName;
		this.email = email;
		this.password = password;
	}

	public String getId() {
		return id;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public String getFullName() {
		return fullName;
	}

	public String getDisplayName() {
		return displayName;
	}

	public String getEmail() {
		return email;
	}

	public String getPassword() {
		return password;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_camera_vc"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_dark_selector"
    android:clickable="true"
    android:drawablePadding="0dp"
    android:drawableTop="@drawable/btn_camera_selector"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingTop="15dp"
    android:text="@string/taking_pictures"
    android:textColor="@android:color/white" />


text:
namespace net {

// static
bool SSLFalseStartBlacklist::IsMember(const std::string& host) {
#if !defined(OS_ANDROID)
  // Blacklist data can't currently be built for Clank
  const std::string last_two_components(LastTwoComponents(host));
  if (last_two_components.empty())
    return false;

  const size_t bucket = Hash(last_two_components) & (kBuckets - 1);
  for (size_t i = kHashTable[bucket]; i < kHashTable[bucket + 1]; ) {
    const size_t blacklist_entry_len = static_cast<uint8>(kHashData[i]);
    if (host.length() >= blacklist_entry_len &&
        !host.compare(host.length() - blacklist_entry_len, blacklist_entry_len,
                      &kHashData[i + 1], blacklist_entry_len) &&
        (host.length() == blacklist_entry_len ||
         host[host.length() - blacklist_entry_len - 1] == '.')) {
      return true;
    }
    i += blacklist_entry_len + 1;
  }
#endif

  return false;
}

}  // namespace net


text:
package alloy.utilities.core;

import java.time.Duration;

import alloy.utilities.core._Exceptions;

/**
 * Created by jlutteringer on 3/16/17.
 */
public class Wait {
	public static final Duration DEFAULT_WAIT = Duration.ofMillis(250);

	public static void await() {
		await(DEFAULT_WAIT);
	}

	public static void await(Duration duration) {
		_Exceptions.propagate(() -> Thread.sleep(duration.toMillis()));
	}
}


text:
title: The Fall of the Eleventh
category: Misc
tags:
- doctor who
- matt smith
- eleventh doctor
- regeneration
---

Spoilers!

The Eleventh Doctor is gone.

  He turned round again, arms outstretched, face calmer and more peaceful than perhaps it'd ever been.

  'We all change,' he said softly, and it was like he was easing a great weight off his chest as he spoke. His expression took on that of a man who had so much wisdom, who had seen so much, that it was hard not to fall right there. 'When you think about it, we are all different people, all through our lives, and that's ok, that's good, you've gotta keep moving, so long as you remember all the people that you used to be!'

  I didn't know what to say. I didn't know how to say it. I couldn't do anything. My expression pleaded him to stop. I was about to lose him forever and there was nothing I could do. I kept my hand almost touching him, barely maintaining enough willpower to keep a distance at all. He didn't even see what this was doing to me. Loving him didn't matter, because he was going to go. I'd never see him again. But I loved him anyway.

  And right to the end, my eyes never left his face.

  fanfiction by raggedybluebox

True to the series, the end of the eleventh was very emotional. Both the tenth and eleventh doctors have had wise and tragic and emotional endings. It was good... and the quotes... you can't get around the quotes. Smith was more of a for-the-kids type of a doctor, but his last moments... let it not be said kids of today can't learn emotion from TV.

The special was great, tied up lots of unanswered questions (and created new ones), brought lots of Who into Christmas (quite literally, Mr. Santa!) and made many weep in sorrow for another fallen man with a big heart. Thank you, Who team, Moffat, Smith, Coleman, Gillan. Raggedy man... goodnight.

  It all just disappears, doesn't it, everything you are, in a moment, like breath in a mirror.


text:
package com.rollsoftware.br.common.properties;

import java.util.Properties;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author Rogério
 * @date October, 2016
 */
public class ApplicationPropertiesTest {

    public ApplicationPropertiesTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of getProperties method, of class ROLLSoftwareProperties.
     */
    @Test
    public void testGetProperties() {
        System.out.println("getProperties");
        Properties properties = ApplicationProperties.getProperties();
        assertTrue("Properties not working!", !properties.isEmpty());
    }

    /**
     * Test of getProperties method, of class ROLLSoftwareProperties.
     */
    /*
     * Test:
     * test=test
     * test.test=${test}.${test}
     * test.insidetest=${test.${test}}
     * Expect:
     * test=test
     * test.test=test.test
     * test.insidetest=test.test
     */
    @Test
    public void testGetPropertiesPrint() {
        System.out.println("testGetPropertiesPrint");
        Properties properties = ApplicationProperties.getProperties();

        properties.entrySet().forEach((entry) -> {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        });
    }

}


text:
prov = $evm.root["miq_provision"]
vm = prov.vm_template
raise "VM not specified" if vm.nil?
ems  = vm.ext_management_system
raise "EMS not found for VM [#{vm.name}" if ems.nil?
tags = prov.get_tags

# Log space required
$evm.log("info", "vm=[#{vm.name}], space required=[#{vm.provisioned_storage}]")

# STORAGE LIMITATIONS
STORAGE_MAX_VMS      = 0
storage_max_vms      = $evm.object['storage_max_vms']
storage_max_vms      = storage_max_vms.strip.to_i if storage_max_vms.kind_of?(String) && !storage_max_vms.strip.empty?
storage_max_vms      = STORAGE_MAX_VMS unless storage_max_vms.kind_of?(Numeric)

STORAGE_MAX_PCT_USED = 100
storage_max_pct_used = $evm.object['storage_max_pct_used']
storage_max_pct_used = storage_max_pct_used.strip.to_i if storage_max_pct_used.kind_of?(String) && !storage_max_pct_used.strip.empty?
storage_max_pct_used = STORAGE_MAX_PCT_USED unless storage_max_pct_used.kind_of?(Numeric)

host = storage = nil
min_registered_vms = nil
prov.eligible_hosts.each do |h|
  next unless h.power_state == "on"

  # Only consider hosts that have the required tags
  next unless tags.all? do |key, value|
    if value.kind_of?(Array)
      value.any? { |v| h.tagged_with?(key, v) }
    else
      h.tagged_with?(key, value)
    end
  end

  nvms = h.vms.length

  # Only consider storages that have the required tags
  storages = h.storages.select do |s|
    tags.all? do |key, value|
      if value.kind_of?(Array)
        value.any? { |v| s.tagged_with?(key, v) }
      else
        s.tagged_with?(key, value)
      end
    end
  end

  # Filter out storages that do not have enough free space for the Vm
  storages = storages.select do |s|
    if s.free_space > vm.provisioned_storage
      true
    else
      $evm.log("info", "Skipping Datastore: [#{s.name}], not enough free space for VM. Available: [#{s.free_space}], Needs: [#{vm.provisioned_storage}]")
      false
    end
  end
  # Filter out storages number of VMs is greater than the max number of VMs
  storages = storages.select do |s|
    if (storage_max_vms == 0) || (s.vms.size < storage_max_vms)
      true
    else
      $evm.log("info", "Skipping Datastore: [#{s.name}], max number of VMs exceeded")
      false
    end
  end
  # Filter out storages where percent used is greater than the max.
  storages = storages.select do |s|
    if (storage_max_pct_used == 100) || (s.v_used_space_percent_of_total < storage_max_pct_used)
      true
    else
      $evm.log("info", "Skipping Datastore: [#{s.name}], percent of used space is exceeded")
      false
    end
  end
  # if minimum registered vms is nil or number of vms on a host is greater than nil
  if min_registered_vms.nil? || nvms < min_registered_vms
    s = storages.sort { |a, b| a.free_space <=> b.free_space }.last
    unless s.nil?
      host    = h
      storage = s
      min_registered_vms = nvms
    end
  end
end

# Set host and storage
obj = $evm.object

if host
  obj["host"] = host
  prov.set_host(host)
end

$evm.log("info", "Selected Datastore:<#{storage.nil? ? "nil" : storage.name}>")
if storage
  obj["storage"] = storage
  prov.set_storage(storage)
end

$evm.log("info", "vm=[#{vm.name}] host=[#{host}] storage=[#{storage}]")


text:
package cn.itcast.test;

import java.lang.reflect.Field;

public class Tool {
	public void setProperty(Object obj, String propertyName, Object value)
			throws NoSuchFieldException, SecurityException,
			IllegalArgumentException, IllegalAccessException {
		// 根据对象获取字节码文件对象
		Class c = obj.getClass();
		// 获取该对象的propertyName成员变量
		Field field = c.getDeclaredField(propertyName);
		// 取消访问检查
		field.setAccessible(true);
		// 给对象的成员变量赋值为指定的值
		field.set(obj, value);
	}
}


text:
/*
Simple Tree jQuery plugin

Based on CSS for simple unobtrusive javascript treeview plugin
developed by Krijn Hoetmer
http://krijnhoetmer.nl/stuff/javascript/list-treeview-menu/

Adapted as a jQuery plugin by Maurizio Manetti
 */

.st-treed, .st-treed ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    background-image: url('../img/vdot.gif');
    background-repeat: repeat-y;
    background-position: 8px 0;
}

.st-treed a {
    text-decoration: none;
    color: #000;
    background-image: url('../img/folder.gif');
    background-repeat: no-repeat;
    background-position: center left;
    padding: 2px 0 2px 20px;
}

.st-treed li {
    padding-top: 4px;
    padding-left: 20px;
    background-image: url('../img/corner.gif');
    background-repeat: no-repeat;
    background-position: 8px 0;
}

.st-treed a:hover {
    text-decoration: underline;
}

.st-treed .st-last {
    background-image: url('../img/corner.gif');
    background-position: 8px 0;
}

.st-treed .st-collapsed, .st-treed .st-open {
    background-repeat: no-repeat;
    background-position: 4px 0;
    cursor: pointer;
}

.st-treed .st-collapsed {
    background-image: url('../img/plus.gif');
}

.st-treed .st-open {
    background-image: url('../img/minus.gif');
}

.st-treed .st-collapsed ul {
    display: none;
}

.st-treed .st-file a {
    background-image: url('../img/file.gif');
}

.st-treed a:hover {
    background-color: transparent;
}


text:
package org.broadleafcommerce.core.catalog.domain;

import java.io.Serializable;

public interface PromotableProduct extends Serializable {
    Product getRelatedProduct();

    String getPromotionMessage();
}


text:
/**
 * Created by yangge on 1/20/2016.
 */
public class VeggiePizza extends Pizza {
}


text:
package proton.utils;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Jason R Briggs
 */
public final class WebUtils {

    public static String getPath(HttpServletRequest request, String... paths) {
        StringBuilder path = new StringBuilder(request.getContextPath());
        path.append(request.getServletPath());
        for (String p : paths) {
            path.append('/').append(p);
        }
        return path.toString();
    }

    public static String getPathInfo(HttpServletRequest request) {
        if (request.getPathInfo() != null && request.getPathInfo().startsWith("/")) {
            return request.getPathInfo().substring(1);
        }
        return request.getPathInfo();
    }
}


text:
using System;
using System.Data;
using System.Data.Common;
using System.IO;
using NUnit.Framework;
using Shuhari.Framework.Data;
using Shuhari.Framework.Data.Common;
using Shuhari.Framework.Data.Mappings;

namespace Shuhari.Framework.UnitTests.Data.Common
{
    [TestFixture]
    public class DbEngineTest
    {
        class TestEngine : DbEngine
        {
            public override IDbConnection CreateConnection()
            {
                throw new NotImplementedException();
            }

            public override IQueryBuilder<T> CreateQueryBuilder<T>(IEntityMapper<T> mapper)
            {
                throw new NotImplementedException();
            }

            protected override DbParameter CreateVendorParameter(string paramName, DbType dbType, object value)
            {
                throw new NotImplementedException();
            }
        }

        [SetUp]
        public void SetUp()
        {
            _engine = new TestEngine();
        }

        private  DbEngine _engine;

        [TestCase(typeof(sbyte))]
        [TestCase(typeof(Stream))]
        public void GetDbType_ClrTypeNotSupported_ShouldThrow(Type clrType)
        {
            Assert.Throws<NotSupportedException>(() => _engine.GetDbType(clrType));
        }

        [TestCase(typeof(byte), DbType.Byte)]
        [TestCase(typeof(short), DbType.Int16)]
        [TestCase(typeof(int), DbType.Int32)]
        [TestCase(typeof(long), DbType.Int64)]
        [TestCase(typeof(bool), DbType.Boolean)]
        [TestCase(typeof(float), DbType.Single)]
        [TestCase(typeof(double), DbType.Double)]
        [TestCase(typeof(decimal), DbType.Decimal)]
        [TestCase(typeof(string), DbType.String)]
        [TestCase(typeof(DateTime), DbType.DateTime2)]
        [TestCase(typeof(byte[]), DbType.Binary)]
        [TestCase(typeof(Guid), DbType.Guid)]
        public void GetDbType_PrimitiveClrTypes_ShouldReturnDbType(Type clrType, DbType dbType)
        {
            Assert.AreEqual(dbType, _engine.GetDbType(clrType));
        }

        [TestCase(typeof(byte?), DbType.Byte)]
        [TestCase(typeof(short?), DbType.Int16)]
        [TestCase(typeof(int?), DbType.Int32)]
        [TestCase(typeof(long?), DbType.Int64)]
        [TestCase(typeof(bool?), DbType.Boolean)]
        [TestCase(typeof(float?), DbType.Single)]
        [TestCase(typeof(double?), DbType.Double)]
        [TestCase(typeof(decimal?), DbType.Decimal)]
        [TestCase(typeof(DateTime?), DbType.DateTime2)]
        [TestCase(typeof(Guid?), DbType.Guid)]
        public void GetDbType_NullableClrTypes_ShouldReturnDbType(Type clrType, DbType dbType)
        {
            Assert.AreEqual(dbType, _engine.GetDbType(clrType));
        }

        [TestCase(typeof(FileMode))]
        [TestCase(typeof(FileMode?))]
        public void GetDbType_EnumTypes_ShouldReturnInt(Type clrType)
        {
            Assert.AreEqual(DbType.Int32, _engine.GetDbType(clrType));
        }
    }
}


text:
/* */
"use strict";
var __extends = (this && this.__extends) || function(d, b) {
  for (var p in b)
    if (b.hasOwnProperty(p))
      d[p] = b[p];
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Subscriber_1 = require('../Subscriber');
function toArray() {
  return this.lift(new ToArrayOperator());
}
exports.toArray = toArray;
var ToArrayOperator = (function() {
  function ToArrayOperator() {}
  ToArrayOperator.prototype.call = function(subscriber, source) {
    return source.subscribe(new ToArraySubscriber(subscriber));
  };
  return ToArrayOperator;
}());
var ToArraySubscriber = (function(_super) {
  __extends(ToArraySubscriber, _super);
  function ToArraySubscriber(destination) {
    _super.call(this, destination);
    this.array = [];
  }
  ToArraySubscriber.prototype._next = function(x) {
    this.array.push(x);
  };
  ToArraySubscriber.prototype._complete = function() {
    this.destination.next(this.array);
    this.destination.complete();
  };
  return ToArraySubscriber;
}(Subscriber_1.Subscriber));


text:
# CSS Performance Hacks

[Implementers' doc]

This document discusses the CSS specs implementers can use in case they have performance issues:

1. `will-change`;
2. CSS containment.

At first sight, using those 2 specs can give tremendous results but you sometimes have to use them in clever ways: it's not just about adding a line of CSS in your stylesheet.

## Will-change

### The fundamental rule of will-change

> Set will-change to the properties you'll actually change, on the elements that are actually changing. And remove it when they stop.

### Abstract

The `will-change` property allows an author to inform the UA ahead of time of what kinds of changes they are likely to make to an element. The UA can then try to optimize how they handle the element ahead of time, performing potentially-expensive work preparing for an animation before the animation actually begins.

**In other words, `will-change` is a UA hint,** it doesn't have any styling effect on the elements for which you're using it. It's worth noting it can have appearance effects though, if a new stacking context is created.

It is, in many ways, an official property for the infamous "translate-z hack." Although it was meant for animation, it can also deal with more simple changes.

### Usage

```
will-change: <animateable-feature> = scroll-position || contents || <custom-ident>
```

#### Scroll-position

Indicates that the author expects to animate or change the scroll position of the element in the near future.

A browser might take this value as a signal to expand the range of content around the scroll window that is rendered, so that longer/faster scrolls can be done smoothly.

#### Contents

Indicates that the author expects to animate or change something about the element's contents in the near future.

A browser might take this value as a signal to cache less aggressively on the element, or avoid caching at all and just continually re-render the element from scratch.

#### custom-ident

Indicates that the author expects to animate or change the property with the given name on the element in the near future.

A browser might take a value of transform as a signal that it should go ahead and promote the element to its own layer immediately, before the element starts to be transformed, to avoid any delay involved in rerendering the old and new layers.

### Drawbacks

By using `will-change`, you're basically telling the browser the element is a few moments away from changing, the browser consequently dedicates memory and resources to this element. **If you use it for too many elements, it will thus degrade performance.**

This property should be considered a last resort, it was not meant for premature optimization. **You should use it only if you have to deal with performance issues.**

### Do's and Dont's

#### Do's

- Use `will-change` sparingly in stylesheets
- Give `will-change` sufficient time to work
- Use `<custom-ident>` to target super specific changes (`left`, `opacity`, etc.)
- Use it in JavaScript if needed (add and remove hint)
- Remove `will-change` after the changes are done

#### Dont's

- Don't declare changes to too many properties
- Don't apply it to too many elements
- Don't waste resources on elements that have stopped changing

### Examples

#### UI elements

Specifying `will-change` for a small number of persistent UI elements in a page which should react snappily to the user is appropriate:

```
body > .sidebar {
  will-change: transform;
  /* Will use 'transform' to slide it out when the user requests. */
}
```

Because this is limited to a small number of elements, the fact that the optimization is rarely actually used doesn't hurt very much.

#### User click

If an element is going to change when a user clicks on it, setting `will-change` on hover will usually give at least 200 milliseconds for the optimizations to be set up, as human reaction time is relatively slow.

```
.element {
  transition: opacity 0.2s;
  opacity: 1;
}

.element:hover {
  will-change: opacity;
}

.element:active {
  opacity: 0.3;
}
```

#### Adding and removing the hint with JavaScript

This is probably the way to go, should you try using `will-change` to optimize performance.

Here we have the hint added on `:hover`, then removed when the animation has ended.

```
var el = document.getElementById('element');

// Set will-change when the element is hovered
el.addEventListener('mouseenter', hintBrowser);
el.addEventListener('animationEnd', removeHint);

function hintBrowser() {
  // The optimizable properties that are going to change
  // in the animation's keyframes block
  this.style.willChange = 'transform, opacity';
}

function removeHint() {
  this.style.willChange = 'auto';
}
```

### References

- [CSS Will Change Module Level 1](https://www.w3.org/TR/css-will-change-1/)
- [Can I Use](http://caniuse.com/#feat=will-change)
- [Mozilla Dev Network](https://developer.mozilla.org/en-US/docs/Web/CSS/will-change)
- [Everything you need to know about the CSS will-change property](https://dev.opera.com/articles/css-will-change-property/)
- [CSS 'will-change' Property: A Performance Case Study](https://www.maxlaumeister.com/blog/css-will-change-property-a-performance-case-study/)

## CSS Containment

**Note: This is only implemented in Blink (Chrome + Opera). It is under consideration for Microsoft Edge.**

### Abstract

The `contain` property indicates that **the element and its contents are, as much as possible, independent of the rest of the page.**

This allows the browser to recalculate layout, style, paint, size, or any combination of them for a limited area of the DOM and not the entire page. To put it simply, it lets developers limit the scope of the browser's styles, layout and paint work.

It was primarily meant for webpages which contain a lot of widgets that are all independent as it can be used to prevent one widget's CSS rules from changing other things on the page.

### Usage

```
contain: strict || content || size || layout || style || paint
```

#### Strict

This is a shorthand for all values, it is equivalent to `contain: size layout style paint`.

#### Content

This is a shorthand for all values but `size`, it is equivalent to `contain: layout style paint`.

#### Size

It indicates that the element can be laid out without the need to examine its descendants.

#### Layout

It indicates that nothing outside can affect the element's internal layout, and vice versa.

#### Style

It indicates that, for properties which can have effects on more than just an element and its descendants, those effects don't escape the containing element.

#### Paint

It indicates that the descendants of the element don't display outside its bounds, so if an element is off-screen or otherwise not visible, its descendants are also guaranteed to be not visible.

### Possible optimizations

In theory, huge performance gains are possible, but it requires a solid knowledge of how browsers work and what causes reflow, relayout, repaint, etc. Judging by examples, I can see how it could be useful but we'll probably have to find inventive and clever ways to leverage it since our scope is very often the root document.

If you need a refresher:

- [How browsers work](https://www.html5rocks.com/en/tutorials/internals/howbrowserswork/)
- [What force layout/reflow](https://gist.github.com/paulirish/5d52fb081b3570c81e3a)

#### Layout

- When laying out the page, the contents of separate containing elements can be laid out in parallel, as they're guaranteed not to affect each other.
- When laying out the page, if the containing element is off-screen or obscured and the layout of the visible parts of the screen do not depend on the size of the containing element (for example, if the containing element is near the end of a block container, and you're viewing the beginning of the block container), the layout of the containing elements' contents can be delayed or done at a lower priority.
- Layout is normally document-scoped so if you change an element's `left` property, every single element in the DOM might need to be checked. Enabling containment here can potentially reduce the number of elements to just a handful, rather than the whole document, saving the browser a ton of unnecessary work and significantly improving performance.

#### Style

- Whenever a property is changed on a descendant of the containing element, calculating what part of the DOM tree is "dirtied" and might need to have its style recalculated can stop at the containing element.
- Containment here is purely about limiting the parts of the tree that are under consideration when styles are mutated, not when they are declared.

#### Paint

- If the containing element is off-screen or obscured, the UA can directly skip trying to paint its contents, as they're guaranteed to be off-screen/obscured as well.
- Unless the clipped content is made accessible via a separate mechanism such as the overflow, resize, or text-overflow properties, the UA can reserve "canvas" space for the element exactly the element's size.
- Because they are guaranteed to be stacking contexts, scrolling elements can be painted into a single GPU layer.
- It acts as a containing block for absolutely positioned and fixed position elements: any children are positioned based on the element, not the document.
- It becomes a stacking context: things like `z-index` will have an effect on the element, and children will be stacked according to the new context.
- It becomes a new formatting context: a block level element will be treated as a new, independent layout environment. Layout outside of the element won't typically affect the containing element's children.

#### Size

- It ensures you don't rely on child elements for sizing, but by itself it doesn't offer much performance benefit.

### References

- [CSS Containment Module Level 1](https://www.w3.org/TR/css-contain-1/)
- [Can I Use](http://caniuse.com/#feat=css-containment)
- [Mozilla Dev Network](https://developer.mozilla.org/en-US/docs/Web/CSS/contain)
- [CSS Containment in Chrome 52](https://developers.google.com/web/updates/2016/06/css-containment)


text:
<?php /* @var $this Controller */ ?>
<?php $this->beginContent('//layouts/main'); ?>

		<?php echo $content; ?>

	<?php
		$this->beginWidget('zii.widgets.CPortlet', array(
			'title'=>'Operations',
		));
		$this->widget('zii.widgets.CMenu', array(
			'items'=>$this->menu,
			'htmlOptions'=>array('class'=>'operations'),
		));
		$this->endWidget();
	?>

<?php $this->endContent(); ?>


text:
require 'test_helper'

class GroupPolicyTest < ActiveSupport::TestCase
  def setup
    @group  = groups :one
    @user   = users :one
  end

  # test update? and create?

  test "grants update access to group's creator" do
    @group.creator = @user
    assert GroupPolicy.new(@user, @group).update?
    assert GroupPolicy.new(@user, @group).edit?
  end

  test "denies update access when not group's creator" do
    @group.creator = users :two
    refute GroupPolicy.new(@user, @group).update?
    refute GroupPolicy.new(@user, @group).edit?
  end

  # test destroy?

  test "grants destroy access to group's creator" do
    @group.creator = @user
    assert GroupPolicy.new(@user, @group).destroy?
  end

  test "denies destroy access when not group's creator" do
    @group.creator = users :two
    refute GroupPolicy.new(@user, @group).destroy?
  end

  # test permitted_attributes

  test "permit only: name, description" do
    permitted = GroupPolicy.new(@user, @group).permitted_attributes
    assert_equal %i(name description), permitted
  end
end


text:
<!--
  The Ohio State University Research Foundation, Emory University,
  the University of Minnesota Supercomputing Institute

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/cagrid-grid-incubation/LICENSE.txt for details.
-->
<!--
-->
<?xml version="1.0"?>

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://incubator.apache.org/ivy/schemas/ivy.xsd">

	<info organisation="hibernate" module="hibernate" revision="3.0.2">
		<license name="LGPL" url="http://www.gnu.org/copyleft/lesser.html"/>
		<description>Hibernate is a powerful, high performance object/relational persistence and
			query service. Hibernate lets you develop persistent classes following object-oriented
			idiom - including association, inheritance, polymorphism, composition, and collections.
			Hibernate allows you to express queries in its own portable SQL extension (HQL), as well
			as in native SQL, or with an object-oriented Criteria and Example API.
			(http://www.hibernate.org/)</description>
	</info>
	<configurations>
		<!-- Public Configurations-->
		<conf name="full" visibility="public"/>
	</configurations>

	<publications>
		<artifact name="hibernate3" conf="full" type="jar"/>
	</publications>

	<dependencies/>
</ivy-module>


text:
module ORTools
  class RoutingIndexManager
    def self.new(num_nodes, num_vehicles, starts, ends = nil)
      if ends
        _new_starts_ends(num_nodes, num_vehicles, starts, ends)
      else
        _new_depot(num_nodes, num_vehicles, starts)
      end
    end
  end
end


text:
package font

import (
	"image"
	"image/draw"
	"log"
)

// Draw font glyphs onto an image
type Draw struct {
	// Dst is the destination image
	Dst draw.Image

	// Src is the source image
	Src image.Image

	// Cursor is the drawing position in the destination image
	Cursor image.Point

	// Face is our font face
	Face Face
}

func (d *Draw) Rune(r rune) {
	dr, mask, maskp, advance, ok := d.Face.Glyph(d.Cursor, r)
	if !ok {
		return
	}
	log.Printf("rune %q at %+v from %+v", r, dr, maskp)
	draw.DrawMask(d.Dst, dr, d.Src, image.ZP, mask, maskp, draw.Over)
	d.Cursor.X += advance
}

func (d *Draw) String(s string) {
	for _, r := range s {
		dr, mask, maskp, advance, ok := d.Face.Glyph(d.Cursor, r)
		if !ok {
			log.Printf("rune %q missing", r)
			continue
		}
		log.Printf("rune %q at %+v from %+v", r, dr, maskp)
		draw.DrawMask(d.Dst, dr, d.Src, image.ZP, mask, maskp, draw.Over)
		d.Cursor.X += advance
	}
}


text:
import vtk

def main():
    # Create five points.
    origin = [0.0, 0.0, 0.0]
    p0 = [1.0, 0.0, 0.0]
    p1 = [0.0, 1.0, 0.0]
    p2 = [0.0, 1.0, 2.0]
    p3 = [1.0, 2.0, 3.0]

    # Create a vtkPoints object and store the points in it
    points = vtk.vtkPoints()
    points.InsertNextPoint(origin)
    points.InsertNextPoint(p0)
    points.InsertNextPoint(p1)
    points.InsertNextPoint(p2)
    points.InsertNextPoint(p3)

    # Create a cell array to store the lines in and add the lines to it
    lines = vtk.vtkCellArray()

    for i in range(0, 3):
        line = vtk.vtkLine()
        line.GetPointIds().SetId(0, i)
        line.GetPointIds().SetId(1, i + 1)
        lines.InsertNextCell(line)

    # Create a polydata to store everything in
    linesPolyData = vtk.vtkPolyData()

    # Add the points to the dataset
    linesPolyData.SetPoints(points)

    # Add the lines to the dataset
    linesPolyData.SetLines(lines)

    # Setup actor and mapper
    colors = vtk.vtkNamedColors()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(linesPolyData)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetLineWidth(4)
    actor.GetProperty().SetColor(colors.GetColor3d("Peacock"))

    # Setup render window, renderer, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Long Line")
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)
    renderer.AddActor(actor)

    renderer.ResetCamera()
    renderer.GetActiveCamera().Azimuth(30)
    renderer.GetActiveCamera().Elevation(30)
    renderer.ResetCameraClippingRange()

    renderer.SetBackground(colors.GetColor3d("Silver"))
    renderWindow.Render()
    renderWindowInteractor.Start()

if __name__ == '__main__':
    main()


text:
<?php $this->beginContent('//layouts/headfoot'); ?>
<div id="page" class="two_columns">
    <?php echo $content; ?>
</div>
<?php $this->endContent(); ?>


text:
import hmac
import hashlib

digest_maker = hmac.new('secret-key', '', hashlib.sha256)

f = open('sample-file.txt', 'rb')
try:
    while True:
        block = f.read(1024)
        if not block:
            break
        digest_maker.update(block)
finally:
    f.close()

digest = digest_maker.hexdigest()
print digest


text:
layout: post

title: Hello world!

---

Привет всем! С этого дня я начинаю вести здесь свой блог о программировании на Java.

Тут я буду размещать отчеты о проделанной работе.


text:
package org.apache.jackrabbit.oak.plugins.nodetype;

import javax.annotation.Nonnull;
import javax.jcr.RepositoryException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NodeDefinition;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.PropertyDefinition;

import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Tree;

/**
 * EffectiveNodeType... TODO
 */
public interface EffectiveNodeType {

    Iterable<NodeType> getAllNodeTypes();

    //Iterable<NodeType> getInheritedNodeTypes();
    //Iterable<NodeType> getMergedNodeTypes();

    /**
     * Determines whether this effective node type representation includes
     * (either through inheritance or aggregation) the given node type.
     *
     * @param nodeTypeName name of node type
     * @return {@code true} if the given node type is included, otherwise {@code false}.
     */
    boolean includesNodeType(String nodeTypeName);

    /**
     * Determines whether this effective node type representation includes
     * (either through inheritance or aggregation) all of the given node types.
     *
     * @param nodeTypeNames array of node type names
     * @return {@code true} if all of the given node types are included,
     *         otherwise {@code false}
     */
    boolean includesNodeTypes(String[] nodeTypeNames);

    /**
     * Determines whether this effective node type supports adding
     * the specified mixin.
     * @param mixin name of mixin type
     * @return {@code true} if the mixin type is supported, otherwise {@code false}
     */
    boolean supportsMixin(String mixin);

    Iterable<NodeDefinition> getNodeDefinitions();

    Iterable<PropertyDefinition> getPropertyDefinitions();

    Iterable<NodeDefinition> getAutoCreateNodeDefinitions();

    Iterable<PropertyDefinition> getAutoCreatePropertyDefinitions();

    Iterable<NodeDefinition> getMandatoryNodeDefinitions();

    Iterable<PropertyDefinition> getMandatoryPropertyDefinitions();

    /**
     * Return all node definitions that match the specified oak name.
     *
     * @param oakName An internal oak name.
     * @return All node definitions that match the given internal oak name.
     */
    @Nonnull
    Iterable<NodeDefinition> getNamedNodeDefinitions(String oakName);

    /**
     * Return all property definitions that match the specified oak name.
     *
     * @param oakName An internal oak name.
     * @return All property definitions that match the given internal oak name.
     */
    @Nonnull
    Iterable<PropertyDefinition> getNamedPropertyDefinitions(String oakName);

    /**
     * Return all residual node definitions.
     *
     * @return All residual node definitions.
     */
    @Nonnull
    Iterable<NodeDefinition> getResidualNodeDefinitions();

    /**
     * Return all residual property definitions.
     *
     * @return All residual property definitions.
     */
    @Nonnull
    Iterable<PropertyDefinition> getResidualPropertyDefinitions();

    void checkSetProperty(PropertyState property) throws RepositoryException;

    void checkRemoveProperty(PropertyState property) throws RepositoryException;

    void checkAddChildNode(String name, NodeType nodeType) throws RepositoryException;

    void checkRemoveNode(String name, NodeType nodeType) throws RepositoryException;

    void checkMandatoryItems(Tree tree) throws ConstraintViolationException;
}


text:
<?php

namespace DCarbone\PHPFHIRGenerated\R4\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRBiologicallyDerivedProduct;

use PHPUnit\Framework\TestCase;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRBiologicallyDerivedProduct\FHIRBiologicallyDerivedProductProcessing;

/**
 * Class FHIRBiologicallyDerivedProductProcessingTest
 * @package \DCarbone\PHPFHIRGenerated\R4\PHPFHIRTests\FHIRElement\FHIRBackboneElement\FHIRBiologicallyDerivedProduct
 */
class FHIRBiologicallyDerivedProductProcessingTest extends TestCase
{
    public function testCanConstructTypeNoArgs()
    {
        $type = new FHIRBiologicallyDerivedProductProcessing();
        $this->assertInstanceOf('\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRBiologicallyDerivedProduct\FHIRBiologicallyDerivedProductProcessing', $type);
    }
}