text:
// version: 2015-08-28
    /**
    * o--------------------------------------------------------------------------------o
    * | This file is part of the RGraph package - you can learn more at:               |
    * |                                                                                |
    * |                          http://www.rgraph.net                                 |
    * |                                                                                |
    * | RGraph is dual licensed under the Open Source GPL (General Public License)     |
    * | v2.0 license and a commercial license which does not mean that you're bound by |
    * | the terms of the GPL. The commercial license is just £99 (GBP) and you can     |
    * | read about it here:                                                            |
    * |                      http://www.rgraph.net/license                             |
    * o--------------------------------------------------------------------------------o
    */

    /**
    * Having this here means that the RGraph libraries can be included in any order, instead of you having
    * to include the common core library first.
    */

    // Define the RGraph global variable
    RGraph = window.RGraph || {isRGraph: true};
    RGraph.Drawing = RGraph.Drawing || {};

    /**
    * The constructor. This function sets up the object. It takes the ID (the HTML attribute) of the canvas as the
    * first argument and the data as the second. If you need to change this, you can.
    *
    * @param string id    The canvas tag ID
    * @param number x    The X position of the label
    * @param number y    The Y position of the label
    * @param number text The text used
    */
    RGraph.Drawing.Image = function (conf)
    {
        /**
        * Allow for object config style
        */
        if (   typeof conf === 'object'
            && typeof conf.x === 'number'
            && typeof conf.y === 'number'
            && typeof conf.src === 'string'
            && typeof conf.id === 'string') {

            var id     = conf.id
            var canvas = document.getElementById(id);
            var x      = conf.x;
            var y      = conf.y;
            var src    = conf.src;

            var parseConfObjectForOptions = true; // Set this so the config is parsed (at the end of the constructor)

        } else {

            var id     = conf;
            var canvas = document.getElementById(id);
            var x      = arguments[1];
            var y      = arguments[2];
            var src    = arguments[3];
        }

        // id, x, y
        this.id                 = id;
        this.canvas             = document.getElementById(this.id);
        this.context            = this.canvas.getContext('2d');
        this.colorsParsed       = false;
        this.canvas.__object__  = this;
        this.alignmentProcessed = false;
        this.original_colors    = [];
        this.firstDraw         = true; // After the first draw this will be false

        /**
        * Store the properties
        */
        this.x   = x;
        this.y   = y;
        this.src = src;
        this.img = new Image();
        this.img.src = this.src;

        /**
        * This defines the type of this shape
        */
        this.type = 'drawing.image';

        /**
        * This facilitates easy object identification, and should always be true
        */
        this.isRGraph = true;

        /**
        * This adds a uid to the object that you can use for identification purposes
        */
        this.uid = RGraph.CreateUID();

        /**
        * This adds a UID to the canvas for identification purposes
        */
        this.canvas.uid = this.canvas.uid ? this.canvas.uid : RGraph.CreateUID();

        /**
        * Some example background properties
        */
        this.properties =
        {
            'chart.src':              null,
            'chart.width':            null,
            'chart.height':           null,
            'chart.halign':           'left',
            'chart.valign':           'top',
            'chart.events.mousemove': null,
            'chart.events.click':     null,
            'chart.shadow':           false,
            'chart.shadow.color':     'gray',
            'chart.shadow.offsetx':   3,
            'chart.shadow.offsety':   3,
            'chart.shadow.blur':      5,
            'chart.tooltips':           null,
            'chart.tooltips.highlight': true,
            'chart.tooltips.css.class': 'RGraph_tooltip',
            'chart.tooltips.event':     'onclick',
            'chart.highlight.stroke':     'rgba(0,0,0,0)',
            'chart.highlight.fill':       'rgba(255,255,255,0.7)',
            'chart.alpha':                1,
            'chart.border':               false,
            'chart.border.color':         'black',
            'chart.border.linewidth':     1,
            'chart.border.radius':        0,
            'chart.background.color':     'rgba(0,0,0,0)'
        }

        /**
        * A simple check that the browser has canvas support
        */
        if (!this.canvas) {
            alert('[DRAWING.IMAGE] No canvas support');
            return;
        }

        /**
        * This can be used to store the coordinates of shapes on the graph
        */
        this.coords = [];

        /**
        * Create the dollar object so that functions can be added to them
        */
        this.$0 = {};

        /*
        * Translate half a pixel for antialiasing purposes - but only if it hasn't beeen
        * done already
        */
        if (!this.canvas.__rgraph_aa_translated__) {
            this.context.translate(0.5,0.5);

            this.canvas.__rgraph_aa_translated__ = true;
        }

        // Short variable names
        var RG    = RGraph;
        var ca    = this.canvas;
        var co    = ca.getContext('2d');
        var prop  = this.properties;
        var jq    = jQuery;
        var pa    = RG.Path;
        var win   = window;
        var doc   = document;
        var ma    = Math;

        /**
        * "Decorate" the object with the generic effects if the effects library has been included
        */
        if (RG.Effects && typeof RG.Effects.decorate === 'function') {
            RG.Effects.decorate(this);
        }

        /**
        * A setter method for setting graph properties. It can be used like this: obj.Set('chart.strokestyle', '#666');
        *
        * @param name  string The name of the property to set OR it can be a map
        *                     of name/value settings like what you set in the constructor
        */
        this.set =
        this.Set = function (name)
        {
            var value = typeof arguments[1] === 'undefined' ? null : arguments[1];

            /**
            * the number of arguments is only one and it's an
            * object - parse it for configuration data and return.
            */
            if (arguments.length === 1 && typeof name === 'object') {
                RG.parseObjectStyleConfig(this, name);
                return this;
            }

            /**
            * This should be done first - prepend the propertyy name with "chart." if necessary
            */
            if (name.substr(0,6) != 'chart.') {
                name = 'chart.' + name;
            }

            // Convert uppercase letters to dot+lower case letter
            name = name.replace(/([A-Z])/g, function (str)
            {
                return '.' + String(RegExp.$1).toLowerCase();
            });

            prop[name] = value;

            return this;
        };

        /**
        * A getter method for retrieving graph properties. It can be used like this: obj.Get('chart.strokestyle');
        *
        * @param name  string The name of the property to get
        */
        this.get =
        this.Get = function (name)
        {
            /**
            * This should be done first - prepend the property name with "chart." if necessary
            */
            if (name.substr(0,6) != 'chart.') {
                name = 'chart.' + name;
            }

            // Convert uppercase letters to dot+lower case letter
            name = name.replace(/([A-Z])/g, function (str)
            {
                return '.' + String(RegExp.$1).toLowerCase()
            });

            return prop[name.toLowerCase()];
        };

        /**
        * Draws the circle
        */
        this.draw =
        this.Draw = function ()
        {
            /**
            * Fire the onbeforedraw event
            */
            RG.FireCustomEvent(this, 'onbeforedraw');

            /**
            * Parse the colors. This allows for simple gradient syntax
            */
            var obj = this;
            this.img.onload = function ()
            {
                if (!obj.colorsParsed) {

                    obj.parseColors();

                    // Don't want to do this again
                    obj.colorsParsed = true;
                }

                obj.width  = this.width;
                obj.height = this.height;

                if (!this.alignmentProcessed) {

                    var customWidthHeight = (typeof obj.properties['chart.width'] == 'number' && typeof obj.properties['chart.width'] == 'number');

                    // Horizontal alignment
                    if (obj.properties['chart.halign'] == 'center') {
                        obj.x -= customWidthHeight ? (obj.properties['chart.width'] / 2) : (this.width / 2);
                    } else if (obj.properties['chart.halign'] == 'right') {
                        obj.x -= customWidthHeight ? obj.properties['chart.width'] : this.width;
                    }

                    // Vertical alignment
                    if (obj.properties['chart.valign'] == 'center') {
                        obj.y -= customWidthHeight ? (obj.properties['chart.height'] / 2) : (this.height / 2);
                    } else if (obj.properties['chart.valign'] == 'bottom') {
                        obj.y -= customWidthHeight ? obj.properties['chart.height'] : this.height;
                    }

                    // Don't do this again
                    this.alignmentProcessed = true;
                }
            }

            // The onload event doesn't always fire - so call it manually as well
            if (this.img.complete || this.img.readyState === 4) {
                this.img.onload();
            }

            /**
            * Draw the image here
            */

            if (prop['chart.shadow']) {
                RG.setShadow(this, prop['chart.shadow.color'], prop['chart.shadow.offsetx'], prop['chart.shadow.offsety'], prop['chart.shadow.blur']);
            }

            var oldAlpha = co.globalAlpha;
            co.globalAlpha = prop['chart.alpha'];

                /**
                * Draw a border around the image
                */
                if (prop['chart.border']) {

                    co.strokeStyle = prop['chart.border.color'];
                    co.lineWidth   = prop['chart.border.linewidth'];

                    var borderRadius = 0;

                    // Work out the borderRadius only if the image has been loaded
                    if (this.width || this.height) {
                        borderRadius = ma.min(this.width / 2, this.height / 2)
                    }

                    if ((prop['chart.width'] / 2) > borderRadius && (prop['chart.height'] / 2) > borderRadius) {
                        borderRadius = ma.min((prop['chart.width'] / 2), (prop['chart.height'] / 2))
                    }

                    if (prop['chart.border.radius'] < borderRadius) {
                        borderRadius = prop['chart.border.radius'];
                    }

                    co.beginPath();
                    this.roundedRect(
                                     ma.round(this.x) - ma.round(co.lineWidth / 2),
                                     ma.round(this.y) - ma.round(co.lineWidth / 2),
                                     (prop['chart.width'] || this.img.width) + co.lineWidth,
                                     (prop['chart.height'] || this.img.height) + co.lineWidth,
                                     borderRadius
                                    );
                }

                if (borderRadius) {
                    co.save();

                    // Draw the rect that casts the shadow

                    // Draw the background color
                    this.drawBackgroundColor(borderRadius);

                    // Clip the canvas
                    co.beginPath();
                    this.roundedRect(
                                     ma.round(this.x) - ma.round(co.lineWidth / 2),
                                     ma.round(this.y) - ma.round(co.lineWidth / 2),
                                     (prop['chart.width'] || this.img.width) + co.lineWidth,
                                     (prop['chart.height'] || this.img.height) + co.lineWidth,
                                     borderRadius
                                    );
                    co.clip();

                } else {

                    // Draw the background color
                    this.drawBackgroundColor(0);
                }

                RG.noShadow(this);

                if (typeof prop['chart.height'] === 'number' || typeof prop['chart.width'] === 'number') {
                    co.drawImage(
                                 this.img,
                                 ma.round(this.x),
                                 ma.round(this.y),
                                 prop['chart.width'] || this.width,
                                 prop['chart.height'] || this.height
                                );
                } else {
                    co.drawImage(
                                 this.img,
                                 ma.round(this.x),
                                 ma.round(this.y)
                                );
                }

                // If borderRadius is enabled restore the canvas to it's pre-clipped state
                if (borderRadius) {
                    co.restore();
                }

                // If the border is enabled need a stroke so that the border is drawn
                if (prop['chart.border']) {
                    RG.noShadow(this);
                    co.stroke();
                }

            co.globalAlpha = oldAlpha;

            //var obj    = this;

            this.img.onload = function ()
            {
                RG.redrawCanvas(ca);

                obj.coords[0] = [Math.round(obj.x), Math.round(obj.y), typeof(prop['chart.width']) == 'number' ? prop['chart.width'] : this.width, typeof prop['chart.height'] == 'number' ? prop['chart.height'] : this.height];

            }

            RG.NoShadow(this);

            /**
            * This installs the event listeners
            */
            RG.InstallEventListeners(this);

            /**
            * Fire the onfirstdraw event
            */
            if (this.firstDraw) {
                RG.fireCustomEvent(this, 'onfirstdraw');
                this.firstDraw = false;
                this.firstDrawFunc();
            }

            /**
            * Fire the ondraw event
            */
            RG.FireCustomEvent(this, 'ondraw');

            return this;
        };

        /**
        * The getObjectByXY() worker method
        */
        this.getObjectByXY = function (e)
        {
            var mouseXY = RG.getMouseXY(e);

            if (this.getShape(e)) {
                return this;
            }
        };

        /**
        * Not used by the class during creating the shape, but is used by event handlers
        * to get the coordinates (if any) of the selected bar
        *
        * @param object e The event object
        * @param object   OPTIONAL You can pass in the bar object instead of the
        *                          function using "this"
        */
        this.getShape = function (e)
        {
            var mouseXY = RG.getMouseXY(e);
            var mouseX  = mouseXY[0];
            var mouseY  = mouseXY[1];

            if (   this.coords
                && this.coords[0]
                && mouseXY[0] >= this.coords[0][0]
                && mouseXY[0] <= (this.coords[0][0] + this.coords[0][2])
                && mouseXY[1] >= this.coords[0][1]
                && mouseXY[1] <= (this.coords[0][1] + this.coords[0][3])) {

                return {
                        0: this, 1: this.coords[0][0], 2: this.coords[0][1], 3: this.coords[0][2], 4: this.coords[0][3], 5: 0,
                        'object': this, 'x': this.coords[0][0], 'y': this.coords[0][1], 'width': this.coords[0][2], 'height': this.coords[0][3], 'index': 0, 'tooltip': prop['chart.tooltips'] ? prop['chart.tooltips'][0] : null
                       };
            }

            return null;
        };

        /**
        * This function positions a tooltip when it is displayed
        *
        * @param obj object     The chart object
        * @param int x          The X coordinate specified for the tooltip
        * @param int y          The Y coordinate specified for the tooltip
        * @param object tooltip The tooltips DIV element
        * @param number idx     The index of the tooltip
        */
        this.positionTooltip = function (obj, x, y, tooltip, idx)
        {
            var canvasXY   = RG.getCanvasXY(obj.canvas);
            var width      = tooltip.offsetWidth;
            var height     = tooltip.offsetHeight;

            // Set the top position
            tooltip.style.left = 0;
            tooltip.style.top  = canvasXY[1] - height - 7 + this.coords[0][1] + (obj.coords[0][3] / 2) + 'px';

            // By default any overflow is hidden
            tooltip.style.overflow = '';

            // The arrow
            var img = new Image();
                img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAFCAYAAACjKgd3AAAARUlEQVQYV2NkQAN79+797+RkhC4M5+/bd47B2dmZEVkBCgcmgcsgbAaA9GA1BCSBbhAuA/AagmwQPgMIGgIzCD0M0AMMAEFVIAa6UQgcAAAAAElFTkSuQmCC';
                img.style.position = 'absolute';
                img.id = '__rgraph_tooltip_pointer__';
                img.style.top = (tooltip.offsetHeight - 2) + 'px';
            tooltip.appendChild(img);

            // Reposition the tooltip if at the edges:

            // LEFT edge
            if ((canvasXY[0] + obj.coords[0][0] + (obj.coords[0][2] / 2) - (width / 2)) < 10) {
                tooltip.style.left = (canvasXY[0] + this.coords[0][0] + (this.coords[0][2] / 2) - (width * 0.1)) + 'px';
                img.style.left = ((width * 0.1) - 8.5) + 'px';

            // RIGHT edge
            } else if ((canvasXY[0] + this.coords[0][0] + (this.coords[0][2] / 2) + (width / 2)) > doc.body.offsetWidth) {
                tooltip.style.left = (canvasXY[0] + this.coords[0][0] + (this.coords[0][2] / 2) - (width * 0.9)) + 'px';
                img.style.left = ((width * 0.9) - 8.5) + 'px';

            // Default positioning - CENTERED
            } else {
                tooltip.style.left = (canvasXY[0] + this.coords[0][0] + (this.coords[0][2] / 2) - (width * 0.5)) + 'px';
                img.style.left = ((width * 0.5) - 8.5) + 'px';
            }
        };

        /**
        * Each object type has its own Highlight() function which highlights the appropriate shape
        *
        * @param object shape The shape to highlight
        */
        this.highlight =
        this.Highlight = function (shape)
        {
            if (prop['chart.tooltips.highlight']) {
                pa(co, ['b','r',this.coords[0][0],this.coords[0][1],this.coords[0][2],this.coords[0][3], 'f',prop['chart.highlight.fill'], 's', prop['chart.highlight.stroke']]);
            }
        };

        /**
        * This allows for easy specification of gradients
        */
        this.parseColors = function ()
        {

            // Save the original colors so that they can be restored when the canvas is reset
            if (this.original_colors.length === 0) {
                this.original_colors['chart.highlight.stroke'] = RG.array_clone(prop['chart.highlight.stroke']);
                this.original_colors['chart.highlight.fill']   = RG.array_clone(prop['chart.highlight.fill']);
            }

            /**
            * Parse various properties for colors
            */
            prop['chart.highlight.stroke'] = this.parseSingleColorForGradient(prop['chart.highlight.stroke']);
            prop['chart.highlight.fill']   = this.parseSingleColorForGradient(prop['chart.highlight.fill']);
        };

        /**
        * Use this function to reset the object to the post-constructor state. Eg reset colors if
        * need be etc
        */
        this.reset = function ()
        {
        };

        /**
        * This parses a single color value
        */
        this.parseSingleColorForGradient = function (color)
        {
            if (!color) {
                return color;
            }

            if (typeof color === 'string' && color.match(/^gradient\((.*)\)$/i)) {

                var parts = RegExp.$1.split(':');

                // Create the gradient
                var grad = co.createLinearGradient(this.x, this.y, this.x + this.img.width, this.y);

                var diff = 1 / (parts.length - 1);

                grad.addColorStop(0, RG.trim(parts[0]));

                for (var j=1; j<parts.length; ++j) {
                    grad.addColorStop(j * diff, RG.trim(parts[j]));
                }
            }

            return grad ? grad : color;
        };

        /**
        * Using a function to add events makes it easier to facilitate method chaining
        *
        * @param string   type The type of even to add
        * @param function func
        */
        this.on = function (type, func)
        {
            if (type.substr(0,2) !== 'on') {
                type = 'on' + type;
            }

            this[type] = func;

            return this;
        };

        /**
        * This function runs once only
        * (put at the end of the file (before any effects))
        */
        this.firstDrawFunc = function ()
        {
        };

        /**
        * This draws a rectangle for the border of the image with optional rounded corners
        */
        this.roundedRect = function (x, y, width, height, radius)
        {
            // Save the existing state of the canvas so that it can be restored later
            co.save();

                // Translate to the given X/Y coordinates
                co.translate(x, y);

                // Move to the center of the top horizontal line
                co.moveTo(width / 2,0);

                // Draw the rounded corners. The connecting lines in between them are drawn automatically
                co.arcTo(width,0,width,height, ma.min(height / 2, radius));
                co.arcTo(width, height, 0, height, ma.min(width / 2, radius));
                co.arcTo(0, height, 0, 0, ma.min(height / 2, radius));
                co.arcTo(0, 0, radius, 0, ma.min(width / 2, radius));

                // Draw a line back to the start coordinates
                co.lineTo(width / 2,0);

            // Restore the state of the canvas to as it was before the save()
            co.restore();
        };

        /**
        *
        */
        this.drawBackgroundColor = function (borderRadius)
        {
            co.beginPath();
            co.fillStyle = prop['chart.background.color'];
            this.roundedRect(
                             ma.round(this.x) - ma.round(co.lineWidth / 2),
                             ma.round(this.y) - ma.round(co.lineWidth / 2),
                             (prop['chart.width'] || this.img.width) + co.lineWidth,
                             (prop['chart.height'] || this.img.height) + co.lineWidth,
                             borderRadius
                            );
            co.fill();
        };

        RG.att(ca);

        /**
        * Objects are now always registered so that the chart is redrawn if need be.
        */
        RG.Register(this);

        /**
        * This is the 'end' of the constructor so if the first argument
        * contains configuration data - handle that.
        */
        if (parseConfObjectForOptions) {
            RG.parseObjectStyleConfig(this, conf.options);
        }
    };


