text:
Linq4JS.Helper.NonEnumerable("Count", function <T>(this: T[], filter?: ((item: T) => boolean) | string): number {
    if (filter != null) {
        return this.Where(filter).length;
    } else {
        return this.length;
    }
});


text:
set -e
set -x

#/app/scripts/wait-for-it.sh -t 0 cassandra-node1:9041 -- echo "CASSANDRA Node1 started"
#/app/scripts/wait-for-it.sh -t 0 cassandra-node2:9041 -- echo "CASSANDRA Node2 started"
#/app/scripts/wait-for-it.sh -t 0 cassandra-node3:9041 -- echo "CASSANDRA Node3 started"

# DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
dir="$(dirname ${BASH_SOURCE[0]} )"
echo "DIR=$dir"

# Usage info
show_help() {
cat << EOF
Usage: ${0##*/} [-r ROLE] [-h IP_ADDRESS] [-p PORT] [-b BIND_IP_ADDRESS] [-d BIND_PORT] [-l LEVEL] [-m MAIN_FQCN] [-c CONFIG_RESOURCE] [-x JVM_MAX_MEMORY] [PATH]...
Analyzes data files at PATH for anomalies

-?                    Display this help and exit

[-r ROLE]             Role node plays in spotlight cluster:
  all: used for single-node use where the node handles all responsibilities
  seed: one of required seed nodes who manage cluster membership
  analysis: algorithm worker processing
  intake: integration point with time series data supplier and executes the spotlight execution stream

[-h IP_ADDRESS]       The hostname or ip clients should connect to. InetAddress.getLocalHost.getHostAddress is used if empty

[-p PORT]             Listening remote port for this node in the processing cluster.
  There must be at least one seed at 2551 or 2552; otherwise can be 0 which is the default

[-H BIND_IP_ADDRESS]  Use this setting to bind a network interface to a different hostname or ip than remoting protocol expects messages
 at. Use "0.0.0.0" to bind to all interfaces. akka.remote.netty.tcp.hostname if empty

[-P BIND_PORT]        Use this setting to bind a network interface to a different port than remoting protocol expects messages at. This may be used when running akka nodes in a separated networks (under NATs or docker containers). Use 0 if you want a random available port. Examples:

 akka.remote.netty.tcp.port = 2552
 akka.remote.netty.tcp.bind-port = 2553
Network interface will be bound to the 2553 port, but remoting protocol will expect messages sent to port 2552.

 akka.remote.netty.tcp.port = 0
 akka.remote.netty.tcp.bind-port = 0
Network interface will be bound to a random port, and remoting protocol will expect messages sent to the bound port.

 akka.remote.netty.tcp.port = 2552
 akka.remote.netty.tcp.bind-port = 0
Network interface will be bound to a random port, but remoting protocol will expect messages sent to port 2552.

 akka.remote.netty.tcp.port = 0
 akka.remote.netty.tcp.bind-port = 2553
Network interface will be bound to the 2553 port, and remoting protocol will expect messages sent to the bound port.

 akka.remote.netty.tcp.port = 2552
 akka.remote.netty.tcp.bind-port = ""
Network interface will be bound to the 2552 port, and remoting protocol will expect messages sent to the bound port.

akka.remote.netty.tcp.port if empty

[-l LEVEL]            SLF4J log level WARN is default: OFF|ALL|TRACE\DEBUG\INFO\WARN\ERROR\FATAL

[-m MAIN_FQCN]        Fully qualified Java classname for the executable main class. spotlight.app.FileBatchExample is default

[-c CONFIG_RESOURCE]  Configuration resource file. application.conf is default

[ -L ]                Force node to execute locally in conjunction with -r all.
[-n JVM_MIN_MEMORY]   Minimum memory allocation for JVM. 1g is default
[-x JVM_MAX_MEMORY]   Maximum memory allocation for JVM. 2g is default
EOF
}

role=${ROLE:-all}
external_hostname=${EXTERNAL_HOSTNAME}
requested_external_port=${REQUESTED_EXTERNAL_PORT}
bind_hostname=${BIND_HOSTNAME}
bind_port=${BIND_PORT}
slf4j_level=${SLF4J_LEVEL:-WARN}
main_class=${MAIN_CLASS:-spotlight.app.FileBatchExample}
jvm_min_memory=${JVM_MIN_MEMORY:-1g}
jvm_max_memory=${JVM_MAX_MEMORY:-2g}
config_resource=${CONFIG_RESOURCE:-application.conf}
force_local=${FORCE_LOCAL:-false}

while getopts :?Lr:h:p:H:P:l:m:c:n:x: opt
do
  case "$opt" in
    r)
      echo "using $OPTARG for role" >&2
      role="$OPTARG"
      ;;
    h)
      echo "using $OPTARG for external_hostname" >&2
      external_hostname="$OPTARG"
      ;;
    p)
      echo "using $OPTARG for requested_external_port" >&2
      requested_external_port="$OPTARG"
      ;;
    H)
      echo "using $OPTARG for bind_hostname" >&2
      bind_hostname="$OPTARG"
      ;;
    P)
      echo "using $OPTARG for bind_port" >&2
      bind_port="$OPTARG"
      ;;
    l)
      echo "using $OPTARG for slf4j_log" >&2
      slf4j_level="$OPTARG"
      ;;
    m)
      echo "using $OPTARG for main_class" >&2
      main_class="$OPTARG"
      ;;
    c)
      echo "using $OPTARG for config_resource" >&2
      config_resource="$OPTARG"
      ;;
    n)
      echo "using $OPTARG for jvm_min_memory" >&2
      jvm_min_memory="$OPTARG"
      ;;
    x)
      echo "using $OPTARG for jvm_max_memory" >&2
      jvm_max_memory="$OPTARG"
      ;;
    L)
      echo "setting true for force_local" >&2
      force_local=true
      ;;
    ?)
      show_help
      exit 0
      ;;
  esac
