text:
<?php

class EventCreatorService {

    private $_data = '';

	/**
	 * Generates an Event class
	 *
	 * @return string formatted code ready to use
	 *
	 */
	public function createEventService($className, $parameterArray) {
		$this->_generateClassHeader($className);
		$this->_generateConstants($className);
		$this->_generateGet($className);
		$this->_generateSet($className);
		$this->_generateClassFooter();
		return $this->_data;
	}

	/**
	 * Generates header for Mapper class
	 *
	 */
	private function _generateClassHeader($className) {
		$this->_data .= "<?php
/**
* file: " . ucfirst(strtolower($className)) . "Event.php
* " . ucfirst(strtolower($className)) . " Event
*
* @author ".ZendModelCreator::getGenerator()."
* @version ".ZendModelCreator::getVersion()."
* @package ".ZendModelCreator::getNamespace()."
* @since " . date("Y-m-d") . "
*/

namespace ".ZendModelCreator::getNamespace()."\Service;

use ArrayObject;

use ".ZendModelCreator::getNamespace()."\Entity\\" . $className . " as " . $className . "Entity;

use Zend\EventManager\Event;

/**
* " . ucfirst(strtolower($className)) . "Event
*
* @author ".ZendModelCreator::getGenerator()."
* @version ".ZendModelCreator::getVersion()."
* @package ".ZendModelCreator::getNamespace()."
* @since " . date("Y-m-d") . "
*
**/
class " . ucfirst(strtolower($className)) . " extends Event
{
";
	}

	/**
	* Generate constants
	*/
	private function _generateConstants($className) {
		$this->_data.="\tconst EVENT_ADD_" . strtoupper($className) . "_POST = 'add" . ucfirst(strtolower($className)) . ".post';\n";
		$this->_data.="\tconst EVENT_UPDATE_" . strtoupper($className) . "_POST = 'update" . ucfirst(strtolower($className)) . ".post';\n";
		$this->_data.="\tconst EVENT_DELETE_" . strtoupper($className) . "_POST = 'delete" . ucfirst(strtolower($className)) . ".post';\n";
		$this->_data.="\n";
	}

	/**
	* Generate get
	*/
	private function _generateGet($className) {
		$this->_data.="\t/**\n";
		$this->_data.="\t* Get record from event\n";
		$this->_data.="\t*\n";
		$this->_data.="\t**/\n";
		$this->_data.="\tpublic function get" . ucfirst(strtolower($className)) . "()\n";
		$this->_data.="\t{\n";
		$this->_data.="\t\t// Return param\n";
		$this->_data.="\t\treturn \$this->getParam('" . strtolower($className) . "');\n";
		$this->_data.="\t}\n\n";
	}

	/**
	* Generate set
	*/
	private function _generateSet($className) {
		$this->_data.="\t/**\n";
		$this->_data.="\t* Set record to event\n";
		$this->_data.="\t*\n";
		$this->_data.="\t**/\n";
		$this->_data.="\tpublic function set" . ucfirst(strtolower($className)) . "(" . $className . "Entity \$" . strtolower($className) . ")\n";
		$this->_data.="\t{\n";
		$this->_data.="\t\t// Set param\n";
		$this->_data.="\t\t\$this->setParam('" . strtolower($className) . "', \$" . strtolower($className) . ");\n";
		$this->_data.="\t\treturn \$this;\n";
		$this->_data.="\t}";
	}

	/**
	 * Generates a footer
	 *
	 */
	private function _generateClassFooter() {
		$this->_data .= "\n}";
	}
}


text:
<?php
namespace app\install;

use app\models\User;
use Yii;

class InstallController extends \yii\web\Controller
{
    public function actionIndex()
    {
        if (!$this->checkDbConnection()) {
            $configFile = str_replace(Yii::getAlias('@webroot'), '', Yii::getAlias('@app')) . '/config/db.php';
            return $this->showError(Yii::t('app', 'Cannot connect to database. Please configure `{0}`.', $configFile));
        }

        $installForm = new InstallForm();

        if ($installForm->load(Yii::$app->request->post()) && $installForm->validate()) {
            $log = $this->migrate($installForm);
            return $this->render('@app/install/finish', compact('log'));
        } else {
            $this->layout = '@vendor/developeruz/yii-kit-core/views/layouts/main-login';
            return $this->render('@app/install/form', compact('installForm'));
        }
    }