text:
import sys

import setuptools

if sys.version_info >= (3,):
    protobuf = 'protobuf>=3.2.0,<4.0.0'
else:
    protobuf = 'protobuf>=2.3.0,<4.0.0'

setuptools.setup(
    name='riemann-client',
    version='7.0.0pre1',

    author="Sam Clements",
    author_email="sam.clements@datasift.com",

    url="https://github.com/borntyping/python-riemann-client",
    description="A Riemann client and command line tool",
    long_description=open('README.rst').read(),
    license="MIT",

    packages=[
        'riemann_client',
    ],

    install_requires=[
        'click>=3.1',
        protobuf
    ],

    extras_require={
        'docs': [
            'sphinx',
            'sphinx_rtd_theme'
        ]
    },

    entry_points={
        'console_scripts': [
            'riemann-client = riemann_client.command:main',
        ]
    },

    classifiers=[
        'Development Status :: 7 - Inactive',
        'License :: OSI Approved',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Software Development :: Libraries',
        'Topic :: System :: Monitoring',
        'Topic :: System :: Networking',
        'Topic :: System :: Systems Administration'
    ],
)

redpajama_set_name: RedPajamaGithub


text:
package mf.org.w3c.dom.xpath;

import mf.org.w3c.dom.DOMException;
import mf.org.w3c.dom.Node;

import mf.org.w3c.dom.xpath.XPathException;

/**
 * The XPathResult interface represents the result of the
 * evaluation of an XPath 1.0 expression within the context of a particular
 * node. Since evaluation of an XPath expression can result in various
 * result types, this object makes it possible to discover and manipulate
 * the type and value of the result.
 *
See also the Document Object Model (DOM) Level 3 XPath Specification.
 */