done
echo "OPTIND: $OPTIND"
echo ${#@}
shift $(($OPTIND - 1))

default_batch_target="$dir/../data"
batch_target=${1-${default_batch_target}}
shift

i=0
args=()

args[i]="--role ${role}"
((++i))

if [ ! "$external_hostname" = "" ]
then
  args[i]="--host \"${external_hostname}\""
  ((++i))
fi

if [ ! "$requested_external_port" = "" ]
then
  args[i]="--port ${requested_external_port}"
  ((++i))
fi

if [ ! "$bind_hostname" = "" ]
then
  args[i]="--bind-hostname \"${bind_hostname}\""
  ((++i))
fi

if [ ! "$bind_port" = "" ]
then
  args[i]="--bind-port ${bind_port}"
  ((++i))
fi

if [ "$force_local" = true ]
then
  args[i]="--force-local"
  ((++i))
fi

echo "running ${main_class} with environment variables:"
echo "  role: ${role}"
echo "  external hostname: ${external_hostname:-<nil>}"
echo "  requested external port: ${requested_external_port:-<nil>}"
echo "  bind hostname: ${bind_hostname:-<nil>}"
echo "  bind port: ${bind_port:-<nil>}"
echo "  batch target: ${batch_target:-<nil>}"
echo "  slf4j log level: ${slf4j_level:-WARN}"
echo "  config resource: ${config_resource}"
echo "  force local: ${force_local}"
echo "  env arguments: ${args[@]}"
echo "  remaining arguments: $@"
echo

echo "  java.library.path=$dir/../../infr/native"
java_agent="$dir/../../infr/coreos/aspectjweaver-1.8.10.jar"
echo "  java_agent=${java_agent}"
echo

cpath="$dir/../target/scala-2.12/*"
echo "classpath=$cpath"
echo

echo "java -classpath ${cpath} -Dconfig.resource=${config_resource} -Djava.library.path=${dir}/../../infr/native -DSLF4J_LEVEL=${slf4j_level:-WARN} -javaagent:${java_agent} -XX:MaxMetaspaceSize=512m -Xms${jvm_min_memory:-1g} -Xmx${jvm_max_memory:-2g} -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -Xloggc:gc_g1_4g_5_5000_1000_60.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps ${main_class:-spotlight.app.FileBatchExample} ${args[@]} ${batch_target} $@"
echo

java -classpath "${cpath}" \
  -Dconfig.resource="${config_resource}" \
  -Djava.library.path="${dir}/../../infr/native" \
  -DSLF4J_LEVEL="${slf4j_level:-WARN}" \
  -javaagent:"${java_agent}" \
  -XX:MaxMetaspaceSize=512m \
  -Xms${jvm_min_memory:-1g} \
  -Xmx${jvm_max_memory:-2g} \
  -XX:+UseG1GC \
  -XX:MaxGCPauseMillis=100 \
  -Xloggc:gc_g1_4g_5_5000_1000_60.log \
  -XX:+PrintGCDetails \
  -XX:+PrintGCDateStamps \
  -XX:+PrintGCTimeStamps \
  ${main_class:-spotlight.app.FileBatchExample} ${args[@]} "${batch_target}" "$@"

redpajama_set_name: RedPajamaGithub


text:
package cs6375.github.io;

import java.lang.Math;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class ID3DecisionTree extends DecisionTree {

    public ID3DecisionTree(TrainingDataSet trainingDataSet) {
        // Generate tree and store the root.
        DecisionTreeNode root = new ID3DecisionTreeNode(trainingDataSet);

        // Put all node into list for random access.
        super.generate(root);
    }

    /**
     * Prune the decision tree based on specific pruning factor.
     *
     * @param factor Pruning factor.
     */
    @Override
    public void prune(double factor, DataSet validation) {
        final int num = (int) Math.floor(this.getSize() * factor);

        double oriRate = this.test(validation);

        double rate;
        for (int count = 0; count < num; count++) {

            double maxIncrease = 0;
            DecisionTreeNode prunedNode = null;

            for (DecisionTreeNode node : this.nodes) {
                if (node.isPruned())
                    continue;
                node.setPruned();
                rate = this.test(validation);
                if (rate - oriRate <= maxIncrease) {
                    node.resetPruned();
                } else {
                    maxIncrease = rate - oriRate;
                    prunedNode = node;
                    node.resetPruned();
                }
            }

            if (prunedNode == null) {
                break;
            }
            prunedNode.setPruned();
            oriRate += maxIncrease;
        }

        // After pruning is complete, regenerate list storing the nodes.
        super.generate(this.nodes.get(0));
    }
}


text:
package org.vertexium.accumulo.util;

import org.apache.accumulo.core.data.Range;
import org.apache.hadoop.io.Text;

public class RangeUtils {
    public static Range createRangeFromString(String key) {
        return new Range(new Text(key));
    }
}


text:
"use strict";

var jsDAV_Collection = require("./../DAV/collection");
var jsDAV_iExtendedCollection = require("./../DAV/interfaces/iExtendedCollection");
var jsDAVACL_iAcl = require("./../DAVACL/interfaces/iAcl")
var jsCardDAV_AddressBook = require("./addressBook");

var Exc = require("./../shared/exceptions");
var Util = require("./../shared/util");

/**
 * UserAddressBooks class
 *
 * The UserAddressBooks collection contains a list of addressbooks associated with a user
 */
var jsCardDAV_UserAddressBooks = module.exports = jsDAV_Collection.extend(jsDAV_iExtendedCollection, jsDAVACL_iAcl, {
    /**
     * Principal uri
     *
     * @var array
     */
    principalUri: null,

    /**
     * carddavBackend
     *
     * @var jsCardDAV_iBackend
     */
    carddavBackend: null,

    /**
     * Constructor
     *
     * @param Backend\BackendInterface carddavBackend
     * @param {String} principalUri
     */
    initialize: function(carddavBackend, principalUri) {
        this.carddavBackend = carddavBackend;
        this.principalUri = principalUri;
    },

    /**
     * Returns the name of this object
     *
     * @return string
     */
    getName: function() {
        return Util.splitPath(this.principalUri)[1];
    },

    /**
     * Updates the name of this object
     *
     * @param {String} name
     * @return void
     */
    setName: function(name, callback) {
        callback(new Exc.MethodNotAllowed());
    },

    /**
     * Deletes this object
     *
     * @return void
     */
    delete: function(callback) {
        callback(new Exc.MethodNotAllowed());
    },

    /**
     * Returns the last modification date
     *
     * @return int
     */
    getLastModified: function(callback) {
        callback(null, null);
    },

    /**
     * Creates a new file under this object.
     *
     * This is currently not allowed
     *
     * @param {String} filename
     * @param resource data
     * @return void
     */
    createFile: function(filename, data, enc, callback) {
        callback(new Exc.MethodNotAllowed("Creating new files in this collection is not supported"));
    },

    /**
     * Creates a new directory under this object.
     *
     * This is currently not allowed.
     *
     * @param {String} filename
     * @return void
     */
    createDirectory: function(filename, callback) {
        callback(new Exc.MethodNotAllowed("Creating new collections in this collection is not supported"));
    },

    /**
     * Returns a single calendar, by name
     *
     * @param {String} name
     * @todo needs optimizing
     * @return jsCardDAV_AddressBook
     */
    getChild: function(name, callback) {
        this.getChildren(function(err, children) {
            if (err)
                return callback(err);

            for (var i = 0, l = children.length; i < l; ++i) {
                if (children[i].getName() == name)
                    return callback(null, children[i]);
            }
            callback(new Exc.NotFound("Addressbook with name '" + name + "' could not be found"));
        });
    },

    /**
     * Returns a list of addressbooks
     *
     * @return array
     */
    getChildren: function(callback) {
        var self = this;
        this.carddavBackend.getAddressBooksForUser(this.principalUri, function(err, addressbooks) {
            if (err)
                return callback(err);

            var objs = addressbooks.map(function(addressbook) {
                return jsCardDAV_AddressBook.new(self.carddavBackend, addressbook);
            });
            callback(null, objs);
        });
    },

    /**
     * Creates a new addressbook
     *
     * @param {String} name
     * @param {Array} resourceType
     * @param {Array} properties
     * @return void
     */
    createExtendedCollection: function(name, resourceType, properties, callback) {
        if (resourceType.indexOf("{" + require("./plugin").NS_CARDDAV + "}addressbook") === -1 || resourceType.length !== 2)
            return callback(Exc.InvalidResourceType("Unknown resourceType for this collection"));

        this.carddavBackend.createAddressBook(this.principalUri, name, properties, callback);
    },

    /**
     * Returns the owner principal
     *
     * This must be a url to a principal, or null if there's no owner
     *
     * @return string|null
     */
    getOwner: function() {
        return this.principalUri;
    },

    /**
     * Returns a group principal
     *
     * This must be a url to a principal, or null if there's no owner
     *
     * @return string|null
     */
    getGroup: function() {
        return null;
    },

    /**
     * Returns a list of ACE's for this node.
     *
     * Each ACE has the following properties:
     *   * 'privilege', a string such as {DAV:}read or {DAV:}write. These are
     *     currently the only supported privileges
     *   * 'principal', a url to the principal who owns the node
     *   * 'protected' (optional), indicating that this ACE is not allowed to
     *      be updated.
     *
     * @return array
     */
    getACL: function() {
        return [
            {
                privilege: "{DAV:}read",
                principal: this.principalUri,
                "protected" : true
            },
            {
                privilege: "{DAV:}write",
                principal: this.principalUri,
                "protected": true
            }
        ];
    },

    /**
     * Updates the ACL
     *
     * This method will receive a list of new ACE's.
     *
     * @param {Array} acl
     * @return void
     */
    setACL: function(acl, callback) {
        callback(new Exc.MethodNotAllowed("Changing ACL is not yet supported"));
    },

    /**
     * Returns the list of supported privileges for this node.
     *
     * The returned data structure is a list of nested privileges.
     * See Sabre\DAVACL\Plugin::getDefaultSupportedPrivilegeSet for a simple
     * standard structure.
     *
     * If null is returned from this method, the default privilege set is used,
     * which is fine for most common usecases.
     *
     * @return array|null
     */
    getSupportedPrivilegeSet: function() {
        return null;
    }
});


text:
<Alloy>
	<Window>
	<View class="container">
		<Label id="header">Login to Corndog Tour.</Label>
		<TextField id="username"  width="250" hintText="Username" ></TextField>
		<TextField id="password"  width="250" hintText="Password" passwordMask="true" ></TextField>
		<Button id="loginButton" onClick="login">Login</Button>
	</View>
	</Window>
</Alloy>


text:
// Universal Module Definition (UMD) for compatibility with modular script loaders
(function (factory) {

    'use strict';

    // Asynchronous Module Definition (AMD) to register plugin as an anonymous module
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    }

    // Default way to register plugin with an existing, global jQuery object
    else {
        /*
            Factory's arguments are the dependencies which are required by the plugin.
            You should add these here to trigger an error if they are missing
         */
        factory(jQuery);
    }

// The actual plugin with its dependencies
}(function ($) {

    'use strict';

    // --- Plugin scope (shared between all plugin instances) ---

    /*
        Define the plugin's name here!
        The name is used to find elements via data-attribute selector which are using this plugin (e.g. data-foobar="")
        It MUST be unique in your jQuery-Scope!
    */
    /**
     * The plugin name and data-attribute name/selector
     * WARNING: THIS WILL OVERWRITE NATIVE AND PREVIOUSLY REGISTERED JQUERY FUNCTIONS - CHOOSE WITH CARE!
     * @type {!string}
     */
    var PLUGIN_NAME = 'foobar';

    /*
        Define the plugin defaults here!
        I like to make everything configurable.
        Also i like this kind of naming to make the usage very clear:
        - selectElement: '.mySelector' (pass a selector or an element/jQuery)
        - tplElement: '<div>__text__</div>' (pass a string or an element/jQuery)
        - classLoading: 'loading' (when you are changing classes somewhere)
        - callbackFinished: $.noop (allow to configure a callback somewhere)
    */
    /**
     * The plugin defaults
     * @type {!Object}
     */
    var defOpts = {
        propertyName: 'value'
    };

    /*
        Store often used elements because of performance
     */
    /**
     * @type {!jQuery}
     */
    var $doc = $(document);

    /**
     * Saves the current value of an element's attribute (e.g. style or class)
     * If attribute is not present FALSE will be saved
     *
     * @param {jQuery} $el
     * @param {string} attr
     */
    function saveAttrOnce($el, attr) {
        if ($el.data('_' + attr) === undefined) {
            var val = $el.attr(attr);
            $el.data('_' + attr, val !== undefined ? val : false);
        }
    }

    /**
     * Restores the latest saved attribute value of an element (e.g. style or class)
     * If attribute was not present it will be removed
     *
     * @param {jQuery} $el
     * @param {string} attr
     */
    function restoreAttr($el, attr) {
        var val = $el.data('_' + attr);
        if (val !== undefined) {
            if (val === false) {
                $el.removeAttr(attr);
            } else {
                $el.attr(attr, val);
            }
        }
    }

    /**
     * Returns a HTML escaped string
     *
     * @param {string} text
     * @returns {string}
     */
    function htmlEncode(text) {
        return document.createElement('div').appendChild(document.createTextNode(text)).parentNode.innerHTML;
    }

    /**
     * Returns a HTML string
     * @param {string} str - encoded HTML
     * @returns {string}
     */
    function htmlDecode(str) {
        var el = document.createElement('div');
        el.innerHTML = str;
        return el.childNodes.length === 0 ? '' : el.childNodes[0].nodeValue;
    }

    /**
     * Returns the given string where all placeholders have been replaced with the given data
     *
     * @param {string} html
     * @param {Object} data
     * @param {Boolean} [escape=true]
     * @returns {string}
     */
    function replacePlaceholders(html, data, escape) {
        var placeholder;
        var replacement;
        escape = escape !== false;
        for (placeholder in data) {
            if (data.hasOwnProperty(placeholder)) {
                placeholder = placeholder.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g, "\\$1"); // escape regex special characters
                replacement = escape ? htmlEncode(data[placeholder]) : data[placeholder];
                html = html.replace(new RegExp('__' + placeholder + '__', 'g'), replacement);
            }
        }
        return html;
    }

    /**
     * Returns a template's HTML as string.
     * Templates can be specified by jQuery-Selector.
     * HTML-Strings will passed through, script templates will be unwrapped and HTML decoded if necessary, normal elements will be converted to string.
     *
     * @param {(string|HTMLElement)} tpl
     * @returns {(string|null)}
     */
    function getTemplate(tpl) {
        tpl = $(tpl)[0];
        if (tpl) {
            switch (tpl.tagName) {
                case 'TEMPLATE':
                    return tpl.innerHTML;
                case 'SCRIPT':
                    switch (tpl.getAttribute('type')) {
                        case 'text/template.html-encoded':
                            return htmlDecode(tpl.innerHTML);
                        case 'text/template':
                            return tpl.innerHTML;
                    }
                    break;
                default:
                    return tpl.outerHTML;
            }
        }
        return null;
    }

    /**
     * Example: A static-like function without access to the instance scope.
     */
    function staticFunction() {
        // Do something here!
    }

    /**
     * Plugin constructor
     * @param {HTMLElement} el
     * @param {Object} args
     * @constructor
     */
    function Plugin(el, args) {

        // --- Instance scope (shared between all plugin functions on the given element) ---

        /**
         * The element which was passed to the plugin
         * @type {?jQuery}
         */
        var $el = $(el);

        /**
         * The plugin settings for this instance
         * @type {!Object}
         */
        var opts = {};

        /**
         * Self-reference
         * @type {!Plugin}
         */
        var self = this;

        /**
         * Init function for setting up this instance
         * The settings are cascaded in the following order:
         *  - the plugin defaults
         *  - the given options via jQuery-call
         *  - the element options via attribute
         *  (latest takes precedence)
         *
         * @param {Object} initOpts
         */
        function init(initOpts) {
            var attrOptStr = $el.attr('data-' + PLUGIN_NAME);
            var attrOpts = attrOptStr ? $.parseJSON(attrOptStr) : {};
            opts = $.extend(opts, defOpts, initOpts, attrOpts);

            // Example: Use a private function
            privateFunction();

            // Example: Bind events
            $el.on('click.' + PLUGIN_NAME, function () {
                // Example: Use static function
                staticFunction();
                // Example: Use public function
                self.publicFunction();
            });
        }

        /**
         * Example: A private function
         */
        function privateFunction() {
            // Do something here!
        }

        /**
         * Example: A public function which can be called from outside:
         * - $('.mySelector').foobar('publicFunction')
         * - $('.mySelector').foobar('publicFunction', {optional: 'additionalParameter'})
         *
         * @param {Object} [args]
         */
        this.publicFunction = function (args) {
            // Do something here

            // If you return something, a plugin call to this function will not be chainable by jQuery
        };

        /**
         * Remove this plugin off the element
         * This function should revert all changes which have been made by this plugin
         */
        this.destroy = function () {
            $el.find('*').addBack().off('.' + PLUGIN_NAME);
            $el.removeData(PLUGIN_NAME);
            $el = null;
        };

        init(args);
    }

    // Register plugin on jQuery
    $.fn[PLUGIN_NAME] = function () {
        var args = arguments || [];
        var val;

        this.each(function () {

            // Prevent multiple instances for same element
            var instance = $.data(this, PLUGIN_NAME);
            if (!instance) {
                instance = new Plugin(this, typeof args[0] === 'object' ? args[0] : {});
                $.data(this, PLUGIN_NAME, instance);
            }

            // Call public function
            // If it returns something, break the loop and return the value
            if (typeof args[0] === 'string') {
                if (typeof instance[args[0]] === 'function') {
                    val = instance[args[0]](args[1]);
                } else {
                    $.error('Method "' + args[0] + '" does not exist for ' + PLUGIN_NAME + ' plugin');
                }
            }

            return val === undefined;
        });

        return val === undefined ? this : val;
    };

    /*
        The setup function will allow you to setup the plugin's defaults without any code changes on the plugin itself.
        This will make it easier to update the plugin. Mostly you will be fine with replacing this file.
        You can call the setup function inline or within another JavaScript using a config object:
            $.<PLUGIN_NAME>(<CONFIG_OBJECT>)
            e.g.:
                $.foobar({ propertyName: 'value' });
     */
    // Register directly to jQuery to give the possibility of overwriting the default options
    $[PLUGIN_NAME] = function (opts) {
        if (typeof opts === 'object') {
            $.extend(defOpts, opts);
        } else {
            $.error('Expected configuration object');
        }
    };

    /*
        Another way to "remotely" configure this plugin will be using a global config object.
        Ensure the global object is present when this plugin is loaded.
     */
    // Try using a global config object
    try {
        $.extend(defOpts, window.config[PLUGIN_NAME]);
    } catch (e) {
    }

    /*
         The plugin will bind itself to all elements which contain the plugin data-attribute (e.g. "data-foobar").
         This happens automatically when document is "ready" and every time when nodes get attached to the DOM.
     */
    // Auto pilot
    new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            for (var i = 0; i < mutation.addedNodes.length; i++) {
                $(mutation.addedNodes[i]).find('[data-' + PLUGIN_NAME + ']').addBack('[data-' + PLUGIN_NAME + ']')[PLUGIN_NAME]();
            }
        });
    }).observe(document.querySelector('body'), {
        childList: true,
        subtree: true
    });
    $('ready', function () {
        $doc.find('[data-' + PLUGIN_NAME + ']')[PLUGIN_NAME]();
    });

}));