    private function checkDbConnection()
    {
        try {
            Yii::$app->db->open();
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    private function showError($text)
    {
        return $this->render('/site/error', ['message' => $text]);
    }

    private function migrate($installForm)
    {
        $webApp = Yii::$app;
        ob_start();
        $consoleConfig = require(Yii::getAlias('@app/config/console.php'));
        $console = new \yii\console\Application($consoleConfig);
        $console->runAction('migrate',
            ['migrationPath' => '@yii/rbac/migrations/', 'interactive' => false]);
        $console->runAction('migrate',
            ['migrationPath' => '@vendor/developeruz/yii-kit-core/migrations/', 'interactive' => false]);

        $console->runAction('migrate',
            ['migrationPath' => '@vendor/dektrium/yii2-user/migrations', 'interactive' => false]);
        $console->runAction('user/create', [$installForm->root_email, $installForm->root_login, $installForm->root_password]);
        $console->runAction('user/confirm', [$installForm->root_email]);

//        $console->runAction('migrate',
//            ['migrationPath' => '@vendor/loveorigami/yii2-plugins-system/src/migrations', 'interactive' => false]);

        $console->runAction('migrate',
            ['migrationPath' => '@vendor/yii2mod/yii2-comments/migrations', 'interactive' => false]);

        $user = User::find()->where(['email' => $installForm->root_email])->one();
        $role = Yii::$app->authManager->createRole('admin');
        $role->description = Yii::t('app', 'Admin');
        Yii::$app->authManager->add($role);
        Yii::$app->authManager->assign($role, $user->getId());

        $permission = Yii::$app->authManager->createPermission('permit');
        Yii::$app->authManager->add($permission);
        Yii::$app->authManager->addChild($role, $permission);

        $permission = Yii::$app->authManager->createPermission('user');
        Yii::$app->authManager->add($permission);
        Yii::$app->authManager->addChild($role, $permission);

        $result = ob_get_contents();
        ob_end_clean();
        Yii::$app = $webApp;
        return str_replace("\n", '<br>', $result);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by robert on 05.02.17.
 */
import expect from 'expect';
import React from 'react';
import { createStore } from 'redux';
import rootReducer from '../reducers';
import io from '../../../node_modules/socket.io-client/';
import * as actions from '../actions/messageAction';

describe('Suite of unit tests', function() {

    let socket;
    let store;
    beforeEach(function(done) {
        // Setup
        store = createStore(rootReducer);
        socket = io.connect('http://localhost:3000', {
            'reconnection delay' : 0
            , 'reopen delay' : 0
            , 'force new connection' : true
        });

        socket.on('connect', function() {
            done();
        });
        socket.on('disconnect', function() {
            console.log('disconnected...');
        })
    });

    afterEach(function(done) {
        // Cleanup
        if(socket.connected) {
            console.log('disconnecting...');
            socket.disconnect();
        }
        else {
            // There will not be a connection unless you have done() in beforeEach, socket.on('connect'...)
            console.log('no connection to break...');
        }
        done();
    });

    describe('Socketio test', function() {

        it('change username', function (done) {
            setTimeout(() => {

                socket.emit('nameAttempt', 'testUser');

                socket.on('nameResult', (result) => {
                    let message;

                    if (result.success) {
                        message = 'Your username is: ' + result.name + '.';
                    } else {
                        message = result.message;
                    }
                    store.dispatch(actions.sendMessage([message]));
                    const actual = store.getState().allMessages[0];
                    const expected = ['Your username is: testUser.'];

                    expect(actual).toEqual(expected);
                    done();
                })
            });
        }, 250);

        it('send messages on join room', function (done) {
            setTimeout(() => {

                socket.emit('join', {
                    newRoom: 'testRoom'
                });

                socket.on('joinResult', (result) => {

                    if(result.room) {
                        store.dispatch(actions.sendMessage(['Room has been changed']));
                        store.dispatch(actions.changeRoom(result.room));
                    }
                    else {
                        store.dispatch(actions.sendMessage('error' + result.error));
                    }

                    const actual = store.getState();

                    const expected = { allMessages: [ [ 'Room has been changed' ] ], currentRoom: 'testRoom' };

                    expect(actual).toEqual(expected);
                    done();
                });
            }, 250);

        });

    });

});


text:
SRC_FILE=index.adoc
OUTPUT_FILE=index.html

all: clean html

.PHONY: test
test:
	@npm test
	@make html
	@npm run lint-html
	@npm run textlint

html:
	@echo "Generate HTML..."
	@npm run embed
	@npm run build
	@echo "Building asciidoc"
	@./_tools/build.sh
	@echo "Done! => ${OUTPUT_FILE}"

pdf:
	@echo "Generate PDF..."
	@npm run embed
	@echo "Building asciidoc"
	@bundle exec asciidoctor -a lang=en -a bookversion=`node ./_tools/cli-book-version.js` \
	-a icons=font -a source-highlighter=coderay --backend docbook \
	-o javascript-promise-book.xml ${SRC_FILE}
	@./_tools/build_pdf.sh javascript-promise-book.xml
	@echo "Done!"

pdf-note:
	@echo "Generate PDF..."
	@npm run embed
	@echo "Building asciidoc"
	@bundle exec asciidoctor -a lang=en -a icons=font -a source-highlighter=coderay --backend docbook \
	-o javascript-promise-omake.xml Appendix-Note/readme.adoc
	@./_tools/build_pdf.sh javascript-promise-omake.xml
	@echo "Done!"

deploy:
	@./_tools/deploy-gh-pages.sh

clean:
	@rm -f {OUTPUT_FILE} javascript-promise-*.pdf javascript-promise-*.xml


text:
function addRhatStringToFigure(targetAxisHandle, rhat)

assert(isscalar(rhat))

subplot(targetAxisHandle)

str = sprintf('$$ \\hat{R} = %1.5f$$', rhat);

% TODO: This fails if we pan and zoom. Maybe add it at a fixed relative
% subplot position?
hText = addTextToFigure('T',str, 10, 'latex');

% visual warning if threshold exceeded
if rhat < RHAT_THRESHOLD()
	hText.BackgroundColor=[1 1 1 0.7];
else
	hText.BackgroundColor=[1 0 0 0.7];
end
end


text:
//
// This file is auto-generated. Please don't modify it!
//
package org.opencv.dnn;

import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDouble;
import org.opencv.core.MatOfInt;
import org.opencv.core.Scalar;
import org.opencv.dnn.DictValue;
import org.opencv.dnn.Layer;
import org.opencv.dnn.Net;
import org.opencv.utils.Converters;

// C++: class Net
/**
 * This class allows to create and manipulate comprehensive artificial neural networks.
 *
 * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances,
 * and edges specify relationships between layers inputs and outputs.
 *
 * Each network layer has unique integer id and unique string name inside its network.
 * LayerId can store either layer name or layer id.
 *
 * This class supports reference counting of its instances, i. e. copies point to the same instance.
 */
public class Net {

    protected final long nativeObj;
    protected Net(long addr) { nativeObj = addr; }

    public long getNativeObjAddr() { return nativeObj; }

    // internal usage only
    public static Net __fromPtr__(long addr) { return new Net(addr); }

    //
    // C++:   cv::dnn::Net::Net()
    //

    public Net() {
        nativeObj = Net_0();
    }

    //
    // C++:  AsyncArray cv::dnn::Net::forwardAsync(String outputName = String())
    //

    // Return type 'AsyncArray' is not supported, skipping the function

    //
    // C++:  Mat cv::dnn::Net::forward(String outputName = String())
    //

    /**
     * Runs forward pass to compute output of layer with name {@code outputName}.
     * @param outputName name for layer which output is needed to get
     * @return blob for first output of specified layer.
     * By default runs forward pass for the whole network.
     */
    public Mat forward(String outputName) {
        return new Mat(forward_0(nativeObj, outputName));
    }

    /**
     * Runs forward pass to compute output of layer with name {@code outputName}.
     * @return blob for first output of specified layer.
     * By default runs forward pass for the whole network.
     */
    public Mat forward() {
        return new Mat(forward_1(nativeObj));
    }

    //
    // C++:  Mat cv::dnn::Net::getParam(LayerId layer, int numParam = 0)
    //

    /**
     * Returns parameter blob of the layer.
     * @param layer name or id of the layer.
     * @param numParam index of the layer parameter in the Layer::blobs array.
     * SEE: Layer::blobs
     * @return automatically generated
     */
    public Mat getParam(DictValue layer, int numParam) {
        return new Mat(getParam_0(nativeObj, layer.getNativeObjAddr(), numParam));
    }

    /**
     * Returns parameter blob of the layer.
     * @param layer name or id of the layer.
     * SEE: Layer::blobs
     * @return automatically generated
     */
    public Mat getParam(DictValue layer) {
        return new Mat(getParam_1(nativeObj, layer.getNativeObjAddr()));
    }

    //
    // C++: static Net cv::dnn::Net::readFromModelOptimizer(String xml, String bin)
    //

    /**
     * Create a network from Intel's Model Optimizer intermediate representation.
     * @param xml XML configuration file with network's topology.
     * @param bin Binary file with trained weights.
     * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
     * backend.
     * @return automatically generated
     */
    public static Net readFromModelOptimizer(String xml, String bin) {
        return new Net(readFromModelOptimizer_0(xml, bin));
    }

    //
    // C++:  Ptr_Layer cv::dnn::Net::getLayer(LayerId layerId)
    //

    /**
     * Returns pointer to layer with specified id or name which the network use.
     * @param layerId automatically generated
     * @return automatically generated
     */
    public Layer getLayer(DictValue layerId) {
        return Layer.__fromPtr__(getLayer_0(nativeObj, layerId.getNativeObjAddr()));
    }

    //
    // C++:  String cv::dnn::Net::dump()
    //

    /**
     * Dump net to String
     * @return String with structure, hyperparameters, backend, target and fusion
     * Call method after setInput(). To see correct backend, target and fusion run after forward().
     */
    public String dump() {
        return dump_0(nativeObj);
    }

    //
    // C++:  bool cv::dnn::Net::empty()
    //

    /**
     * Returns true if there are no layers in the network.
     * @return automatically generated
     */
    public boolean empty() {
        return empty_0(nativeObj);
    }

    //
    // C++:  int cv::dnn::Net::getLayerId(String layer)
    //

    /**
     * Converts string name of the layer to the integer identifier.
     * @return id of the layer, or -1 if the layer wasn't found.
     * @param layer automatically generated
     */
    public int getLayerId(String layer) {
        return getLayerId_0(nativeObj, layer);
    }

    //
    // C++:  int cv::dnn::Net::getLayersCount(String layerType)
    //

    /**
     * Returns count of layers of specified type.
     * @param layerType type.
     * @return count of layers
     */
    public int getLayersCount(String layerType) {
        return getLayersCount_0(nativeObj, layerType);
    }

    //
    // C++:  int64 cv::dnn::Net::getFLOPS(MatShape netInputShape)
    //

    public long getFLOPS(MatOfInt netInputShape) {
        Mat netInputShape_mat = netInputShape;
        return getFLOPS_0(nativeObj, netInputShape_mat.nativeObj);
    }

    //
    // C++:  int64 cv::dnn::Net::getFLOPS(int layerId, MatShape netInputShape)
    //

    public long getFLOPS(int layerId, MatOfInt netInputShape) {
        Mat netInputShape_mat = netInputShape;
        return getFLOPS_1(nativeObj, layerId, netInputShape_mat.nativeObj);
    }

    //
    // C++:  int64 cv::dnn::Net::getFLOPS(int layerId, vector_MatShape netInputShapes)
    //

    public long getFLOPS(int layerId, List<MatOfInt> netInputShapes) {
        return getFLOPS_2(nativeObj, layerId, netInputShapes);
    }

    //
    // C++:  int64 cv::dnn::Net::getFLOPS(vector_MatShape netInputShapes)
    //

    /**
     * Computes FLOP for whole loaded model with specified input shapes.
     * @param netInputShapes vector of shapes for all net inputs.
     * @return computed FLOP.
     */
    public long getFLOPS(List<MatOfInt> netInputShapes) {
        return getFLOPS_3(nativeObj, netInputShapes);
    }

    //
    // C++:  int64 cv::dnn::Net::getPerfProfile(vector_double& timings)
    //

    /**
     * Returns overall time for inference and timings (in ticks) for layers.
     * Indexes in returned vector correspond to layers ids. Some layers can be fused with others,
     * in this case zero ticks count will be return for that skipped layers.
     * @param timings vector for tick timings for all layers.
     * @return overall ticks for model inference.
     */
    public long getPerfProfile(MatOfDouble timings) {
        Mat timings_mat = timings;
        return getPerfProfile_0(nativeObj, timings_mat.nativeObj);
    }

    //
    // C++:  vector_String cv::dnn::Net::getLayerNames()
    //

    public List<String> getLayerNames() {
        return getLayerNames_0(nativeObj);
    }

    //
    // C++:  vector_String cv::dnn::Net::getUnconnectedOutLayersNames()
    //

    /**
     * Returns names of layers with unconnected outputs.
     * @return automatically generated
     */
    public List<String> getUnconnectedOutLayersNames() {
        return getUnconnectedOutLayersNames_0(nativeObj);
    }

    //
    // C++:  vector_int cv::dnn::Net::getUnconnectedOutLayers()
    //

    /**
     * Returns indexes of layers with unconnected outputs.
     * @return automatically generated
     */
    public MatOfInt getUnconnectedOutLayers() {
        return MatOfInt.fromNativeAddr(getUnconnectedOutLayers_0(nativeObj));
    }

    //
    // C++:  void cv::dnn::Net::connect(String outPin, String inpPin)
    //

    /**
     * Connects output of the first layer to input of the second layer.
     * @param outPin descriptor of the first layer output.
     * @param inpPin descriptor of the second layer input.
     *
     * Descriptors have the following template <DFN>&lt;layer_name&gt;[.input_number]</DFN>:
     * - the first part of the template <DFN>layer_name</DFN> is sting name of the added layer.
     * If this part is empty then the network input pseudo layer will be used;
     * - the second optional part of the template <DFN>input_number</DFN>
     * is either number of the layer input, either label one.
     * If this part is omitted then the first layer input will be used.
     *
     * SEE: setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex()
     */
    public void connect(String outPin, String inpPin) {
        connect_0(nativeObj, outPin, inpPin);
    }

    //
    // C++:  void cv::dnn::Net::dumpToFile(String path)
    //

    /**
     * Dump net structure, hyperparameters, backend, target and fusion to dot file
     * @param path   path to output file with .dot extension
     * SEE: dump()
     */
    public void dumpToFile(String path) {
        dumpToFile_0(nativeObj, path);
    }

    //
    // C++:  void cv::dnn::Net::enableFusion(bool fusion)
    //

    /**
     * Enables or disables layer fusion in the network.
     * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default.
     */
    public void enableFusion(boolean fusion) {
        enableFusion_0(nativeObj, fusion);
    }

    //
    // C++:  void cv::dnn::Net::forward(vector_Mat& outputBlobs, String outputName = String())
    //

    /**
     * Runs forward pass to compute output of layer with name {@code outputName}.
     * @param outputBlobs contains all output blobs for specified layer.
     * @param outputName name for layer which output is needed to get
     * If {@code outputName} is empty, runs forward pass for the whole network.
     */
    public void forward(List<Mat> outputBlobs, String outputName) {
        Mat outputBlobs_mat = new Mat();
        forward_2(nativeObj, outputBlobs_mat.nativeObj, outputName);
        Converters.Mat_to_vector_Mat(outputBlobs_mat, outputBlobs);
        outputBlobs_mat.release();
    }

    /**
     * Runs forward pass to compute output of layer with name {@code outputName}.
     * @param outputBlobs contains all output blobs for specified layer.
     * If {@code outputName} is empty, runs forward pass for the whole network.
     */
    public void forward(List<Mat> outputBlobs) {
        Mat outputBlobs_mat = new Mat();
        forward_3(nativeObj, outputBlobs_mat.nativeObj);
        Converters.Mat_to_vector_Mat(outputBlobs_mat, outputBlobs);
        outputBlobs_mat.release();
    }

    //
    // C++:  void cv::dnn::Net::forward(vector_Mat& outputBlobs, vector_String outBlobNames)
    //

    /**
     * Runs forward pass to compute outputs of layers listed in {@code outBlobNames}.
     * @param outputBlobs contains blobs for first outputs of specified layers.
     * @param outBlobNames names for layers which outputs are needed to get
     */
    public void forward(List<Mat> outputBlobs, List<String> outBlobNames) {
        Mat outputBlobs_mat = new Mat();
        forward_4(nativeObj, outputBlobs_mat.nativeObj, outBlobNames);
        Converters.Mat_to_vector_Mat(outputBlobs_mat, outputBlobs);
        outputBlobs_mat.release();
    }

    //
    // C++:  void cv::dnn::Net::forward(vector_vector_Mat& outputBlobs, vector_String outBlobNames)
    //

    // Unknown type 'vector_vector_Mat' (O), skipping the function

    //
    // C++:  void cv::dnn::Net::getLayerTypes(vector_String& layersTypes)
    //

    /**
     * Returns list of types for layer used in model.
     * @param layersTypes output parameter for returning types.
     */
    public void getLayerTypes(List<String> layersTypes) {
        getLayerTypes_0(nativeObj, layersTypes);
    }

    //
    // C++:  void cv::dnn::Net::getLayersShapes(MatShape netInputShape, vector_int& layersIds, vector_vector_MatShape& inLayersShapes, vector_vector_MatShape& outLayersShapes)
    //

    // Unknown type 'vector_vector_MatShape' (O), skipping the function

    //
    // C++:  void cv::dnn::Net::getLayersShapes(vector_MatShape netInputShapes, vector_int& layersIds, vector_vector_MatShape& inLayersShapes, vector_vector_MatShape& outLayersShapes)
    //

    // Unknown type 'vector_vector_MatShape' (O), skipping the function

    //
    // C++:  void cv::dnn::Net::getMemoryConsumption(MatShape netInputShape, size_t& weights, size_t& blobs)
    //

    public void getMemoryConsumption(MatOfInt netInputShape, long[] weights, long[] blobs) {
        Mat netInputShape_mat = netInputShape;
        double[] weights_out = new double[1];
        double[] blobs_out = new double[1];
        getMemoryConsumption_0(nativeObj, netInputShape_mat.nativeObj, weights_out, blobs_out);
        if(weights!=null) weights[0] = (long)weights_out[0];
        if(blobs!=null) blobs[0] = (long)blobs_out[0];
    }

    //
    // C++:  void cv::dnn::Net::getMemoryConsumption(int layerId, MatShape netInputShape, size_t& weights, size_t& blobs)
    //

    public void getMemoryConsumption(int layerId, MatOfInt netInputShape, long[] weights, long[] blobs) {
        Mat netInputShape_mat = netInputShape;
        double[] weights_out = new double[1];
        double[] blobs_out = new double[1];
        getMemoryConsumption_1(nativeObj, layerId, netInputShape_mat.nativeObj, weights_out, blobs_out);
        if(weights!=null) weights[0] = (long)weights_out[0];
        if(blobs!=null) blobs[0] = (long)blobs_out[0];
    }

    //
    // C++:  void cv::dnn::Net::getMemoryConsumption(int layerId, vector_MatShape netInputShapes, size_t& weights, size_t& blobs)
    //

    public void getMemoryConsumption(int layerId, List<MatOfInt> netInputShapes, long[] weights, long[] blobs) {
        double[] weights_out = new double[1];
        double[] blobs_out = new double[1];
        getMemoryConsumption_2(nativeObj, layerId, netInputShapes, weights_out, blobs_out);
        if(weights!=null) weights[0] = (long)weights_out[0];
        if(blobs!=null) blobs[0] = (long)blobs_out[0];
    }

    //
    // C++:  void cv::dnn::Net::setHalideScheduler(String scheduler)
    //

    /**
     * Compile Halide layers.
     * @param scheduler Path to YAML file with scheduling directives.
     * SEE: setPreferableBackend
     *
     * Schedule layers that support Halide backend. Then compile them for
     * specific target. For layers that not represented in scheduling file
     * or if no manual scheduling used at all, automatic scheduling will be applied.
     */
    public void setHalideScheduler(String scheduler) {
        setHalideScheduler_0(nativeObj, scheduler);
    }

    //
    // C++:  void cv::dnn::Net::setInput(Mat blob, String name = "", double scalefactor = 1.0, Scalar mean = Scalar())
    //

    /**
     * Sets the new input value for the network
     * @param blob        A new blob. Should have CV_32F or CV_8U depth.
     * @param name        A name of input layer.
     * @param scalefactor An optional normalization scale.
     * @param mean        An optional mean subtraction values.
     * SEE: connect(String, String) to know format of the descriptor.
     *
     * If scale or mean values are specified, a final input blob is computed
     * as:
     * \(input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\)
     */
    public void setInput(Mat blob, String name, double scalefactor, Scalar mean) {
        setInput_0(nativeObj, blob.nativeObj, name, scalefactor, mean.val[0], mean.val[1], mean.val[2], mean.val[3]);
    }

    /**
     * Sets the new input value for the network
     * @param blob        A new blob. Should have CV_32F or CV_8U depth.
     * @param name        A name of input layer.
     * @param scalefactor An optional normalization scale.
     * SEE: connect(String, String) to know format of the descriptor.
     *
     * If scale or mean values are specified, a final input blob is computed
     * as:
     * \(input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\)
     */
    public void setInput(Mat blob, String name, double scalefactor) {
        setInput_1(nativeObj, blob.nativeObj, name, scalefactor);
    }

    /**
     * Sets the new input value for the network
     * @param blob        A new blob. Should have CV_32F or CV_8U depth.
     * @param name        A name of input layer.
     * SEE: connect(String, String) to know format of the descriptor.
     *
     * If scale or mean values are specified, a final input blob is computed
     * as:
     * \(input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\)
     */
    public void setInput(Mat blob, String name) {
        setInput_2(nativeObj, blob.nativeObj, name);
    }

    /**
     * Sets the new input value for the network
     * @param blob        A new blob. Should have CV_32F or CV_8U depth.
     * SEE: connect(String, String) to know format of the descriptor.
     *
     * If scale or mean values are specified, a final input blob is computed
     * as:
     * \(input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\)
     */
    public void setInput(Mat blob) {
        setInput_3(nativeObj, blob.nativeObj);
    }

    //
    // C++:  void cv::dnn::Net::setInputsNames(vector_String inputBlobNames)
    //

    /**
     * Sets outputs names of the network input pseudo layer.
     *
     * Each net always has special own the network input pseudo layer with id=0.
     * This layer stores the user blobs only and don't make any computations.
     * In fact, this layer provides the only way to pass user data into the network.
     * As any other layer, this layer can label its outputs and this function provides an easy way to do this.
     * @param inputBlobNames automatically generated
     */
    public void setInputsNames(List<String> inputBlobNames) {
        setInputsNames_0(nativeObj, inputBlobNames);
    }

    //
    // C++:  void cv::dnn::Net::setParam(LayerId layer, int numParam, Mat blob)
    //

    /**
     * Sets the new value for the learned param of the layer.
     * @param layer name or id of the layer.
     * @param numParam index of the layer parameter in the Layer::blobs array.
     * @param blob the new value.
     * SEE: Layer::blobs
     * <b>Note:</b> If shape of the new blob differs from the previous shape,
     * then the following forward pass may fail.
     */
    public void setParam(DictValue layer, int numParam, Mat blob) {
        setParam_0(nativeObj, layer.getNativeObjAddr(), numParam, blob.nativeObj);
    }

    //
    // C++:  void cv::dnn::Net::setPreferableBackend(int backendId)
    //

    /**
     * Ask network to use specific computation backend where it supported.
     * @param backendId backend identifier.
     * SEE: Backend
     *
     * If OpenCV is compiled with Intel's Inference Engine library, DNN_BACKEND_DEFAULT
     * means DNN_BACKEND_INFERENCE_ENGINE. Otherwise it equals to DNN_BACKEND_OPENCV.
     */
    public void setPreferableBackend(int backendId) {
        setPreferableBackend_0(nativeObj, backendId);
    }

    //
    // C++:  void cv::dnn::Net::setPreferableTarget(int targetId)
    //

    /**
     * Ask network to make computations on specific target device.
     * @param targetId target identifier.
     * SEE: Target
     *
     * List of supported combinations backend / target:
     * |                        | DNN_BACKEND_OPENCV | DNN_BACKEND_INFERENCE_ENGINE | DNN_BACKEND_HALIDE |
     * |------------------------|--------------------|------------------------------|--------------------|
     * | DNN_TARGET_CPU         |                  + |                            + |                  + |
     * | DNN_TARGET_OPENCL      |                  + |                            + |                  + |
     * | DNN_TARGET_OPENCL_FP16 |                  + |                            + |                    |
     * | DNN_TARGET_MYRIAD      |                    |                            + |                    |
     * | DNN_TARGET_FPGA        |                    |                            + |                    |
     */
    public void setPreferableTarget(int targetId) {
        setPreferableTarget_0(nativeObj, targetId);
    }

    @Override
    protected void finalize() throws Throwable {
        delete(nativeObj);
    }

    // C++:   cv::dnn::Net::Net()
    private static native long Net_0();

    // C++:  Mat cv::dnn::Net::forward(String outputName = String())
    private static native long forward_0(long nativeObj, String outputName);
    private static native long forward_1(long nativeObj);

    // C++:  Mat cv::dnn::Net::getParam(LayerId layer, int numParam = 0)
    private static native long getParam_0(long nativeObj, long layer_nativeObj, int numParam);
    private static native long getParam_1(long nativeObj, long layer_nativeObj);

    // C++: static Net cv::dnn::Net::readFromModelOptimizer(String xml, String bin)
    private static native long readFromModelOptimizer_0(String xml, String bin);

    // C++:  Ptr_Layer cv::dnn::Net::getLayer(LayerId layerId)
    private static native long getLayer_0(long nativeObj, long layerId_nativeObj);

    // C++:  String cv::dnn::Net::dump()
    private static native String dump_0(long nativeObj);

    // C++:  bool cv::dnn::Net::empty()
    private static native boolean empty_0(long nativeObj);

    // C++:  int cv::dnn::Net::getLayerId(String layer)
    private static native int getLayerId_0(long nativeObj, String layer);

    // C++:  int cv::dnn::Net::getLayersCount(String layerType)
    private static native int getLayersCount_0(long nativeObj, String layerType);

    // C++:  int64 cv::dnn::Net::getFLOPS(MatShape netInputShape)
    private static native long getFLOPS_0(long nativeObj, long netInputShape_mat_nativeObj);

    // C++:  int64 cv::dnn::Net::getFLOPS(int layerId, MatShape netInputShape)
    private static native long getFLOPS_1(long nativeObj, int layerId, long netInputShape_mat_nativeObj);

    // C++:  int64 cv::dnn::Net::getFLOPS(int layerId, vector_MatShape netInputShapes)
    private static native long getFLOPS_2(long nativeObj, int layerId, List<MatOfInt> netInputShapes);

    // C++:  int64 cv::dnn::Net::getFLOPS(vector_MatShape netInputShapes)
    private static native long getFLOPS_3(long nativeObj, List<MatOfInt> netInputShapes);

    // C++:  int64 cv::dnn::Net::getPerfProfile(vector_double& timings)
    private static native long getPerfProfile_0(long nativeObj, long timings_mat_nativeObj);

    // C++:  vector_String cv::dnn::Net::getLayerNames()
    private static native List<String> getLayerNames_0(long nativeObj);

    // C++:  vector_String cv::dnn::Net::getUnconnectedOutLayersNames()
    private static native List<String> getUnconnectedOutLayersNames_0(long nativeObj);

    // C++:  vector_int cv::dnn::Net::getUnconnectedOutLayers()
    private static native long getUnconnectedOutLayers_0(long nativeObj);

    // C++:  void cv::dnn::Net::connect(String outPin, String inpPin)
    private static native void connect_0(long nativeObj, String outPin, String inpPin);

    // C++:  void cv::dnn::Net::dumpToFile(String path)
    private static native void dumpToFile_0(long nativeObj, String path);

    // C++:  void cv::dnn::Net::enableFusion(bool fusion)
    private static native void enableFusion_0(long nativeObj, boolean fusion);

    // C++:  void cv::dnn::Net::forward(vector_Mat& outputBlobs, String outputName = String())
    private static native void forward_2(long nativeObj, long outputBlobs_mat_nativeObj, String outputName);
    private static native void forward_3(long nativeObj, long outputBlobs_mat_nativeObj);

    // C++:  void cv::dnn::Net::forward(vector_Mat& outputBlobs, vector_String outBlobNames)
    private static native void forward_4(long nativeObj, long outputBlobs_mat_nativeObj, List<String> outBlobNames);

    // C++:  void cv::dnn::Net::getLayerTypes(vector_String& layersTypes)
    private static native void getLayerTypes_0(long nativeObj, List<String> layersTypes);

    // C++:  void cv::dnn::Net::getMemoryConsumption(MatShape netInputShape, size_t& weights, size_t& blobs)
    private static native void getMemoryConsumption_0(long nativeObj, long netInputShape_mat_nativeObj, double[] weights_out, double[] blobs_out);

    // C++:  void cv::dnn::Net::getMemoryConsumption(int layerId, MatShape netInputShape, size_t& weights, size_t& blobs)
    private static native void getMemoryConsumption_1(long nativeObj, int layerId, long netInputShape_mat_nativeObj, double[] weights_out, double[] blobs_out);

    // C++:  void cv::dnn::Net::getMemoryConsumption(int layerId, vector_MatShape netInputShapes, size_t& weights, size_t& blobs)
    private static native void getMemoryConsumption_2(long nativeObj, int layerId, List<MatOfInt> netInputShapes, double[] weights_out, double[] blobs_out);

    // C++:  void cv::dnn::Net::setHalideScheduler(String scheduler)
    private static native void setHalideScheduler_0(long nativeObj, String scheduler);

    // C++:  void cv::dnn::Net::setInput(Mat blob, String name = "", double scalefactor = 1.0, Scalar mean = Scalar())
    private static native void setInput_0(long nativeObj, long blob_nativeObj, String name, double scalefactor, double mean_val0, double mean_val1, double mean_val2, double mean_val3);
    private static native void setInput_1(long nativeObj, long blob_nativeObj, String name, double scalefactor);
    private static native void setInput_2(long nativeObj, long blob_nativeObj, String name);
    private static native void setInput_3(long nativeObj, long blob_nativeObj);

    // C++:  void cv::dnn::Net::setInputsNames(vector_String inputBlobNames)
    private static native void setInputsNames_0(long nativeObj, List<String> inputBlobNames);

    // C++:  void cv::dnn::Net::setParam(LayerId layer, int numParam, Mat blob)
    private static native void setParam_0(long nativeObj, long layer_nativeObj, int numParam, long blob_nativeObj);

    // C++:  void cv::dnn::Net::setPreferableBackend(int backendId)
    private static native void setPreferableBackend_0(long nativeObj, int backendId);

    // C++:  void cv::dnn::Net::setPreferableTarget(int targetId)
    private static native void setPreferableTarget_0(long nativeObj, int targetId);

    // native support for java finalize()
    private static native void delete(long nativeObj);

}


text:
import * as Expressions from "../../2_statements/expressions";
import {StatementNode} from "../../nodes";
import {CurrentScope} from "../_current_scope";
import {StatementSyntax} from "../_statement_syntax";
import {ReferenceType} from "../_reference";

export class Unassign implements StatementSyntax {
  public runSyntax(node: StatementNode, scope: CurrentScope, filename: string): void {
    const target = node?.findDirectExpression(Expressions.TargetFieldSymbol);
    if (target) {
      const token = target.getFirstToken();
      const found = scope.findVariable(token.getStr());
      if (found === undefined) {
        throw new Error(`"${token.getStr()}" not found, Unassign`);
      }
      scope.addReference(token, found, ReferenceType.DataWriteReference, filename);
    }
  }
}


text:
package kv

import (
	"sort"
	"time"

	"golang.org/x/net/context"
	"google.golang.org/grpc"

	"github.com/cockroachdb/cockroach/pkg/internal/client"
	"github.com/cockroachdb/cockroach/pkg/roachpb"
	"github.com/cockroachdb/cockroach/pkg/rpc"
	"github.com/cockroachdb/cockroach/pkg/util/envutil"
	"github.com/cockroachdb/cockroach/pkg/util/log"
	"github.com/cockroachdb/cockroach/pkg/util/syncutil"
	"github.com/cockroachdb/cockroach/pkg/util/tracing"
	"github.com/opentracing/opentracing-go"
)

// Allow local calls to be dispatched directly to the local server without
// sending an RPC.
var enableLocalCalls = envutil.EnvOrDefaultBool("COCKROACH_ENABLE_LOCAL_CALLS", true)

// A SendOptions structure describes the algorithm for sending RPCs to one or
// more replicas, depending on error conditions and how many successful
// responses are required.
type SendOptions struct {
	// SendNextTimeout is the duration after which RPCs are sent to
	// other replicas in a set.
	SendNextTimeout time.Duration

	transportFactory TransportFactory

	metrics *DistSenderMetrics
}

type batchClient struct {
	remoteAddr string
	conn       *grpc.ClientConn
	client     roachpb.InternalClient
	args       roachpb.BatchRequest
	healthy    bool
	retried    bool
	pending    bool
}

// BatchCall contains a response and an RPC error (note that the
// response contains its own roachpb.Error, which is separate from
// BatchCall.Err), and is analogous to the net/rpc.Call struct.
type BatchCall struct {
	Reply *roachpb.BatchResponse
	Err   error
}

// TransportFactory encapsulates all interaction with the RPC
// subsystem, allowing it to be mocked out for testing. The factory
// function returns a Transport object which is used to send the given
// arguments to one or more replicas in the slice.
//
// In addition to actually sending RPCs, the transport is responsible
// for ordering replicas in accordance with SendOptions.Ordering and
// transport-specific knowledge such as connection health or latency.
//
// TODO(bdarnell): clean up this crufty interface; it was extracted
// verbatim from the non-abstracted code.
type TransportFactory func(
	SendOptions, *rpc.Context, ReplicaSlice, roachpb.BatchRequest,
) (Transport, error)

// Transport objects can send RPCs to one or more replicas of a range.
// All calls to Transport methods are made from a single thread, so
// Transports are not required to be thread-safe.
type Transport interface {
	// IsExhausted returns true if there are no more replicas to try.
	IsExhausted() bool

	// SendNext sends the rpc (captured at creation time) to the next
	// replica. May panic if the transport is exhausted. Should not
	// block; the transport is responsible for starting other goroutines
	// as needed.
	SendNext(context.Context, chan<- BatchCall)

	// MoveToFront locates the specified replica and moves it to the
	// front of the ordering of replicas to try. If the replica has
	// already been tried, it will be retried. If the specified replica
	// can't be found, this is a noop.
	MoveToFront(roachpb.ReplicaDescriptor)

	// Close is called when the transport is no longer needed. It may
	// cancel any pending RPCs without writing any response to the channel.
	Close()
}

// grpcTransportFactoryImpl is the default TransportFactory, using GRPC.
// Do not use this directly - use grpcTransportFactory instead.
//
// During race builds, we wrap this to hold on to and read all obtained
// requests in a tight loop, exposing data races; see transport_race.go.
func grpcTransportFactoryImpl(
	opts SendOptions, rpcContext *rpc.Context, replicas ReplicaSlice, args roachpb.BatchRequest,
) (Transport, error) {
	clients := make([]batchClient, 0, len(replicas))
	for _, replica := range replicas {
		conn, err := rpcContext.GRPCDial(replica.NodeDesc.Address.String())
		if err != nil {
			return nil, err
		}
		argsCopy := args
		argsCopy.Replica = replica.ReplicaDescriptor
		remoteAddr := replica.NodeDesc.Address.String()
		clients = append(clients, batchClient{
			remoteAddr: remoteAddr,
			conn:       conn,
			client:     roachpb.NewInternalClient(conn),
			args:       argsCopy,
			healthy:    rpcContext.ConnHealth(remoteAddr) == nil,
		})
	}

	// Put known-unhealthy clients last.
	splitHealthy(clients)

	return &grpcTransport{
		opts:           opts,
		rpcContext:     rpcContext,
		orderedClients: clients,
	}, nil
}

type grpcTransport struct {
	opts            SendOptions
	rpcContext      *rpc.Context
	clientIndex     int
	orderedClients  []batchClient
	clientPendingMu syncutil.Mutex // protects access to all batchClient pending flags
}

func (gt *grpcTransport) IsExhausted() bool {
	return gt.clientIndex == len(gt.orderedClients)
}

// SendNext invokes the specified RPC on the supplied client when the
// client is ready. On success, the reply is sent on the channel;
// otherwise an error is sent.
func (gt *grpcTransport) SendNext(ctx context.Context, done chan<- BatchCall) {
	client := gt.orderedClients[gt.clientIndex]
	gt.clientIndex++
	gt.setPending(client.args.Replica, true)

	// Fork the original context as this async send may outlast the
	// caller's context.
	// TODO(andrei): We shouldn't have to fork the ctx here; it's sketchy that
	// these spans can outlast the caller's context. Instead, DistSender should
	// wait on all the RPCs that it sends and it should also have the ability to
	// cancel them when it received the first result.
	ctx, sp := tracing.ForkCtxSpan(ctx, "grpcTransport SendNext")
	go func() {
		gt.opts.metrics.SentCount.Inc(1)
		reply, err := func() (*roachpb.BatchResponse, error) {
			if enableLocalCalls {
				if localServer := gt.rpcContext.GetLocalInternalServerForAddr(client.remoteAddr); localServer != nil {
					// Clone the request. At the time of writing, Replica may mutate it
					// during command execution which can lead to data races.
					//
					// TODO(tamird): we should clone all of client.args.Header, but the
					// assertions in protoutil.Clone fire and there seems to be no
					// reasonable workaround.
					origTxn := client.args.Txn
					if origTxn != nil {
						clonedTxn := origTxn.Clone()
						client.args.Txn = &clonedTxn
					}
					gt.opts.metrics.LocalSentCount.Inc(1)
					log.VEvent(ctx, 2, "sending request to local server")
					return localServer.Batch(ctx, &client.args)
				}
			}

			log.VEventf(ctx, 2, "sending request to %s", client.remoteAddr)
			reply, err := client.client.Batch(ctx, &client.args)
			if reply != nil {
				for i := range reply.Responses {
					if err := reply.Responses[i].GetInner().Verify(client.args.Requests[i].GetInner()); err != nil {
						log.Error(ctx, err)
					}
				}
			}
			return reply, err
		}()
		gt.setPending(client.args.Replica, false)
		tracing.FinishSpan(sp)
		done <- BatchCall{Reply: reply, Err: err}
	}()
}

func (gt *grpcTransport) MoveToFront(replica roachpb.ReplicaDescriptor) {
	gt.clientPendingMu.Lock()
	defer gt.clientPendingMu.Unlock()
	for i := range gt.orderedClients {
		if gt.orderedClients[i].args.Replica == replica {
			// If a call to this replica is active or retried, don't move it.
			if gt.orderedClients[i].pending || gt.orderedClients[i].retried {
				return
			}
			// If we've already processed the replica, decrement the current
			// index before we swap.
			if i < gt.clientIndex {
				gt.orderedClients[i].retried = true
				gt.clientIndex--
			}
			// Swap the client representing this replica to the front.
			gt.orderedClients[i], gt.orderedClients[gt.clientIndex] =
				gt.orderedClients[gt.clientIndex], gt.orderedClients[i]
			return
		}
	}
}

func (*grpcTransport) Close() {
	// TODO(bdarnell): Save the cancel functions of all pending RPCs and
	// call them here. (it's fine to ignore them for now since they'll
	// time out anyway)
}

// NB: this method's callers may have a reference to the client they wish to
// mutate, but the clients reside in a slice which is shuffled via
// MoveToFront, making it unsafe to mutate the client through a reference to
// the slice.
func (gt *grpcTransport) setPending(replica roachpb.ReplicaDescriptor, pending bool) {
	gt.clientPendingMu.Lock()
	defer gt.clientPendingMu.Unlock()
	for i := range gt.orderedClients {
		if gt.orderedClients[i].args.Replica == replica {
			gt.orderedClients[i].pending = pending
			return
		}
	}
}

// splitHealthy splits the provided client slice into healthy clients and
// unhealthy clients, based on their connection state. Healthy clients will
// be rearranged first in the slice, and unhealthy clients will be rearranged
// last. Within these two groups, the rearrangement will be stable. The function
// will then return the number of healthy clients.
func splitHealthy(clients []batchClient) int {
	var nHealthy int
	sort.Stable(byHealth(clients))
	for _, client := range clients {
		if client.healthy {
			nHealthy++
		}
	}
	return nHealthy
}

// byHealth sorts a slice of batchClients by their health with healthy first.
type byHealth []batchClient

func (h byHealth) Len() int           { return len(h) }
func (h byHealth) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h byHealth) Less(i, j int) bool { return h[i].healthy && !h[j].healthy }

// SenderTransportFactory wraps a client.Sender for use as a KV
// Transport. This is useful for tests that want to use DistSender
// without a full RPC stack.
func SenderTransportFactory(tracer opentracing.Tracer, sender client.Sender) TransportFactory {
	return func(
		_ SendOptions, _ *rpc.Context, _ ReplicaSlice, args roachpb.BatchRequest,
	) (Transport, error) {
		return &senderTransport{tracer, sender, args, false}, nil
	}
}

type senderTransport struct {
	tracer opentracing.Tracer
	sender client.Sender
	args   roachpb.BatchRequest

	called bool
}

func (s *senderTransport) IsExhausted() bool {
	return s.called
}

func (s *senderTransport) SendNext(ctx context.Context, done chan<- BatchCall) {
	if s.called {
		panic("called an exhausted transport")
	}
	s.called = true
	sp := s.tracer.StartSpan("node")
	defer sp.Finish()
	ctx = opentracing.ContextWithSpan(ctx, sp)
	log.Event(ctx, s.args.String())
	br, pErr := s.sender.Send(ctx, s.args)
	if br == nil {
		br = &roachpb.BatchResponse{}
	}
	if br.Error != nil {
		panic(roachpb.ErrorUnexpectedlySet(s.sender, br))
	}
	br.Error = pErr
	if pErr != nil {
		log.Event(ctx, "error: "+pErr.String())
	}
	done <- BatchCall{Reply: br}
}

func (s *senderTransport) MoveToFront(replica roachpb.ReplicaDescriptor) {
}

func (s *senderTransport) Close() {
}


text:
#ifndef ELEKTRA_KDBTHREAD_HPP
#define ELEKTRA_KDBTHREAD_HPP

#include <kdbcontext.hpp>

#include <kdb.hpp>

#include <algorithm>
#include <cassert>
#include <functional>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <vector>

namespace kdb
{

/// Subject from Observer pattern for ThreadContext
class ThreadSubject
{
public:
	virtual void notify (KeySet & ks) = 0;
	virtual void syncLayers () = 0;
};

struct LayerAction
{
	LayerAction (bool activate_, std::shared_ptr<Layer> const & layer_) : activate (activate_), layer (std::move (layer_))
	{
	}
	bool activate; // false if deactivate
	std::shared_ptr<Layer> layer;
};

/// A vector of layers
typedef std::unordered_map<std::string, LayerAction> LayerMap;
typedef std::unordered_map<std::string, std::vector<std::function<void ()>>> FunctionMap;

/// A data structure that is stored by context inside the Coordinator
struct PerContext
{
	KeySet toUpdate;
	LayerMap toActivate;
};

class ThreadNoContext
{
public:
	/**
	 * @brief attach a new value
	 *
	 * NoContext will never update anything
	 */
	void attachByName (ELEKTRA_UNUSED std::string const & key_name, ELEKTRA_UNUSED ValueObserver & ValueObserver)
	{
	}

	/**
	 * @brief The evaluated equals the non-evaluated name!
	 *
	 * @return NoContext always returns the same string
	 */
	std::string evaluate (std::string const & key_name) const
	{
		return key_name;
	}

	std::string evaluate (std::string const & key_name,
			      std::function<bool (std::string const &, std::string &, bool in_group)> const &) const
	{
		return key_name;
	}

	/**
	 * @brief (Re)attaches a ValueSubject to a thread or simply
	 *        execute code in a locked section.
	 *
	 * NoContext just executes the function but does so in a
	 * thread-safe way
	 *
	 * @param c the command to apply
	 */
	void execute (Command & c)
	{
		std::lock_guard<std::mutex> lock (m_mutex);
		c ();
	}

private:
	std::mutex m_mutex;
};

/**
 * @brief Thread safe coordination of ThreadContext per Threads.
 */
class Coordinator
{
public:
	template <typename T>
	void onLayerActivation (std::function<void ()> f)
	{
		std::lock_guard<std::mutex> lock (m_mutexOnActivate);
		std::shared_ptr<Layer> layer = std::make_shared<T> ();
		m_onActivate[layer->id ()].push_back (f);
	}

	template <typename T>
	void onLayerDeactivation (std::function<void ()> f)
	{
		std::lock_guard<std::mutex> lock (m_mutexOnDeactivate);
		std::shared_ptr<Layer> layer = std::make_shared<T> ();
		m_onDeactivate[layer->id ()].push_back (f);
	}

	void onLayerActivation (std::string layerid, std::function<void ()> f)
	{
		std::lock_guard<std::mutex> lock (m_mutexOnActivate);
		m_onActivate[layerid].push_back (f);
	}

	void onLayerDeactivation (std::string layerid, std::function<void ()> f)
	{
		std::lock_guard<std::mutex> lock (m_mutexOnDeactivate);
		m_onDeactivate[layerid].push_back (f);
	}

	void clearOnLayerActivation (std::string layerid)
	{
		std::lock_guard<std::mutex> lock (m_mutexOnActivate);
		m_onActivate[layerid].clear ();
	}

	void clearOnLayerDeactivation (std::string layerid)
	{
		std::lock_guard<std::mutex> lock (m_mutexOnDeactivate);
		m_onDeactivate[layerid].clear ();
	}

	std::unique_lock<std::mutex> requireLock ()
	{
		std::unique_lock<std::mutex> lock (m_mutex);
		return lock;
	}

	Coordinator ()
	{
		std::lock_guard<std::mutex> lock (m_mutex);
		m_updates.insert (std::make_pair (nullptr, PerContext ()));
	}

	~Coordinator ()
	{
#if DEBUG
		for (auto & i : m_updates)
		{
			std::cout << "coordinator " << this << " left over: " << i.first << " with updates: " << i.second.toUpdate.size ()
				  << " activations: " << i.second.toActivate.size () << std::endl;
		}
#endif
	}

private:
	friend class ThreadContext;

	void attach (ThreadSubject * c)
	{
		std::lock_guard<std::mutex> lock (m_mutex);
		m_updates.insert (std::make_pair (c, m_updates[nullptr]));
	}

	void detach (ThreadSubject * c)
	{
		std::lock_guard<std::mutex> lock (m_mutex);
		m_updates.erase (c);
	}

	/**
	 * @brief Update the given ThreadContext with newly assigned
	 * values.
	 */
	void updateNewlyAssignedValues (ThreadSubject * c)
	{
		std::lock_guard<std::mutex> lock (m_mutex);
		KeySet & toUpdate = m_updates[c].toUpdate;
		if (toUpdate.size () == 0) return;

		c->notify (toUpdate);
		toUpdate.clear ();
	}

	/**
	 * @brief Receive a function to be executed and remember
	 * which keys need a update in the other ThreadContexts.
	 */
	void execute (Command & c)
	{
		std::lock_guard<std::mutex> lock (m_mutex);
		Command::Pair ret = c ();
		c.oldKey = ret.first;
		c.newKey = ret.second;
		if (c.hasChanged)
		{
			for (auto & i : m_updates)
			{
				i.second.toUpdate.append (Key (c.newKey, KEY_END));
			}
		}
	}

	void runOnActivate (std::shared_ptr<Layer> layer)
	{
		std::lock_guard<std::mutex> lock (m_mutexOnActivate);
		for (auto && f : m_onActivate[layer->id ()])
		{
			f ();
		}
	}

	/**
	 * @brief Request that some layer needs to be globally
	 * activated.
	 *
	 * @param cc requests it and already has it updated itself
	 * @param layer to activate for all threads
	 */
	void globalActivate (ThreadSubject * cc, std::shared_ptr<Layer> layer)
	{
		runOnActivate (layer);

		std::lock_guard<std::mutex> lock (m_mutex);
		for (auto & c : m_updates)
		{
			// caller itself has it already activated
			if (cc == c.first) continue;
			c.second.toActivate.insert (std::make_pair (layer->id (), LayerAction (true, layer)));
		}
	}

	void runOnDeactivate (std::shared_ptr<Layer> layer)
	{
		std::lock_guard<std::mutex> lock (m_mutexOnDeactivate);
		for (auto && f : m_onDeactivate[layer->id ()])
		{
			f ();
		}
	}

	void globalDeactivate (ThreadSubject * cc, std::shared_ptr<Layer> layer)
	{
		runOnDeactivate (layer);

		std::lock_guard<std::mutex> lock (m_mutex);
		for (auto & c : m_updates)
		{
			// caller itself has it already deactivated
			if (cc == c.first) continue;
			c.second.toActivate.insert (std::make_pair (layer->id (), LayerAction (false, layer)));
		}
	}

	/**
	 * @param cc requester of its updates
	 *
	 * @see globalActivate
	 * @return all layers for that subject
	 */
	LayerMap fetchGlobalActivation (ThreadSubject * cc)
	{
		std::lock_guard<std::mutex> lock (m_mutex);
		LayerMap ret;
		ret.swap (m_updates[cc].toActivate);
		return ret;
	}

	/// stores per context updates not yet delievered
	/// nullptr is for full history to be copied to new contexts
	std::unordered_map<ThreadSubject *, PerContext> m_updates;
	/// mutex protecting m_updates
	std::mutex m_mutex;
	FunctionMap m_onActivate;
	std::mutex m_mutexOnActivate;
	FunctionMap m_onDeactivate;
	std::mutex m_mutexOnDeactivate;
};

class ThreadContext : public ThreadSubject, public Context
{
public:
	typedef std::reference_wrapper<ValueSubject> ValueRef;

	explicit ThreadContext (Coordinator & gc) : m_gc (gc)
	{
		m_gc.attach (this);
	}

	~ThreadContext ()
	{
		m_gc.detach (this);
#if DEBUG
		for (auto & i : m_keys)
		{
			std::cout << "threadcontext " << this << " left over: " << i.first << std::endl;
		}
#endif
	}

	Coordinator & global ()
	{
		return m_gc;
	}

	Coordinator & g ()
	{
		return m_gc;
	}

	template <typename T, typename... Args>
	std::shared_ptr<Layer> activate (Args &&... args)
	{
		syncLayers ();
		std::shared_ptr<Layer> layer = Context::activate<T> (std::forward<Args> (args)...);
		m_gc.globalActivate (this, layer);
		return layer;
	}

	std::shared_ptr<Layer> activate (std::string key, std::string value)
	{
		syncLayers ();
		std::shared_ptr<Layer> layer = Context::activate (key, value);
		m_gc.globalActivate (this, layer);
		return layer;
	}

	std::shared_ptr<Layer> activate (Wrapped const & value)
	{
		syncLayers ();
		std::shared_ptr<Layer> layer = Context::activate (value);
		m_gc.globalActivate (this, layer);
		return layer;
	}

	template <typename T, typename... Args>
	std::shared_ptr<Layer> deactivate (Args &&... args)
	{
		syncLayers ();
		std::shared_ptr<Layer> layer = Context::deactivate<T> (std::forward<Args> (args)...);
		m_gc.globalDeactivate (this, layer);
		return layer;
	}

	std::shared_ptr<Layer> deactivate (std::string key, std::string value)
	{
		syncLayers ();
		std::shared_ptr<Layer> layer = Context::deactivate (key, value);
		m_gc.globalDeactivate (this, layer);
		return layer;
	}

	std::shared_ptr<Layer> deactivate (Wrapped const & value)
	{
		syncLayers ();
		std::shared_ptr<Layer> layer = Context::deactivate (value);
		m_gc.globalDeactivate (this, layer);
		return layer;
	}

	void syncLayers () override
	{
		// now activate/deactive layers
		Events e;
		for (auto const & l : m_gc.fetchGlobalActivation (this))
		{
			if (l.second.activate)
			{
				activateLayer (l.second.layer);
			}
			else
			{
				deactivateLayer (l.second.layer);
			}
			e.push_back (l.first);
		}
		notifyByEvents (e);

		// pull in assignments from other threads
		m_gc.updateNewlyAssignedValues (this);
	}

	virtual void sync ()
	{
		syncLayers ();
		notifyKeySetUpdate ();
	}

	/**
	 * @brief Command dispatching
	 *
	 * @param c the command to execute
	 */
	void execute (Command & c) override
	{
		m_gc.execute (c);
		if (c.oldKey != c.newKey)
		{
			if (!c.oldKey.empty ())
			{
				m_keys.erase (c.oldKey);
			}
			if (!c.newKey.empty ())
			{
				m_keys.insert (std::make_pair (c.newKey, ValueRef (c.v)));
			}
		}
	}

	/**
	 * @brief notify all keys
	 *
	 * Locked during execution, safe to use ks
	 *
	 * @param ks
	 */
	void notify (KeySet & ks) override
	{
		for (auto const & k : ks)
		{
			auto const & f = m_keys.find (k.getName ());
			if (f == m_keys.end ()) continue; // key already had context change
			f->second.get ().notifyInThread ();
		}
	}

private:
	Coordinator & m_gc;
	/**
	 * @brief A map of values this ThreadContext is responsible for.
	 */
	std::unordered_map<std::string, ValueRef> m_keys;
};

template <typename T, typename PolicySetter1 = DefaultPolicyArgs, typename PolicySetter2 = DefaultPolicyArgs,
	  typename PolicySetter3 = DefaultPolicyArgs, typename PolicySetter4 = DefaultPolicyArgs,
	  typename PolicySetter5 = DefaultPolicyArgs>
using ThreadValue = Value<T, ContextPolicyIs<ThreadContext>, PolicySetter1, PolicySetter2, PolicySetter3, PolicySetter4, PolicySetter5>;

typedef ThreadValue<uint32_t> ThreadInteger;
typedef ThreadValue<bool> ThreadBoolean;
typedef ThreadValue<std::string> ThreadString;
} // namespace kdb

#endif


text:
package alabno.database;

import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import alabno.utils.FileUtils;

public class MySqlDatabaseConnection implements DatabaseConnection {

    // JDBC driver name and database URL
    private String DB_URL;

    // Database credentials
    static final String USER = "python";
    private String dbPassword = "";

    private Connection conn;

    public MySqlDatabaseConnection() {
        if (System.getenv("ALABNOLOCAL").equals("1")) {
            DB_URL = "jdbc:mysql://localhost:3306/Automarker";
        } else {
            DB_URL = "jdbc:mysql://tc.jstudios.ovh:3306/Automarker";
        }

        setupPassword();
        connect();
    }

    private void setupPassword() {
        String workDir = FileUtils.getWorkDir();
        String passwordPath = workDir + "/dbpass.txt";
        File passwordFile = new File(passwordPath);
        Scanner scanner = null;
        try {
            scanner = new Scanner(passwordFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("Could not find the password file! Make sure to use RunServer");
            System.exit(1);
        }
        String thePassword = scanner.nextLine();
        scanner.close();
        this.dbPassword = thePassword;
    }

    private void connect() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            DriverManager.setLoginTimeout(10);
            conn = DriverManager.getConnection(DB_URL, USER, dbPassword);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /* (non-Javadoc)
     * @see alabno.database.DatabaseConnection#retrieveQueryString(java.lang.String)
     */
    @Override
    public synchronized List<Map<String, String>> retrieveQueryString(String sql) {
        return retrieveQueryString(sql, true);
    }

    // if `retry` is set, the database will try to re-establish
    // a broken connection and query again. Otherwise, it will
    // print the Exception to console
    private List<Map<String, String>> retrieveQueryString(String sql, boolean retry) {
        List<Map<String, String>> result = new ArrayList<>();

        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            Map<String, String> row;
            ResultSetMetaData metaData = rs.getMetaData();
            Integer columnCount = metaData.getColumnCount();

            while (rs.next()) {
                row = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    row.put(metaData.getColumnName(i), rs.getString(i));
                }
                result.add(row);
            }

            rs.close();
            stmt.close();
        } catch (Exception e) {
            connect();
            if (retry) {
                return retrieveQueryString(sql, false);
            } else {
                e.printStackTrace();
            }
        }

        return result;
    }

    /* (non-Javadoc)
     * @see alabno.database.DatabaseConnection#retrieveQuery(java.lang.String)
     */
    @Override
    public synchronized List<Map<String, Object>> retrieveQuery(String query) {
        return retrieveQuery(query, new String[0], true);
    }

    /* (non-Javadoc)
     * @see alabno.database.DatabaseConnection#retrieveStatement(java.lang.String, java.lang.String[])
     */
    @Override
    public synchronized List<Map<String, Object>> retrieveStatement(String query, String[] parameters) {
        return retrieveQuery(query, parameters, true);
    }

    // if `retry` is set, the database will try to re-establish
    // a broken connection and query again. Otherwise, it will
    // print the Exception to console
    private List<Map<String, Object>> retrieveQuery(String query, String[] parameters, boolean retry) {
        List<Map<String, Object>> result = new ArrayList<>();

        try {
            PreparedStatement stmt = conn.prepareStatement(query);
            for (int i = 0; i < parameters.length; i++) {
                stmt.setString(i + 1, parameters[i]);
            }

            ResultSet rs = stmt.executeQuery();

            Map<String, Object> row;
            ResultSetMetaData metaData = rs.getMetaData();
            Integer columnCount = metaData.getColumnCount();
            while (rs.next()) {
                row = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    row.put(metaData.getColumnName(i), rs.getObject(i));
                }
                result.add(row);
            }

            rs.close();
            stmt.close();
        } catch (Exception e) {
            connect();
            if (retry) {
                return retrieveQuery(query, parameters, false);
            } else {
                e.printStackTrace();
            }
        }
        return result;
    }

    /* (non-Javadoc)
     * @see alabno.database.DatabaseConnection#executeQuery(java.lang.String)
     */
    @Override
    public synchronized int executeQuery(String query) {
        return executeQuery(query, true);
    }

    // if `retry` is set, the database will try to re-establish
    // a broken connection and query again. Otherwise, it will
    // print the Exception to console
    private int executeQuery(String query, boolean retry) {
        int result = 0;
        try {
            Statement stmt = conn.createStatement();
            result = stmt.executeUpdate(query);
            stmt.close();
        } catch (Exception e) {
            connect();
            if (retry) {
                return executeQuery(query, false);
            } else {
                e.printStackTrace();
            }
        }
        return result;
    }

    /* (non-Javadoc)
     * @see alabno.database.DatabaseConnection#executeStatement(java.lang.String, java.lang.String[])
     */
    @Override
    public synchronized int executeStatement(String query, String[] parameters) {
        return executeStatement(query, parameters, true);
    }

    private int executeStatement(String query, String[] parameters, boolean retry) {
        int result = 0;
        try {
            PreparedStatement stmt = conn.prepareStatement(query);
            for (int i = 0; i < parameters.length; i++) {
                stmt.setString(i + 1, parameters[i]);
            }
            result = stmt.executeUpdate();
            stmt.close();
        } catch (Exception e) {
            connect();
            if (retry) {
                return executeStatement(query, parameters, false);
            } else {
                e.printStackTrace();
            }
        }

        return result;
    }

    /* (non-Javadoc)
     * @see alabno.database.DatabaseConnection#executeTransaction(alabno.database.TransactionBuilder)
     */
    @Override
    public synchronized int executeTransaction(TransactionBuilder tb) {
        int result = 0;
        try {
            conn.setAutoCommit(false);

            for (TransactionElement element : tb.getElements()) {
                String query = element.getSql();
                String[] parameters = element.getArgs();

                PreparedStatement stmt = conn.prepareStatement(query);
                for (int i = 0; i < parameters.length; i++) {
                    stmt.setString(i + 1, parameters[i]);
                }
                result = stmt.executeUpdate();
                stmt.close();
            }

            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            connect();
        } finally {
            try {
                conn.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

}


text:
---
layout: default
class: Analyzer
title: -output  FILE
summary: Specify the output directory or file.
---

TODO how does this relate to -outputmask?

/**
	 * Calculate the output file for the given target. The strategy is:
	 *
	 * <pre>
	 * parameter given if not null and not directory
	 * if directory, this will be the output directory
	 * based on bsn-version.jar
	 * name of the source file if exists
	 * Untitled-[n]
	 * </pre>
	 *
	 * @param output
	 *            may be null, otherwise a file path relative to base
	 */
	public File getOutputFile(String output) {

		if (output == null)
			output = get(Constants.OUTPUT);

		File outputDir;

		if (output != null) {
			File outputFile = getFile(output);
			if (outputFile.isDirectory())
				outputDir = outputFile;
			else
				return outputFile;
		} else
			outputDir = getBase();

		Entry<String,Attrs> name = getBundleSymbolicName();
		if (name != null) {
			String bsn = name.getKey();
			String version = getBundleVersion();
			Version v = Version.parseVersion(version);
			String outputName = bsn + "-" + v.getWithoutQualifier() + Constants.DEFAULT_JAR_EXTENSION;
			return new File(outputDir, outputName);
		}

		File source = getJar().getSource();
		if (source != null) {
			String outputName = source.getName();
			return new File(outputDir, outputName);
		}

		error("Cannot establish an output name from %s, nor bsn, nor source file name, using Untitled", output);
		int n = 0;
		File f = getFile(outputDir, "Untitled");
		while (f.isFile()) {
			f = getFile(outputDir, "Untitled-" + n++);
		}
		return f;
	}


text:
using OpenSage.Data.Ini;

namespace OpenSage.Logic.Object
{
    public sealed class LaserUpdateModuleData : ClientUpdateModuleData
    {
        internal static LaserUpdateModuleData Parse(IniParser parser) => parser.ParseBlock(FieldParseTable);

        private static readonly IniParseTable<LaserUpdateModuleData> FieldParseTable = new IniParseTable<LaserUpdateModuleData>
        {
            { "MuzzleParticleSystem", (parser, x) => x.MuzzleParticleSystem = parser.ParseAssetReference() },
            { "ParentFireBoneName", (parser, x) => x.ParentFireBoneName = parser.ParseBoneName() },
            { "ParentFireBoneOnTurret", (parser, x) => x.ParentFireBoneOnTurret = parser.ParseBoolean() },
            { "TargetParticleSystem", (parser, x) => x.TargetParticleSystem = parser.ParseAssetReference() },
            { "PunchThroughScalar", (parser, x) => x.PunchThroughScalar = parser.ParseFloat() },
            { "LaserLifetime", (parser, x) => x.LaserLifetime = parser.ParseInteger() }
        };

        public string MuzzleParticleSystem { get; private set; }
        public string ParentFireBoneName { get; private set; }
        public bool ParentFireBoneOnTurret { get; private set; }
        public string TargetParticleSystem { get; private set; }

        [AddedIn(SageGame.CncGeneralsZeroHour)]
        public float PunchThroughScalar { get; private set; }

        [AddedIn(SageGame.Bfme)]
        public int LaserLifetime { get; private set; }
    }
}


text:
/**
 * Separate processing code commit data for the product widget
 */
(function () {
    'use strict';

    angular
        .module(HygieiaConfig.module)
        .factory('productCommitData', function () {
            return {
                process: process
            }
        });

    function process(dependencies) {
        // unwrap dependencies
        var db = dependencies.db,
            configuredTeam = dependencies.configuredTeam,
            $q = dependencies.$q,
            isReload = dependencies.isReload,
            pipelineData = dependencies.pipelineData,
            nowTimestamp = dependencies.nowTimestamp,
            ctrlStages = dependencies.ctrlStages;

        // timestamps
        var now = moment(),
            dateEnds = now.valueOf(),
            ninetyDaysAgo = now.add(-90, 'days').valueOf(),
            dateBegins = ninetyDaysAgo;

        // querying pipeline commits by date will only return production commits that have
        // moved to prod since that last request. this way we can avoid sending 90 days
        // of production commit data with each request. all other environments will show
        // a current snapshot of data
        var collectorItemId = configuredTeam.collectorItemId;

        // get our pipeline commit data. start by seeing if we've already run this request
        db.lastRequest.where('[type+id]').equals(['pipeline-commit', collectorItemId]).first().then(processLastRequestResponse);

        function processLastRequestResponse(lastRequest) {
            // if we already have made a request, just get the delta
            if (lastRequest) {
                dateBegins = lastRequest.timestamp;
            }

            pipelineData
                .commits(dateBegins, nowTimestamp, collectorItemId)
                .then(function (response) {
                    return processPipelineCommitResponse(response, lastRequest);
                })
                .then(processPipelineCommitData)
                .finally(function () {
                    dependencies.cleanseData(db.prodCommit, ninetyDaysAgo);
                });
        }

        function processPipelineCommitResponse(response, lastRequest) {
            if (!response.length) {
                return $q.reject('No response found');
            }

            // we only requested one team so it's safe to assume
            // that it's in the first position
            response = response[0];

            // don't continue saving local data
            if (HygieiaConfig.local && isReload) {
                return response;
            }

            // save the request object so we can get the delta next time as well
            if (lastRequest) {
                lastRequest.timestamp = dateEnds;
                lastRequest.save();
            }
            // need to add a new item
            else {
                db.lastRequest.add({
                    id: collectorItemId,
                    type: 'pipeline-commit',
                    timestamp: dateEnds
                });
            }

            // put all results in the database
            _(response.stages.Prod).forEach(function (commit) {
                // extend the commit object with fields we need
                // to search the db
                commit.collectorItemId = collectorItemId;
                commit.timestamp = commit.processedTimestamps.Prod;

                db.prodCommit.add(commit);
            });

            return response;
        }

        function processPipelineCommitData(team) {
            db.prodCommit.where('[collectorItemId+timestamp]').between([collectorItemId, ninetyDaysAgo], [collectorItemId, dateEnds]).toArray(function (rows) {
                team.stages.Prod = _(rows).sortBy('timestamp').reverse().value();

                var teamStageData = {},
                    stageDurations = {},
                    stages = [].concat(ctrlStages); // create a local copy so it doesn't get overwritten

                // go backward through the stages and define commit data.
                // reverse should make it easier to calculate time in the previous stage
                _(stages).reverse().forEach(function (currentStageName) {
                    var commits = [], // store our new commit object
                        localStages = [].concat(ctrlStages), // create a copy of the stages
                        previousStages = _(localStages.splice(0, localStages.indexOf(currentStageName))).reverse().value(); // only look for stages before this one

                    // loop through each commit and create our own custom commit object
                    _(team.stages[currentStageName]).forEach(function (commitObj) {
                        var commit = {
                            author: commitObj.scmAuthor || 'NA',
                            message: commitObj.scmCommitLog || 'No message',
                            id: commitObj.scmRevisionNumber,
                            timestamp: commitObj.scmCommitTimestamp,
                            in: {} //placeholder for stage duration data per commit
                        };

                        // make sure this stage exists to track durations
                        if (!stageDurations[currentStageName]) {
                            stageDurations[currentStageName] = [];
                        }

                        // use this commit to calculate time in the current stage
                        var currentStageTimestampCompare = commit.timestamp;
                        if (commitObj.processedTimestamps[currentStageName]) {
                            currentStageTimestampCompare = commitObj.processedTimestamps[currentStageName];
                        }

                        // use this time in our metric calculations
                        var timeInCurrentStage = nowTimestamp - currentStageTimestampCompare;
                        stageDurations[currentStageName].push(timeInCurrentStage);

                        // make sure current stage is set
                        commit.in[currentStageName] = timeInCurrentStage;

                        // on each commit, set data for how long it was in each stage by looping
                        // through any previous stage and subtracting its timestamp from the next stage
                        var currentStageTimestamp = commitObj.processedTimestamps[currentStageName];
                        _(previousStages).forEach(function (previousStage) {
                            if (!commitObj.processedTimestamps[previousStage] || isNaN(currentStageTimestamp)) {
                                return;
                            }

                            var previousStageTimestamp = commitObj.processedTimestamps[previousStage],
                                timeInPreviousStage = currentStageTimestamp - previousStageTimestamp;

                            // it is possible that a hot-fix or some other change was made which caused
                            // the commit to skip an earlier environment. In this case just set that
                            // time to 0 so it's considered in the calculation, but does not negatively
                            // take away from the average
                            timeInPreviousStage = Math.max(timeInPreviousStage, 0);

                            // add how long it was in the previous stage
                            commit.in[previousStage] = timeInPreviousStage;

                            // add this number to the stage duration array so it can be used
                            // to calculate each stages average duration individually
                            if (!stageDurations[previousStage]) {
                                stageDurations[previousStage] = [];
                            }

                            // add this time to our duration list
                            stageDurations[previousStage].push(timeInPreviousStage);

                            // now use this as our new current timestamp
                            currentStageTimestamp = previousStageTimestamp;
                        });

                        // add our commit object back
                        commits.push(commit);
                    });

                    // make sure commits are always set
                    teamStageData[currentStageName] = {
                        commits: commits
                    }
                });

                // now that we've added all the duration data for all commits in each stage
                // we can calculate the averages and std deviation and put the data on the stage
                _(stageDurations).forEach(function (durationArray, currentStageName) {
                    if (!teamStageData[currentStageName]) {
                        teamStageData[currentStageName] = {};
                    }

                    var stats = getStageDurationStats(durationArray);
                    angular.extend(teamStageData[currentStageName], {
                        stageAverageTime: stats.mean,
                        stageStdDeviation: stats.deviation
                    })
                });

                // now that we have average and std deviation we can determine if a commit
                // has been in the environment for longer than 2 std deviations in which case
                // it should be marked as a failure
                _(teamStageData).forEach(function (data, stage) {

                    if (!data.stageStdDeviation || !data.commits) {
                        return;
                    }

                    _(data.commits).forEach(function (commit) {
                        // use the time it's been in the existing environment to compare
                        var timeInStage = commit.in[stage];

                        commit.errorState = timeInStage > 2 * data.stageStdDeviation;
                    });
                });

                // create some summary data used in each stage's cell
                _(teamStageData).forEach(function (stageData, stageName) {
                    stageData.summary = {
                        // helper for determining whether this stage has current commits
                        hasCommits: stageData.commits && stageData.commits.length ? true : false,

                        // green block count
                        commitsInsideTimeframe: _(stageData.commits).filter(function (c) {
                            return !c.errorState;
                        }).value().length,

                        // red block count
                        commitsOutsideTimeframe: _(stageData.commits).filter({errorState: true}).value().length,

                        // stage last updated text
                        lastUpdated: (function (stageData) {
                            if (!stageData.commits || !stageData.commits.length) {
                                return false;
                            }

                            // try to get the last commit to enter this stage by evaluating the duration
                            // for this current stage, otherwise use the commit timestamp
                            var lastUpdatedDuration = _(stageData.commits).map(function (commit) {
                                    return commit.in[stageName] || moment().valueOf() - commit.timestamp;
                                }).min().value(),
                                lastUpdated = moment().add(-1 * lastUpdatedDuration, 'milliseconds');

                            return {
                                longDisplay: lastUpdated.format('MMMM Do YYYY, h:mm:ss a'),
                                shortDisplay: lastUpdated.dash('ago')
                            }
                        })(stageData),

                        // stage deviation
                        deviation: (function (stageData) {
                            if (stageData.stageStdDeviation == undefined) {
                                return false;
                            }

                            // determine how to display the standard deviation
                            var number = moment.duration(2 * stageData.stageStdDeviation).minutes(),
                                desc = 'min';

                            if (number > 60 * 24) {
                                desc = 'day';
                                number = Math.round(number / 24 / 60);
                            }
                            else if (number > 60) {
                                desc = 'hour';
                                number = Math.round(number / 60);
                            }

                            return {
                                number: number,
                                descriptor: desc
                            }
                        })(stageData),

                        average: (function (stageData) {
                            // determine how to display the average time
                            if (!stageData.stageAverageTime) {
                                return false;
                            }

                            var average = moment.duration(stageData.stageAverageTime);

                            return {
                                days: Math.floor(average.asDays()),
                                hours: average.hours(),
                                minutes: average.minutes()
                            }
                        })(stageData)
                    };
                });

                // calculate info used in prod cell
                var teamProdData = {
                        averageDays: '--',
                        totalCommits: 0
                    },
                    commitTimeToProd = _(team.stages)
                    // limit to prod
                        .filter(function (val, key) {
                            return key == 'Prod'
                        })
                        // make all commits a single array
                        .reduce(function (num, commits) {
                            return num + commits;
                        })
                        // they should, but make sure the commits have a prod timestamp
                        .filter(function (commit) {
                            return commit.processedTimestamps && commit.processedTimestamps['Prod'];
                        })
                        // calculate their time to prod
                        .map(function (commit) {
                            return {
                                duration: commit.processedTimestamps['Prod'] - commit.scmCommitTimestamp,
                                commitTimestamp: commit.scmCommitTimestamp
                            };
                        });

                teamProdData.totalCommits = commitTimeToProd.length;

                if (commitTimeToProd.length > 1) {
                    var averageDuration = _(commitTimeToProd).pluck('duration').reduce(function (a, b) {
                            return a + b;
                        }) / commitTimeToProd.length;

                    teamProdData.averageDays = Math.floor(moment.duration(averageDuration).asDays());

                    var plotData = _(commitTimeToProd).map(function (ttp) {
                        var daysAgo = -1 * moment.duration(moment().diff(ttp.commitTimestamp)).asDays();
                        return [daysAgo, ttp.duration];
                    }).value();

                    var averageToProdResult = regression('linear', plotData);
                    teamProdData.trendUp = averageToProdResult.equation[0] > 0;
                }

                // handle the api telling us which stages need configuration
                if (team.unmappedStages) {
                    for (var stageName in teamStageData) {
                        teamStageData[stageName].needsConfiguration = team.unmappedStages.indexOf(stageName) != -1;
                    }
                }

                dependencies.setTeamData(team.collectorItemId, {
                    stages: teamStageData,
                    prod: teamProdData
                });
            });
        }

        function getStageDurationStats(a) {
            var r = {mean: 0, variance: 0, deviation: 0}, t = a.length;
            for (var m, s = 0, l = t; l--; s += a[l]);
            for (m = r.mean = s / t, l = t, s = 0; l--; s += Math.pow(a[l] - m, 2));
            return r.deviation = Math.sqrt(r.variance = s / t), r;
        }
    }
})();


text:
#ifndef __RGB_LCD_H__
#define __RGB_LCD_H__

#include <inttypes.h>
#include "Print.h"

// Device I2C Arress
#define LCD_ADDRESS     (0x7c>>1)
#define RGB_ADDRESS     (0xc4>>1)

// color define
#define WHITE           0
#define RED             1
#define GREEN           2
#define BLUE            3

#define REG_RED         0x04        // pwm2
#define REG_GREEN       0x03        // pwm1
#define REG_BLUE        0x02        // pwm0

#define REG_MODE1       0x00
#define REG_MODE2       0x01
#define REG_OUTPUT      0x08

// commands
#define LCD_CLEARDISPLAY 0x01
#define LCD_RETURNHOME 0x02
#define LCD_ENTRYMODESET 0x04
#define LCD_DISPLAYCONTROL 0x08
#define LCD_CURSORSHIFT 0x10
#define LCD_FUNCTIONSET 0x20
#define LCD_SETCGRAMADDR 0x40
#define LCD_SETDDRAMADDR 0x80

// flags for display entry mode
#define LCD_ENTRYRIGHT 0x00
#define LCD_ENTRYLEFT 0x02
#define LCD_ENTRYSHIFTINCREMENT 0x01
#define LCD_ENTRYSHIFTDECREMENT 0x00

// flags for display on/off control
#define LCD_DISPLAYON 0x04
#define LCD_DISPLAYOFF 0x00
#define LCD_CURSORON 0x02
#define LCD_CURSOROFF 0x00
#define LCD_BLINKON 0x01
#define LCD_BLINKOFF 0x00

// flags for display/cursor shift
#define LCD_DISPLAYMOVE 0x08
#define LCD_CURSORMOVE 0x00
#define LCD_MOVERIGHT 0x04
#define LCD_MOVELEFT 0x00

// flags for function set
#define LCD_8BITMODE 0x10
#define LCD_4BITMODE 0x00
#define LCD_2LINE 0x08
#define LCD_1LINE 0x00
#define LCD_5x10DOTS 0x04
#define LCD_5x8DOTS 0x00

class rgb_lcd : public Print
{

public:
  rgb_lcd();

  void begin(uint8_t cols, uint8_t rows, uint8_t charsize = LCD_5x8DOTS);

  void clear();
  void home();

  void noDisplay();
  void display();
  void noBlink();
  void blink();
  void noCursor();
  void cursor();
  void scrollDisplayLeft();
  void scrollDisplayRight();
  void leftToRight();
  void rightToLeft();
  void autoscroll();
  void noAutoscroll();

  void createChar(uint8_t, uint8_t[]);
  void setCursor(uint8_t, uint8_t);

  virtual size_t write(uint8_t);
  void command(uint8_t);

  // color control
  void setRGB(unsigned char r, unsigned char g, unsigned char b);               // set rgb
  void setPWM(unsigned char color, unsigned char pwm){setReg(color, pwm);}      // set pwm

  void setColor(unsigned char color);
  void setColorAll(){setRGB(0, 0, 0);}
  void setColorWhite(){setRGB(255, 255, 255);}

  // blink the LED backlight
  void blinkLED(void);
  void noBlinkLED(void);

  using Print::write;

private:
  void send(uint8_t, uint8_t);
  void setReg(unsigned char addr, unsigned char dta);

  uint8_t _displayfunction;
  uint8_t _displaycontrol;
  uint8_t _displaymode;

  uint8_t _initialized;

  uint8_t _numlines,_currline;
};

#endif


text:
using System.Linq;

namespace NominateAndVote.DataModel.Common
{
    public class PocoWithIdStore<TId, TPoco> : PocoStore<TPoco>
        where TId : struct
        where TPoco : BasePocoWithId<TId, TPoco>, new()
    {
        public bool Contains(TId id)
        {
            return Contains(new TPoco { Id = id });
        }

        public TPoco Get(TId id)
        {
            return this.SingleOrDefault(p => p.IdEquals(id));
        }

        public bool Remove(TId id)
        {
            return Remove(new TPoco { Id = id });
        }
    }
}


text:
local ffi = require "ffi"
local pkt = require "packet"

require "utils"
require "headers"

local ntoh, hton = ntoh, hton
local ntoh16, hton16 = ntoh16, hton16
local bor, band, bnot, rshift, lshift= bit.bor, bit.band, bit.bnot, bit.rshift, bit.lshift
local istype = ffi.istype
local format = string.format

-- FIXME
-- ICMPv6 and ICMPv4 use different values for the same types/codes which causes some complications when handling this with only one header:
-- - getString() does not work for ICMPv6 correctly without some ugly workarounds (basically adding 'ipv4' flags to getString()'s of type/code and header)
-- 	 currently getString() simply does not recognise ICMPv6
-- - Furthermore, packetDump would need a change to pass this flag when calling getString()
-- TODO
-- remove messageBody, instead use new packetCreate with additional header { "ip4", "messageBody" } or similar

---------------------------------------------------------------------------
---- ICMPv4 constants
---------------------------------------------------------------------------

--- Icmp4 protocol constants
local icmp = {}

--- Icmp4 type-code pair: echo reply
icmp.ECHO_REPLY					= { type = 0, code = 0 }
--- Icmp4 type-code pair: echo request
icmp.ECHO_REQUEST 				= { type = 8, code = 0 }

--- Icmp4 type-code pair: destination unreachable - port unreachable
icmp.DST_UNR_PORT_UNR		 	= { type = 3, code = 3 }

--- Icmp4 type-code pair: time exceeded - TTL exceeded
icmp.TIME_EXCEEDED_TTL_EXPIRED	= { type = 11, code = 0 }

--------------------------------------------------------------------------
---- ICMPv6 constants
---------------------------------------------------------------------------

--- Icmp6 protocol constants
local icmp6 = {}

--- Icmp6 type-code pair: echo request
icmp6.ECHO_REQUEST				= { type = 128, code = 0 }
--- Icmp6 type-code pair: echo reply
icmp6.ECHO_REPLY				= { type = 129, code = 0 }

---------------------------------------------------------------------------
---- ICMP header
---------------------------------------------------------------------------

--- Module for icmp_header struct (see \ref headers.lua).
local icmpHeader = {}
icmpHeader.__index = icmpHeader

--- Set the type.
--- @param int Type of the icmp header as 8 bit integer.
function icmpHeader:setType(int)
	int = int or icmp.ECHO_REQUEST.type
	self.type = int
end

--- Retrieve the type.
--- @return Type as 8 bit integer.
function icmpHeader:getType()
	return self.type
end

--- Retrieve the type.
--- does not work for ICMPv6 (ICMPv6 uses different values)
--- @return Type as string.
function icmpHeader:getTypeString()
	local type = self:getType()
	local cleartext = "unknown"

	if type == icmp.ECHO_REPLY.type then
		cleartext = "echo reply"
	elseif type == icmp.ECHO_REQUEST.type then
		cleartext = "echo request"
	elseif type == icmp.DST_UNR_PORT_UNR.type then
		cleartext = "dst. unr."
	elseif type == icmp.TIME_EXCEEDED_TTL_EXPIRED.type then
		cleartext = "time exceeded"
	end

	return format("%s (%s)", type, cleartext)
end

--- Set the code.
--- @param int Code of the icmp header as 8 bit integer.
function icmpHeader:setCode(int)
	int = int or icmp.ECHO_REQUEST.code
	self.code = int
end

--- Retrieve the code.
--- @return Code as 8 bit integer.
function icmpHeader:getCode()
	return self.code
end

--- Retrieve the code.
--- does not work for ICMPv6
--- @return Code as string.
function icmpHeader:getCodeString()
	local type = self:getType()
	local code = self:getCode()
	local cleartext = "unknown"

	if type == icmp.ECHO_REPLY.type then
		cleartext = code == icmp.ECHO_REPLY.code and "correct" or "wrong"

	elseif type == icmp.ECHO_REQUEST.type then
		cleartext = code == icmp.ECHO_REQUEST.code and "correct" or "wrong"

	elseif type == icmp.DST_UNR_PORT_UNR.type then
		if code == icmp.DST_UNR_PORT_UNR.code then
			cleartext = "port unr."
		end

	elseif type == icmp.TIME_EXCEEDED_TTL_EXPIRED.type then
		if code == icmp.TIME_EXCEEDED_TTL_EXPIRED.code then
			cleartext = "ttl expired"
		end
	end

	return format("%s (%s)", code, cleartext)
end

--- Set the checksum.
--- @param int Checksum of the icmp header as 16 bit integer.
function icmpHeader:setChecksum(int)
	int = int or 0
	self.cs = hton16(int)
end

--- Calculate the checksum
--- @param len Number of bytes that the checksum will be computed over
function icmpHeader:calculateChecksum(len)
	len = len or sizeof(self)
	self:setChecksum(0)
	self:setChecksum(hton16(checksum(self, len)))
end

--- Retrieve the checksum.
--- @return Checksum as 16 bit integer.
function icmpHeader:getChecksum()
	return hton16(self.cs)
end

--- Retrieve the checksum.
--- @return Checksum as string.
function icmpHeader:getChecksumString()
	return format("0x%04x", self:getChecksum())
end

--- Set the message body.
--- @param int Message body of the icmp header as TODO.
function icmpHeader:setMessageBody(body)
	body = body or 0
	--self.body.uint8_t = body
end

--- Retrieve the message body.
--- @return Message body as TODO.
function icmpHeader:getMessageBody()
	return self.body
end

--- Retrieve the message body.
--- @return Message body as string TODO.
function icmpHeader:getMessageBodyString()
	return "<some data>"
end

--- Set all members of the icmp header.
--- Per default, all members are set to default values specified in the respective set function.
--- Optional named arguments can be used to set a member to a user-provided value.
--- @param args Table of named arguments. Available arguments: Type, Code, Checksum, MessageBody
--- @param pre prefix for namedArgs. Default 'icmp'.
--- @code
--- fill() --- only default values
--- fill{ icmpCode=3 } --- all members are set to default values with the exception of icmpCode
--- @endcode
function icmpHeader:fill(args, pre)
	args = args or {}
	pre = pre or "icmp"

	self:setType(args[pre .. "Type"])
	self:setCode(args[pre .. "Code"])
	self:setChecksum(args[pre .. "Checksum"])
	self:setMessageBody(args[pre .. "MessageBody"])
end

--- Retrieve the values of all members.
--- @param pre prefix for namedArgs. Default 'icmp'.
--- @return Table of named arguments. For a list of arguments see "See also".
--- @see icmpHeader:fill
function icmpHeader:get(pre)
	pre = pre or "icmp"

	local args = {}
	args[pre .. "Type"] = self:getType()
	args[pre .. "Code"] = self:getCode()
	args[pre .. "Checksum"] = self:getChecksum()
	args[pre .. "MessageBody"] = self:getMessageBody()

	return args
end

--- Retrieve the values of all members.
--- Does not work correctly for ICMPv6 packets
--- @return Values in string format.
function icmpHeader:getString()
	return "ICMP type "			.. self:getTypeString()
			.. " code "		.. self:getCodeString()
			.. " cksum "	.. self:getChecksumString()
			.. " body "		.. self:getMessageBodyString() .. " "
end

--- Resolve which header comes after this one (in a packet).
--- For instance: in tcp/udp based on the ports.
--- This function must exist and is only used when get/dump is executed on
--- an unknown (mbuf not yet casted to e.g. tcpv6 packet) packet (mbuf)
--- @return String next header (e.g. 'udp', 'icmp', nil)
function icmpHeader:resolveNextHeader()
	return nil
end

--- Change the default values for namedArguments (for fill/get).
--- This can be used to for instance calculate a length value based on the total packet length.
--- See proto/ip4.setDefaultNamedArgs as an example.
--- This function must exist and is only used by packet.fill.
--- @param pre The prefix used for the namedArgs, e.g. 'icmp'
--- @param namedArgs Table of named arguments (see See Also)
--- @param nextHeader The header following after this header in a packet
--- @param accumulatedLength The so far accumulated length for previous headers in a packet
--- @see icmpHeader:fill
function icmpHeader:setDefaultNamedArgs(pre, namedArgs, nextHeader, accumulatedLength)
	return namedArgs
end

------------------------------------------------------------------------
---- Packets
------------------------------------------------------------------------

--- Cast the packet to an Icmp4 packet
pkt.getIcmp4Packet = packetCreate("eth", "ip4", "icmp")
--- Cast the packet to an Icmp6 packet
pkt.getIcmp6Packet = packetCreate("eth", "ip6", "icmp")
--- Cast the packet to either an Icmp4 (nil/true) or Icmp6 (false) packet, depending on the passed boolean.
pkt.getIcmpPacket = function(self, ip4) ip4 = ip4 == nil or ip4 if ip4 then return pkt.getIcmp4Packet(self) else return pkt.getIcmp6Packet(self) end end

------------------------------------------------------------------------
---- Metatypes
------------------------------------------------------------------------

ffi.metatype("struct icmp_header", icmpHeader)

return icmp, icmp6


text:
package annis.sqlgen.model;

import annis.model.QueryNode;
import annis.model.DataObject;

@SuppressWarnings("serial")
public abstract class Join extends DataObject {

	protected QueryNode target;

	public Join(QueryNode target) {
		this.target = target;
	}

	public QueryNode getTarget() {
		return target;
	}

	public void setTarget(QueryNode target) {
		this.target = target;
	}

}


text:
class ScmChangelogEntry < Versioneye::Model

  include Mongoid::Document
  include Mongoid::Timestamps

  field :language   , type: String
  field :prod_key   , type: String
  field :version    , type: String

  field :change_date  , type: DateTime, :default => DateTime.now
  field :author       , type: String
  field :action       , type: String
  field :file         , type: String
  field :revision     , type: String
  field :revision_base, type: String
  field :message      , type: String
  field :message_md   , type: Boolean, :default => false

end