public interface XPathResult {
    // XPathResultType
    /**
     * This code does not represent a specific type. An evaluation of an XPath
     * expression will never produce this type. If this type is requested,
     * then the evaluation returns whatever type naturally results from
     * evaluation of the expression.
     *
If the natural result is a node set when ANY_TYPE was
     * requested, then UNORDERED_NODE_ITERATOR_TYPE is always
     * the resulting type. Any other representation of a node set must be
     * explicitly requested.
     */
    public static final short ANY_TYPE                  = 0;
    /**
     * The result is a number as defined by [XPath 1.0].
     * Document modification does not invalidate the number, but may mean
     * that reevaluation would not yield the same number.
     */
    public static final short NUMBER_TYPE               = 1;
    /**
     * The result is a string as defined by [XPath 1.0].
     * Document modification does not invalidate the string, but may mean
     * that the string no longer corresponds to the current document.
     */
    public static final short STRING_TYPE               = 2;
    /**
     * The result is a boolean as defined by [XPath 1.0].
     * Document modification does not invalidate the boolean, but may mean
     * that reevaluation would not yield the same boolean.
     */
    public static final short BOOLEAN_TYPE              = 3;
    /**
     * The result is a node set as defined by [XPath 1.0] that
     * will be accessed iteratively, which may not produce nodes in a
     * particular order. Document modification invalidates the iteration.
     *
This is the default type returned if the result is a node set and
     * ANY_TYPE is requested.
     */
    public static final short UNORDERED_NODE_ITERATOR_TYPE = 4;
    /**
     * The result is a node set as defined by [XPath 1.0] that
     * will be accessed iteratively, which will produce document-ordered
     * nodes. Document modification invalidates the iteration.
     */
    public static final short ORDERED_NODE_ITERATOR_TYPE = 5;
    /**
     * The result is a node set as defined by [XPath 1.0] that
     * will be accessed as a snapshot list of nodes that may not be in a
     * particular order. Document modification does not invalidate the
     * snapshot but may mean that reevaluation would not yield the same
     * snapshot and nodes in the snapshot may have been altered, moved, or
     * removed from the document.
     */
    public static final short UNORDERED_NODE_SNAPSHOT_TYPE = 6;
    /**
     * The result is a node set as defined by [XPath 1.0] that
     * will be accessed as a snapshot list of nodes that will be in original
     * document order. Document modification does not invalidate the
     * snapshot but may mean that reevaluation would not yield the same
     * snapshot and nodes in the snapshot may have been altered, moved, or
     * removed from the document.
     */
    public static final short ORDERED_NODE_SNAPSHOT_TYPE = 7;
    /**
     * The result is a node set as defined by [XPath 1.0] and
     * will be accessed as a single node, which may be nullif
     * the node set is empty. Document modification does not invalidate the
     * node, but may mean that the result node no longer corresponds to the
     * current document. This is a convenience that permits optimization
     * since the implementation can stop once any node in the resulting set
     * has been found.
     *
If there is more than one node in the actual result, the single
     * node returned might not be the first in document order.
     */
    public static final short ANY_UNORDERED_NODE_TYPE   = 8;
    /**
     * The result is a node set as defined by [XPath 1.0] and
     * will be accessed as a single node, which may be null if
     * the node set is empty. Document modification does not invalidate the
     * node, but may mean that the result node no longer corresponds to the
     * current document. This is a convenience that permits optimization
     * since the implementation can stop once the first node in document
     * order of the resulting set has been found.
     *
If there are more than one node in the actual result, the single
     * node returned will be the first in document order.
     */
    public static final short FIRST_ORDERED_NODE_TYPE   = 9;

    /**
     * A code representing the type of this result, as defined by the type
     * constants.
     */
    public short getResultType();

    /**
     * The value of this number result. If the native double type of the DOM
     * binding does not directly support the exact IEEE 754 result of the
     * XPath expression, then it is up to the definition of the binding to
     * specify how the XPath number is converted to the native binding
     * number.
     * @exception XPathException
     *   TYPE_ERR: raised if resultType is not
     *   NUMBER_TYPE.
     */
    public double getNumberValue()
                             throws XPathException;

    /**
     * The value of this string result.
     * @exception XPathException
     *   TYPE_ERR: raised if resultType is not
     *   STRING_TYPE.
     */
    public String getStringValue()
                             throws XPathException;

    /**
     * The value of this boolean result.
     * @exception XPathException
     *   TYPE_ERR: raised if resultType is not
     *   BOOLEAN_TYPE.
     */
    public boolean getBooleanValue()
                             throws XPathException;

    /**
     * The value of this single node result, which may be null.
     * @exception XPathException
     *   TYPE_ERR: raised if resultType is not
     *   ANY_UNORDERED_NODE_TYPE or
     *   FIRST_ORDERED_NODE_TYPE.
     */
    public Node getSingleNodeValue()
                             throws XPathException;

    /**
     * Signifies that the iterator has become invalid. True if
     * resultType is UNORDERED_NODE_ITERATOR_TYPE
     * or ORDERED_NODE_ITERATOR_TYPE and the document has been
     * modified since this result was returned.
     */
    public boolean getInvalidIteratorState();

    /**
     * The number of nodes in the result snapshot. Valid values for
     * snapshotItem indices are 0 to
     * snapshotLength-1 inclusive.
     * @exception XPathException
     *   TYPE_ERR: raised if resultType is not
     *   UNORDERED_NODE_SNAPSHOT_TYPE or
     *   ORDERED_NODE_SNAPSHOT_TYPE.
     */
    public int getSnapshotLength()
                             throws XPathException;

    /**
     * Iterates and returns the next node from the node set or
     * nullif there are no more nodes.
     * @return Returns the next node.
     * @exception XPathException
     *   TYPE_ERR: raised if resultType is not
     *   UNORDERED_NODE_ITERATOR_TYPE or
     *   ORDERED_NODE_ITERATOR_TYPE.
     * @exception DOMException
     *   INVALID_STATE_ERR: The document has been mutated since the result was
     *   returned.
     */
    public Node iterateNext()
                            throws XPathException, DOMException;

    /**
     * Returns the indexth item in the snapshot collection. If
     * index is greater than or equal to the number of nodes in
     * the list, this method returns null. Unlike the iterator
     * result, the snapshot does not become invalid, but may not correspond
     * to the current document if it is mutated.
     * @param index Index into the snapshot collection.
     * @return The node at the indexth position in the
     *   NodeList, or null if that is not a valid
     *   index.
     * @exception XPathException
     *   TYPE_ERR: raised if resultType is not
     *   UNORDERED_NODE_SNAPSHOT_TYPE or
     *   ORDERED_NODE_SNAPSHOT_TYPE.
     */
    public Node snapshotItem(int index)
                             throws XPathException;

}


text:
namespace blink {

void EmbeddedContentPainter::PaintReplaced(const PaintInfo& paint_info,
                                           const PhysicalOffset& paint_offset) {
  EmbeddedContentView* embedded_content_view =
      layout_embedded_content_.GetEmbeddedContentView();
  if (!embedded_content_view)
    return;

  // Apply the translation to offset the content within the object's border-box
  // only if we're not using a transform node for this. If the frame size is
  // frozen then |ReplacedContentTransform| is used instead.
  gfx::Point paint_location;
  if (!layout_embedded_content_.FrozenFrameSize().has_value()) {
    paint_location = ToRoundedPoint(
        paint_offset + layout_embedded_content_.ReplacedContentRect().offset);
  }

  gfx::Vector2d view_paint_offset =
      paint_location - embedded_content_view->FrameRect().origin();
  CullRect adjusted_cull_rect = paint_info.GetCullRect();
  adjusted_cull_rect.Move(-view_paint_offset);
  embedded_content_view->Paint(paint_info.context, paint_info.GetPaintFlags(),
                               adjusted_cull_rect, view_paint_offset);
}

}  // namespace blink


text:
package com.example.netease.market;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;

import com.example.netease.market.bean.Item;
import com.example.netease.market.common.DownloadManager;
import com.example.netease.market.common.DownloadUtils;
import com.example.netease.market.common.Downloader;
import com.example.netease.market.utils.ApkUtils;
import com.example.netease.market.utils.BitmapCache;
import com.example.netease.market.utils.Constants;
import com.example.netease.market.R;
import de.greenrobot.event.EventBus;
/**
 *
 * @author Dengxiaohua
 *
 */
public class AppDetails extends Activity implements OnClickListener {

	protected static final String TAG = "mopo";
	// apk下载地址
	private String mAppUrl;
//	 图片
	 public Bitmap iconBitmap;
	// 图片下载地址
	private String mAppIcon;
	// 应用类别
	private String mAppCategory;
	// 应用名
	private String mAppName;
	// 应用描述
	private String mAppDescription;
	// 应用版本
	private String mAppVersion;
	// 应用大小
	private String mAppSize;
	// 应用评分等级
	private String mAppLevel;
	// 应用包名
	private String mAppPkg;
	private int mAppTStatus ;

	// 下载安装按钮
	private Button mBtnDownload;
	private TextView mDownloadInfo;
	// 图标
	private ImageView mImgIcon,down;
	// 应用名组件
	private TextView mTxtAppName;
	// 应用类型组件
	private TextView type;
	// 应用大小组件
	private TextView size;
	// 应用版本组件
	private TextView author;
	// 应用描述组件
	private TextView mTxtAppDescription;
	// 应用详情加载组件
	private TextView tv_load_more;
	// 应用星级
	private RatingBar mRatingBar;

	ProgressBar progressBar;

	private Item item ;