text:
import * as React           from "react";
import * as ReactDOM        from "react-dom";
import {CabeiriApp}         from "../../cabeiri.app";
import {VProject}           from "../../components/vproject"
import {VGraph}             from "./vgraph"
import {VRootGraphList}     from "../../components/graph/vrootgraph.list"
import {CID, CabeiriLang}   from "cabeiri-lang"

export class RootGraphesState
{
    public selectedRootGraph : CID = CID.CID_NONE;
}

export class VRootGraphes extends React.Component<{}, RootGraphesState>
{
    constructor(props : {})
    {
        super(props);
        this.state = new RootGraphesState();
    }

    onRootGraphSelected = (selectedRootGraph : CID) =>
    {
        var graphState : RootGraphesState = new RootGraphesState();
        graphState.selectedRootGraph = selectedRootGraph;
        this.setState(graphState);
    }

    componentDidMount ()
    {
    }

    render ()
    {
        return

                            <VRootGraphList onItemSelected={this.onRootGraphSelected} searchLabel="Graphes"/>

                            <VGraph rootGraphCID={this.state.selectedRootGraph}/>

;
    };
};

React.createFactory(VRootGraphes);


text:
#ifndef Local_h
#define Local_h

#include "Handle.h"
#include "JSGlobalData.h"

/*
    A strongly referenced handle whose lifetime is temporary, limited to a given
    LocalScope. Use Locals for local values on the stack. It is an error to
    create a Local outside of any LocalScope.
*/

namespace JSC {

template <typename T> class Local : public Handle<T> {
    friend class LocalScope;
    using Handle<T>::slot;

public:
    typedef typename Handle<T>::ExternalType ExternalType;

    Local(JSGlobalData&, ExternalType = ExternalType());
    Local(JSGlobalData&, Handle<T>);
    Local(const Local<T>&); // Adopting constructor. Used to return a Local to a calling function.

    Local& operator=(ExternalType);
    Local& operator=(Handle<T>);

private:
    Local(HandleSlot, ExternalType); // Used by LocalScope::release() to move a Local to a containing scope.
    void set(ExternalType);
};

template <typename T> inline Local<T>::Local(JSGlobalData& globalData, ExternalType value)
    : Handle<T>(globalData.allocateLocalHandle())
{
    set(value);
}

template <typename T> inline Local<T>::Local(JSGlobalData& globalData, Handle<T> other)
    : Handle<T>(globalData.allocateLocalHandle())
{
    set(other.get());
}

template <typename T> inline Local<T>::Local(const Local<T>& other)
    : Handle<T>(other.slot())
{
    const_cast<Local<T>&>(other).setSlot(0); // Prevent accidental sharing.
}

template <typename T> inline Local<T>::Local(HandleSlot slot, ExternalType value)
    : Handle<T>(slot, value)
{
}

template <typename T> inline Local<T>& Local<T>::operator=(ExternalType value)
{
    set(value);
    return *this;
}

template <typename T> inline Local<T>& Local<T>::operator=(Handle<T> other)
{
    set(other.get());
    return *this;
}

template <typename T> inline void Local<T>::set(ExternalType externalType)
{
    ASSERT(slot());
    ASSERT(!HandleTypes<T>::toJSValue(externalType) || !HandleTypes<T>::toJSValue(externalType).isCell() || Heap::isMarked(HandleTypes<T>::toJSValue(externalType).asCell()));
    *slot() = externalType;
}

template <typename T, unsigned inlineCapacity = 0> class LocalStack {
    typedef typename Handle<T>::ExternalType ExternalType;
public:
    LocalStack(JSGlobalData& globalData)
        : m_globalData(&globalData)
        , m_count(0)
    {
    }

    ExternalType peek() const
    {
        ASSERT(m_count > 0);
        return m_stack[m_count - 1].get();
    }

    ExternalType pop()
    {
        ASSERT(m_count > 0);
        return m_stack[--m_count].get();
    }

    void push(ExternalType value)
    {
        if (m_count == m_stack.size())
            m_stack.append(Local<T>(*m_globalData, value));
        else
            m_stack[m_count] = value;
        m_count++;
    }

    bool isEmpty() const { return !m_count; }
    unsigned size() const { return m_count; }

private:
    RefPtr<JSGlobalData> m_globalData;
    Vector<Local<T>, inlineCapacity> m_stack;
    unsigned m_count;
};

}

namespace WTF {

template<typename T> struct VectorTraits<JSC::Local<T> > : SimpleClassVectorTraits {
    static const bool needsDestruction = false;
    static const bool canInitializeWithMemset = false;
    static const bool canCompareWithMemcmp = false;
};

}

#endif


text:
package com.redhat.ceylon.compiler.java.language;

public interface GetterBoolean {
    boolean get_();
}


text:
targets		 := pep.umd.js
bin        := $(shell npm bin)
browserify := $(bin)/browserify pep.js

# -- Building --
dist/${targets}: dist
	$(browserify) --standalone pep > $@

dist:
	mkdir dist

bundle: dist/pep.umd.js

clean: dist
	rm -rf dist

# -- Other tasks --
test:
	node ./test/tap.js

.PHONY: test


text:
.. _filesys:

*************************
File and Directory Access
*************************

The modules described in this chapter deal with disk files and directories.  For
example, there are modules for reading the properties of files, manipulating
paths in a portable way, and creating temporary files.  The full list of modules
in this chapter is:

.. toctree::

   os.path.rst
   fileinput.rst
   stat.rst
   statvfs.rst
   filecmp.rst
   tempfile.rst
   glob.rst
   fnmatch.rst
   linecache.rst
   shutil.rst
   dircache.rst
   macpath.rst

.. seealso::

   Section :ref:`bltin-file-objects`
      A description of Python's built-in file objects.

   Module :mod:`os`
      Operating system interfaces, including functions to work with files at a lower
      level than the built-in file object.


text:
<?php
namespace Application\Todo;

/**
 * Kontrak untuk todo item.
 *
 * @author zakyalvan
 */
abstract class AbstractTodoItem {
	/**
	 * Context dari todo item.
	 *
	 * @var string
	 */
	protected $context;

	/**
	 * Data untuk todo item
	 *
	 * @var array
	 */
	protected $datas = array();

	/**
	 * Url untuk mengeksekusi todo item.
	 *
	 * @var string
	 */
	protected $actionUrl;

	/**
	 * Kapan todo item ini dibuat/mulai aktif.
	 *
	 * @var unknown
	 */
	protected $createdDate;

	public function __construct($context, $actionUrl, $createdDate) {
		$this->setContext($context);
		$this->setActionUrl($actionUrl);
		$this->setCreatedDate($createdDate);
	}

	public function getContext() {
		return $this->context;
	}
	protected function setContext($context) {
		$this->context = $context;
	}

	public function getActionUrl() {
		return $this->formatActionUrl();
	}
	protected function setActionUrl($actionUrl) {
		$this->actionUrl = $actionUrl;
	}

	public function getCreatedDate() {
		return $this->createdDate;
	}
	protected function setCreatedDate($createdDate) {
		$this->createdDate = $createdDate;
	}

	public function getData($name) {
		if(isset($this->datas[$name])) {
			return $this->datas[$name];
		}
		return null;
	}
	public function hasData($name) {
		return isset($this->datas[$name]);
	}
	public function setData($name, $value) {
		$this->datas[$name] = $value;
	}

	public function __get($name) {
		return $this->getData($name);
	}
	public function __set($name, $value) {
		$this->setData($name, $value);
	}
	public function __isset($name) {
		return $this->hasData($name);
	}

	/**
	 * @return url string
	 */
	abstract protected function formatActionUrl();
}


text:
require 'rubygems'
require 'mechanize'
require 'nokogiri'

#Change these
stops = {
  "home"   => [ ["PRG", "1333"],  ["UCB", "1323"], ["TC",  "1313"] ],
  "campus" => [ ["TC",  "1100"],  ["UCB", "1101"], ["PRG", "1101"] ]
}
location = ARGV[0] || ((%x[sudo iwlist scan 2>&1].match(/(VT_WLAN|VT-Wireless)/)) ? "campus" : "home")