	private final int MAX_LINES = 4;
	private boolean isClickable = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game_info_detail);
		Intent intent = getIntent();
		if(!EventBus.getDefault().isRegistered(this)){
			EventBus.getDefault().register(this) ;
		}
		mAppUrl = intent.getStringExtra(Constants.KEY_APP_URL);
		mAppName = intent.getStringExtra(Constants.KEY_APP_NAME);
		mAppDescription = intent.getStringExtra(Constants.KEY_APP_DESCRIPTION);
		mAppLevel = intent.getStringExtra(Constants.KEY_APP_RATING);
		mAppCategory = intent.getStringExtra(Constants.KEY_APP_TYPE);
		mAppSize = intent.getStringExtra(Constants.KEY_APP_SIZE);
		mAppVersion = intent.getStringExtra(Constants.KEY_APP_AUTHOR);
		mAppIcon = intent.getStringExtra(Constants.KEY_APP_ICON);
		mAppPkg = intent.getStringExtra(Constants.KEY_APP_PKG);
		mAppTStatus = intent.getIntExtra(Constants.KEY_APP_T_STATUS ,Item.T_INSTALL);

		item = new Item() ;
		item.downloadUrl = mAppUrl ;
		item.title = mAppName ;
		item.des = mAppDescription ;
		item.rjxj = mAppLevel ;
		item.fl = mAppCategory ;
		item.size = mAppSize ;
		item.bb = mAppVersion ;
		item.iconUrl = mAppIcon ;
		item.pkg = mAppPkg ;
		item.t_install = mAppTStatus ;

		findViewById(R.id.backa).setOnClickListener(this);
		mBtnDownload = (Button) findViewById(R.id.imdownload);
		mBtnDownload.setOnClickListener(this);
		mImgIcon = (ImageView) findViewById(R.id.itemImage_logo);
		BitmapCache bc = new BitmapCache(item.iconUrl);
		if (bc.mBitmap == null)
			bc.loadIcon(this, mImgIcon);
		else {
			mImgIcon.setImageBitmap(bc.mBitmap);
		}
		mTxtAppName = (TextView) findViewById(R.id.itemText_name);
		mTxtAppName.setText(item.title);
		mDownloadInfo = (TextView)findViewById(R.id.download_info) ;
		type = (TextView) findViewById(R.id.itemText_type_name);
		type.setText("类型:"+item.fl);
		size = (TextView) findViewById(R.id.tv_game_size);
		size.setText("大小:" + item.size);
		author = (TextView) findViewById(R.id.tv_author);
		author.setText("版本:" + item.bb);
		mTxtAppDescription = (TextView) findViewById(R.id.tv_games_desc);
		mTxtAppDescription.setText(item.des);
		mTxtAppDescription.setMaxLines(MAX_LINES);
		tv_load_more = (TextView) findViewById(R.id.tv_loadmore);
		tv_load_more.setOnClickListener(this);
		mRatingBar = (RatingBar) findViewById(R.id.ratingBar_score);
		mRatingBar.setRating(Float.valueOf(item.rjxj));
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		down = (ImageView) findViewById(R.id.down);
	}

	public void onEvent(AppEvent.OnPkgAddedEvent e){
		Log.d(TAG ,"onEvent:OnPkgAddedEvent:"+e.getPkg()) ;
		if(!e.getPkg().equals(mAppPkg)){
			return ;
		}
		item.t_install = Item.T_INSTALLED ;
		progressBar.setVisibility(View.GONE) ;
		mDownloadInfo.setVisibility(View.GONE) ;
		mBtnDownload.setText("启动") ;
	}

	public void onEvent(AppEvent.OnPkgRemovedEvent e){
		Log.d(TAG ,"onEvent:OnPkgRemovedEvent:"+e.getPkg()) ;
		if(!e.getPkg().equals(mAppPkg)){
			return ;
		}
		item.t_install = Item.T_INSTALL ;
		progressBar.setVisibility(View.GONE) ;
		mDownloadInfo.setVisibility(View.GONE) ;
		mBtnDownload.setText("安装") ;
	}

	public void onEvent(AppEvent.OnDownloadStartEvent e){
		Log.d(TAG ,"onEvent:OnDownloadStartEvent:"+e.getItem().toString()) ;
		if(!e.getItem().downloadUrl.equals(mAppUrl)){
			return ;
		}
		runOnUiThread(new Runnable(){
			@Override
			public void run() {
				progressBar.setVisibility(View.VISIBLE) ;
				mDownloadInfo.setVisibility(View.VISIBLE) ;
				mDownloadInfo.setText("0%") ;
				mBtnDownload.setText("取消") ;
			}}) ;
	}
	public void onEvent(AppEvent.OnDownloadingEvent e){
		Log.d(TAG ,"onEvent:OnDownloadingEvent:"+e.getItem().toString()) ;
		if(!e.getItem().downloadUrl.equals(mAppUrl)){
			return ;
		}
		final int progress = e.getItem().progress ;
		runOnUiThread(new Runnable(){
			@Override
			public void run() {
				progressBar.setVisibility(View.VISIBLE) ;
				mDownloadInfo.setVisibility(View.VISIBLE) ;
				mDownloadInfo.setText(progress+"%") ;
				mBtnDownload.setText("取消") ;}});
	}
	public void onEvent(AppEvent.OnDownloadFinishEvent e){
		Log.d(TAG ,"onEvent:OnDownloadFinishEvent:"+e.getItem().toString()) ;
		if(!e.getItem().downloadUrl.equals(mAppUrl)){
			return ;
		}
		runOnUiThread(new Runnable(){
			@Override
			public void run() {
				progressBar.setVisibility(View.GONE) ;
				mDownloadInfo.setVisibility(View.GONE) ;
				mBtnDownload.setText("安装") ;}});
	}
	public void onEvent(AppEvent.OnDownloadCancelEvent e){
		Log.d(TAG ,"AppDetails:onEvent:OnDownloadCancelEvent:"+e.getItem().toString()) ;
		if(!e.getItem().downloadUrl.equals(mAppUrl)){
			return ;
		}
		runOnUiThread(new Runnable(){
			@Override
			public void run() {
				progressBar.setVisibility(View.GONE) ;
				mDownloadInfo.setVisibility(View.GONE) ;
				mBtnDownload.setText("下载") ;}});
	}

	@Override
	protected void onResume(){
		super.onResume();
		switch(item.t_install){
		case Item.T_CANCELING:
			down.setVisibility(View.GONE);
			progressBar.setVisibility(View.GONE) ;
			mDownloadInfo.setVisibility(View.GONE) ;
			mBtnDownload.setText("下载") ;
			break ;
		case Item.T_DOWNLOADED:
			down.setVisibility(View.GONE);
			progressBar.setVisibility(View.GONE) ;
			mDownloadInfo.setVisibility(View.GONE) ;
			mBtnDownload.setText("安装") ;
			break ;
		case Item.T_DOWNLOADING:
			down.setVisibility(View.VISIBLE) ;
			progressBar.setVisibility(View.VISIBLE) ;
			mDownloadInfo.setVisibility(View.VISIBLE) ;
			mBtnDownload.setText("取消") ;
			break ;
		case Item.T_INSTALL:
			down.setVisibility(View.VISIBLE) ;
			progressBar.setVisibility(View.GONE) ;
			mDownloadInfo.setVisibility(View.GONE) ;
			mBtnDownload.setText("下载") ;
			break ;
		case Item.T_INSTALLED:
			down.setVisibility(View.GONE);
			progressBar.setVisibility(View.GONE) ;
			mDownloadInfo.setVisibility(View.GONE) ;
			mBtnDownload.setText("启动") ;
			break ;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imdownload:
			switch(item.t_install){
			case Item.T_DOWNLOADING:
				// cancel downloading
				downloadCancel(item) ;
				break ;
			case Item.T_CANCELING:
			case Item.T_INSTALL:
				// start download
					startDownload(item) ;
				break ;
			case Item.T_INSTALLED:
				// start apk
				startApk(item) ;
				break ;
			case Item.T_DOWNLOADED:
				// install apk
				installApk(item) ;
				break ;
			}
			break;
		case R.id.tv_loadmore:
			if (!isClickable) {
				mTxtAppDescription.setMaxLines(mTxtAppDescription.getLineCount());
				tv_load_more.setText("收起");
				isClickable = true;
			} else {
				mTxtAppDescription.setMaxLines(MAX_LINES);
				tv_load_more.setText("详情>");
				isClickable = false;
			}
			break;
		case R.id.backa:
			finish();
			break;
		default:
			break;
		}
	}

	private void installApk(Item item){
		item.t_install = Item.T_DOWNLOADED ;
		item.progress = 100 ;
		EventBus.getDefault().post(new AppEvent.OnApkInstallEvent(item)) ;
		ApkUtils.install(this, ApkUtils.getDownloadFile(item)) ;
	}

	private void startApk(Item item){
		item.t_install = Item.T_INSTALLED ;
		item.progress = 0 ;
		ApkUtils.runPackge(this, item.pkg) ;
		EventBus.getDefault().post(new AppEvent.OnApkStartEvent(item)) ;
	}

	private void startDownload(final Item item) {
		item.t_install = Item.T_DOWNLOADING ;
		item.progress = 0 ;
		EventBus.getDefault().post(new AppEvent.OnDownloadStartEvent(item)) ;
//		String keyName = LocalDataUtils.genName(item.downloadUrl);
		//检查apk文件是否存在
		final File file_apk =  ApkUtils.getDownloadFile(item) ;
		//启动下载器
		if(DownloadManager.exist(item.downloadUrl))
			return;
		Downloader downloader = DownloadUtils.start(this, file_apk, item.downloadUrl, new DownloadUtils.DownloadListener() {

			private long lastTime ;
			@Override
			public void onStart(int total) {
				Log.d(TAG ,"Downloader:onStart:"+total) ;
			}

			@Override
			public void onProgress(int cur, float prog) {
				if(item.t_install != Item.T_CANCELING){
					if(System.currentTimeMillis()-lastTime >300){
							progressBar.setMax(item.progress);
							Log.d(TAG ,"Downloader:onProgress:"+prog) ;
							item.t_install = Item.T_DOWNLOADING ;
							item.progress = (int)prog ;
							lastTime = System.currentTimeMillis() ;
							EventBus.getDefault().post(new AppEvent.OnDownloadingEvent(item)) ;
					}

				}
			}

			@Override
			public void onFinish() {
				Log.d(TAG ,"Downloader:onFinish") ;
				item.t_install = Item.T_DOWNLOADED ;
				item.progress = 100 ;
				EventBus.getDefault().post(new AppEvent.OnDownloadFinishEvent(item)) ;
				DownloadManager.remove(item.downloadUrl);
			}

			@Override
			public void onCancel() {
				Log.d(TAG ,"Downloader:onCancel") ;
				file_apk.delete() ;
			}
		});
		DownloadManager.add(item.downloadUrl, downloader);

	}

	private void downloadCancel(Item item){
		item.t_install = Item.T_CANCELING ;
		item.progress = 0 ;
		EventBus.getDefault().post(new AppEvent.OnDownloadCancelEvent(item)) ;
		DownloadManager.getDownloader(item.downloadUrl).cancel() ;
		DownloadManager.remove(item.downloadUrl);
	}

	@Override
	protected void onDestroy(){
		super.onDestroy() ;
		EventBus.getDefault().unregister(this) ;
	}
}


text:
import sys

def is_python2():
    return sys.version_info.major == 2

def is_python27():
    return sys.version_info.major == 2 and  sys.version_info.minor == 7

def is_python3():
    return sys.version_info.major == 3

def is_list(var):
    """
    Test if variable var is list

    :return: True if var is list, False if var is not list
    :rtype:  bol
    """
    return isinstance(var, list)

def is_tuple(var):
    return isinstance(var, tuple)

def is_num(var):
    """
    Test if variable var is number (int or float)

    :return: True if var is number, False otherwise.
    :rtype:  bol
    """
    return isinstance(var, int) or isinstance(var, float)

def is_dict(var):
    return isinstance(var, dict)

def is_string(var):
    return isinstance(var, str)

def is_function(var):
    """
    Test if variable is function (has a __call__ attribute)

    :return: True if var is function, False otherwise.
    :rtype:  bol
    """
    return hasattr(var, '__call__')

def is_none(var):
    return var is None

def is_empty(lst):
    return len(lst) == 0

def is_not_empty(lst):
    return len(lst) !=0

def is_pos(x):
    return x > 0

def is_neg(x):
    return x < 0

#-------------------------------#
#  OPERATING SYSTEM DETECTION   #
#-------------------------------#

def is_unix():
    return sys.platform.startswith('linux') or \
           sys.platform.startswith('bsd') or \
           sys.platform.startswith('darwin')

def is_linux():
    """
    :return: Return True if OS is Linux, False otherwise
    :rtype: bool
    """
    return sys.platform.startswith('linux')

def is_windows():
    """
    :return: Return True if OS is Windows, False otherwise
    :rtype: bool
    """
    return sys.platform.startswith('win')

def is_darwin():
    """
    :return: Return True if OS is OSX, False otherwise
    :rtype: bool
    """
    return sys.platform.startswith('darwin')

def is_bsd():
    """
    :return: Return True if OS is BSD, False otherwise
    :rtype: bool
    """
    return sys.platform.startswith('bsd')