def startMatch(input, list)
  list.each do |item|
    if item.match(/^#{input}/) then
      return item
    end
  end
end

#Get next stop time for given route and stop
def getNextTime(route, stop)
  agent = Mechanize.new
  agent.redirect_ok = false

  begin
    #Send Route
    page = agent.get("http://www.bt4u.org/Mobile.aspx")

    routeName = startMatch(
      route,
      page.forms.first.field_with(:id => "routeListBox").options.map { |o| o.value }
    )
    page.forms.first.set_fields({ "routeListBox" => routeName })
    page = page.forms.first.submit(page.forms.first.buttons[0])

    #Send Stop Id
    stopName = startMatch(
      stop,
      page.forms.first.field_with(:id => "stopListBox").options.map { |o| o.value }
    )
    page.forms.first.set_fields({ "stopListBox" => stopName})
    page = page.forms.first.submit(page.forms.first.buttons[0])

    #Parse and Return Next Bus
    return Nokogiri::HTML(page.body).css('#repeaterItems_DepartureTime_0').text().split(': ').last

  rescue Exception => e
    return false
  end
end

#Run get next time until we find a stop
yourStop = "N/A", stopTime = "N/A"
catch :busStopFound do

  stops[location].each do |stop|
    yourStop = stop
    stopTime = getNextTime(stop[0], stop[1]) || "N/A"
    throw :busStopFound unless stopTime == "N/A"
  end

end

puts "#{yourStop.join} at #{stopTime}"


text:
namespace Castle.Facilities.AspectSharp.Tests.Components
{
	using System;
	using System.Text;

	/// <summary>
	/// Summary description for MemoryLogger.
	/// </summary>
	public class MemoryLogger : ILogger
	{
		private StringBuilder _messages = new StringBuilder();

		public MemoryLogger()
		{
		}

		#region ILogger Members

		public void Trace(String content)
		{
		}

		public void Enter(String name)
		{
			_messages.Append("Entering " + name + " ");
		}

		public void Leave(String name)
		{
			_messages.Append("Leaving " + name + " ");
		}

		public String Contents
		{
			get { return _messages.ToString(); }
		}

		#endregion
	}
}


text:
package net.festivoice;

import java.lang.*;
import java.net.*;
import java.util.concurrent.*;
import org.xiph.speex.SpeexEncoder;
import javax.sound.sampled.*;

public class StreamSender extends Thread
{

	private ThreadedPacketSender.SessionInfo sessionInfo;

	private TargetDataLine targetDataLine;

	private ThreadedPacketSender[] packetSender;
	private BlockingQueue<byte[]> blockingQueue;

	private int baseByteArraySize;
	private CodecInfo codecInfo;

	private boolean isListenOnly = false;

	private boolean endFlag = false;

	public static class CodecInfo
	{
		public AudioFormat format;
		public int mode;
		public int quality;
		public boolean vbr;
		public int countFrames;

		public CodecInfo(AudioFormat format, int mode, int quality, boolean vbr, int countFrames)
		{
			this.format = format;
			this.mode = mode;
			this.quality = quality;
			this.vbr = vbr;
			this.countFrames = countFrames;
		}
	}

	public StreamSender(ThreadedPacketSender.SessionInfo sessionInfo, TargetDataLine targetDataLine, CodecInfo codecInfo) throws LineUnavailableException
	{
		this.blockingQueue = new LinkedBlockingQueue<byte[]>(16);

		packetSender = new ThreadedPacketSender[1];
		for(int i=0; i < packetSender.length; ++i) {
			packetSender[i] = new ThreadedPacketSender(sessionInfo, codecInfo, blockingQueue);
		}
		this.codecInfo = codecInfo;

		// DataLine
		this.targetDataLine = targetDataLine;

		// Sound buffer
		baseByteArraySize = packetSender[0].getBaseArraySize();
	}

	public int getDecodeBufferSize()
	{
		return baseByteArraySize * codecInfo.countFrames;
	}

	public void setListenOnly(boolean flag)
	{
		if(flag != isListenOnly && targetDataLine != null) {
			if(flag) {
				targetDataLine.stop();
			} else {
				targetDataLine.flush();
				targetDataLine.start();
			}
		}
		isListenOnly = flag;
	}

	public void end()
	{
		endFlag = true;
	}

	public void run()
	{
		for(ThreadedPacketSender s : packetSender) {
			s.start();
		}
		try {
			while (!endFlag) {

				if(isListenOnly) {
					Thread.sleep(500);
					byte[] zero = new byte[0];
					blockingQueue.put(zero);

				} else {
					// Input voice data
					byte[] soundBuffer = new byte[baseByteArraySize * codecInfo.countFrames];
					targetDataLine.read(soundBuffer, 0, baseByteArraySize);
					for (int i = 1; i < codecInfo.countFrames; i++) {
						targetDataLine.read(soundBuffer, baseByteArraySize * i, baseByteArraySize);
					}

					// put
					blockingQueue.put(soundBuffer);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


text:
package com.bernard.beaconportal.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

public class Monday extends Fragment {

	private String BBand, CBand, FBand, DBand, EBand, HBand, ABand;

	private EditText editBBand;
	private EditText editCBand;
	private EditText editFBand;
	private EditText editEBand;
	private EditText editDBand;
	private EditText editHBand;
	private EditText editABand;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		setHasOptionsMenu(true);

		SharedPreferences sharedpref = getActivity().getSharedPreferences(
				"monday", Context.MODE_PRIVATE);
		ABand = sharedpref.getString("a_Band", null);
		BBand = sharedpref.getString("b_Band", null);
		CBand = sharedpref.getString("c_Band", null);
		DBand = sharedpref.getString("d_Band", null);
		EBand = sharedpref.getString("e_Band", null);
		FBand = sharedpref.getString("f_Band", null);
		HBand = sharedpref.getString("h_Band", null);

		View view = inflater.inflate(R.layout.monday, container, false);

		TextView AValue = (TextView) view.findViewById(R.id.bandText11);
		AValue.setText("A Band");

		editABand = ((EditText) view.findViewById(R.id.editText11));
		editABand.setText(ABand, TextView.BufferType.EDITABLE);

		TextView BValue = (TextView) view.findViewById(R.id.bandText22);
		BValue.setText("B Band");

		editBBand = ((EditText) view.findViewById(R.id.editText22));
		editBBand.setText(BBand, TextView.BufferType.EDITABLE);

		TextView CValue = (TextView) view.findViewById(R.id.bandText33);
		CValue.setText("C Band");

		editCBand = ((EditText) view.findViewById(R.id.editText33));
		editCBand.setText(CBand, TextView.BufferType.EDITABLE);

		TextView DValue = (TextView) view.findViewById(R.id.bandText44);
		DValue.setText("D Band");

		editDBand = ((EditText) view.findViewById(R.id.editText44));
		editDBand.setText(DBand, TextView.BufferType.EDITABLE);

		TextView EValue = (TextView) view.findViewById(R.id.bandText55);
		EValue.setText("E Band");

		editEBand = ((EditText) view.findViewById(R.id.editText55));
		editEBand.setText(EBand, TextView.BufferType.EDITABLE);

		TextView FValue = (TextView) view.findViewById(R.id.bandText66);
		FValue.setText("F Band");

		editFBand = ((EditText) view.findViewById(R.id.editText66));
		editFBand.setText(FBand, TextView.BufferType.EDITABLE);

		TextView HValue = (TextView) view.findViewById(R.id.bandText77);
		HValue.setText("H Band");

		editHBand = ((EditText) view.findViewById(R.id.editText77));
		editHBand.setText(HBand, TextView.BufferType.EDITABLE);

		LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
				this.mClickedReceiver, new IntentFilter("clicked!"));

		return view;

	}

	private BroadcastReceiver mClickedReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context paramAnonymousContext,
				Intent paramAnonymousIntent) {

			SharedPreferences.Editor localEditor = getActivity()
					.getSharedPreferences("monday", Context.MODE_PRIVATE)
					.edit();

			localEditor.putString("a_Band", editABand.getText().toString());
			localEditor.putString("b_Band", editBBand.getText().toString());
			localEditor.putString("c_Band", editCBand.getText().toString());
			localEditor.putString("d_Band", editDBand.getText().toString());
			localEditor.putString("e_Band", editEBand.getText().toString());
			localEditor.putString("f_Band", editFBand.getText().toString());
			localEditor.putString("h_Band", editHBand.getText().toString());

			localEditor.apply();

		}
	};

	@Override
	public void onDestroy()

	{

		LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(
				this.mClickedReceiver);

		super.onDestroy();

	}

}


text:
import React from 'react';
import { connect } from 'react-redux';

import { load as loadResults } from './Actions';
import SOQuestionsList from '../SOQuestionsList/SOQuestionsList';

class SOHot extends React.Component {
  static propTypes = {
    questions: React.PropTypes.array.isRequired,
    dispatch: React.PropTypes.func.isRequired,
    loaded: React.PropTypes.bool.isRequired
  };

  componentWillMount() {
    const { loaded, dispatch } = this.props;
    if (!loaded) {
      dispatch(loadResults());
    }
  }

  render() {
    const { questions } = this.props;
    return (

Hot on StackOverflow

        <SOQuestionsList questions={questions} highlightable uniquePrefix="sohot_" />

    );
  }
}

const mapStateToProps = (state) => (
  {
    questions: state.sohot.data.results,
    loaded: state.sohot.loaded
  }
);

export default connect(mapStateToProps)(SOHot);


text:
#include "config.h"
#include "core/dom/NodeRareData.h"

#include "core/dom/WebCoreMemoryInstrumentation.h"
#include "wtf/MemoryInstrumentationHashMap.h"

namespace WebCore {

struct SameSizeAsNodeRareData {
    unsigned m_bitfields : 20;
    void* m_pointer[3];
};

COMPILE_ASSERT(sizeof(NodeRareData) == sizeof(SameSizeAsNodeRareData), NodeRareDataShouldStaySmall);

void NodeListsNodeData::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
    info.addMember(m_childNodeList, "childNodeList");
    info.addMember(m_atomicNameCaches, "atomicNameCaches");
    info.addMember(m_nameCaches, "nameCaches");
    info.addMember(m_tagNodeListCacheNS, "tagNodeListCacheNS");
}

void NodeRareData::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
    info.addMember(m_nodeLists, "nodeLists");
    info.addMember(m_mutationObserverData, "mutationObserverData");
}

} // namespace WebCore


text:
<?php

$prevFolder = "../";
include_once("../_setup.php");

// Start Page

$consoleObj = new ConsoleOption($mysqli);

$cID = $consoleObj->findConsoleIDByName("Plugin Manager");
$consoleObj->select($cID);
$consoleInfo = $consoleObj->get_info_filtered();

$member = new Member($mysqli);
$member->select($_SESSION['btUsername']);

$pluginObj = new btPlugin($mysqli);

// Check Login
$LOGIN_FAIL = true;
if($member->authorizeLogin($_SESSION['btPassword']) && $member->hasAccess($consoleObj) && isset($_GET['plugin'])) {

	$pluginInstaller = new PluginInstaller($mysqli);

	require(BASE_DIRECTORY."plugins/".$_GET['plugin']."/install_setup.php");

	$pluginInstaller->uninstall();

	if(!$pluginInstaller->isInstalled()) {
		$member->logAction("Uninstalled ".$pluginInstaller->pluginName." Plugin.");
	}

}

?>


text:
require 'spec_helper'

describe Authentication do
  let(:options) { { access_key_id: '44CF9590006BF252F707', access_key_secret: 'OtxrzxIsfpFjA7SwPzILwy8Bw21TLhquhboDYROV' }}
  let(:request) { Net::HTTP::Put.new('/oss-example/nelson') }

  context Authentication::Signature do
    it 'should be a string' do
      expect(Authentication::Signature.new(request, {}, options)).to be_a_kind_of String
    end
  end

  context Authentication::Header do
    before do
      request['Content-Type'] = 'text/html'
      request['Content-Md5'] = 'ODBGOERFMDMzQTczRUY3NUE3NzA5QzdFNUYzMDQxNEM='
      request['Date'] = 'Thu, 17 Nov 2005 18:49:58 GMT'
      request['X-OSS-Meta-Author'] = 'foo@bar.com'
      request['X-OSS-Magic'] = 'abracadabra'
      options.merge!(bucket: 'oss-example', object: 'nelson')
    end
    it 'should be a string' do
      expect(Authentication::Header.new(request, {}, options)).to be_a_kind_of String
    end

    it 'should have valid value' do
      auth = "OSS #{options[:access_key_id]}:26NBxoKdsyly4EDv6inkoDft/yA="
      expect(Authentication::Header.new(request, {}, options)).to eq auth
    end
  end

  context Authentication::URL do
    let(:request) { Net::HTTP::Get.new('/oss-example/oss-api.pdf') }
    let(:expires) { 1141889120 }
    it 'should be a string' do
      expect(Authentication::URL.new(request, {}, options.merge(expires: expires))).to be_a_kind_of String
    end

    it 'should have valid value' do
      # TODO 文档里写的跟Python 跑出来的不一样
      auth = "?OSSAccessKeyId=44CF9590006BF252F707&Expires=1141889120&Signature=EwaNTn1erJGkimiJ9WmXgwnANLc%3D"
      # expect(Authentication::URL.new(request, {}, options.merge(expires: expires))).to eq auth
    end
  end
end


text:
Algorithms
==========

This repository contains a list of well known algorithms implementations


text:
#ifndef DBCOMMON_SRC_DBCOMMON_COMMON_VECTOR_DECIMAL_VECTOR_H_
#define DBCOMMON_SRC_DBCOMMON_COMMON_VECTOR_DECIMAL_VECTOR_H_

#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "dbcommon/common/vector.h"
#include "dbcommon/type/decimal.h"