text:
package com.amazonaws.services.medialive.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 * Placeholder documentation for CreateInputResponse
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateInputResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    private Input input;

    /**
     * @param input
     */

    public void setInput(Input input) {
        this.input = input;
    }

    /**
     * @return
     */

    public Input getInput() {
        return this.input;
    }

    /**
     * @param input
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public CreateInputResult withInput(Input input) {
        setInput(input);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getInput() != null)
            sb.append("Input: ").append(getInput());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof CreateInputResult == false)
            return false;
        CreateInputResult other = (CreateInputResult) obj;
        if (other.getInput() == null ^ this.getInput() == null)
            return false;
        if (other.getInput() != null && other.getInput().equals(this.getInput()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getInput() == null) ? 0 : getInput().hashCode());
        return hashCode;
    }

    @Override
    public CreateInputResult clone() {
        try {
            return (CreateInputResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Account_UpdateFromDataResponse xmlns="http://e-conomic.com">
      <Account_UpdateFromDataResult>
        <Number>42</Number>
      </Account_UpdateFromDataResult>
    </Account_UpdateFromDataResponse>
  </soap:Body>
</soap:Envelope>


text:
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'spec'
require 'spec/rails'

Spec::Runner.configure do |config|
  # If you're not using ActiveRecord you should remove these
  # lines, delete config/database.yml and disable :active_record
  # in your config/boot.rb
  config.use_transactional_fixtures = true
  config.use_instantiated_fixtures  = false
  config.fixture_path = RAILS_ROOT + '/spec/fixtures/'

  # == Fixtures
  #
  # You can declare fixtures for each example_group like this:
  #   describe "...." do
  #     fixtures :table_a, :table_b
  #
  # Alternatively, if you prefer to declare them only once, you can
  # do so right here. Just uncomment the next line and replace the fixture
  # names with your fixtures.
  #
  config.global_fixtures = :projects, :project_statuses, :project_maturities, :users

  #
  # If you declare global fixtures, be aware that they will be declared
  # for all of your examples, even those that don't use them.
  #
  # You can also declare which fixtures to use (for example fixtures for test/fixtures):
  #
  # config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
  #
  # == Mock Framework
  #
  # RSpec uses it's own mocking framework by default. If you prefer to
  # use mocha, flexmock or RR, uncomment the appropriate line:
  #
  # config.mock_with :mocha
  # config.mock_with :flexmock
  # config.mock_with :rr
  #
  # == Notes
  #
  # For more information take a look at Spec::Example::Configuration and Spec::Runner
end

module Spec
  module Mocks
    module Methods
      def stub_association!(association_name, methods_to_be_stubbed = {})
        mock_association = Spec::Mocks::Mock.new(association_name.to_s)
        methods_to_be_stubbed.each do |method, return_value|
          mock_association.stub!(method).and_return(return_value)
        end
        self.stub!(association_name).and_return(mock_association)
      end
    end
  end
end


text:
require 'test_helper'

class OntologyClassTest < ActiveSupport::TestCase
  test 'initialization' do
    o = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://fish#bob')
    assert o.uri.is_a?(RDF::URI)
    assert_equal 'http://fish#bob', o.uri.to_s
    assert_nil o.description
    assert_empty o.subclasses

    o = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://fish#bob'), 'fred'
    assert_equal 'http://fish#bob', o.uri.to_s
    assert_nil o.description
    assert_equal 'fred', o.label
    assert_empty o.subclasses

    o = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://fish#bob'), 'fred', 'the fred'
    assert_equal 'http://fish#bob', o.uri.to_s
    assert_equal 'fred', o.label
    assert_equal 'the fred', o.description
    assert_empty o.subclasses

    o = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://fish#bob'), 'fred', 'the fred', [RDF::URI.new('http://fish#baby_bob')]
    assert_equal 'http://fish#bob', o.uri.to_s
    assert_equal 'fred', o.label
    assert_equal 'the fred', o.description
    assert_equal 1, o.subclasses.count
    assert_equal 'http://fish#baby_bob', o.subclasses.first.to_s

    o = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://fish#bob'), 'fred', 'the fred', [RDF::URI.new('http://fish#baby_bob')], [], 'assay'
    assert_equal 'http://fish#bob', o.uri.to_s
    assert_equal 'fred', o.label
    assert_equal 'the fred', o.description
    assert_equal 1, o.subclasses.count
    assert_equal 'http://fish#baby_bob', o.subclasses.first.to_s
    assert_equal 'assay', o.term_type
  end

  test 'flattened' do
    o1 = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://o1')
    o2 = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://o2')
    o3 = Seek::Ontologies::OntologyClass.new(RDF::URI.new('http://o3'), nil, nil, [o1, o2])
    o4 = Seek::Ontologies::OntologyClass.new(RDF::URI.new('http://o4'), nil, nil, [o3])

    list = o4.flatten_hierarchy
    assert_equal 4, list.count
    assert_includes list, o1
    assert_includes list, o2
    assert_includes list, o3
    assert_includes list, o4
  end

  test 'hash_by_uri' do
    o1 = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://o1')
    o2 = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://o2')
    o3 = Seek::Ontologies::OntologyClass.new(RDF::URI.new('http://o3'), nil, nil, [o1, o2])
    o4 = Seek::Ontologies::OntologyClass.new(RDF::URI.new('http://o4'), nil, nil, [o3])
    hash = o4.hash_by_uri

    assert_equal 4, hash.keys.count
    assert_equal o2, hash[o2.uri.to_s]
    assert_equal o4, hash[o4.uri.to_s]
  end

  test 'hash by label' do
    o1 = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://o1'), 'o1'
    o2 = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://o2')
    o3 = Seek::Ontologies::OntologyClass.new(RDF::URI.new('http://o3'), 'O3', nil, [o1, o2])
    o4 = Seek::Ontologies::OntologyClass.new(RDF::URI.new('http://o4'), 'o4', nil, [o3])

    hash = o4.hash_by_label

    assert_equal 4, hash.keys.count
    assert_equal o1, hash['o1']

    # key should be downcased
    assert_equal o3, hash['o3']
    assert_nil hash['O3']
  end

  test 'uri as string' do
    o = Seek::Ontologies::OntologyClass.new 'http://fish#bob'
    assert o.uri.is_a?(RDF::URI)
  end

  test 'must have uri' do
    assert_raises(Exception) do
      Seek::Ontologies::OntologyClass.new(nil, 'fred')
    end
  end

  test 'label if missing' do
    o = Seek::Ontologies::OntologyClass.new RDF::URI.new('http://fish#bob_monkhouse')
    assert_equal 'Bob monkhouse', o.label
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
          cq:actions="[text:Bootstrap - Search Pagination,-,edit,annotate,copymove,insert,delete]"
          cq:layout="editbar"
          jcr:primaryType="cq:EditConfig">
    <cq:listeners
            jcr:primaryType="cq:EditListenersConfig"
            afterdelete="REFRESH_PAGE"
            afteredit="REFRESH_PAGE"
            afterinsert="REFRESH_PAGE"
            afterMove="REFRESH_PAGE"/>
</jcr:root>


text:
<?php namespace Fungku\HubSpot\Api;

class EmailEvents extends Api
{
    /**
     * Get campaign IDs for a portal.
     *
     * @param array $params Optional parameters
     * @return mixed
     */
    public function getCampaignIds($params)
    {
        $endpoint = "/email/public/v1/campaigns";

        $options['query'] = $this->getQuery($params);

        return $this->request('get', $endpoint, $options);
    }

    /**
     * Get campaign data for a given campaign.
     *
     * @param int $campaign_id
     * @param int $application_id
     * @return mixed
     */
    public function getCampaignById($campaign_id, $application_id)
    {
        $endpoint = "/email/public/v1/campaigns/{$campaign_id}";

        $options['query'] = ['appId' => $application_id];

        return $this->request('get', $endpoint, $options);
    }

    /**
     * Get email events for a campaign or recipient.
     *
     * @param array $params Optional parameters
     * @return mixed
     */
    public function get(array $params)
    {
        $endpoint = "/email/public/v1/events";

        $options['query'] = $this->getQuery($params);

        return $this->request('get', $endpoint, $options);
    }

    /**
     * Get event data for a specific event.
     *
     * @param int $id The event ID
     * @param int $created Timestamp (milliseconds) when the event was created
     * @return mixed
     */
    public function getById($id, $created)
    {
        $endpoint = "/email/public/v1/events/{$created}/{$id}";

        return $this->request('get', $endpoint);
    }

}


text:
using FluentResults;
using MediatR;

namespace ApiTemplate.Api.Application.Common.Validation
{
    public class CommandBase : IRequest<Result>
    {
        public bool IgnoreWarnings { get; set; } = false;
    }
}


text:
"""
small script that creates a nginx configuration with all reachable web container for the product database
"""
import os
from docker import Client

if __name__ == "__main__":
    cli = Client(base_url='unix://var/run/docker.sock')
    hosts = []
    for c in cli.containers(filters={"label": "productdb=web"}):
        # get a valid hostname for the nginx configuration, reachability on the same network is expected
        hosts.append(c["Names"][-1].lstrip("/"))

    with open(os.path.join("/etc/nginx/template/default.template.conf")) as f:
        content = f.read()

    server_list = "\n".join(["\tserver %s:8443 max_fails=5 fail_timeout=15s;" % host for host in hosts])

    content = """\
upstream webapp {
    least_conn;
%s
}

%s""" % (server_list, content)

    with open("/etc/nginx/conf.d/default.conf", "w+") as f:
        f.write(content)


text:
package de.mpicbg.knime.hcs.base.nodes.manip.col.splitinterval;

import java.util.LinkedList;
import java.util.List;

import org.knime.core.data.DataCell;
import org.knime.core.data.DataColumnSpec;
import org.knime.core.data.DataColumnSpecCreator;
import org.knime.core.data.DataRow;
import org.knime.core.data.DataType;
import org.knime.core.data.container.AbstractCellFactory;
import org.knime.core.data.def.BooleanCell;
import org.knime.core.data.def.BooleanCell.BooleanCellFactory;
import org.knime.core.data.def.DoubleCell;
import org.knime.core.data.def.IntervalCell;

/**
 * cell factory for Split Interval node
 *
 * @author Antje Janosch
 *
 */
public class SplitIntervalCellFactory extends AbstractCellFactory {

	// name and index of source column
	private final String m_sourceColumnName;
	private final int m_sourceIndex;
	// if checked, columns with include/exclude flags will be created
	private final boolean m_createModeColumns;