namespace dbcommon {

class DecimalVector : public Vector {
 public:
  explicit DecimalVector(bool ownData)
      : Vector(ownData),
        auxiliaryValues(ownData),
        scaleValues(ownData),
        rawValues(true),
        lengths(true),
        valPtrs(true) {
    if (ownData) {
      values.reserve(sizeof(uint64_t) * DEFAULT_NUMBER_TUPLES_PER_BATCH);
      auxiliaryValues.reserve(sizeof(int64_t) *
                              DEFAULT_NUMBER_TUPLES_PER_BATCH);
      scaleValues.reserve(sizeof(int64_t) * DEFAULT_NUMBER_TUPLES_PER_BATCH);
    }
    setTypeKind(DECIMALNEWID);
  }

  ~DecimalVector() override {}

  uint64_t getNumOfRowsPlain() const override {
    return values.size() / sizeof(uint64_t);
  }

  dbcommon::ByteBuffer *getAuxiliaryValueBuffer() override {
    return &auxiliaryValues;
  }

  dbcommon::ByteBuffer *getScaleValueBuffer() override { return &scaleValues; }

  const char *getAuxiliaryValue() const override {
    return auxiliaryValues.data();
  }

  const char *getScaleValue() const override { return scaleValues.data(); }

  void setValue(const char *value, uint64_t size) override {
    assert(!getOwnData() && value != nullptr && size >= 0);
    values.setData(value, size);
  }

  void setAuxiliaryValue(const char *value, uint64_t size) override {
    assert(!getOwnData() && value != nullptr && size >= 0);
    auxiliaryValues.setData(value, size);
  }

  void setScaleValue(const char *value, uint64_t size) override {
    assert(!getOwnData() && value != nullptr && size >= 0);
    scaleValues.setData(value, size);
  }

  bool checkZeroValue() const override;

  const char *read(uint64_t index, uint64_t *len, bool *null) const override;

  std::string readPlain(uint64_t index, bool *null) const override;

  void readPlainScalar(uint64_t index, Scalar *scalar) const override;

  void append(const std::string &strValue, bool null) override;

  void append(const char *v, uint64_t valueLen, bool null) override;

  void append(const Datum &datum, bool null) override;

  void append(const Scalar *scalar) override;

  void append(Vector *src, uint64_t index) override;

  void append(Vector *vect) override;

  void append(Vector *vect, SelectList *sel) override;

  void materialize() override;

  void reset(bool resetBelongingTupleBatch = false) override {
    Vector::reset(resetBelongingTupleBatch);
    values.resize(0);
    auxiliaryValues.resize(0);
    scaleValues.resize(0);
    rawValues.resize(0);
    lengths.resize(0);
    valPtrs.resize(0);
  }

  std::unique_ptr<Vector> cloneSelected(const SelectList *sel) const override;

  std::unique_ptr<Vector> extract(const SelectList *sel, uint64_t start,
                                  uint64_t end) const override;

  std::unique_ptr<Vector> replicateItemToVec(uint64_t index,
                                             int replicateNum) const override;

  void merge(size_t plainSize, const std::vector<Datum> &data,
             const std::vector<SelectList *> &sels) override;

  bool isValid() const override {
    Vector::isValid();

    if (hasNulls) {
      assert(nulls.size() == values.size() / sizeof(uint64_t));
      assert(nulls.size() == auxiliaryValues.size() / sizeof(int64_t));
      assert(nulls.size() == scaleValues.size() / sizeof(int64_t));
    }
    return true;
  }

  void hash(std::vector<uint64_t> &retval) const override;

  void cdbHash(std::vector<uint64_t> &retval) const override;

  void swap(Vector &vect) override;

  dbcommon::ByteBuffer *getValueBuffer() override { return &values; }

  const char **getValPtrs() const override {
    return reinterpret_cast<const char **>(valPtrs.data());
  }

  const uint64_t *getLengths() const override {
    return reinterpret_cast<const uint64_t *>(lengths.data());
  }

  void checkGroupByKeys(std::vector<const void *> &dataPtrSrc) const override;

  uint64_t checkGroupByKey(uint64_t index, const char *dataPtr) const override;

  uint64_t getSerializeSizeInternal() const override;

  void serializeInternal(NodeSerializer *serializer) override;

  void deserializeInternal(NodeDeserializer *deserializer) override;

  void selectDistinct(SelectList *selected, Scalar *scalar) override;

  void selectDistinct(SelectList *selected, Vector *vect) override;

  const char *readRawValue(uint64_t index, uint64_t *len, bool *null) const;

  void computeRawValueAndValPtrs();

 protected:
  void resizeInternal(size_t plainSize) override;

  static uint64_t computeValPtrs(const char *vals, const uint64_t *lens,
                                 const bool *nulls, uint64_t size,
                                 const char **valPtrs) {
    const char *ptr = vals;

    if (nulls) {
      for (uint64_t i = 0; i < size; i++) {
        valPtrs[i] = ptr;
        ptr += nulls[i] ? 0 : lens[i];
      }
    } else {
      for (uint64_t i = 0; i < size; i++) {
        valPtrs[i] = ptr;
        ptr += lens[i];
      }
    }

    return ptr - vals;
  }
  dbcommon::ByteBuffer auxiliaryValues;
  dbcommon::ByteBuffer scaleValues;
  dbcommon::ByteBuffer rawValues;
  dbcommon::ByteBuffer lengths;
  dbcommon::ByteBuffer valPtrs;
  mutable DecimalVar readBuffer[2];
  mutable uint8_t nextBuffer = 0;
  struct DecimalDataInfo {
    char isNull;
    char padding[sizeof(DecimalVar) - 1];
    int64_t highbitsData;
    uint64_t lowbitsData;
    int64_t scaleData;
  };
};

}  // namespace dbcommon

#endif  // DBCOMMON_SRC_DBCOMMON_COMMON_VECTOR_DECIMAL_VECTOR_H_


text:
FROM phusion/baseimage:0.9.15

CMD ["/sbin/my_init"]

RUN /etc/my_init.d/00_regen_ssh_host_keys.sh

RUN apt-get update
RUN apt-get -y upgrade

RUN apt-get install -y python-pip python-numpy python-scipy \
                       python-matplotlib python-beautifulsoup \
                       python-parse python-yaml rabbitmq-server

RUN pip install -U future cython
RUN pip install scikit-learn==0.16.1

# RUN apt-get install -y python3-dev python3-pip python3-numpy \
#                        python3-scipy python3-matplotlib
# RUN pip3 install psutil future cython parse scikit-learn beautifulsoup4 \
#                  flask requests

ENTRYPOINT ["/sbin/my_init", "--"]


text:
async function getHealth(req, h) {
    await req.db.raw('select 1+1 as result');
    return h.response({
        status: 'ok'
    });
}
getHealth.config = {
    auth: false,
    description: 'Get the status of the server'
};
module.exports.GET = getHealth;


text:
require 'helper'

class RubyNameTest < MiniTest::Unit::TestCase
  # ruby_name is a no-op when an empty string is provided.
  def test_ruby_name_with_empty_name
    assert_equal('', Heroics.ruby_name(''))
  end

  # ruby_name converts capitals in a name to lowercase.
  def test_ruby_name_with_capitals
    assert_equal('capitalizedname', Heroics.ruby_name('CapitalizedName'))
  end

  # ruby_name converts dashes in a name to underscores.
  def test_ruby_name_with_dashes
    assert_equal('dashed_name', Heroics.ruby_name('dashed-name'))
  end

  # ruby_name converts spaces in a name to underscores.
  def test_ruby_name_with_spaces
    assert_equal('spaced_name', Heroics.ruby_name('spaced name'))
  end
end

class PrettyNameTest < MiniTest::Unit::TestCase
  # pretty_name is a no-op when an empty string is provided.
  def test_pretty_name_with_empty_name
    assert_equal('', Heroics.pretty_name(''))
  end

  # pretty_name converts capitals in a name to lowercase.
  def test_pretty_name_with_capitals
    assert_equal('capitalizedname', Heroics.pretty_name('CapitalizedName'))
  end

  # pretty_name converts underscores in a name to dashes.
  def test_pretty_name_with_underscores
    assert_equal('dashed-name', Heroics.pretty_name('dashed_name'))
  end

  # pretty_name converts spaces in a name to underscores.
  def test_pretty_name_with_spaces
    assert_equal('spaced-name', Heroics.pretty_name('spaced name'))
  end
end


text:
using namespace ofp;

bool MultipartReply::validateInput(Validation *context) const {
  context->setLengthRemaining(replyBodySize());

  const UInt8 vers = version();

  switch (replyType()) {
    case OFPMP_DESC:
      return context->validate<MPDesc>(replyBody(), OFP_VERSION_1);
    case OFPMP_FLOW_DESC:
      return context->validateArrayVariableSize<MPFlowStatsReply>(
          replyBody(), OFP_VERSION_1);
    case OFPMP_AGGREGATE_STATS:
      if (vers >= OFP_VERSION_6) {
        return context->validate<MPAggregateStatsReplyV6>(replyBody(),
                                                          OFP_VERSION_6);
      }
      return context->validate<MPAggregateStatsReply>(replyBody(),
                                                      OFP_VERSION_1);
    case OFPMP_TABLE_STATS: {
      // We do NOT support OFPMP_TABLE_STATS for OF versions 1.1 and 1.2.
      if (vers == OFP_VERSION_2 || vers == OFP_VERSION_3) {
        context->multipartTypeIsNotSupportedForVersion();
        return false;
      }
      return context->validateArrayFixedSize<MPTableStats>(replyBody(),
                                                           OFP_VERSION_1);
    }
    case OFPMP_PORT_STATS:
      return context->validateArrayVariableSize<MPPortStats>(replyBody(),
                                                             OFP_VERSION_1);
    case OFPMP_QUEUE_STATS:
      return context->validateArrayFixedSize<MPQueueStats>(replyBody(),
                                                           OFP_VERSION_1);
    case OFPMP_GROUP_STATS:
      return context->validateArrayVariableSize<MPGroupStats>(replyBody(),
                                                              OFP_VERSION_2);
    case OFPMP_GROUP_DESC:
      return context->validateArrayVariableSize<MPGroupDesc>(replyBody(),
                                                             OFP_VERSION_2);
    case OFPMP_GROUP_FEATURES:
      return context->validate<MPGroupFeatures>(replyBody(), OFP_VERSION_3);
    case OFPMP_METER_STATS:
      return context->validateArrayVariableSize<MPMeterStats>(replyBody(),
                                                              OFP_VERSION_4);
    case OFPMP_METER_CONFIG:
      return context->validateArrayVariableSize<MPMeterConfig>(replyBody(),
                                                               OFP_VERSION_4);
    case OFPMP_METER_FEATURES:
      return context->validate<MPMeterFeatures>(replyBody(), OFP_VERSION_4);
    case OFPMP_TABLE_FEATURES:
      return context->validateArrayVariableSize<MPTableFeatures>(replyBody(),
                                                                 OFP_VERSION_4);
    case OFPMP_PORT_DESC:
      return context->validateArrayVariableSize<Port>(replyBody(),
                                                      OFP_VERSION_1);
    case OFPMP_TABLE_DESC:
      return context->validateArrayVariableSize<TableDesc>(replyBody(),
                                                           OFP_VERSION_5);
    case OFPMP_QUEUE_DESC:
      return context->validateArrayVariableSize<QueueDesc>(replyBody(),
                                                           OFP_VERSION_5);
    case OFPMP_FLOW_MONITOR:
      return context->validateArrayVariableSize<MPFlowMonitorReply>(
          replyBody(), OFP_VERSION_5);
    case OFPMP_EXPERIMENTER:
      return context->validate<MPExperimenter>(replyBody(), OFP_VERSION_1,
                                               false);
    case OFPMP_UNSUPPORTED:
      break;
  }

  context->multipartTypeIsNotSupported();

  return false;
}

UInt32 MultipartReplyBuilder::send(Writable *channel) {
  UInt8 version = channel->version();
  UInt32 xid = channel->nextXid();

  size_t msgLen = body_.size();
  if (version == OFP_VERSION_1) {
    msgLen += MultipartReply::UnpaddedSizeVersion1;
  } else {
    msgLen += sizeof(msg_);
  }

  msg_.header_.setVersion(version);
  msg_.header_.setXid(xid);
  msg_.header_.setLength(msgLen);

  if (version == OFP_VERSION_1) {
    msg_.header_.setRawType(deprecated::v1::OFPT_STATS_REPLY);
    channel->write(&msg_, MultipartReply::UnpaddedSizeVersion1);
  } else {
    msg_.header_.setType(OFPT_MULTIPART_REPLY);
    channel->write(&msg_, sizeof(msg_));
  }

  channel->write(body_.data(), body_.size());
  channel->flush();

  return xid;
}

void MultipartReplyBuilder::sendUsingReplyBody(MemoryChannel *channel,
                                               const void *data, size_t length,
                                               size_t offset) {
  // Break reply body into chunks on a clean boundary. Offset specifies where
  // the length is located.

  ByteRange body{data, length};

  while (body.size() > MAX_BODY_SIZE) {
    size_t chunkSize =
        detail::ProtocolRangeSplitOffset(MAX_BODY_SIZE, 0, body, offset);
    assert(chunkSize <= MAX_BODY_SIZE);
    assert(chunkSize <= body.size());
    assert(chunkSize > 0);

    setReplyFlags(OFPMPF_MORE);
    setReplyBody(body.data(), chunkSize);
    send(channel);

    // Keep sending messages with the same xid.
    channel->setNextXid(msg_.header_.xid());

    body = SafeByteRange(body.data(), body.size(), chunkSize);
  }

  setReplyFlags(OFPMPF_NONE);
  setReplyBody(body.data(), body.size());
}


text:
sillygame
=========

A sily little experiment in making a js game. Based on http://learnjs.io/blog/2013/11/16/simple-2d-game/


text:
package org.praisenter.ui.slide.animation;

import org.praisenter.data.slide.animation.AnimationOperation;
import org.praisenter.data.slide.animation.AnimationOrientation;

import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.util.Duration;

public final class SplitTransition extends CustomTransition {
	private final ObjectProperty<Duration> duration;
	private final ObjectProperty<AnimationOrientation> orientation;
	private final ObjectProperty<AnimationOperation> operation;
	private final ObjectProperty<Bounds> bounds;

	public SplitTransition() {
		this.duration = new SimpleObjectProperty<Duration>();
		this.orientation = new SimpleObjectProperty<AnimationOrientation>();
		this.operation = new SimpleObjectProperty<AnimationOperation>();
		this.bounds = new SimpleObjectProperty<Bounds>();

		this.duration.addListener((obs, ov, nv) -> {
			this.setCycleDuration(nv);
		});
	}

	@Override
	protected void interpolate(double frac) {
		Node node = this.node.get();
		if (node == null) return;

		AnimationOrientation orientation = this.orientation.get();
		if (orientation == null) return;

		AnimationOperation operation = this.operation.get();
		if (operation == null) return;

		Shape clip = null;
		switch(orientation) {
			case HORIZONTAL:
				switch(operation) {
					case COLLAPSE:
						clip = getHorizontalCollapse(frac);
						break;
					case EXPAND:
						clip = getHorizontalExpand(frac);
						break;
					default:
						break;
				}
				break;
			case VERTICAL:
				switch(operation) {
					case COLLAPSE:
						clip = getVerticalCollapse(frac);
						break;
					case EXPAND:
						clip = getVerticalExpand(frac);
						break;
					default:
						break;
				}
				break;
			default:
				break;
		}

		node.setClip(clip);
	}

	@Override
	public void stop() {
		super.stop();
		Node node = this.node.get();
		if (node == null) return;
		node.setClip(null);
	}

	private Shape getHorizontalCollapse(double frac) {
		Bounds bounds = this.bounds.get();
		double x = bounds.getMinX();
		double y = bounds.getMinY();
		double w = bounds.getWidth();
		double h = bounds.getHeight();

		double hh = h * 0.5;

		Rectangle all = new Rectangle(x, y, w, h);
		Rectangle cut = new Rectangle(x, y + hh * frac, w, h * (1.0 - frac));

		if (this.isInTransition()) {
			return Shape.subtract(all, cut);
		} else {
			return cut;
		}
	}

	private Shape getHorizontalExpand(double frac) {
		Bounds bounds = this.bounds.get();
		double x = bounds.getMinX();
		double y = bounds.getMinY();
		double w = bounds.getWidth();
		double h = bounds.getHeight();

		double hh = h * 0.5;

		Rectangle all = new Rectangle(x, y, w, h);
		Rectangle cut = new Rectangle(x, y + hh * (1.0 - frac), w, h * frac);

		if (this.isInTransition()) {
			return cut;
		} else {
			return Shape.subtract(all, cut);
		}
	}

	private Shape getVerticalCollapse(double frac) {
		Bounds bounds = this.bounds.get();
		double x = bounds.getMinX();
		double y = bounds.getMinY();
		double w = bounds.getWidth();
		double h = bounds.getHeight();

		double hw = w * 0.5;

		Rectangle all = new Rectangle(x, y, w, h);
		Rectangle cut = new Rectangle(x + hw * frac, y, w * (1.0 - frac), h);

		if (this.isInTransition()) {
			return Shape.subtract(all, cut);
		} else {
			return cut;
		}
	}

	private Shape getVerticalExpand(double frac) {
		Bounds bounds = this.bounds.get();
		double x = bounds.getMinX();
		double y = bounds.getMinY();
		double w = bounds.getWidth();
		double h = bounds.getHeight();

		double hw = w * 0.5;

		Rectangle all = new Rectangle(x, y, w, h);
		Rectangle cut = new Rectangle(x + hw * (1.0 - frac), y, w * frac, h);

		if (this.isInTransition()) {
			return cut;
		} else {
			return Shape.subtract(all, cut);
		}
	}

	public Duration getDuration() {
		return this.duration.get();
	}

	public void setDuration(Duration duration) {
		this.duration.set(duration);
	}

	public ObjectProperty<Duration> durationProperty() {
		return this.duration;
	}

	public AnimationOrientation getOrientation() {
		return this.orientation.get();
	}

	public void setOrientation(AnimationOrientation orientation) {
		this.orientation.set(orientation);
	}

	public ObjectProperty<AnimationOrientation> orientationProperty() {
		return this.orientation;
	}

	public AnimationOperation getOperation() {
		return this.operation.get();
	}

	public void setOperation(AnimationOperation operation) {
		this.operation.set(operation);
	}

	public ObjectProperty<AnimationOperation> operationProperty() {
		return this.operation;
	}

	public void setBounds(Bounds bounds) {
		this.bounds.set(bounds);
	}

	public Bounds getBounds() {
		return this.bounds.get();
	}

	public ObjectProperty<Bounds> boundsProperty() {
		return this.bounds;
	}
}


text:
require 'rubygems'
require 'ffi'

module Ropie
    extend FFI::Library
    ffi_lib './libopie.so'

    attach_function 'opieetob', [:pointer, :string], :int
    attach_function 'opiebtoe', [:string, :pointer], :string
end

ptr1 = FFI::MemoryPointer.new(:pointer, 1)
ptr2 = FFI::MemoryPointer.new(:pointer, 1)
Ropie.opieetob(ptr1, "NASH AIR GAWK LO FISK OBOE")
#puts ptr
puts Ropie.opiebtoe('134543596', ptr1)


text:
Ext.define('RedmineApp.view.RedmineStatusChart', {
    extend: 'Ext.chart.PolarChart',
    xtype: 'redmine-status-chart',
    requires: ['Ext.draw.Component',
        'Ext.chart.series.Pie',
        'Ext.chart.interactions.Rotate',
        'Ext.TitleBar',
        'Ext.chart.interactions.ItemHighlight',
        'Ext.chart.interactions.PanZoom',
        'Ext.chart.interactions.ItemInfo'],
    initialize: function() {
        this.callParent();
        this.createStore();
    },
    createStore: function() {
        var store = RedmineApp.app.getCurrentIssuesStore();
        var me = this;
        store.addListener('load', function(store, records, successful, operation, eOpts) {
            store.setGroupField('status_name');
            var groups = store.getGroups();
            Ext.define('IssueByStatus', {
                extend: 'Ext.data.Model',
                config: {
                    fields: [{
                            name: 'name',
                        }, {
                            name: 'total_statuses',
                            convert: function(value, record) {
                                return record.raw.children.length;
                            }
                        }]
                }
            });
            var groupStore = Ext.create('Ext.data.Store', {
                model: 'IssueByStatus',
                data: groups
            });
            me.bindStore(groupStore);
        });
    },
    config: {
        layout: 'fit',
        colors: ["green", "pink", "yellow", "#94ae0a", "#a61120", "#115fa6", "red", "blue", "orange", "#ffd13e", "#FF7518", "#FFDF00", "grey", "#ff8809"],
        style: {background: 'white'},
        interactions: ['rotate', 'itemhighlight', 'panzoom', 'iteminfo'],
        innerPadding: 45,
        axes: [
        ],
        series: [
            {
                type: 'pie',
                renderer: function(sprite, record, attr, index, store) {
                    return Ext.apply(attr, {
                        fill: ['blue', 'green', 'black', 'red', 'pink'][index % 5]
                    });
                },
                animate: true,
                xField: 'total_statuses',
                fill: true,
                label: {
                    field: 'name',
                    display: 'rotate',
                    contrast: true,
                    font: '18px "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif'
                },
                donut: 25,
                highlightCfg:
                        {
                            margin: 20
                        },
                style: {
                    stroke: 'black',
                    lineWidth: 2
                }
            }
        ]

    }
});


text:
using System.Collections.Generic;
using System.Runtime.Serialization;
using DvachBrowser3.Links;