	/**
	 * constructor
	 *
	 * @param sourceColumnName		name of interval column
	 * @param sourceIndex			index of interval column in spec
	 * @param createModeColumns		setting, whether create incl./excl. flags as columns
	 */
	public SplitIntervalCellFactory(String sourceColumnName, int sourceIndex, boolean createModeColumns) {
		super();
		m_sourceColumnName = sourceColumnName;
		m_sourceIndex = sourceIndex;
		m_createModeColumns = createModeColumns;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public DataCell[] getCells(DataRow row) {

		// if interval cell has missing value
		if(row.getCell(m_sourceIndex).isMissing()) {
			if(m_createModeColumns) {
				return new DataCell[] {
						DataType.getMissingCell(),
						DataType.getMissingCell(),
						DataType.getMissingCell(),
						DataType.getMissingCell()
				};
			} else {
				return new DataCell[] {
						DataType.getMissingCell(),
						DataType.getMissingCell(),
				};
			}
		}

		IntervalCell ivCell = (IntervalCell) row.getCell(m_sourceIndex);

		double leftBound = ivCell.getLeftBound();
		double rightBound = ivCell.getRightBound();
		boolean inclLeft = ivCell.leftBoundIncluded();
		boolean inclRight = ivCell.rightBoundIncluded();

		if(m_createModeColumns) {
			return new DataCell[] {
					BooleanCellFactory.create(inclLeft),
					new DoubleCell(leftBound),
					new DoubleCell(rightBound),
					BooleanCellFactory.create(inclRight)
					};
		} else {
			return new DataCell[] {
					new DoubleCell(leftBound),
					new DoubleCell(rightBound),
					};
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public DataColumnSpec[] getColumnSpecs() {
		List<DataColumnSpec> columnsToAdd = new LinkedList<DataColumnSpec>();
		DataColumnSpecCreator colCreator;

		if(m_createModeColumns) {
			colCreator = new DataColumnSpecCreator(m_sourceColumnName + " [includeLeft]", BooleanCell.TYPE);
			columnsToAdd.add(colCreator.createSpec());
		}
		colCreator = new DataColumnSpecCreator(m_sourceColumnName + " [leftBound]", DoubleCell.TYPE);
		columnsToAdd.add(colCreator.createSpec());
		colCreator = new DataColumnSpecCreator(m_sourceColumnName + " [rightBound]", DoubleCell.TYPE);
		columnsToAdd.add(colCreator.createSpec());
		if(m_createModeColumns) {
			colCreator = new DataColumnSpecCreator(m_sourceColumnName + " [includeRight]", BooleanCell.TYPE);
			columnsToAdd.add(colCreator.createSpec());
		}

		return columnsToAdd.toArray(new DataColumnSpec[columnsToAdd.size()]);
	}

}


text:
package cn.felord.wepay.ali.sdk.api.domain;

import cn.felord.wepay.ali.sdk.api.AlipayObject;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField;

/**
 * 红包数据结构
 *
 * @author auto create
 * @version $Id: $Id
 */
public class NewsfeedMediaGiftInfo extends AlipayObject {

	private static final long serialVersionUID = 5831712676137812962L;

	/**
	 * 地址
	 */
	@ApiField("action")
	private String action;

	/**
	 * 安卓的高度
	 */
	@ApiField("adr_height")
	private String adrHeight;

	/**
	 * 安卓缩略图
	 */
	@ApiField("adr_thumb")
	private String adrThumb;

	/**
	 * 安卓宽度
	 */
	@ApiField("adr_width")
	private String adrWidth;

	/**
	 * ios高度
	 */
	@ApiField("ios_height")
	private String iosHeight;

	/**
	 * ios缩略图
	 */
	@ApiField("ios_thumb")
	private String iosThumb;

	/**
	 * ios宽度
	 */
	@ApiField("ios_width")
	private String iosWidth;

	/**
	 * 大图
	 */
	@ApiField("theme")
	private String theme;

	/**
	 * 红包类型all、f、m
	 */
	@ApiField("type")
	private String type;

	/**
	 *
Getter for the field action.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getAction() {
		return this.action;
	}
	/**
	 *
Setter for the field action.

	 *
	 * @param action a {@link java.lang.String} object.
	 */
	public void setAction(String action) {
		this.action = action;
	}

	/**
	 *
Getter for the field adrHeight.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getAdrHeight() {
		return this.adrHeight;
	}
	/**
	 *
Setter for the field adrHeight.

	 *
	 * @param adrHeight a {@link java.lang.String} object.
	 */
	public void setAdrHeight(String adrHeight) {
		this.adrHeight = adrHeight;
	}

	/**
	 *
Getter for the field adrThumb.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getAdrThumb() {
		return this.adrThumb;
	}
	/**
	 *
Setter for the field adrThumb.

	 *
	 * @param adrThumb a {@link java.lang.String} object.
	 */
	public void setAdrThumb(String adrThumb) {
		this.adrThumb = adrThumb;
	}

	/**
	 *
Getter for the field adrWidth.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getAdrWidth() {
		return this.adrWidth;
	}
	/**
	 *
Setter for the field adrWidth.

	 *
	 * @param adrWidth a {@link java.lang.String} object.
	 */
	public void setAdrWidth(String adrWidth) {
		this.adrWidth = adrWidth;
	}

	/**
	 *
Getter for the field iosHeight.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getIosHeight() {
		return this.iosHeight;
	}
	/**
	 *
Setter for the field iosHeight.

	 *
	 * @param iosHeight a {@link java.lang.String} object.
	 */
	public void setIosHeight(String iosHeight) {
		this.iosHeight = iosHeight;
	}

	/**
	 *
Getter for the field iosThumb.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getIosThumb() {
		return this.iosThumb;
	}
	/**
	 *
Setter for the field iosThumb.

	 *
	 * @param iosThumb a {@link java.lang.String} object.
	 */
	public void setIosThumb(String iosThumb) {
		this.iosThumb = iosThumb;
	}

	/**
	 *
Getter for the field iosWidth.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getIosWidth() {
		return this.iosWidth;
	}
	/**
	 *
Setter for the field iosWidth.

	 *
	 * @param iosWidth a {@link java.lang.String} object.
	 */
	public void setIosWidth(String iosWidth) {
		this.iosWidth = iosWidth;
	}

	/**
	 *
Getter for the field theme.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getTheme() {
		return this.theme;
	}
	/**
	 *
Setter for the field theme.

	 *
	 * @param theme a {@link java.lang.String} object.
	 */
	public void setTheme(String theme) {
		this.theme = theme;
	}

	/**
	 *
Getter for the field type.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getType() {
		return this.type;
	}
	/**
	 *
Setter for the field type.

	 *
	 * @param type a {@link java.lang.String} object.
	 */
	public void setType(String type) {
		this.type = type;
	}

}


text:
package io.opentelemetry.sdk.trace;

import io.opentelemetry.api.internal.Utils;
import io.opentelemetry.api.trace.Span;

/** Builder for {@link SpanLimits}. */
public final class SpanLimitsBuilder {

  private static final int DEFAULT_SPAN_MAX_NUM_ATTRIBUTES = 128;
  private static final int DEFAULT_SPAN_MAX_NUM_EVENTS = 128;
  private static final int DEFAULT_SPAN_MAX_NUM_LINKS = 128;
  private static final int DEFAULT_SPAN_MAX_NUM_ATTRIBUTES_PER_EVENT = 128;
  private static final int DEFAULT_SPAN_MAX_NUM_ATTRIBUTES_PER_LINK = 128;

  private int maxNumAttributes = DEFAULT_SPAN_MAX_NUM_ATTRIBUTES;
  private int maxNumEvents = DEFAULT_SPAN_MAX_NUM_EVENTS;
  private int maxNumLinks = DEFAULT_SPAN_MAX_NUM_LINKS;
  private int maxNumAttributesPerEvent = DEFAULT_SPAN_MAX_NUM_ATTRIBUTES_PER_EVENT;
  private int maxNumAttributesPerLink = DEFAULT_SPAN_MAX_NUM_ATTRIBUTES_PER_LINK;
  private int maxAttributeValueLength = SpanLimits.DEFAULT_SPAN_MAX_ATTRIBUTE_LENGTH;

  SpanLimitsBuilder() {}

  /**
   * Sets the max number of attributes per {@link Span}.
   *
   * @param maxNumberOfAttributes the max number of attributes per {@link Span}. Must be positive.
   * @return this.
   * @throws IllegalArgumentException if {@code maxNumberOfAttributes} is not positive.
   */
  public SpanLimitsBuilder setMaxNumberOfAttributes(int maxNumberOfAttributes) {
    Utils.checkArgument(maxNumberOfAttributes > 0, "maxNumberOfAttributes must be greater than 0");
    this.maxNumAttributes = maxNumberOfAttributes;
    return this;
  }

  /**
   * Sets the max number of events per {@link Span}.
   *
   * @param maxNumberOfEvents the max number of events per {@link Span}. Must be positive.
   * @return this.
   * @throws IllegalArgumentException if {@code maxNumberOfEvents} is not positive.
   */
  public SpanLimitsBuilder setMaxNumberOfEvents(int maxNumberOfEvents) {
    Utils.checkArgument(maxNumberOfEvents > 0, "maxNumberOfEvents must be greater than 0");
    this.maxNumEvents = maxNumberOfEvents;
    return this;
  }

  /**
   * Sets the max number of links per {@link Span}.
   *
   * @param maxNumberOfLinks the max number of links per {@link Span}. Must be positive.
   * @return this.
   * @throws IllegalArgumentException if {@code maxNumberOfLinks} is not positive.
   */
  public SpanLimitsBuilder setMaxNumberOfLinks(int maxNumberOfLinks) {
    Utils.checkArgument(maxNumberOfLinks > 0, "maxNumberOfLinks must be greater than 0");
    this.maxNumLinks = maxNumberOfLinks;
    return this;
  }

  /**
   * Sets the max number of attributes per event.
   *
   * @param maxNumberOfAttributesPerEvent the max number of attributes per event. Must be positive.
   * @return this.
   * @throws IllegalArgumentException if {@code maxNumberOfAttributesPerEvent} is not positive.
   */
  public SpanLimitsBuilder setMaxNumberOfAttributesPerEvent(int maxNumberOfAttributesPerEvent) {
    Utils.checkArgument(
        maxNumberOfAttributesPerEvent > 0, "maxNumberOfAttributesPerEvent must be greater than 0");
    this.maxNumAttributesPerEvent = maxNumberOfAttributesPerEvent;
    return this;
  }

  /**
   * Sets the max number of attributes per link.
   *
   * @param maxNumberOfAttributesPerLink the max number of attributes per link. Must be positive.
   * @return this.
   * @throws IllegalArgumentException if {@code maxNumberOfAttributesPerLink} is not positive.
   */
  public SpanLimitsBuilder setMaxNumberOfAttributesPerLink(int maxNumberOfAttributesPerLink) {
    Utils.checkArgument(
        maxNumberOfAttributesPerLink > 0, "maxNumberOfAttributesPerLink must be greater than 0");
    this.maxNumAttributesPerLink = maxNumberOfAttributesPerLink;
    return this;
  }

  /**
   * Sets the max number of characters for string attribute values. For string array attribute
   * values, applies to each entry individually.
   *
   * @param maxAttributeValueLength the max number of characters for attribute strings. Must not be
   *     negative.
   * @return this.
   * @throws IllegalArgumentException if {@code maxAttributeValueLength} is negative.
   */
  public SpanLimitsBuilder setMaxAttributeValueLength(int maxAttributeValueLength) {
    Utils.checkArgument(
        maxAttributeValueLength > -1, "maxAttributeValueLength must be non-negative");
    this.maxAttributeValueLength = maxAttributeValueLength;
    return this;
  }

  /** Builds and returns a {@link SpanLimits} with the values of this builder. */
  public SpanLimits build() {
    return SpanLimits.create(
        maxNumAttributes,
        maxNumEvents,
        maxNumLinks,
        maxNumAttributesPerEvent,
        maxNumAttributesPerLink,
        maxAttributeValueLength);
  }
}


text:
#include "src/actions/ver.h"

#include <iostream>
#include <string>

#include "modsecurity/actions/action.h"
#include "modsecurity/transaction.h"
#include "modsecurity/rule.h"
#include "src/macro_expansion.h"

namespace modsecurity {
namespace actions {

bool Ver::evaluate(Rule *rule, Transaction *transaction) {
    rule->m_ver = m_parser_payload;
    return true;
}

}  // namespace actions
}  // namespace modsecurity


text:
<?php

namespace MYPS\Security\DoctrineBehaviors\DI;

use Kdyby\Events\DI\EventsExtension;
use Nette;
use Nette\DI\CompilerExtension;

class UserAccessibleExtension extends CompilerExtension
{

	public function loadConfiguration()
	{
		$builder = $this->getContainerBuilder();

		$builder->addDefinition($this->prefix('listener'))
			->setClass('MYPS\Security\DoctrineBehaviors\ORM\UserAccessibleListener', [
				'@' . $this->getClassAnalyzer()->getClass()
			])
			->setAutowired(FALSE)
			->addTag(EventsExtension::TAG_SUBSCRIBER);
	}

    protected function getClassAnalyzer()
    {
        $builder = $this->getContainerBuilder();
        if ($builder->hasDefinition('knp.classAnalyzer')) {
            return $builder->getDefinition('knp.classAnalyzer');
        }
        return $builder->addDefinition('knp.classAnalyzer')
            ->setClass('Knp\DoctrineBehaviors\Reflection\ClassAnalyzer');
    }

}


text:
package consulo.desktop.swt.ui.impl.layout;

import consulo.desktop.swt.ui.impl.layout.data.LayoutDataWithSize;
import consulo.ui.Size;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Layout;

/**
 * Port of AWT BorderLayout to SWT.
 *
 * @author Yannick Saillet
 */
class BorderLayout extends Layout {
  public static class BorderData implements LayoutDataWithSize {
    public String position;

    public int width = -1;

    public int height = -1;

    public BorderData(String position) {
      this.position = position;
    }

    @Override
    public void setSize(Size size) {
      width = size.getWidth();
      height = size.getHeight();
    }

    @Override
    public String toString() {
      return "BorderData{" + "position='" + position + '\'' + '}';
    }
  }

  public final static String CENTER = "Center";
  public final static String EAST = "East";
  public final static String NORTH = "North";
  public final static String SOUTH = "South";
  public final static String WEST = "West";

  //-----------------------

  private int hgap, vgap;
  private Control centerChild, eastChild, northChild, southChild, westChild;

  public BorderLayout() {
    super();
  }

  public BorderLayout(int hgap, int vgap) {
    this.hgap = hgap;
    this.vgap = vgap;
  }

  @Override
  protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
    readLayoutData(composite);
    Point size = new Point(0, 0);

    Point preferredSize;
    if (northChild != null) {
      preferredSize = getPreferredSize(northChild, wHint, SWT.DEFAULT, flushCache);
      size.y += preferredSize.y + vgap;
    }

    if (southChild != null) {
      preferredSize = getPreferredSize(southChild, wHint, SWT.DEFAULT, flushCache);
      size.y += preferredSize.y + vgap;
    }

    if (westChild != null) {
      preferredSize = getPreferredSize(westChild, SWT.DEFAULT, hHint, flushCache);
      size.x += preferredSize.x + hgap;

      if (preferredSize.y > size.y) {
        size.y = preferredSize.y;
      }
    }

    if (eastChild != null) {
      preferredSize = getPreferredSize(eastChild, SWT.DEFAULT, hHint, flushCache);
      size.x += preferredSize.x + hgap;

      if (preferredSize.y > size.y) {
        size.y = preferredSize.y;
      }
    }

    if (centerChild != null) {
      preferredSize = getPreferredSize(centerChild, wHint, hHint, flushCache);
      size.x += preferredSize.x;
      size.y += preferredSize.y;
    }
    return size;
  }

  @Override
  protected void layout(Composite composite, boolean flushCache) {
    readLayoutData(composite);
    Rectangle clientArea = composite.getClientArea();
    int top = clientArea.y;
    int bottom = clientArea.y + clientArea.height;
    int left = clientArea.x;
    int right = clientArea.x + clientArea.width;

    Point preferredSize;
    if (northChild != null) {
      preferredSize = getPreferredSize(northChild, clientArea.width, SWT.DEFAULT, flushCache);
      northChild.setBounds(left, top, right - left, preferredSize.y);
      top += preferredSize.y + vgap;
    }

    if (southChild != null) {
      preferredSize = getPreferredSize(southChild, clientArea.width, SWT.DEFAULT, flushCache);
      southChild.setBounds(left, bottom - preferredSize.y, right - left, preferredSize.y);
      bottom -= preferredSize.y + vgap;
    }

    if (westChild != null) {
      preferredSize = getPreferredSize(westChild, SWT.DEFAULT, bottom - top, flushCache);
      westChild.setBounds(left, top, preferredSize.x, bottom - top);
      left += preferredSize.x + hgap;
    }

    if (eastChild != null) {
      preferredSize = getPreferredSize(eastChild, SWT.DEFAULT, bottom - top, flushCache);
      eastChild.setBounds(right - preferredSize.x, top, preferredSize.x, bottom - top);
      right -= preferredSize.x + hgap;
    }

    if (centerChild != null) {
      centerChild.setBounds(left, top, right - left, bottom - top);
    }
  }

  /**
   * Read the layout data of the children of a composite.
   *
   * @param composite the parent composite
   */
  private void readLayoutData(Composite composite) {
    northChild = southChild = eastChild = westChild = centerChild = null;
    Control[] children = composite.getChildren();
    for (int i = 0; i < children.length; i++) {
      //if (!children[i].isVisible())
      //  continue;

      BorderData layoutData = (BorderData)children[i].getLayoutData();
      String position = layoutData.position;

      if (NORTH.equals(position)) {
        northChild = children[i];
      }
      else if (SOUTH.equals(position)) {
        southChild = children[i];
      }
      else if (EAST.equals(position)) {
        eastChild = children[i];
      }
      else if (WEST.equals(position)) {
        westChild = children[i];
      }
      else {
        centerChild = children[i];
      }
    }
  }

  protected Point getPreferredSize(Control control, int wHint, int hHint, boolean changed) {
    if (!control.isVisible()) {
      return new Point(0, 0);
    }

    Point point = control.computeSize(wHint, hHint, changed);

    Object layoutData = control.getLayoutData();
    if (layoutData instanceof BorderData data) {
      if (data.width != -1) {
        point.x = data.width;
      }

      if (data.height != -1) {
        point.y = data.height;
      }
    }
    return point;
  }

  /**
   * @return Returns the hgap.
   */
  public int getHgap() {
    return hgap;
  }

  /**
   * @param hgap The hgap to set.
   */
  public void setHgap(int hgap) {
    this.hgap = hgap;
  }

  /**
   * @return Returns the vgap.
   */
  public int getVgap() {
    return vgap;
  }

  /**
   * @param vgap The vgap to set.
   */
  public void setVgap(int vgap) {
    this.vgap = vgap;
  }
}


text:
import logging
import sys

from pyflink.common.time import Instant

from pyflink.common import Types
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.table import (DataTypes, TableDescriptor, Schema, StreamTableEnvironment)
from pyflink.table.expressions import col, row_interval, CURRENT_ROW
from pyflink.table.window import Over

def tumble_window_demo():
    env = StreamExecutionEnvironment.get_execution_environment()
    env.set_parallelism(1)
    t_env = StreamTableEnvironment.create(stream_execution_environment=env)

    # define the source with watermark definition
    ds = env.from_collection(
        collection=[
            (Instant.of_epoch_milli(1000), 'Alice', 110.1),
            (Instant.of_epoch_milli(4000), 'Bob', 30.2),
            (Instant.of_epoch_milli(3000), 'Alice', 20.0),
            (Instant.of_epoch_milli(2000), 'Bob', 53.1),
            (Instant.of_epoch_milli(5000), 'Alice', 13.1),
            (Instant.of_epoch_milli(3000), 'Bob', 3.1),
            (Instant.of_epoch_milli(7000), 'Bob', 16.1),
            (Instant.of_epoch_milli(10000), 'Alice', 20.1)
        ],
        type_info=Types.ROW([Types.INSTANT(), Types.STRING(), Types.FLOAT()]))

    table = t_env.from_data_stream(
        ds,
        Schema.new_builder()
              .column_by_expression("ts", "CAST(f0 AS TIMESTAMP(3))")
              .column("f1", DataTypes.STRING())
              .column("f2", DataTypes.FLOAT())
              .watermark("ts", "ts - INTERVAL '3' SECOND")
              .build()
    ).alias("ts", "name", "price")

    # define the sink
    t_env.create_temporary_table(
        'sink',
        TableDescriptor.for_connector('print')
                       .schema(Schema.new_builder()
                               .column('name', DataTypes.STRING())
                               .column('total_price', DataTypes.FLOAT())
                               .build())
                       .build())

    # define the over window operation
    table = table.over_window(
        Over.partition_by(col("name"))
            .order_by(col("ts"))
            .preceding(row_interval(2))
            .following(CURRENT_ROW)
            .alias('w')) \
        .select(col('name'), col('price').max.over(col('w')))

    # submit for execution
    table.execute_insert('sink') \
         .wait()
    # remove .wait if submitting to a remote cluster, refer to
    # https://nightlies.apache.org/flink/flink-docs-stable/docs/dev/python/faq/#wait-for-jobs-to-finish-when-executing-jobs-in-mini-cluster
    # for more details

if __name__ == '__main__':
    logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")

    tumble_window_demo()


text:
.class public interface abstract Landroid/hardware/hdmi/IHdmiControlCallback;
.super Ljava/lang/Object;
.source "IHdmiControlCallback.java"

# interfaces
.implements Landroid/os/IInterface;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/hardware/hdmi/IHdmiControlCallback$Stub;
    }
.end annotation

# virtual methods
.method public abstract onComplete(I)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method


text:
void startupLog(const char* msg)
{
    printXY(0, 0, msg);
}

void printErrorAndDie(const char *message)
{
    if (strlen(message) == 0)
        message = "printErrorAndDie called with zero length message";

    displayMultilineText(message);

    exit(1);
}

void printLuaErrorAndDie(lua_State *L, const char *errorContext)
{
    // TODO errorContext?
    printErrorAndDie(lua_tostring(L, -1));
}

void outOfMemory(void)
{
    printErrorAndDie("out of memory");
}

static int luaPanicHook(lua_State *L)
{
    // TODO use paging
    printXY(0, 3, "Lua panic:");
    printXY(0, 4, (char*)lua_tostring(L, -1));

    getKey();
    return 0;  // return to Lua to abort
}

struct luaL_Reg *
copyLuaFunctionTable(const luaL_Reg *sourceEntries, const char *prefixToDrop)
{
    int count = 0;
    luaL_Reg *entry = (luaL_Reg *)sourceEntries;
    for (; entry -> name; ++entry, ++count);

    size_t rawSize = (count + 1) * sizeof(luaL_Reg);
    char* rawStorage = malloc(rawSize);
    memset(rawStorage, 0, rawSize);

    luaL_Reg* copy = (luaL_Reg*)rawStorage;

    const luaL_Reg *original = sourceEntries;
    while (original -> name)
    {
        const char* name = original -> name;
        if (prefixToDrop)
        {
            size_t prefixLength = strlen(prefixToDrop);
            if (strncmp(name, prefixToDrop, prefixLength) == 0)
                name = name + prefixLength;
        }

        copy -> name = name;
        copy -> func = original -> func;
        ++original;
        ++copy;
    }

    return (struct luaL_Reg *)rawStorage;
}

int genericMain(void)
{
    int status;
    lua_State *L = NULL;

    clearScreen();
    startupLog("Initializing...");

    L = luaL_newstate();
    lua_atpanic(L, &luaPanicHook);

    luaL_openlibs(L);

    // register the lua modules provided from the C side
    platformLuaBindingSetupHook(L);

    {
        // set lua load path
        lua_getglobal(L, "package");
        lua_pushstring(L, "./lua/?.lua;?/init.lua");
        lua_setfield(L, -2, "path");
    }

    startupLog("Running script...");

    squished_lua[squished_lua_len - 1] = 0;
    status = luaL_dostring(L, squished_lua);
    if (status)
        printLuaErrorAndDie(L, "running main lua script");

    clearScreen();
    startupLog("Cleaning up...");

    lua_pop(L, 1);  // Take the returned value out of the stack
    lua_close(L);   // Cya, Lua

    startupLog("Exiting...");
    return 0;
}


text:
#ifndef SIMD_H
#define SIMD_H

#include <snlsys/snlsys.h>

#if defined(SNLMATH_SHARED_BUILD)
  #define SNLMATH_API EXPORT_SYM
#else
  #define SNLMATH_API IMPORT_SYM
#endif

#ifdef SIMD_SSE2
  #include "sse/sse.h"
#else
  #error unsupported_platform
#endif

#endif /* SIMD_H */


text:
package com.rninstabugsdk.rninstabugsdk;

import android.content.Context;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class InstabugSDKPackage implements ReactPackage {

  private Context mContext;

  public InstabugSDKPackage(Context context) {
    mContext = context;
  }

  @Override
  public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    List<NativeModule> modules = new ArrayList<>();
    modules.add(new com.rninstabugsdk.rninstabugsdk.InstabugSDKModule(reactContext, mContext));
    return modules;
  }