namespace DvachBrowser3
{
    /// <summary>
    /// Хранилище любых данных.
    /// </summary>
    [DataContract(Namespace = CoreConstants.DvachBrowserNamespace)]
    [KnownType(typeof(BoardLinkBase))]
    [KnownType(typeof(BoardLinkBase[]))]
    [KnownType(typeof(string[]))]
    public sealed class CustomDictionaryData
    {
        /// <summary>
        /// Данные.
        /// </summary>
        [DataMember]
        public Dictionary<string, object> Data { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="Theme.DesignDemo" parent="Base.Theme.DesignDemo">
    </style>

    <style name="Base.Theme.DesignDemo" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">#2196F3</item>
        <item name="colorPrimaryDark">#1976D2</item>
        <item name="colorAccent">#536DFE</item>
        <item name="android:windowBackground">@color/window_background</item>
    </style>

    <style name="Widget.CardContent" parent="android:Widget">
        <item name="android:paddingLeft">16dp</item>
        <item name="android:paddingRight">16dp</item>
        <item name="android:paddingTop">24dp</item>
        <item name="android:paddingBottom">24dp</item>
        <item name="android:orientation">vertical</item>
    </style>

</resources>


text:
jscomponent
===========

Component system for JavaScript (ECMA 5)


text:
package parser_test

import (
	"github.com/projectcalico/libcalico-go/lib/selector/parser"

	"fmt"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"
)

var _ = DescribeTable("StringSet contains tests",
	func(input []string) {
		// Making a StringSet is destructive so start with a copy.
		var cpy []string
		if input != nil {
			cpy = make([]string, len(input))
			copy(cpy, input)
		}
		stringSet := parser.ConvertToStringSetInPlace(cpy)

		By("containing all the input values", func() {
			for _, s := range input {
				Expect(stringSet.Contains(s)).To(BeTrue(),
					fmt.Sprintf("input %v == %v didn't contain %v", input, stringSet, s))
			}
		})

		By("not containing unexpected values", func() {
			for _, s := range input {
				Expect(stringSet.Contains(s+"bogus")).To(BeFalse(),
					fmt.Sprintf("input %v == %v contained %vbogus", input, stringSet, s))
			}
		})

		By("Containing at most the number of input elements", func() {
			Expect(len(stringSet)).To(BeNumerically("<=", len(input)))
		})
	},
	Entry("nil", nil),
	Entry("Empty", []string{}),
	Entry("a", []string{"a"}),
	Entry("a, b", []string{"a", "b"}),
	Entry("a, b, c", []string{"a", "b", "c"}),
	Entry("a, b, c, d", []string{"a", "b", "c", "d"}),
	Entry("foo, bar, baz, baz", []string{"foo", "bar", "baz", "baz"}),
	Entry("foo, foo, baz, baz", []string{"foo", "foo", "baz", "baz"}),
)

var _ = DescribeTable("StringSet dedupe",
	func(input, expected []string) {
		// Making a StringSet is destructive so start with a copy.
		var cpy []string
		if input != nil {
			cpy = make([]string, len(input))
			copy(cpy, input)
		}
		stringSet := parser.ConvertToStringSetInPlace(cpy)
		Expect([]string(stringSet)).To(Equal(expected))
	},
	Entry("empty", []string{}, []string{}),
	Entry("without dupes", []string{"a", "b"}, []string{"a", "b"}),
	Entry("with dupes", []string{"b", "a", "b", "a"}, []string{"a", "b"}),
)


text:
//=================================================================================================

//=================================================================================================

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <cstdlib>
#include <iostream>
#include <blazetest/mathtest/hermitianmatrix/SubmatrixComplexTest.h>

namespace blazetest {

namespace mathtest {

namespace hermitianmatrix {

//=================================================================================================
//
//  CONSTRUCTORS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Constructor for the HermitianMatrix submatrix test.
//
// \exception std::runtime_error Operation error detected.
*/
SubmatrixComplexTest::SubmatrixComplexTest()
{
   testAssignment<DHT>();
   testAddAssign<DHT>();
   testSubAssign<DHT>();

   testAssignment<DOHT>();
   testAddAssign<DOHT>();
   testSubAssign<DOHT>();

   testAssignment<SHT>();
   testAddAssign<SHT>();
   testSubAssign<SHT>();

   testAssignment<SOHT>();
   testAddAssign<SOHT>();
   testSubAssign<SOHT>();
}
//*************************************************************************************************

} // namespace hermitianmatrix

} // namespace mathtest

} // namespace blazetest

//=================================================================================================
//
//  MAIN FUNCTION
//
//=================================================================================================

//*************************************************************************************************
int main()
{
   std::cout << "   Running HermitianMatrix submatrix complex test..." << std::endl;

   try
   {
      RUN_HERMITIANMATRIX_SUBMATRIXCOMPLEX_TEST;
   }
   catch( std::exception& ex ) {
      std::cerr << "\n\n ERROR DETECTED during HermitianMatrix submatrix complex test:\n"
                << ex.what() << "\n";
      return EXIT_FAILURE;
   }

   return EXIT_SUCCESS;
}
//*************************************************************************************************


text:
#ifndef HEADER_DVAVOPENHOMEORGPLAYLISTMANAGER1CPP
#define HEADER_DVAVOPENHOMEORGPLAYLISTMANAGER1CPP

#include <OpenHome/Types.h>
#include <OpenHome/Buffer.h>
#include <OpenHome/Net/Cpp/DvDevice.h>
#include <OpenHome/Net/Core/DvProvider.h>
#include <OpenHome/Net/Cpp/DvInvocation.h>

#include <string>

namespace OpenHome {
namespace Net {

class IDviInvocation;
class PropertyInt;
class PropertyUint;
class PropertyBool;
class PropertyString;
class PropertyBinary;

/**
 * Provider for the av.openhome.org:PlaylistManager:1 UPnP service
 * @ingroup Providers
 */
class DvProviderAvOpenhomeOrgPlaylistManager1Cpp : public DvProvider
{
public:
    virtual ~DvProviderAvOpenhomeOrgPlaylistManager1Cpp() {}
    /**
     * Set the value of the Metadata property
     *
     * Can only be called if EnablePropertyMetadata has previously been called.
     *
     * @return  true if the value has been updated; false if aValue was the same as the previous value
     */
    bool SetPropertyMetadata(const std::string& aValue);
    /**
     * Get a copy of the value of the Metadata property
     *
     * Can only be called if EnablePropertyMetadata has previously been called.
     */
    void GetPropertyMetadata(std::string& aValue);
    /**
     * Set the value of the ImagesXml property
     *
     * Can only be called if EnablePropertyImagesXml has previously been called.
     *
     * @return  true if the value has been updated; false if aValue was the same as the previous value
     */
    bool SetPropertyImagesXml(const std::string& aValue);
    /**
     * Get a copy of the value of the ImagesXml property
     *
     * Can only be called if EnablePropertyImagesXml has previously been called.
     */
    void GetPropertyImagesXml(std::string& aValue);
    /**
     * Set the value of the IdArray property
     *
     * Can only be called if EnablePropertyIdArray has previously been called.
     *
     * @return  true if the value has been updated; false if aValue was the same as the previous value
     */
    bool SetPropertyIdArray(const std::string& aValue);
    /**
     * Get a copy of the value of the IdArray property
     *
     * Can only be called if EnablePropertyIdArray has previously been called.
     */
    void GetPropertyIdArray(std::string& aValue);
    /**
     * Set the value of the TokenArray property
     *
     * Can only be called if EnablePropertyTokenArray has previously been called.
     *
     * @return  true if the value has been updated; false if aValue was the same as the previous value
     */
    bool SetPropertyTokenArray(const std::string& aValue);
    /**
     * Get a copy of the value of the TokenArray property
     *
     * Can only be called if EnablePropertyTokenArray has previously been called.
     */
    void GetPropertyTokenArray(std::string& aValue);
    /**
     * Set the value of the PlaylistsMax property
     *
     * Can only be called if EnablePropertyPlaylistsMax has previously been called.
     *
     * @return  true if the value has been updated; false if aValue was the same as the previous value
     */
    bool SetPropertyPlaylistsMax(uint32_t aValue);
    /**
     * Get a copy of the value of the PlaylistsMax property
     *
     * Can only be called if EnablePropertyPlaylistsMax has previously been called.
     */
    void GetPropertyPlaylistsMax(uint32_t& aValue);
    /**
     * Set the value of the TracksMax property
     *
     * Can only be called if EnablePropertyTracksMax has previously been called.
     *
     * @return  true if the value has been updated; false if aValue was the same as the previous value
     */
    bool SetPropertyTracksMax(uint32_t aValue);
    /**
     * Get a copy of the value of the TracksMax property
     *
     * Can only be called if EnablePropertyTracksMax has previously been called.
     */
    void GetPropertyTracksMax(uint32_t& aValue);
protected:
    /**
     * Constructor
     *
     * @param[in] aDevice  Device which owns this provider
     */
    DvProviderAvOpenhomeOrgPlaylistManager1Cpp(DvDeviceStd& aDevice);
    /**
     * Enable the Metadata property.
     */
    void EnablePropertyMetadata();
    /**
     * Enable the ImagesXml property.
     */
    void EnablePropertyImagesXml();
    /**
     * Enable the IdArray property.
     */
    void EnablePropertyIdArray();
    /**
     * Enable the TokenArray property.
     */
    void EnablePropertyTokenArray();
    /**
     * Enable the PlaylistsMax property.
     */
    void EnablePropertyPlaylistsMax();
    /**
     * Enable the TracksMax property.
     */
    void EnablePropertyTracksMax();
    /**
     * Signal that the action Metadata is supported.
     * The action's availability will be published in the device's service.xml.
     * Metadata must be overridden if this is called.
     */
    void EnableActionMetadata();
    /**
     * Signal that the action ImagesXml is supported.
     * The action's availability will be published in the device's service.xml.
     * ImagesXml must be overridden if this is called.
     */
    void EnableActionImagesXml();
    /**
     * Signal that the action PlaylistReadArray is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistReadArray must be overridden if this is called.
     */
    void EnableActionPlaylistReadArray();
    /**
     * Signal that the action PlaylistReadList is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistReadList must be overridden if this is called.
     */
    void EnableActionPlaylistReadList();
    /**
     * Signal that the action PlaylistRead is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistRead must be overridden if this is called.
     */
    void EnableActionPlaylistRead();
    /**
     * Signal that the action PlaylistSetName is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistSetName must be overridden if this is called.
     */
    void EnableActionPlaylistSetName();
    /**
     * Signal that the action PlaylistSetDescription is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistSetDescription must be overridden if this is called.
     */
    void EnableActionPlaylistSetDescription();
    /**
     * Signal that the action PlaylistSetImageId is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistSetImageId must be overridden if this is called.
     */
    void EnableActionPlaylistSetImageId();
    /**
     * Signal that the action PlaylistInsert is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistInsert must be overridden if this is called.
     */
    void EnableActionPlaylistInsert();
    /**
     * Signal that the action PlaylistDeleteId is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistDeleteId must be overridden if this is called.
     */
    void EnableActionPlaylistDeleteId();
    /**
     * Signal that the action PlaylistMove is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistMove must be overridden if this is called.
     */
    void EnableActionPlaylistMove();
    /**
     * Signal that the action PlaylistsMax is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistsMax must be overridden if this is called.
     */
    void EnableActionPlaylistsMax();
    /**
     * Signal that the action TracksMax is supported.
     * The action's availability will be published in the device's service.xml.
     * TracksMax must be overridden if this is called.
     */
    void EnableActionTracksMax();
    /**
     * Signal that the action PlaylistArrays is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistArrays must be overridden if this is called.
     */
    void EnableActionPlaylistArrays();
    /**
     * Signal that the action PlaylistArraysChanged is supported.
     * The action's availability will be published in the device's service.xml.
     * PlaylistArraysChanged must be overridden if this is called.
     */
    void EnableActionPlaylistArraysChanged();
    /**
     * Signal that the action Read is supported.
     * The action's availability will be published in the device's service.xml.
     * Read must be overridden if this is called.
     */
    void EnableActionRead();
    /**
     * Signal that the action ReadList is supported.
     * The action's availability will be published in the device's service.xml.
     * ReadList must be overridden if this is called.
     */
    void EnableActionReadList();
    /**
     * Signal that the action Insert is supported.
     * The action's availability will be published in the device's service.xml.
     * Insert must be overridden if this is called.
     */
    void EnableActionInsert();
    /**
     * Signal that the action DeleteId is supported.
     * The action's availability will be published in the device's service.xml.
     * DeleteId must be overridden if this is called.
     */
    void EnableActionDeleteId();
    /**
     * Signal that the action DeleteAll is supported.
     * The action's availability will be published in the device's service.xml.
     * DeleteAll must be overridden if this is called.
     */
    void EnableActionDeleteAll();
private:
    /**
     * Metadata action.
     *
     * Will be called when the device stack receives an invocation of the
     * Metadata action for the owning device.
     * Must be implemented iff EnableActionMetadata was called.
     */
    virtual void Metadata(IDvInvocationStd& aInvocation, std::string& aMetadata);
    /**
     * ImagesXml action.
     *
     * Will be called when the device stack receives an invocation of the
     * ImagesXml action for the owning device.
     * Must be implemented iff EnableActionImagesXml was called.
     */
    virtual void ImagesXml(IDvInvocationStd& aInvocation, std::string& aImagesXml);
    /**
     * PlaylistReadArray action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistReadArray action for the owning device.
     * Must be implemented iff EnableActionPlaylistReadArray was called.
     */
    virtual void PlaylistReadArray(IDvInvocationStd& aInvocation, uint32_t aId, std::string& aArray);
    /**
     * PlaylistReadList action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistReadList action for the owning device.
     * Must be implemented iff EnableActionPlaylistReadList was called.
     */
    virtual void PlaylistReadList(IDvInvocationStd& aInvocation, const std::string& aIdList, std::string& aPlaylistList);
    /**
     * PlaylistRead action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistRead action for the owning device.
     * Must be implemented iff EnableActionPlaylistRead was called.
     */
    virtual void PlaylistRead(IDvInvocationStd& aInvocation, uint32_t aId, std::string& aName, std::string& aDescription, uint32_t& aImageId);
    /**
     * PlaylistSetName action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistSetName action for the owning device.
     * Must be implemented iff EnableActionPlaylistSetName was called.
     */
    virtual void PlaylistSetName(IDvInvocationStd& aInvocation, uint32_t aId, const std::string& aName);
    /**
     * PlaylistSetDescription action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistSetDescription action for the owning device.
     * Must be implemented iff EnableActionPlaylistSetDescription was called.
     */
    virtual void PlaylistSetDescription(IDvInvocationStd& aInvocation, uint32_t aId, const std::string& aDescription);
    /**
     * PlaylistSetImageId action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistSetImageId action for the owning device.
     * Must be implemented iff EnableActionPlaylistSetImageId was called.
     */
    virtual void PlaylistSetImageId(IDvInvocationStd& aInvocation, uint32_t aId, uint32_t aImageId);
    /**
     * PlaylistInsert action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistInsert action for the owning device.
     * Must be implemented iff EnableActionPlaylistInsert was called.
     */
    virtual void PlaylistInsert(IDvInvocationStd& aInvocation, uint32_t aAfterId, const std::string& aName, const std::string& aDescription, uint32_t aImageId, uint32_t& aNewId);
    /**
     * PlaylistDeleteId action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistDeleteId action for the owning device.
     * Must be implemented iff EnableActionPlaylistDeleteId was called.
     */
    virtual void PlaylistDeleteId(IDvInvocationStd& aInvocation, uint32_t aValue);
    /**
     * PlaylistMove action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistMove action for the owning device.
     * Must be implemented iff EnableActionPlaylistMove was called.
     */
    virtual void PlaylistMove(IDvInvocationStd& aInvocation, uint32_t aId, uint32_t aAfterId);
    /**
     * PlaylistsMax action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistsMax action for the owning device.
     * Must be implemented iff EnableActionPlaylistsMax was called.
     */
    virtual void PlaylistsMax(IDvInvocationStd& aInvocation, uint32_t& aValue);
    /**
     * TracksMax action.
     *
     * Will be called when the device stack receives an invocation of the
     * TracksMax action for the owning device.
     * Must be implemented iff EnableActionTracksMax was called.
     */
    virtual void TracksMax(IDvInvocationStd& aInvocation, uint32_t& aValue);
    /**
     * PlaylistArrays action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistArrays action for the owning device.
     * Must be implemented iff EnableActionPlaylistArrays was called.
     */
    virtual void PlaylistArrays(IDvInvocationStd& aInvocation, uint32_t& aToken, std::string& aIdArray, std::string& aTokenArray);
    /**
     * PlaylistArraysChanged action.
     *
     * Will be called when the device stack receives an invocation of the
     * PlaylistArraysChanged action for the owning device.
     * Must be implemented iff EnableActionPlaylistArraysChanged was called.
     */
    virtual void PlaylistArraysChanged(IDvInvocationStd& aInvocation, uint32_t aToken, bool& aValue);
    /**
     * Read action.
     *
     * Will be called when the device stack receives an invocation of the
     * Read action for the owning device.
     * Must be implemented iff EnableActionRead was called.
     */
    virtual void Read(IDvInvocationStd& aInvocation, uint32_t aId, uint32_t aTrackId, std::string& aMetadata);
    /**
     * ReadList action.
     *
     * Will be called when the device stack receives an invocation of the
     * ReadList action for the owning device.
     * Must be implemented iff EnableActionReadList was called.
     */
    virtual void ReadList(IDvInvocationStd& aInvocation, uint32_t aId, const std::string& aTrackIdList, std::string& aTrackList);
    /**
     * Insert action.
     *
     * Will be called when the device stack receives an invocation of the
     * Insert action for the owning device.
     * Must be implemented iff EnableActionInsert was called.
     */
    virtual void Insert(IDvInvocationStd& aInvocation, uint32_t aId, uint32_t aAfterTrackId, const std::string& aMetadata, uint32_t& aNewTrackId);
    /**
     * DeleteId action.
     *
     * Will be called when the device stack receives an invocation of the
     * DeleteId action for the owning device.
     * Must be implemented iff EnableActionDeleteId was called.
     */
    virtual void DeleteId(IDvInvocationStd& aInvocation, uint32_t aId, uint32_t aTrackId);
    /**
     * DeleteAll action.
     *
     * Will be called when the device stack receives an invocation of the
     * DeleteAll action for the owning device.
     * Must be implemented iff EnableActionDeleteAll was called.
     */
    virtual void DeleteAll(IDvInvocationStd& aInvocation, uint32_t aId);
private:
    DvProviderAvOpenhomeOrgPlaylistManager1Cpp();
    void DoMetadata(IDviInvocation& aInvocation);
    void DoImagesXml(IDviInvocation& aInvocation);
    void DoPlaylistReadArray(IDviInvocation& aInvocation);
    void DoPlaylistReadList(IDviInvocation& aInvocation);
    void DoPlaylistRead(IDviInvocation& aInvocation);
    void DoPlaylistSetName(IDviInvocation& aInvocation);
    void DoPlaylistSetDescription(IDviInvocation& aInvocation);
    void DoPlaylistSetImageId(IDviInvocation& aInvocation);
    void DoPlaylistInsert(IDviInvocation& aInvocation);
    void DoPlaylistDeleteId(IDviInvocation& aInvocation);
    void DoPlaylistMove(IDviInvocation& aInvocation);
    void DoPlaylistsMax(IDviInvocation& aInvocation);
    void DoTracksMax(IDviInvocation& aInvocation);
    void DoPlaylistArrays(IDviInvocation& aInvocation);
    void DoPlaylistArraysChanged(IDviInvocation& aInvocation);
    void DoRead(IDviInvocation& aInvocation);
    void DoReadList(IDviInvocation& aInvocation);
    void DoInsert(IDviInvocation& aInvocation);
    void DoDeleteId(IDviInvocation& aInvocation);
    void DoDeleteAll(IDviInvocation& aInvocation);
private:
    PropertyString* iPropertyMetadata;
    PropertyString* iPropertyImagesXml;
    PropertyBinary* iPropertyIdArray;
    PropertyBinary* iPropertyTokenArray;
    PropertyUint* iPropertyPlaylistsMax;
    PropertyUint* iPropertyTracksMax;
};

} // namespace Net
} // namespace OpenHome

#endif // HEADER_DVAVOPENHOMEORGPLAYLISTMANAGER1CPP


text:
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
module Main where

import Slides.Presentation
import Data.FileEmbed

index :: String
index = $(embedStringFile "test/index.html")

sample :: Presentation
sample =
    emptyPresentation {
        slides = [
            Slide [
                Header 2 "Title",
                Sequence Immediate [
                    -- this delay does nothing because the parent Immediate overrides it
                    UnfoldConcatList Delay [
                        Header 3 "Example",
                        UnfoldList Immediate [
                            "These lines will unfold one by one.",
                            "You can use some markdown in these strings like _this_ or *this* \
                            \or __this__ or **this**.",
                            "unicodešđčćž"
                        ]
                    ],
                    List [
                        "This list will be shown in place of the previous title-list-diagram.",
                        "This item will be shown immediately with the last one."
                    ]
                ] -- note that the above title "Title" will remain there during the sequence.
            ],
            Slide [
                Header 2 "Another slide",
                List [
                    "Some text describing stuff.",
                    "More text."
                ]
            ]
        ]
    }

main :: IO ()
main = if renderPresentation sample == index then putStrLn "Test passed."
                                             else putStrLn "Test failed."


text:
namespace tools::finite::opt {
    template<typename Scalar>
    void internal::eig_executor(const TensorsFinite &tensors, const opt_mps &initial_mps, std::vector<opt_mps> &results, const OptMeta &meta) {
        const auto problem_size = tensors.active_problem_size();
        if(problem_size > settings::precision::max_size_full_diag)
            throw except::logic_error("eig_executor: the Hamiltonian is too large for eig: {}", problem_size);
        eig::solver solver;
        if(meta.optMode == OptMode::VARIANCE) {
            tools::log->trace("Full diagonalization of local (H-E)²");
            const auto &matrix = tensors.get_effective_hamiltonian_squared<Scalar>();
            solver.eig(matrix.data(), matrix.dimension(0), 'I', 1, 1, 0.0, 1.0, 1);
        } else if(meta.optMode == OptMode::ENERGY) {
            tools::log->trace("Full diagonalization of local H");
            const auto &matrix = tensors.get_effective_hamiltonian<Scalar>();
            int         SR_il  = 1; // min nev index (starts from 1)
            int         SR_iu  = 1; // max nev index
            int         LR_il  = static_cast<int>(matrix.dimension(0));
            int         LR_iu  = static_cast<int>(matrix.dimension(0));
            switch(meta.optRitz) {
                case OptRitz::SR: solver.eig(matrix.data(), matrix.dimension(0), 'I', SR_il, SR_iu, 0.0, 1.0, 1); break;
                case OptRitz::LR: solver.eig(matrix.data(), matrix.dimension(0), 'I', LR_il, LR_iu, 0.0, 1.0, 1); break;
                case OptRitz::SM: {
                    auto eigval = initial_mps.get_eigval();
                    auto eigvar = initial_mps.get_variance();
                    auto vl     = eigval - 2 * eigvar;
                    auto vu     = eigval + 2 * eigvar;
                    solver.eig(matrix.data(), matrix.dimension(0), 'V', 1, 1, vl, vu, 10);
                    break;
                }
            }
        } else {
            tools::log->trace("Full diagonalization of local H");
            const auto &matrix = tensors.get_effective_hamiltonian<Scalar>();
            solver.eig(matrix.data(), matrix.dimension(0), eig::Vecs::ON);
        }
        tools::finite::opt::internal::eigs_extract_results(tensors, initial_mps, meta, solver, results, false);
    }
    template void internal::eig_executor<real>(const TensorsFinite &tensors, const opt_mps &initial_mps, std::vector<opt_mps> &results, const OptMeta &meta);
    template void internal::eig_executor<cplx>(const TensorsFinite &tensors, const opt_mps &initial_mps, std::vector<opt_mps> &results, const OptMeta &meta);

    opt_mps internal::eig_optimize_energy(const TensorsFinite &tensors, const opt_mps &initial_mps, [[maybe_unused]] const AlgorithmStatus &status,
                                          OptMeta &meta) {
        tools::log->debug("Energy optimization with ritz {} | type {}", enum2sv(meta.optRitz), enum2sv(meta.optType));
        if(meta.optMode != OptMode::ENERGY)
            throw except::runtime_error("Wrong optimization mode [{}]. Expected [{}]", enum2sv(meta.optMode), enum2sv(OptMode::ENERGY));
        if(meta.optRitz == OptRitz::SM and not tensors.model->is_shifted())
            throw std::runtime_error("eig_optimize_energy with ritz [SM] requires energy-shifted MPO ");

        auto                 t_gs = tid::tic_scope("eig-ene");
        std::vector<opt_mps> results;
        switch(meta.optType) {
            case OptType::REAL: eig_executor<real>(tensors, initial_mps, results, meta); break;
            case OptType::CPLX: eig_executor<cplx>(tensors, initial_mps, results, meta); break;
        }

        if(results.size() >= 2) std::sort(results.begin(), results.end(), Comparator(meta, initial_mps.get_energy()));
        for(const auto &mps : results) reports::eigs_add_entry(mps, spdlog::level::info);
        reports::print_eigs_report();
        if(results.empty())
            return initial_mps; // Solver failed
        else
            return results.front();
    }

}


text:
packages
========

.. automodule:: canbeAny.packages
	:members:

subpackage and modules
----------------------

.. toctree::
   :maxdepth: 1

	subpackage1 <subpackage1/__init__>
	subpackage2 <subpackage2/__init__>