  public List<Class<? extends JavaScriptModule>> createJSModules() {
    return Collections.emptyList();
  }

  @Override
  public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
  }

}


text:
movies = {
  Memento: 3,
  Primer: 4,
  Ishtar: 1
}

puts "What would you like to do?"
puts "-- Type 'add' to add a movie."
puts "-- Type 'update' to update a movie."
puts "-- Type 'display' to display all movies."
puts "-- Type 'delete' to delete a movie."

choice = gets.chomp.downcase
case choice
when 'add'
  puts "What movie do you want to add?"
  title = gets.chomp
  if movies[title.to_sym].nil?
    puts "What's the rating? (Type a number 0 to 4.)"
    rating = gets.chomp
    movies[title.to_sym] = rating.to_i
    puts "Added!"
  else
    puts "That movie already exists! Its rating is #{movies[title.to_sym]}."
  end
when 'update'
  puts "What movie do you want to update?"
  title = gets.chomp
  if movies[title.to_sym].nil?
    puts "Movie not found!"
  else
    puts "What's the new rating? (Type a number 0 to 4.)"
    rating = gets.chomp
    movies[title.to_sym] = rating.to_i
    puts "Updated!"
  end
when 'display'
  movies.each do |movie, rating|
    puts "Movies!"
  end
when 'delete'
  puts "What movie do you want to delete?"
  title = gets.chomp
  if movies[title.to_sym].nil?
    puts "Movie not found!"
  else
    movies.delete(title.to_sym)
    puts "Deleted!"
  end
else
  puts "Error"
end


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

-->
<resources>

    <!-- ### ACTION MODE ======================================================================= -->

    <dimen name="ui_action_button_close_mode_margin_start">12dp</dimen>
    <dimen name="ui_action_button_close_mode_margin_end">12dp</dimen>
</resources>


text:
import { remote } from 'electron';

async function showOpenDialog(opts) {
  return new Promise((fulfill, reject) => {
    let { dialog } = remote;
    dialog.showOpenDialog(opts, selections => {
      fulfill(selections);
    });
  });
}

export default {
  async getDirectoryAsync(currentDirectory) {
    let selections = await showOpenDialog({
      defaultPath: currentDirectory,
      properties: ['openDirectory', 'createDirectory'],
    });

    if (selections == null) {
      return null;
    }

    return selections[0];
  },

  async openExpAsync() {
    let selections = await showOpenDialog({
      properties: ['openDirectory'],
    });

    if (selections == null) {
      console.log('No selections; cancelled Open Exp');
      return null;
    }

    let projectRoot = selections[0];
    return projectRoot;
  },
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/locations/specific-locations/bodies-of-water/pacific-ocean" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/locations/specific-locations/bodies-of-water/pacific-ocean</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Pacific Ocean</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/locations/specific-locations/bodies-of-water/pacific-ocean</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/locations/specific-locations/bodies-of-water/pacific-ocean</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
package org.deeplearning4j.graph.data;

import org.deeplearning4j.graph.api.Edge;

/** EdgeLineProcessor is used during data loading from a file, where each edge is on a separate line<br>
 * Provides flexibility in loading graphs with arbitrary objects/properties that can be represented in a text format
 * Can also be used handle conversion of edges between non-numeric vertices to an appropriate numbered format
 * @param <E> type of the edge returned
 */
public interface EdgeLineProcessor<E> {

    /** Process a line of text into an edge.
     * May return null if line is not a valid edge (i.e., comment line etc)
     */
    Edge<E> processLine(String line);

}


text:
by Ortal Shnaps & Eyal Perry.

Application of the method described in http://psb.stanford.edu/psb-online/proceedings/psb16/shnaps.pdf

To run: ./inferer.py

See inferer.py source for configurations and data sources.


text: from .flaskapp import app


text:
import Main from '../../app/main.desktop'
// order of the above 2 must NOT change. needed for patching / hot loading to be correct
import * as NotificationsGen from '../../actions/notifications-gen'
import * as React from 'react'
import ReactDOM from 'react-dom'
import RemoteProxies from '../remote/proxies.desktop'
import Root from './container.desktop'
import makeStore from '../../store/configure-store'
import {makeEngine} from '../../engine'
import {disable as disableDragDrop} from '../../util/drag-drop'
import flags from '../../util/feature-flags'
import {dumpLogs} from '../../actions/platform-specific/index.desktop'
import {initDesktopStyles} from '../../styles/index.desktop'
import {_setDarkModePreference} from '../../styles/dark-mode'
import {isWindows} from '../../constants/platform'
import {useSelector} from '../../util/container'
import {isDarkMode} from '../../constants/config'
import type {TypedActions} from '../../actions/typed-actions-gen'
import KB2 from '../../util/electron.desktop'

const {ipcRendererOn, requestWindowsStartService, appStartedUp} = KB2.functions

// node side plumbs through initial pref so we avoid flashes
const darkModeFromNode = window.location.search.match(/darkModePreference=(alwaysLight|alwaysDark|system)/)

if (darkModeFromNode) {
  const dm = darkModeFromNode[1]
  switch (dm) {
    case 'alwaysLight':
    case 'alwaysDark':
    case 'system':
      _setDarkModePreference(dm)
  }
}

// Top level HMR accept
if (module.hot) {
  module.hot.accept()
}

let _store: any

const setupStore = () => {
  let store = _store
  let initListeners: any
  if (!_store) {
    const configured = makeStore()
    store = configured.store
    initListeners = configured.initListeners

    _store = store
    if (__DEV__ && flags.admin) {
      // @ts-ignore codemode issue
      window.DEBUGStore = _store
    }
  }

  return {initListeners, store}
}

const setupApp = (store, initListeners) => {
  disableDragDrop()
  const eng = makeEngine(store.dispatch)
  initListeners()
  eng.listenersAreReady()

  ipcRendererOn?.('KBdispatchAction', (_: any, action: TypedActions) => {
    // we MUST convert this else we'll run into issues with redux. See https://github.com/rackt/redux/issues/830
    // This is because this is touched due to the remote proxying. We get a __proto__ which causes the _.isPlainObject check to fail. We use
    setTimeout(() => {
      try {
        store.dispatch({
          payload: action.payload,
          type: action.type,
        })
      } catch (_) {}
    }, 0)
  })

  // See if we're connected, and try starting keybase if not
  if (isWindows) {
    setTimeout(() => {
      requestWindowsStartService?.()
    }, 0)
  }

  // After a delay dump logs in case some startup stuff happened
  setTimeout(() => {
    dumpLogs()
      .then(() => {})
      .catch(() => {})
  }, 5 * 1000)

  // Handle notifications from the service
  store.dispatch(NotificationsGen.createListenForNotifications())

  appStartedUp?.()
}

const FontLoader = () => (

kb

source code pro 500

source code pro 600

keybase 400

keybase 400 i

keybase 600

keybase 600 i

keybase 700

keybase 700 i

)

let store

const DarkCSSInjector = () => {
  const isDark = useSelector(state => isDarkMode(state.config))
  React.useEffect(() => {
    // inject it in body so modals get darkMode also
    if (isDark) {
      document.body.classList.add('darkMode')
      document.body.classList.remove('lightMode')
    } else {
      document.body.classList.remove('darkMode')
      document.body.classList.add('lightMode')
    }
  }, [isDark])
  return null
}

const render = (Component = Main) => {
  const root = document.getElementById('root')
  if (!root) {
    throw new Error('No root element?')
  }

  // Note we get warnings about moving to createRoot but react-native-web doesn't actually
  // work with it yet, the nav is broken when enabled
  ReactDOM.render(
    <Root store={store}>
      <DarkCSSInjector />
      <RemoteProxies />
      <FontLoader />

        <Component />

    </Root>,
    root
  )
}

const setupHMR = _ => {
  const accept = module.hot && module.hot.accept
  if (!accept) {
    return
  }

  const refreshMain = () => {
    try {
      const NewMain = require('../../app/main.desktop').default
      render(NewMain)
    } catch (_) {}
  }

  accept(['../../app/main.desktop'], refreshMain)
  accept('../../common-adapters/index.js', () => {})
}

const load = () => {
  if (global.DEBUGLoaded) {
    // only load once
    console.log('Bail on load() on HMR')
    return
  }
  global.DEBUGLoaded = true
  initDesktopStyles()
  const temp = setupStore()
  const {initListeners} = temp
  store = temp.store
  setupApp(store, initListeners)
  setupHMR(store)
  render()
}

load()