text:
function asyncFunction() {
	if (1 == 1){
		return Promise.resolve("OK1");
	}
	else{
		return Promise.reject(new Error("Wrong1"));
	}
}
/*
 *Equal to this version

function asyncFunction() {
	return new Promise(function(res,rej){
		if (1 === 1){
			res("OK");
		}
		else{
			rej(new Error("Wrong"));
		}
	});
}
*/
function anotherAsyncFunction(){
	if (2 == 2){
		return Promise.resolve("OK2");
	}
	else{
		return Promise.reject(new Error("Wrong2"));
	}
}

//Use a Promise array.call then() when all Promise is resolve->then() or reject->catch()
Promise.all([asyncFunction(),anotherAsyncFunction()]).then(function(val){
	console.log("All:" + val);
}).catch(function(err){
	console.error("All:" + err);
})

//Use a Promise array.call then() when any Promise is resolve->then() or reject->catch()
Promise.race([asyncFunction(),anotherAsyncFunction()]).then(function(val){
	console.log("Race:" + val);
}).catch(function(err){
	console.error("Race:" + err);
});

console.log("This call first.Promise is async");


text:
package org.xeustechnologies.jtar;

import java.io.File;
import java.util.Date;

/**
 * @author Kamran Zafar
 *
 */
public class TarEntry {
    protected File file;
    protected TarHeader header;

    private TarEntry() {
        this.file = null;
        this.header = new TarHeader();
    }

    public TarEntry(File file, String entryName) {
        this();
        this.file = file;
        this.extractTarHeader( entryName );
    }

    public TarEntry(byte[] headerBuf) {
        this();
        this.parseTarHeader( headerBuf );
    }

    public boolean equals(TarEntry it) {
        return this.header.name.toString().equals( it.header.name.toString() );
    }

    public boolean isDescendent(TarEntry desc) {
        return desc.header.name.toString().startsWith( this.header.name.toString() );
    }

    public TarHeader getHeader() {
        return this.header;
    }

    public String getName() {
        return this.header.name.toString();
    }

    public void setName(String name) {
        this.header.name = new StringBuffer( name );
    }

    public int getUserId() {
        return this.header.userId;
    }

    public void setUserId(int userId) {
        this.header.userId = userId;
    }

    public int getGroupId() {
        return this.header.groupId;
    }

    public void setGroupId(int groupId) {
        this.header.groupId = groupId;
    }

    public String getUserName() {
        return this.header.userName.toString();
    }

    public void setUserName(String userName) {
        this.header.userName = new StringBuffer( userName );
    }

    public String getGroupName() {
        return this.header.groupName.toString();
    }

    public void setGroupName(String groupName) {
        this.header.groupName = new StringBuffer( groupName );
    }

    public void setIds(int userId, int groupId) {
        this.setUserId( userId );
        this.setGroupId( groupId );
    }

    public void setModTime(long time) {
        this.header.modTime = time / 1000;
    }

    public void setModTime(Date time) {
        this.header.modTime = time.getTime() / 1000;
    }

    public Date getModTime() {
        return new Date( this.header.modTime * 1000 );
    }

    public File getFile() {
        return this.file;
    }

    public long getSize() {
        return this.header.size;
    }

    public void setSize(long size) {
        this.header.size = size;
    }

    /**
     * Checks if the org.xeustechnologies.jtar entry is a directory
     *
     * @return
     */
    public boolean isDirectory() {
        if( this.file != null )
            return this.file.isDirectory();

        if( this.header != null ) {
            if( this.header.linkFlag == TarHeader.LF_DIR )
                return true;

            if( this.header.name.toString().endsWith( "/" ) )
                return true;
        }

        return false;
    }

    /**
     * Extract header from File
     *
     * @param entryName
     */
    public void extractTarHeader(String entryName) {
        String name = entryName;

        name = name.replace( File.separatorChar, '/' );

        if( name.startsWith( "/" ) )
            name = name.substring( 1 );

        header.linkName = new StringBuffer( "" );

        header.name = new StringBuffer( name );

        if( file.isDirectory() ) {
            header.mode = 040755;
            header.linkFlag = TarHeader.LF_DIR;
            if( header.name.charAt( header.name.length() - 1 ) != '/' )
                header.name.append( "/" );
        } else {
            header.mode = 0100644;
            header.linkFlag = TarHeader.LF_NORMAL;
        }

        header.size = file.length();
        header.modTime = file.lastModified() / 1000;
        header.checkSum = 0;
        header.devMajor = 0;
        header.devMinor = 0;
    }

    /**
     * Calculate checksum
     *
     * @param buf
     * @return
     */
    public long computeCheckSum(byte[] buf) {
        long sum = 0;

        for( int i = 0; i < buf.length; ++i ) {
            sum += 255 & buf[i];
        }

        return sum;
    }

    /**
     * Writes the header to the byte buffer
     *
     * @param outbuf
     */
    public void writeEntryHeader(byte[] outbuf) {
        int offset = 0;

        offset = TarHeader.getNameBytes( this.header.name, outbuf, offset, TarHeader.NAMELEN );
        offset = Octal.getOctalBytes( this.header.mode, outbuf, offset, TarHeader.MODELEN );
        offset = Octal.getOctalBytes( this.header.userId, outbuf, offset, TarHeader.UIDLEN );
        offset = Octal.getOctalBytes( this.header.groupId, outbuf, offset, TarHeader.GIDLEN );

        long size = this.header.size;

        offset = Octal.getLongOctalBytes( size, outbuf, offset, TarHeader.SIZELEN );
        offset = Octal.getLongOctalBytes( this.header.modTime, outbuf, offset, TarHeader.MODTIMELEN );

        int csOffset = offset;
        for( int c = 0; c < TarHeader.CHKSUMLEN; ++c )
            outbuf[offset++] = (byte) ' ';

        outbuf[offset++] = this.header.linkFlag;

        offset = TarHeader.getNameBytes( this.header.linkName, outbuf, offset, TarHeader.NAMELEN );
        offset = TarHeader.getNameBytes( this.header.magic, outbuf, offset, TarHeader.MAGICLEN );
        offset = TarHeader.getNameBytes( this.header.userName, outbuf, offset, TarHeader.UNAMELEN );
        offset = TarHeader.getNameBytes( this.header.groupName, outbuf, offset, TarHeader.GNAMELEN );
        offset = Octal.getOctalBytes( this.header.devMajor, outbuf, offset, TarHeader.DEVLEN );
        offset = Octal.getOctalBytes( this.header.devMinor, outbuf, offset, TarHeader.DEVLEN );

        for( ; offset < outbuf.length; )
            outbuf[offset++] = 0;

        long checkSum = this.computeCheckSum( outbuf );

        Octal.getCheckSumOctalBytes( checkSum, outbuf, csOffset, TarHeader.CHKSUMLEN );
    }

    /**
     * Parses the tar header to the byte buffer
     *
     * @param header
     * @param bh
     */
    public void parseTarHeader(byte[] bh) {
        int offset = 0;

        header.name = TarHeader.parseName( bh, offset, TarHeader.NAMELEN );
        offset += TarHeader.NAMELEN;

        header.mode = (int) Octal.parseOctal( bh, offset, TarHeader.MODELEN );
        offset += TarHeader.MODELEN;

        header.userId = (int) Octal.parseOctal( bh, offset, TarHeader.UIDLEN );
        offset += TarHeader.UIDLEN;

        header.groupId = (int) Octal.parseOctal( bh, offset, TarHeader.GIDLEN );
        offset += TarHeader.GIDLEN;

        header.size = Octal.parseOctal( bh, offset, TarHeader.SIZELEN );
        offset += TarHeader.SIZELEN;

        header.modTime = Octal.parseOctal( bh, offset, TarHeader.MODTIMELEN );
        offset += TarHeader.MODTIMELEN;

        header.checkSum = (int) Octal.parseOctal( bh, offset, TarHeader.CHKSUMLEN );
        offset += TarHeader.CHKSUMLEN;

        header.linkFlag = bh[offset++];

        header.linkName = TarHeader.parseName( bh, offset, TarHeader.NAMELEN );
        offset += TarHeader.NAMELEN;

        header.magic = TarHeader.parseName( bh, offset, TarHeader.MAGICLEN );
        offset += TarHeader.MAGICLEN;

        header.userName = TarHeader.parseName( bh, offset, TarHeader.UNAMELEN );
        offset += TarHeader.UNAMELEN;

        header.groupName = TarHeader.parseName( bh, offset, TarHeader.GNAMELEN );
        offset += TarHeader.GNAMELEN;

        header.devMajor = (int) Octal.parseOctal( bh, offset, TarHeader.DEVLEN );
        offset += TarHeader.DEVLEN;

        header.devMinor = (int) Octal.parseOctal( bh, offset, TarHeader.DEVLEN );
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * public script for report
 *
 *  -- namespaces --
 *  $ : jQuery
 *  l : message resource
 *  hbs : handlebars
 *  Chart : Chart
 */
(function ($, l, hbs, Chart) {
    $.fn.extend({
        scoreTable: function (data) {
            var table = $(this),
                thead = $('thead', table),
                tbody = $('tbody', table);

            var numericCols = thead.find('th').toArray().map(function (th, i) {
                var numeric = $(th).hasClass('numeric');
                return numeric ? i : null
            }).filter(function (col) {
                    return col != null;
                });

            var tmpl = {
                bodyRow: hbs.templates['score-report-table-body-row']
            };
            var len = data.length;
            $('#score-table-count').text(['1-' + len, '/', len].join('')).hide();
            tbody.htmlHandlebars(tmpl.bodyRow, data);
            table.sortableTable(function () {

            }, function (v1, v2, col) {
                var isNumeric = numericCols.indexOf(col) != -1;
                if (isNumeric) {
                    return v1 - v1;
                } else {
                    return v1.localeCompare(v2);
                }
            });

            return table
        },
        scoreListSection: function (data) {
            var section = $(this),
                table = $('#score-table', section);

            data = data
                .sort(function (a, b) {
                    return Number(b.total) - Number(a.total);
                })
                .map(function (data, i) {
                    data['rank'] = (i + 1);
                    return data;
                });

            table
                .scoreTable(data)
                .trigger('resize-book');

            return section;
        },
        prepareDraw: function () {
            var canvas = $(this);
            canvas.removeAttr('style')
                .removeAttr('width')
                .removeAttr('height');
            var
                w = canvas.width(),
                h = canvas.height();
            canvas.attr({
                width: w,
                height: h
            });
            return canvas[0].getContext('2d');
        },
        top10ChartCanvas: function (data) {
            var canvas = $(this);

            data = data.slice(0, 10);
            canvas.data({
                labels: data.map(function (data) {
                    return $.trim(data.real_name) || data.username;
                }),
                values: data.map(function (data) {
                    return Number(data.total);
                })
            });

            canvas.draw = function (animation) {
                var ctx = canvas.prepareDraw();
                new Chart(ctx)
                    .Bar({
                        labels: canvas.data('labels'),
                        datasets: [
                            {
                                fillColor: canvas.data('fillcolor'),
                                strokeColor: canvas.data('strockcolor'),
                                data: canvas.data('values')
                            }
                        ]
                    }, {
                        animation: animation
                    });
            };
            return canvas;
        },
        teamCanvas: function (data) {
            var canvas = $(this);

            var tmpl = {
                labels: hbs.templates['pie-chart-labels']
            };

            var pointMap = {};
            data.forEach(function (data) {
                var team_name = data.team_name;
                pointMap[team_name] = (pointMap[team_name] || 0) + Number(data.total);
            });
            var teamNames = Object.keys(pointMap),
                colors = $.rainbowColor(canvas.data('basecolor'), teamNames.length + 1);
            colors.shift();
            var pieData = teamNames.map(function (team_name, i) {
                return {
                    label: team_name,
                    value: pointMap[team_name],
                    color: colors[i]
                }
            });

            canvas.after(tmpl.labels(pieData));
            var labels = canvas.next('.pie-chart-labels');

            canvas.data({
                pie: pieData
            });
            canvas.draw = function (animation) {
                var ctx = canvas.prepareDraw();
                new Chart(ctx).Pie(canvas.data('pie'), {
                    animation: animation,
                    animationEasing: "easeOutQuart"
                });
                labels.css({
                    left: canvas.width() / 2 + 180
                });
            };
            return canvas;
        },
        scoreChartSection: function (data) {
            var section = $(this),
                top10canvas = $('#top10-chart-canvas', section).top10ChartCanvas(data),
                teamCanvas = $('#team-chart-canvas', section).teamCanvas(data);

            section.draw = function (animation) {
                top10canvas.draw(animation);
                teamCanvas.draw(animation);
            };

            section.draw(true);
            return section;
        }
    })
    ;

    $(function () {
        var win = $(window),
            body = $(document.body);

        var data = d && d['report'];

        $('#score-list-section', body).scoreListSection(data['score'] || []);
        var scoreChartSection = $('#score-chart-section', body).scoreChartSection(data['score'] || []);

        win.resize(function () {
            scoreChartSection.draw(false);
        });

        $('#sub-nav', body).subNav('report');

    });
})
    (jQuery, window['l'], Handlebars, Chart);


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class LogFilter extends CFilter{

	protected function preFilter($filterChain)
	{
		return true;
	}

	protected function postFilter($filterChain)
	{

        $model=new Log;

        $model->uid=1;
        $model->uname='wolf';
        $model->content='testtesttest';
        $model->module=Yii::app()->controller->id;
        $model->action=Yii::app()->controller->action->id;
        $model->utype=1;

        if($model->validate()){
            $model->save();
        }else{
            echo json_encode($model->errors);
        }
	}
}


text:
;
(function () {

    "use strict";
    var root = this,
        _jp = root.jsPlumb,
        _ju = root.jsPlumbUtil;

    var makeConnector = function (_jsPlumb, renderMode, connectorName, connectorArgs, forComponent) {
            if (!_jsPlumb.Defaults.DoNotThrowErrors && jsPlumb.Connectors[renderMode][connectorName] == null)
                throw { msg: "jsPlumb: unknown connector type '" + connectorName + "'" };

            return new _jp.Connectors[renderMode][connectorName](connectorArgs, forComponent);
        },
        _makeAnchor = function (anchorParams, elementId, _jsPlumb) {
            return (anchorParams) ? _jsPlumb.makeAnchor(anchorParams, elementId, _jsPlumb) : null;
        },
        _updateConnectedClass = function (conn, element, _jsPlumb, remove) {
            if (element != null) {
                element._jsPlumbConnections = element._jsPlumbConnections || {};
                if (remove)
                    delete element._jsPlumbConnections[conn.id];
                else
                    element._jsPlumbConnections[conn.id] = true;

                if (_ju.isEmpty(element._jsPlumbConnections)) {
                    _jsPlumb.removeClass(element, _jsPlumb.connectedClass);
                }
                else
                    _jsPlumb.addClass(element, _jsPlumb.connectedClass);
            }
        };

    _jp.Connection = function (params) {
        var _newEndpoint = params.newEndpoint;

        this.id = params.id;
        this.connector = null;
        this.idPrefix = "_jsplumb_c_";
        this.defaultLabelLocation = 0.5;
        this.defaultOverlayKeys = ["Overlays", "ConnectionOverlays"];
        // if a new connection is the result of moving some existing connection, params.previousConnection
        // will have that Connection in it. listeners for the jsPlumbConnection event can look for that
        // member and take action if they need to.
        this.previousConnection = params.previousConnection;
        this.source = _jp.getElement(params.source);
        this.target = _jp.getElement(params.target);
        // sourceEndpoint and targetEndpoint override source/target, if they are present. but
        // source is not overridden if the Endpoint has declared it is not the final target of a connection;
        // instead we use the source that the Endpoint declares will be the final source element.
        if (params.sourceEndpoint) this.source = params.sourceEndpoint.getElement();
        if (params.targetEndpoint) this.target = params.targetEndpoint.getElement();

        _jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments);

        this.sourceId = this._jsPlumb.instance.getId(this.source);
        this.targetId = this._jsPlumb.instance.getId(this.target);
        this.scope = params.scope; // scope may have been passed in to the connect call. if it wasn't, we will pull it from the source endpoint, after having initialised the endpoints.
        this.endpoints = [];
        this.endpointStyles = [];

        var _jsPlumb = this._jsPlumb.instance;

        _jsPlumb.manage(this.sourceId, this.source);
        _jsPlumb.manage(this.targetId, this.target);

        this._jsPlumb.visible = true;
        this._jsPlumb.editable = params.editable === true;
        this._jsPlumb.params = {
            cssClass: params.cssClass,
            container: params.container,
            "pointer-events": params["pointer-events"],
            editorParams: params.editorParams,
            overlays: params.overlays
        };
        this._jsPlumb.lastPaintedAt = null;

        // listen to mouseover and mouseout events passed from the container delegate.
        this.bind("mouseover", function () {
            this.setHover(true);
        }.bind(this));
        this.bind("mouseout", function () {
            this.setHover(false);
        }.bind(this));

// INITIALISATION CODE

        this.makeEndpoint = function (isSource, el, elId, ep) {
            elId = elId || this._jsPlumb.instance.getId(el);
            return this.prepareEndpoint(_jsPlumb, _newEndpoint, this, ep, isSource ? 0 : 1, params, el, elId);
        };

        var eS = this.makeEndpoint(true, this.source, this.sourceId, params.sourceEndpoint),
            eT = this.makeEndpoint(false, this.target, this.targetId, params.targetEndpoint);

        if (eS) _ju.addToList(params.endpointsByElement, this.sourceId, eS);
        if (eT) _ju.addToList(params.endpointsByElement, this.targetId, eT);
        // if scope not set, set it to be the scope for the source endpoint.
        if (!this.scope) this.scope = this.endpoints[0].scope;

        // if explicitly told to (or not to) delete endpoints on detach, override endpoint's preferences
        if (params.deleteEndpointsOnDetach != null) {
            this.endpoints[0]._deleteOnDetach = params.deleteEndpointsOnDetach;
            this.endpoints[1]._deleteOnDetach = params.deleteEndpointsOnDetach;
        }
        else {
            // otherwise, unless the endpoints say otherwise, mark them for deletion.
            if (!this.endpoints[0]._doNotDeleteOnDetach) this.endpoints[0]._deleteOnDetach = true;
            if (!this.endpoints[1]._doNotDeleteOnDetach) this.endpoints[1]._deleteOnDetach = true;
        }

// -------------------------- DEFAULT TYPE ---------------------------------------------

        // DETACHABLE
        var _detachable = _jsPlumb.Defaults.ConnectionsDetachable;
        if (params.detachable === false) _detachable = false;
        if (this.endpoints[0].connectionsDetachable === false) _detachable = false;
        if (this.endpoints[1].connectionsDetachable === false) _detachable = false;
        // REATTACH
        var _reattach = params.reattach || this.endpoints[0].reattachConnections || this.endpoints[1].reattachConnections || _jsPlumb.Defaults.ReattachConnections;

        this.appendToDefaultType({
            detachable: _detachable,
            rettach: _reattach,
            paintStyle:this.endpoints[0].connectorStyle || this.endpoints[1].connectorStyle || params.paintStyle || _jsPlumb.Defaults.PaintStyle || jsPlumb.Defaults.PaintStyle,
            hoverPaintStyle:this.endpoints[0].connectorHoverStyle || this.endpoints[1].connectorHoverStyle || params.hoverPaintStyle || _jsPlumb.Defaults.HoverPaintStyle || jsPlumb.Defaults.HoverPaintStyle
        });

        var _suspendedAt = _jsPlumb.getSuspendedAt();
        if (!_jsPlumb.isSuspendDrawing()) {
            // paint the endpoints
            var myInfo = _jsPlumb.getCachedData(this.sourceId),
                myOffset = myInfo.o, myWH = myInfo.s,
                otherInfo = _jsPlumb.getCachedData(this.targetId),
                otherOffset = otherInfo.o,
                otherWH = otherInfo.s,
                initialTimestamp = _suspendedAt || _jsPlumb.timestamp(),
                anchorLoc = this.endpoints[0].anchor.compute({
                    xy: [ myOffset.left, myOffset.top ], wh: myWH, element: this.endpoints[0],
                    elementId: this.endpoints[0].elementId,
                    txy: [ otherOffset.left, otherOffset.top ], twh: otherWH, tElement: this.endpoints[1],
                    timestamp: initialTimestamp
                });

            this.endpoints[0].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp });

            anchorLoc = this.endpoints[1].anchor.compute({
                xy: [ otherOffset.left, otherOffset.top ], wh: otherWH, element: this.endpoints[1],
                elementId: this.endpoints[1].elementId,
                txy: [ myOffset.left, myOffset.top ], twh: myWH, tElement: this.endpoints[0],
                timestamp: initialTimestamp
            });
            this.endpoints[1].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp });
        }

        this.getTypeDescriptor = function () {
            return "connection";
        };
        this.getAttachedElements = function () {
            return this.endpoints;
        };

        this.isDetachable = function () {
            return this._jsPlumb.detachable === true;
        };
        this.setDetachable = function (detachable) {
            this._jsPlumb.detachable = detachable === true;
        };
        this.isReattach = function () {
            return this._jsPlumb.reattach === true || this.endpoints[0].reattachConnections === true || this.endpoints[1].reattachConnections === true;
        };
        this.setReattach = function (reattach) {
            this._jsPlumb.reattach = reattach === true;
        };

// END INITIALISATION CODE

// COST + DIRECTIONALITY
        // if cost not supplied, try to inherit from source endpoint
        this._jsPlumb.cost = params.cost || this.endpoints[0].getConnectionCost();
        this._jsPlumb.directed = params.directed;
        // inherit directed flag if set no source endpoint
        if (params.directed == null) this._jsPlumb.directed = this.endpoints[0].areConnectionsDirected();
// END COST + DIRECTIONALITY

// PARAMETERS
        // merge all the parameters objects into the connection.  parameters set
        // on the connection take precedence; then source endpoint params, then
        // finally target endpoint params.
        var _p = jsPlumb.extend({}, this.endpoints[1].getParameters());
        _jp.extend(_p, this.endpoints[0].getParameters());
        _jp.extend(_p, this.getParameters());
        this.setParameters(_p);
// END PARAMETERS

// PAINTING

        this.setConnector(this.endpoints[0].connector || this.endpoints[1].connector || params.connector || _jsPlumb.Defaults.Connector || _jp.Defaults.Connector, true);
        var data = params.data == null || !jsPlumbUtil.isObject(params.data) ? {} : params.data;
        this.getData = function() { return data; };
        this.setData = function(d) { data = d || {}; };
        this.mergeData = function(d) { data = jsPlumb.extend(data, d); };

        // the very last thing we do is apply types, if there are any.
        var _types = [ "default",  params.type, this.endpoints[0].connectionType, this.endpoints[1].connectionType ].join(" ");
        if (/[^\s]/.test(_types))
            this.addType(_types, params.data, true);

        this.updateConnectedClass();

// END PAINTING
    };

    _ju.extend(_jp.Connection, _jp.OverlayCapableJsPlumbUIComponent, {
        applyType: function (t, doNotRepaint, typeMap) {

            // none of these things result in the creation of objects so can be ignored.
            if (t.detachable != null) this.setDetachable(t.detachable);
            if (t.reattach != null) this.setReattach(t.reattach);
            if (t.scope) this.scope = t.scope;

            if (t.cssClass != null && this.canvas) this._jsPlumb.instance.addClass(this.canvas, t.cssClass);

            var _anchors = null;
            // this also results in the creation of objects.
            if (t.anchor) {
                // note that even if the param was anchor, we store `anchors`.
                _anchors = this.getCachedTypeItem("anchors", typeMap.anchor);
                if (_anchors == null) {
                    _anchors = [ this._jsPlumb.instance.makeAnchor(t.anchor), this._jsPlumb.instance.makeAnchor(t.anchor) ];
                    this.cacheTypeItem("anchors", _anchors, typeMap.anchor);
                }
            }
            else if (t.anchors) {
                _anchors = this.getCachedTypeItem("anchors", typeMap.anchors);
                if (_anchors == null) {
                    _anchors = [
                        this._jsPlumb.instance.makeAnchor(t.anchors[0]),
                        this._jsPlumb.instance.makeAnchor(t.anchors[1])
                    ];
                    this.cacheTypeItem("anchors", _anchors, typeMap.anchors);
                }
            }
            if (_anchors != null) {
                this.endpoints[0].anchor = _anchors[0];
                this.endpoints[1].anchor = _anchors[1];
            }

            _jp.OverlayCapableJsPlumbUIComponent.applyType(this, t);
        },
        addClass: function (c, informEndpoints) {
            if (informEndpoints) {
                this.endpoints[0].addClass(c);
                this.endpoints[1].addClass(c);
                if (this.suspendedEndpoint) this.suspendedEndpoint.addClass(c);
            }
            if (this.connector) {
                this.connector.addClass(c);
            }
        },
        removeClass: function (c, informEndpoints) {
            if (informEndpoints) {
                this.endpoints[0].removeClass(c);
                this.endpoints[1].removeClass(c);
                if (this.suspendedEndpoint) this.suspendedEndpoint.removeClass(c);
            }
            if (this.connector) {
                this.connector.removeClass(c);
            }
        },
        isVisible: function () {
            return this._jsPlumb.visible;
        },
        setVisible: function (v) {
            this._jsPlumb.visible = v;
            if (this.connector)
                this.connector.setVisible(v);
            this.repaint();
        },
        cleanup: function () {
            this.updateConnectedClass(true);
            this.endpoints = null;
            this.source = null;
            this.target = null;
            if (this.connector != null) {
                this.connector.cleanup(true);
                this.connector.destroy(true);
            }
            this.connector = null;
        },
        updateConnectedClass:function(remove) {
            _updateConnectedClass(this, this.source, this._jsPlumb.instance, remove);
            _updateConnectedClass(this, this.target, this._jsPlumb.instance, remove);
        },
        setHover: function (state) {
            if (this.connector && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
                this.connector.setHover(state);
                root.jsPlumb[state ? "addClass" : "removeClass"](this.source, this._jsPlumb.instance.hoverSourceClass);
                root.jsPlumb[state ? "addClass" : "removeClass"](this.target, this._jsPlumb.instance.hoverTargetClass);
            }
        },
        getUuids:function() {
            return [ this.endpoints[0].getUuid(), this.endpoints[1].getUuid() ];
        },
        getCost: function () {
            return this._jsPlumb.cost;
        },
        setCost: function (c) {
            this._jsPlumb.cost = c;
        },
        isDirected: function () {
            return this._jsPlumb.directed === true;
        },
        getConnector: function () {
            return this.connector;
        },
        prepareConnector:function(connectorSpec, typeId) {
            var connectorArgs = {
                    _jsPlumb: this._jsPlumb.instance,
                    cssClass: this._jsPlumb.params.cssClass,
                    container: this._jsPlumb.params.container,
                    "pointer-events": this._jsPlumb.params["pointer-events"]
                },
                renderMode = this._jsPlumb.instance.getRenderMode(),
                connector;

            if (_ju.isString(connectorSpec))
                connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec, connectorArgs, this); // lets you use a string as shorthand.
            else if (_ju.isArray(connectorSpec)) {
                if (connectorSpec.length == 1)
                    connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], connectorArgs, this);
                else
                    connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], _ju.merge(connectorSpec[1], connectorArgs), this);
            }
            if (typeId != null) connector.typeId = typeId;
            return connector;
        },
        setPreparedConnector: function(connector, doNotRepaint, doNotChangeListenerComponent, typeId) {

            var previous;
            // the connector will not be cleaned up if it was set as part of a type, because `typeId` will be set on it
            // and we havent passed in `true` for "force" here.
            if (this.connector != null) {
                previous = this.connector;
                this.connector.cleanup();
                this.connector.destroy();
            }

            this.connector = connector;
            if (typeId) {
                this.cacheTypeItem("connector", connector, typeId);
            }

            this.canvas = this.connector.canvas;
            this.bgCanvas = this.connector.bgCanvas;

            // new: instead of binding listeners per connector, we now just have one delegate on the container.
            // so for that handler we set the connection as the '_jsPlumb' member of the canvas element, and
            // bgCanvas, if it exists, which it does right now in the VML renderer, so it won't from v 2.0.0 onwards.
            if (this.canvas) this.canvas._jsPlumb = this;
            if (this.bgCanvas) this.bgCanvas._jsPlumb = this;

            if (previous != null) {
                var o = this.getOverlays();
                for (var i = 0; i < o.length; i++) {
                    if (o[i].transfer) o[i].transfer(this.connector);
                }
            }

            if (!doNotChangeListenerComponent) this.setListenerComponent(this.connector);
            if (!doNotRepaint) this.repaint();
        },
        setConnector: function (connectorSpec, doNotRepaint, doNotChangeListenerComponent, typeId) {
            var connector = this.prepareConnector(connectorSpec, typeId);
            this.setPreparedConnector(connector, doNotRepaint, doNotChangeListenerComponent, typeId);
        },
        paint: function (params) {

            if (!this._jsPlumb.instance.isSuspendDrawing() && this._jsPlumb.visible) {
                params = params || {};
                var timestamp = params.timestamp,
                // if the moving object is not the source we must transpose the two references.
                    swap = false,
                    tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId,
                    tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;

                if (timestamp == null || timestamp != this._jsPlumb.lastPaintedAt) {
                    var sourceInfo = this._jsPlumb.instance.updateOffset({elId:sId}).o,
                        targetInfo = this._jsPlumb.instance.updateOffset({elId:tId}).o,
                        sE = this.endpoints[sIdx], tE = this.endpoints[tIdx];

                    var sAnchorP = sE.anchor.getCurrentLocation({xy: [sourceInfo.left, sourceInfo.top], wh: [sourceInfo.width, sourceInfo.height], element: sE, timestamp: timestamp}),
                        tAnchorP = tE.anchor.getCurrentLocation({xy: [targetInfo.left, targetInfo.top], wh: [targetInfo.width, targetInfo.height], element: tE, timestamp: timestamp});

                    this.connector.resetBounds();

                    this.connector.compute({
                        sourcePos: sAnchorP,
                        targetPos: tAnchorP,
                        sourceEndpoint: this.endpoints[sIdx],
                        targetEndpoint: this.endpoints[tIdx],
                        lineWidth: this._jsPlumb.paintStyleInUse.lineWidth,
                        sourceInfo: sourceInfo,
                        targetInfo: targetInfo
                    });

                    var overlayExtents = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };

                    // compute overlays. we do this first so we can get their placements, and adjust the
                    // container if needs be (if an overlay would be clipped)
                    for (var i in this._jsPlumb.overlays) {
                        if (this._jsPlumb.overlays.hasOwnProperty(i)) {
                            var o = this._jsPlumb.overlays[i];
                            if (o.isVisible()) {
                                this._jsPlumb.overlayPlacements[i] = o.draw(this.connector, this._jsPlumb.paintStyleInUse, this.getAbsoluteOverlayPosition(o));
                                overlayExtents.minX = Math.min(overlayExtents.minX, this._jsPlumb.overlayPlacements[i].minX);
                                overlayExtents.maxX = Math.max(overlayExtents.maxX, this._jsPlumb.overlayPlacements[i].maxX);
                                overlayExtents.minY = Math.min(overlayExtents.minY, this._jsPlumb.overlayPlacements[i].minY);
                                overlayExtents.maxY = Math.max(overlayExtents.maxY, this._jsPlumb.overlayPlacements[i].maxY);
                            }
                        }
                    }

                    var lineWidth = parseFloat(this._jsPlumb.paintStyleInUse.lineWidth || 1) / 2,
                        outlineWidth = parseFloat(this._jsPlumb.paintStyleInUse.lineWidth || 0),
                        extents = {
                            xmin: Math.min(this.connector.bounds.minX - (lineWidth + outlineWidth), overlayExtents.minX),
                            ymin: Math.min(this.connector.bounds.minY - (lineWidth + outlineWidth), overlayExtents.minY),
                            xmax: Math.max(this.connector.bounds.maxX + (lineWidth + outlineWidth), overlayExtents.maxX),
                            ymax: Math.max(this.connector.bounds.maxY + (lineWidth + outlineWidth), overlayExtents.maxY)
                        };
                    // paint the connector.
                    this.connector.paint(this._jsPlumb.paintStyleInUse, null, extents);
                    // and then the overlays
                    for (var j in this._jsPlumb.overlays) {
                        if (this._jsPlumb.overlays.hasOwnProperty(j)) {
                            var p = this._jsPlumb.overlays[j];
                            if (p.isVisible()) {
                                p.paint(this._jsPlumb.overlayPlacements[j], extents);
                            }
                        }
                    }
                }
                this._jsPlumb.lastPaintedAt = timestamp;
            }
        },
        repaint: function (params) {
            params = params || {};
            this.paint({ elId: this.sourceId, recalc: !(params.recalc === false), timestamp: params.timestamp});
        },
        prepareEndpoint: function (_jsPlumb, _newEndpoint, conn, existing, index, params, element, elementId) {
            var e;
            if (existing) {
                conn.endpoints[index] = existing;
                existing.addConnection(conn);
            } else {
                if (!params.endpoints) params.endpoints = [ null, null ];
                var ep = params.endpoints[index] || params.endpoint || _jsPlumb.Defaults.Endpoints[index] || jsPlumb.Defaults.Endpoints[index] || _jsPlumb.Defaults.Endpoint || jsPlumb.Defaults.Endpoint;
                if (!params.endpointStyles) params.endpointStyles = [ null, null ];
                if (!params.endpointHoverStyles) params.endpointHoverStyles = [ null, null ];
                var es = params.endpointStyles[index] || params.endpointStyle || _jsPlumb.Defaults.EndpointStyles[index] || jsPlumb.Defaults.EndpointStyles[index] || _jsPlumb.Defaults.EndpointStyle || jsPlumb.Defaults.EndpointStyle;
                // Endpoints derive their fillStyle from the connector's strokeStyle, if no fillStyle was specified.
                if (es.fillStyle == null && params.paintStyle != null)
                    es.fillStyle = params.paintStyle.strokeStyle;

                if (es.outlineColor == null && params.paintStyle != null)
                    es.outlineColor = params.paintStyle.outlineColor;
                if (es.outlineWidth == null && params.paintStyle != null)
                    es.outlineWidth = params.paintStyle.outlineWidth;

                var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _jsPlumb.Defaults.EndpointHoverStyles[index] || jsPlumb.Defaults.EndpointHoverStyles[index] || _jsPlumb.Defaults.EndpointHoverStyle || jsPlumb.Defaults.EndpointHoverStyle;
                // endpoint hover fill style is derived from connector's hover stroke style
                if (params.hoverPaintStyle != null) {
                    if (ehs == null) ehs = {};
                    if (ehs.fillStyle == null) {
                        ehs.fillStyle = params.hoverPaintStyle.strokeStyle;
                    }
                }
                var a = params.anchors ? params.anchors[index] :
                        params.anchor ? params.anchor :
                            _makeAnchor(_jsPlumb.Defaults.Anchors[index], elementId, _jsPlumb) ||
                            _makeAnchor(_jp.Defaults.Anchors[index], elementId, _jsPlumb) ||
                            _makeAnchor(_jsPlumb.Defaults.Anchor, elementId, _jsPlumb) ||
                            _makeAnchor(_jp.Defaults.Anchor, elementId, _jsPlumb),
                    u = params.uuids ? params.uuids[index] : null;

                e = _newEndpoint({
                    paintStyle: es, hoverPaintStyle: ehs, endpoint: ep, connections: [ conn ],
                    uuid: u, anchor: a, source: element, scope: params.scope,
                    reattach: params.reattach || _jsPlumb.Defaults.ReattachConnections,
                    detachable: params.detachable || _jsPlumb.Defaults.ConnectionsDetachable
                });
                conn.endpoints[index] = e;

                if (params.drawEndpoints === false) e.setVisible(false, true, true);

            }
            return e;
        }

    }); // END Connection class
}).call(this);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SoundProcessor</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="date" content="2018-04-24">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

SEARCH:
<input type="text" id="search" value=" " disabled="disabled">
<input type="reset" id="reset" value=" " disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package ev3dev.sensors.microphone

Class SoundProcessor

<map id="G" name="G">
<area shape="rect" id="node1_0" href="./AtomicFloat.html" title="ev3dev.sensors.microphone.AtomicFloat" alt="" coords="16,484,364,699"/>
<area shape="rect" id="node1" href="./AtomicFloat.html" title="<TABLE>" alt="" coords="5,479,375,704"/>
<area shape="rect" id="node2_1" href="./Microphone.html" title="ev3dev.sensors.microphone.Microphone" alt="" coords="85,11,295,108"/>
<area shape="rect" id="node2" href="./Microphone.html" title="<TABLE>" alt="" coords="75,5,305,113"/>
<area shape="rect" id="node3_2" href="./SoundProcessor.html" title="ev3dev.sensors.microphone.SoundProcessor" alt="" coords="99,167,281,425"/>
<area shape="rect" id="node3" href="./SoundProcessor.html" title="<TABLE>" alt="" coords="89,161,291,431"/>
</map>

java.lang.Object

java.lang.Thread

ev3dev.sensors.microphone.SoundProcessor

All Implemented Interfaces:

java.lang.Runnable

public class SoundProcessor
extends java.lang.Thread

Nested Class Summary

Nested classes/interfaces inherited from class java.lang.Thread

java.lang.Thread.State, java.lang.Thread.UncaughtExceptionHandler

Field Summary

Fields

Modifier and Type
Field and Description

private javax.sound.sampled.AudioFormat
audioFormat

private boolean
BIG_ENDIAN

private byte[]
buf

private int
bufferByteSize

private int
CHANNELS

private javax.sound.sampled.TargetDataLine
line

private float
SAMPLE_RATE

private int
SAMPLE_SIZE_IN_BITS

private float[]
samples

private boolean
SIGNED

private AtomicFloat
value

Fields inherited from class java.lang.Thread

MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY

Constructor Summary

Constructors

Constructor and Description

SoundProcessor()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

float
getValue()

void
init()

void
run()

Methods inherited from class java.lang.Thread

activeCount, checkAccess, clone, countStackFrames, currentThread, destroy, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, onSpinWait, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, stop, suspend, toString, yield

Methods inherited from class java.lang.Object

equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

SAMPLE_RATE

private final float SAMPLE_RATE

See Also:

Constant Field Values

SAMPLE_SIZE_IN_BITS

private final int SAMPLE_SIZE_IN_BITS

See Also:

Constant Field Values

CHANNELS

private final int CHANNELS

See Also:

Constant Field Values

SIGNED

private final boolean SIGNED

See Also:

Constant Field Values

BIG_ENDIAN

private final boolean BIG_ENDIAN

See Also:

Constant Field Values

audioFormat

private final javax.sound.sampled.AudioFormat audioFormat

line

private javax.sound.sampled.TargetDataLine line

bufferByteSize

private final int bufferByteSize

See Also:

Constant Field Values

buf

private final byte[] buf

samples

private final float[] samples

value

private AtomicFloat value

Constructor Detail

SoundProcessor

public SoundProcessor()

Method Detail

init

public void init()

run

public void run()

Specified by:

run in interface java.lang.Runnable

Overrides:

run in class java.lang.Thread

getValue

public float getValue()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package ru.skycelot.plicanterra.metamodel.transfer;

/**
 *
 */
public class Link {

    public Long id;
    public Long referencedTemplate;
    public String code;
    public String name;
    public String desc;
    public LinkType type;
    public Boolean exclusive;
    public Boolean editable;

    public Link(ru.skycelot.plicanterra.metamodel.Link link) {
        id = link.id;
        code = link.code;
        name = link.name;
        desc = link.description;
    }
}


text:
"""

.. dialect:: mysql+oursql
    :name: OurSQL
    :dbapi: oursql
    :connectstring: mysql+oursql://<user>:<password>@<host>[:<port>]/<dbname>
    :url: http://packages.python.org/oursql/

.. note::

    The OurSQL MySQL dialect is legacy and is no longer supported upstream,
    and is **not tested as part of SQLAlchemy's continuous integration**.
    The recommended MySQL dialects are mysqlclient and PyMySQL.

Unicode
-------

Please see :ref:`mysql_unicode` for current recommendations on unicode
handling.

"""

from .base import BIT
from .base import MySQLDialect
from .base import MySQLExecutionContext
from ... import types as sqltypes
from ... import util

class _oursqlBIT(BIT):
    def result_processor(self, dialect, coltype):
        """oursql already converts mysql bits, so."""

        return None

class MySQLExecutionContext_oursql(MySQLExecutionContext):
    @property
    def plain_query(self):
        return self.execution_options.get("_oursql_plain_query", False)

class MySQLDialect_oursql(MySQLDialect):
    driver = "oursql"

    if util.py2k:
        supports_unicode_binds = True
        supports_unicode_statements = True

    supports_native_decimal = True

    supports_sane_rowcount = True
    supports_sane_multi_rowcount = True
    execution_ctx_cls = MySQLExecutionContext_oursql

    colspecs = util.update_copy(
        MySQLDialect.colspecs, {sqltypes.Time: sqltypes.Time, BIT: _oursqlBIT}
    )

    @classmethod
    def dbapi(cls):
        return __import__("oursql")

    def do_execute(self, cursor, statement, parameters, context=None):
        """Provide an implementation of
        *cursor.execute(statement, parameters)*."""

        if context and context.plain_query:
            cursor.execute(statement, plain_query=True)
        else:
            cursor.execute(statement, parameters)

    def do_begin(self, connection):
        connection.cursor().execute("BEGIN", plain_query=True)

    def _xa_query(self, connection, query, xid):
        if util.py2k:
            arg = connection.connection._escape_string(xid)
        else:
            charset = self._connection_charset
            arg = connection.connection._escape_string(
                xid.encode(charset)
            ).decode(charset)
        arg = "'%s'" % arg
        connection.execution_options(_oursql_plain_query=True).execute(
            query % arg
        )

    # Because mysql is bad, these methods have to be
    # reimplemented to use _PlainQuery. Basically, some queries
    # refuse to return any data if they're run through
    # the parameterized query API, or refuse to be parameterized
    # in the first place.
    def do_begin_twophase(self, connection, xid):
        self._xa_query(connection, "XA BEGIN %s", xid)

    def do_prepare_twophase(self, connection, xid):
        self._xa_query(connection, "XA END %s", xid)
        self._xa_query(connection, "XA PREPARE %s", xid)

    def do_rollback_twophase(
        self, connection, xid, is_prepared=True, recover=False
    ):
        if not is_prepared:
            self._xa_query(connection, "XA END %s", xid)
        self._xa_query(connection, "XA ROLLBACK %s", xid)

    def do_commit_twophase(
        self, connection, xid, is_prepared=True, recover=False
    ):
        if not is_prepared:
            self.do_prepare_twophase(connection, xid)
        self._xa_query(connection, "XA COMMIT %s", xid)

    # Q: why didn't we need all these "plain_query" overrides earlier ?
    # am i on a newer/older version of OurSQL ?
    def has_table(self, connection, table_name, schema=None):
        return MySQLDialect.has_table(
            self,
            connection.connect().execution_options(_oursql_plain_query=True),
            table_name,
            schema,
        )

    def get_table_options(self, connection, table_name, schema=None, **kw):
        return MySQLDialect.get_table_options(
            self,
            connection.connect().execution_options(_oursql_plain_query=True),
            table_name,
            schema=schema,
            **kw
        )

    def get_columns(self, connection, table_name, schema=None, **kw):
        return MySQLDialect.get_columns(
            self,
            connection.connect().execution_options(_oursql_plain_query=True),
            table_name,
            schema=schema,
            **kw
        )

    def get_view_names(self, connection, schema=None, **kw):
        return MySQLDialect.get_view_names(
            self,
            connection.connect().execution_options(_oursql_plain_query=True),
            schema=schema,
            **kw
        )

    def get_table_names(self, connection, schema=None, **kw):
        return MySQLDialect.get_table_names(
            self,
            connection.connect().execution_options(_oursql_plain_query=True),
            schema,
        )

    def get_schema_names(self, connection, **kw):
        return MySQLDialect.get_schema_names(
            self,
            connection.connect().execution_options(_oursql_plain_query=True),
            **kw
        )

    def initialize(self, connection):
        return MySQLDialect.initialize(
            self, connection.execution_options(_oursql_plain_query=True)
        )

    def _show_create_table(
        self, connection, table, charset=None, full_name=None
    ):
        return MySQLDialect._show_create_table(
            self,
            connection._contextual_connect(
                close_with_result=True
            ).execution_options(_oursql_plain_query=True),
            table,
            charset,
            full_name,
        )

    def is_disconnect(self, e, connection, cursor):
        if isinstance(e, self.dbapi.ProgrammingError):
            return (
                e.errno is None
                and "cursor" not in e.args[1]
                and e.args[1].endswith("closed")
            )
        else:
            return e.errno in (2006, 2013, 2014, 2045, 2055)

    def create_connect_args(self, url):
        opts = url.translate_connect_args(
            database="db", username="user", password="passwd"
        )
        opts.update(url.query)

        util.coerce_kw_type(opts, "port", int)
        util.coerce_kw_type(opts, "compress", bool)
        util.coerce_kw_type(opts, "autoping", bool)
        util.coerce_kw_type(opts, "raise_on_warnings", bool)

        util.coerce_kw_type(opts, "default_charset", bool)
        if opts.pop("default_charset", False):
            opts["charset"] = None
        else:
            util.coerce_kw_type(opts, "charset", str)
        opts["use_unicode"] = opts.get("use_unicode", True)
        util.coerce_kw_type(opts, "use_unicode", bool)

        # FOUND_ROWS must be set in CLIENT_FLAGS to enable
        # supports_sane_rowcount.
        opts.setdefault("found_rows", True)

        ssl = {}
        for key in [
            "ssl_ca",
            "ssl_key",
            "ssl_cert",
            "ssl_capath",
            "ssl_cipher",
        ]:
            if key in opts:
                ssl[key[4:]] = opts[key]
                util.coerce_kw_type(ssl, key[4:], str)
                del opts[key]
        if ssl:
            opts["ssl"] = ssl

        return [[], opts]

    def _extract_error_code(self, exception):
        return exception.errno

    def _detect_charset(self, connection):
        """Sniff out the character set in use for connection results."""

        return connection.connection.charset

    def _compat_fetchall(self, rp, charset=None):
        """oursql isn't super-broken like MySQLdb, yaaay."""
        return rp.fetchall()

    def _compat_fetchone(self, rp, charset=None):
        """oursql isn't super-broken like MySQLdb, yaaay."""
        return rp.fetchone()

    def _compat_first(self, rp, charset=None):
        return rp.first()

dialect = MySQLDialect_oursql


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Web.Http;
using NuGet.Server.V2.Controllers;

namespace NuGet.Server.V2.Samples.OwinHost.Controllers
{
    /// <summary>
    /// Controller that exposes Program.NuGetPrivateRepository as NuGet OData feed
    /// that allows read/download access for all authenticated users.
    /// delete/upload is not allowed (no authenticationservice is passed to NuGetODataControllers constructor)
    /// </summary>
    [Authorize]
    public class NuGetPrivateODataController : NuGetODataController
    {
        public NuGetPrivateODataController()
            : base(Program.NuGetPrivateRepository)
            // Replace line above with the one below to allow upload/delete for all authenticated users
            // : base(Program.NuGetPrivateRepository, new ApiKeyPackageAuthenticationService(false, null))
        {
        }
    }
}


text:
@interface JZStudentInfoViewController ()

@end

@implementation JZStudentInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"学生信息";
    [self setUI];
    [self loadData];
}

- (void)setUI {
    self.header.imageView.image = [UIImage imageNamed:@"manager_role_student_pic"];
    self.header.detailLabel.text = _roleInfo.schoolName;
    [self cellWithTitle:@"姓名:" detail:_roleInfo.studentName index:0];
    [self cellWithTitle:@"班级:" detail:_roleInfo.className index:1];

}

- (void)cellWithTitle:(NSString *)title detail:(NSString *)detail index:(NSInteger)index {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 150+50*index, WIDTH, 50)];

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 30)];
    titleLabel.text = title;
    [view addSubview:titleLabel];

    UILabel *detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, 10, WIDTH-140, 30)];
    detailLabel.text = detail;
    [view addSubview:detailLabel];

    UILabel *border = [[UILabel alloc] initWithFrame:CGRectMake(0, 49, WIDTH, 1)];
    border.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:border];

    [self.view addSubview:view];
}

- (void)loadData {

}

@end


text:
#include "remote_process_client.h"
#include <string.h>
#include <stdlib.h>
#include <assert.h>

typedef struct remote_process_client remote_process_client;

#define WRITE_BYTE(x) client_write_byte(client, x)
#define WRITE_INT32(x) client_write_int32(client, x)
#define WRITE_STRING(x) client_write_string(client, x)
#define FLUSH() client_flush_buffer(client);

#define READ_BYTE() client_read_byte(client)
#define READ_BOOL() (ct_bool)READ_BYTE()
#define READ_ENUM(enum_type) (enum enum_type)(signed char)client_read_byte(client)
#define READ_INT32() client_read_int32(client)
#define READ_INT64() client_read_int64(client)
#define READ_DOUBLE() client_read_double(client)
#define READ_STRING() client_read_string(client);

#define VERIFY(actual_value, expected_value) if (actual_value != expected_value) { exit(10011); }

#define FIX_BYTE_ORDER(size)                    \
    if (!client->is_little_endian)              \
        reverse_in_place((char*)&(data), size);

static int is_little_endian()
{
    union {
        uint16 value;
        unsigned char bytes[2];
    } test = {0x0201};

    return 1 == test.bytes[0];
}

static void reverse_in_place(char *data, size_t size)
{
    char *end = data + (size - 1);
    while (end > data) {
        char tmp = *data;
        *data++ = *end;
        *end-- = tmp;
    }
}

static void reverse(char *dest, const char *src, size_t size)
{
    src += size - 1;
    while (size--) {
        *dest++ = *src--;
    }
}

static unsigned char client_read_byte(const remote_process_client *client)
{
    unsigned char data;
    if (0 != socket_recv(client->socket, (char*)&data, 1)) {
        exit(10012);
    }
    return data;
}

static void client_read_bytes(const remote_process_client *client, void *data, size_t size)
{
    if (0 != socket_recv(client->socket, (char*)data, size)) {
        exit(10012);
    }
}

static int32 client_read_int32(const remote_process_client *client)
{
    int32 data;
    client_read_bytes(client, &data, 4);
    FIX_BYTE_ORDER(4);
    return data;
}

static int64 client_read_int64(const remote_process_client *client)
{
    int64 data;
    client_read_bytes(client, &data, 8);
    FIX_BYTE_ORDER(8);
    return data;
}

static double client_read_double(const remote_process_client *client)
{
    double data;
    client_read_bytes(client, &data, 8);
    FIX_BYTE_ORDER(8);
    return data;
}

static char *client_read_string(const remote_process_client *client)
{
    int32 length = READ_INT32();
    char *str;
    if (length < 0) {
        exit(10014);
    }

    str = (char*)malloc(length + 1);
    if (NULL == str) {
        /* Out of memory, probably incorrect length */
        exit(10014);
    }

    client_read_bytes(client, str, (size_t)length);
    str[length] = 0;
    return str;
}

int client_read_boolean(const remote_process_client *client)
{
    return 0 != client_read_byte(client);
}

static void client_flush_buffer(remote_process_client *client)
{
    if (client->write_pointer == client->write_buffer)
        return;

    if (0 != socket_send(client->socket, client->write_buffer, client->write_pointer - client->write_buffer)) {
        exit(10013);
    }
    client->write_pointer = client->write_buffer;
}

static void client_write_bytes(remote_process_client *client, const void *data, size_t size)
{
    ptrdiff_t bytes_left;
    while ((bytes_left = client->write_buffer + CLIENT_WRITE_BUFFER_SIZE - client->write_pointer) <= (ptrdiff_t)size) {
        memcpy(client->write_pointer, data, bytes_left);
        data = (const char*)data + bytes_left;
        size -= bytes_left;
        client->write_pointer += bytes_left;
        client_flush_buffer(client);
    }
    memcpy(client->write_pointer, data, size);
    client->write_pointer += size;
}

static void client_write_byte(remote_process_client *client, unsigned char x)
{
    client_write_bytes(client, &x, 1);
}

static void client_write_int32(remote_process_client *client, int32 data)
{
    FIX_BYTE_ORDER(4);
    client_write_bytes(client, &data, 4);
}

static void client_write_double(remote_process_client *client, double data)
{
    FIX_BYTE_ORDER(8);
    client_write_bytes(client, &data, 8);
}

static void client_write_string(remote_process_client *client, const char *str)
{
    int32 length = (int32)strlen(str);
    WRITE_INT32(length);
    client_write_bytes(client, str, length);
}

void client_init(remote_process_client *client, const char* host, unsigned port, const char *token)
{

    client->is_little_endian = is_little_endian();
    client->socket = socket_init_tcp();
    client->token = token;
    client->write_pointer = client->write_buffer;

    client->cells_read = client->cell_visibilities_read = 0;
    memset(client->cells, 0, sizeof(client->cells));
    client->cell_visibilities = NULL;

    if (0 != socket_connect(client->socket, host, port)) {
        exit(10001);
    }

    socket_enable_nagle_algorithm(client->socket, 0);
}

void client_close(remote_process_client *client)
{
    if (INVALID_SOCKET != client->socket) {
        socket_close(client->socket);
        client->socket = INVALID_SOCKET;
    }
    if (NULL != client->cell_visibilities) {
        free(client->cell_visibilities);
    }
}

void client_write_token(remote_process_client *client, const char *token)
{
    WRITE_BYTE(MSG_AUTHENTICATION_TOKEN);
    WRITE_STRING(token);
    FLUSH();
}

void client_write_protocol_version(remote_process_client *client)
{
    WRITE_BYTE(MSG_PROTOCOL_VERSION);
    WRITE_INT32(2);
    FLUSH();
}

void client_write_move(remote_process_client *client, const struct ct_move *move)
{
    WRITE_BYTE(MSG_MOVE_MESSAGE);
    WRITE_BYTE(1);
    WRITE_BYTE((signed char)move->action);
    WRITE_BYTE((signed char)move->direction);
    WRITE_INT32(move->position.x);
    WRITE_INT32(move->position.y);
    FLUSH();
}

int client_read_team_size(const remote_process_client *client) {
    VERIFY(READ_ENUM(ct_message_type), MSG_TEAM_SIZE);
    return READ_INT32();
}

void client_read_game_context(const remote_process_client *client, struct ct_game *game) {
    VERIFY(READ_ENUM(ct_message_type), MSG_GAME_CONTEXT);
    if (!READ_BOOL()) {
        exit(10017);
    }

    memset(game, 0xCC, sizeof(struct ct_game));
    game->move_count = READ_INT32();
    game->last_player_elimination_score = READ_INT32();
    game->player_elimination_score = READ_INT32();
    game->trooper_elimination_score = READ_INT32();
    game->trooper_damage_score_factor = READ_DOUBLE();
    game->stance_change_cost = READ_INT32();
    game->standing_move_cost = READ_INT32();
    game->kneeling_move_cost = READ_INT32();
    game->prone_move_cost = READ_INT32();
    game->commander_aura_bonus_action_points = READ_INT32();
    game->commander_aura_range = READ_DOUBLE();
    game->commander_request_enemy_disposition_cost = READ_INT32();
    game->commander_request_enemy_disposition_max_offset = READ_INT32();
    game->field_medic_heal_cost = READ_INT32();
    game->field_medic_heal_bonus_hitpoints = READ_INT32();
    game->field_medic_heal_self_bonus_hitpoints = READ_INT32();
    game->sniper_standing_stealth_bonus = READ_DOUBLE();
    game->sniper_kneeling_stealth_bonus = READ_DOUBLE();
    game->sniper_prone_stealth_bonus = READ_DOUBLE();
    game->sniper_standing_shooting_range_bonus = READ_DOUBLE();
    game->sniper_kneeling_shooting_range_bonus = READ_DOUBLE();
    game->sniper_prone_shooting_range_bonus = READ_DOUBLE();
    game->scout_stealth_bonus_negation = READ_DOUBLE();
    game->grenade_throw_cost = READ_INT32();
    game->grenade_throw_range = READ_DOUBLE();
    game->grenade_direct_damage = READ_INT32();
    game->grenade_collateral_damage = READ_INT32();
    game->medikit_use_cost = READ_INT32();
    game->medikit_bonus_hitpoints = READ_INT32();
    game->medikit_heal_self_bonus_hitpoints = READ_INT32();
    game->field_ration_eat_cost = READ_INT32();
    game->field_ration_bonus_action_points = READ_INT32();
}

static void client_read_players(const remote_process_client *client, struct ct_mutable_world *world) {
    int players_count = READ_INT32();
    int i;
    world->players_count = players_count;
    if (players_count < 0) {
        exit(10003);
    }

    world->players = (struct ct_player*)malloc(players_count * sizeof(struct ct_player));
    memset(world->players, 0xCC, players_count * sizeof(struct ct_player));

    for (i = 0; i < players_count; ++i) {
        struct ct_player *player = &world->players[i];
        if (!READ_BOOL()) {
            exit(10004);
        }
        player->id = READ_INT64();
        player->name = READ_STRING();
        player->score = READ_INT32();
        player->strategy_crashed = READ_BOOL();
        player->approximate_position.x = READ_INT32();
        player->approximate_position.y = READ_INT32();
    }
}

static void client_read_trooper(const remote_process_client *client, struct ct_trooper *trooper) {
    if (!READ_BOOL()) {
        exit(10006);
    }
    memset(trooper, 0xCC, sizeof(*trooper));

    trooper->id = READ_INT64();
    trooper->position.x = READ_INT32();
    trooper->position.y = READ_INT32();
    trooper->player_id = READ_INT64();
    trooper->teammate_index = READ_INT32();
    trooper->is_teammate = READ_BOOL();
    trooper->type = READ_ENUM(ct_trooper_type);
    trooper->stance = READ_ENUM(ct_trooper_stance);
    trooper->hitpoints = READ_INT32();
    trooper->max_hitpoints = READ_INT32();
    trooper->action_points = READ_INT32();
    trooper->initial_action_points = READ_INT32();
    trooper->vision_range = READ_DOUBLE();
    trooper->shooting_range = READ_DOUBLE();
    trooper->shoot_cost = READ_INT32();
    trooper->standing_damage = READ_INT32();
    trooper->kneeling_damage = READ_INT32();
    trooper->prone_damage = READ_INT32();
    trooper->damage = READ_INT32();
    trooper->is_holding_grenade = READ_BOOL();
    trooper->is_holding_medkit = READ_BOOL();
    trooper->is_holding_field_ration = READ_BOOL();
}

static void client_read_troopers(const remote_process_client *client, struct ct_mutable_world *world) {
    int i;
    int troopers_count = READ_INT32();
    world->troopers_count = troopers_count;

    if (troopers_count < 0) {
        exit(10005);
    }

    world->troopers = (struct ct_trooper*)malloc(troopers_count * sizeof(struct ct_trooper));
    memset(world->troopers, 0xCC, troopers_count * sizeof(struct ct_trooper));

    for (i = 0; i < troopers_count; ++i) {
        client_read_trooper(client, &world->troopers[i]);
    }
}

static void client_read_bonuses(const remote_process_client *client, struct ct_mutable_world *world) {
    int i;
    int bonuses_count = READ_INT32();
    world->bonuses_count = bonuses_count;

    if (bonuses_count < 0) {
        exit(10009);
    }

    world->bonuses = (struct ct_bonus*)malloc(bonuses_count * sizeof(struct ct_bonus));
    memset(world->bonuses, 0xCC, bonuses_count * sizeof(struct ct_bonus));

    for (i = 0; i < bonuses_count; ++i) {
        struct ct_bonus *bonus = &world->bonuses[i];
        if (!READ_BOOL()) {
            exit(10010);
        }
        bonus->id = READ_INT64();
        bonus->position.x = READ_INT32();
        bonus->position.y = READ_INT32();
        bonus->type = READ_ENUM(ct_bonus_type);
    }
}

static void client_read_cells(remote_process_client *client, struct ct_mutable_world *world) {
    int width, height, x, y;

    if (!client->cells_read)
    {
        client->cells_read = 1;
        memset(client->cells, 0, sizeof(client->cells));
        width = world->width;
        height = world->height;
        /* I won't actually read sizes here, instead I'll just verify their correctness */
        if (READ_INT32() != width) {
            exit(10007);
        }

        for (x = 0; x < width; ++x) {
            if (READ_INT32() != height) {
                exit(10008);
            }
            for (y = 0; y < height; ++y) {
                client->cells[y][x] = READ_ENUM(ct_cell_type);
            }
        }
    }
    assert(sizeof(client->cells) == sizeof(world->cells));
    memcpy(world->cells, client->cells, sizeof(client->cells));
}

static void client_read_cell_visibilities(remote_process_client *client, struct ct_mutable_world *world) {
    int width, height, x0, y0, x1, y1;

    if (!client->cell_visibilities_read)
    {
        client->cell_visibilities_read = 1;
        client->cell_visibilities = (ct_cell_visibilities_t *)malloc(sizeof(ct_cell_visibilities_t));
        memset(client->cell_visibilities, 0, sizeof(*client->cell_visibilities));
        width = world->width;
        height = world->height;
        /* I won't actually read sizes here, instead I'll just verify their correctness */
        if (READ_INT32() != width) {
            exit(10018);
        }
        if (READ_INT32() != height) {
            exit(10019);
        }
        if (READ_INT32() != _STANCE_COUNT_) {
            exit(10020);
        }

        for (x0 = 0; x0 < width; ++x0) {
            for (y0 = 0; y0 < height; ++y0) {
                for (x1 = 0; x1 < width; ++x1) {
                    for (y1 = 0; y1 < height; ++y1) {
                        int i;
                        ct_bool vis[_STANCE_COUNT_];
                        client_read_bytes(client, vis, _STANCE_COUNT_);
                        for (i = 0; i < _STANCE_COUNT_; ++i) {
                            (*client->cell_visibilities)[i][y0][x0][y1][x1] = vis[i];
                        }
                    }
                }
            }
        }
    }

    world->cell_visibilities = (ct_cell_visibilities_t *)malloc(sizeof(ct_cell_visibilities_t));
    memcpy(world->cell_visibilities, client->cell_visibilities, sizeof(*world->cell_visibilities));
}

static void client_read_world(remote_process_client *client, struct ct_mutable_world *world) {
    if (!READ_BOOL()) {
        exit(10002);
    }

    memset(world, 0xCC, sizeof(*world));

    world->move_index = READ_INT32();
    world->width = READ_INT32();
    world->height = READ_INT32();

    /* Will return error if the map sizes are bigger than we expect */
    if (world->width > MAP_WIDTH_ALIGNED) {
        exit(10007);
    }
    if (world->height > MAP_HEIGHT) {
        exit(10008);
    }

    client_read_players(client, world);
    client_read_troopers(client, world);
    client_read_bonuses(client, world);

    client_read_cells(client, world);
    client_read_cell_visibilities(client, world);
}

int client_read_player_context(remote_process_client *client, struct ct_player_context *context) {
    enum ct_message_type message_type = READ_ENUM(ct_message_type);
    if (MSG_GAME_OVER == message_type) {
        return -1;
    }
    VERIFY(message_type, MSG_PLAYER_CONTEXT);
    if (!READ_BOOL()) {
        return -1;
    }
    client_read_trooper(client, &context->trooper);
    client_read_world(client, &context->world);
    return 0;
}


text:
namespace
{
	using namespace ogl;
}

void Context::collect_garbage()
{
	for ( auto& obj : this->disposal_queue )
		obj->orphan();

	this->disposal_queue.clear();
}	// collect_garbage

Shader* Context::use_shader( const Shader::Type ty )
{
	if ( ty == Shader::Type::Unknown )
	{
		if ( this->active_shader )
			this->active_shader->stopUsingProgram();
		this->active_shader = nullptr;
	}
	else
	{
		auto it = std::find_if( this->shaders.begin(), this->shaders.end(), [ &ty ]( const std::shared_ptr<Shader>& what ) { return what->type == ty;  } );
		if ( it == this->shaders.end() )
			throw std::runtime_error( "Shader type not found" );
		this->active_shader = it->get();
		this->active_shader->useProgram();
	}
	return this->active_shader;
}


text:
(function(window, document, $) {
  'use strict';

  var pluginName = 'asSelectable';

  var Plugin = $[pluginName] = function(element, options) {
    this.element = element;
    this.$element = $(element);
    this.options = $.extend({}, Plugin.defaults, options, this.$element.data());

    this.init();
  };

  Plugin.defaults = {
    allSelector: '.selectable-all',
    itemSelector: '.selectable-item',
    rowSelector: 'tr',
    rowSelectable: false,
    rowActiveClass: 'active',
    onChange: null
  };

  Plugin.prototype = {
    constructor: Plugin,
    init: function() {
      var self = this;
      var options = this.options;

      self.$element.on('change', options.allSelector, function() {
        var value = $(this).prop("checked");
        self.getItems().each(function() {
          var $one = $(this);
          $one.prop("checked", value).trigger('change', [true]);;
          self.selectRow($one, value);
        });
      });

      self.$element.on('click', options.itemSelector, function(e) {
        var $one = $(this),
          value = $one.prop("checked");
        self.selectRow($one, value);
        e.stopPropagation();
      });

      self.$element.on('change', options.itemSelector, function() {
        var $all = self.$element.find(options.allSelector),
          $row = self.getItems(),
          total = $row.length,
          checked = self.getSelected().length;

        if (total === checked) {
          $all.prop('checked', true);
        } else {
          $all.prop('checked', false);
        }

        self._trigger('change', checked);

        if (typeof options.callback === 'function') {
          options.callback.call(this);
        }
      });

      if (options.rowSelectable) {
        self.$element.on('click', options.rowSelector, function(e) {
          if ("checkbox" !== e.target.type && "button" !== e.target.type && "a" !== e.target.tagName.toLowerCase() && !$(e.target).parent("div.checkbox-custom").length) {
            var $checkbox = $(options.itemSelector, this),
              value = $checkbox.prop("checked");
            $checkbox.prop("checked", !value);
            self.selectRow($checkbox, !value);
          }
        });
      }
    },

    selectRow: function(item, value) {
      if (value) {
        item.parents(this.options.rowSelector).addClass(this.options.rowActiveClass);
      } else {
        item.parents(this.options.rowSelector).removeClass(this.options.rowActiveClass);
      }
    },

    getItems: function() {
      return this.$element.find(this.options.itemSelector);
    },

    getSelected: function() {
      return this.getItems().filter(':checked');
    },

    _trigger: function(eventType) {
      var method_arguments = Array.prototype.slice.call(arguments, 1),
        data = [this].concat(method_arguments);

      // event
      this.$element.trigger(pluginName + '::' + eventType, data);

      // callback
      eventType = eventType.replace(/\b\w+\b/g, function(word) {
        return word.substring(0, 1).toUpperCase() + word.substring(1);
      });
      var onFunction = 'on' + eventType;
      if (typeof this.options[onFunction] === 'function') {
        this.options[onFunction].apply(this, method_arguments);
      }
    },
  };

  $.fn[pluginName] = function(options) {
    if (typeof options === 'string') {
      var method = options;
      var method_arguments = Array.prototype.slice.call(arguments, 1);

      if (/^\_/.test(method)) {
        return false;
      } else if ((/^(get)/.test(method))) {
        var api = this.first().data(pluginName);

        if (api && typeof api[method] === 'function') {
          return api[method].apply(api, method_arguments);
        }
      } else {
        return this.each(function() {
          var api = $.data(this, pluginName);
          if (api && typeof api[method] === 'function') {
            api[method].apply(api, method_arguments);
          }
        });
      }
    } else {
      return this.each(function() {
        if (!$.data(this, pluginName)) {
          $.data(this, pluginName, new Plugin(this, options));
        }
      });
    }
  };
})(window, document, jQuery);


text:
require_relative '../../../../lib/aws/s3/s3_object'
require 'net/http'

describe AWS::S3::S3Object do
  let(:signing_date) { 'fake_date_string' }
  let(:bucket) { double(:name => 'test-bucket') }
  let(:object_name) { 'test-object' }
  subject(:object) { AWS::S3::S3Object.new(bucket, object_name) }

  describe '#body' do
    it { should respond_to(:body, :body=) }

    it 'nils body_stream on set' do
      object.body_stream = 'a stream'

      expect { object.body = 'test' }.to change(subject, :body_stream).from('a stream').to(nil)
    end
  end

  describe '#body_stream' do
    it { should respond_to(:body_stream, :body_stream=) }

    it 'nils body on set' do
      object.body = 'test'

      expect { object.body_stream = 'a stream' }.to change(subject, :body).from('test').to(nil)
    end
  end

  describe '#headers' do
    it { should respond_to(:headers) }

    describe 'defaults' do
      subject { object.headers }

      it { should include 'Content-Type' => 'application/x-www-form-urlencoded' }
      it { should include 'Expect' => '100-continue' }
    end
  end

  it { should respond_to(:acl, :acl=) }

  describe '#request_headers' do
    subject { object.request_headers }

    it { should include object.headers }
    it { should_not include 'Date' }
    it { should_not include 'Authorization' }

    context 'when body set' do
      before { object.body = "\x80\u3042" }

      it { should include 'Content-Length' => '4' }
    end

    context 'when body_stream set' do
      before { object.body_stream = double(:size => 42) }

      it { should include 'Content-Length' => '42' }
    end

    context 'when acl set' do
      before { object.acl = 'public-read' }

      it { should include 'x-amz-acl' => 'public-read' }
    end

    describe 'Date header' do
      subject { object.request_headers(signing_date) }

      it { should include 'Date' => signing_date }
    end

    describe 'Authorization header' do
      let(:authorization) { 'fake_authorization_string' }
      subject { object.request_headers(signing_date, authorization) }

      it { should include 'Authorization' => authorization }
    end
  end

  describe '#signing_string' do
    let(:method) { 'PUT' }
    before {
      object.acl = 'public-read'
      object.headers['Content-Type'] = 'something/else'
    }
    subject { object.signing_string(method, signing_date) }

    it { should eq "#{method}

something/else
#{signing_date}
x-amz-acl:public-read
/#{bucket.name}/#{object_name}"
    }
  end
end


text:
package main

import (
	"fmt"
	"time"

	"code.cloudfoundry.org/lager"
	uaaclient "github.com/cloudfoundry-community/go-uaa"

	m "github.com/alphagov/paas-cf/tools/metrics/pkg/metrics"
)

type UAAClientConfig struct {
	Endpoint     string
	ClientID     string
	ClientSecret string
}

func UAAGauges(
	logger lager.Logger,
	cfg *UAAClientConfig,
	interval time.Duration,
) m.MetricReadCloser {
	return m.NewMetricPoller(interval, func(w m.MetricWriter) error {
		lsession := logger.Session("uaa-gauges")

		metrics, err := UAAMetrics(lsession, cfg)
		if err != nil {
			lsession.Error("Failed to get UAA metrics", err)
			return err
		}

		lsession.Info("Writing UAA metrics")
		return w.WriteMetrics(metrics)
	})
}

func UAAMetrics(logger lager.Logger, cfg *UAAClientConfig) ([]m.Metric, error) {
	lsession := logger.Session("uaa-metrics")
	lsession.Info("Started UAA metrics")

	uaa := uaaclient.New(cfg.Endpoint, "").WithClientCredentials(
		cfg.ClientID, cfg.ClientSecret, uaaclient.JSONWebToken,
	)

	err := uaa.Validate()
	if err != nil {
		lsession.Error("Failed to validate UAA client", err)
		return []m.Metric{}, err
	}
	lsession.Info("Validated UAA client")

	users, err := uaa.ListAllUsers("", "", "origin,lastLogonTime", "")
	if err != nil {
		lsession.Error("Failed to list all UAA users", err)
		return []m.Metric{}, err
	}
	lsession.Info("Listed all UAA users")

	metrics := make([]m.Metric, 0)

	lsession.Info("Computing UAA users by origin")
	metrics = append(metrics, UAAUsersByOriginGauges(users)...)

	lsession.Info("Computing active UAA users by origin")
	metrics = append(metrics, UAAActiveUsersByOriginGauges(users)...)

	lsession.Info(fmt.Sprintf("Found %d metrics", len(metrics)))

	lsession.Info("Finished UAA metrics")
	return metrics, nil
}

func UAAUsersByOriginGauges(users []uaaclient.User) []m.Metric {
	usersByOriginCount := make(map[string]int, 0)
	for _, user := range users {
		usersByOriginCount[user.Origin] += 1
	}

	metrics := make([]m.Metric, 0)
	for origin, usersCount := range usersByOriginCount {
		metrics = append(metrics, m.Metric{
			Kind:  m.Gauge,
			Time:  time.Now(),
			Name:  "uaa.users",
			Value: float64(usersCount),
			Tags: m.MetricTags{
				{Label: "origin", Value: origin},
			},
			Unit: "count",
		})
	}

	return metrics
}

func UAAActiveUsers(users []uaaclient.User) []uaaclient.User {
	activeUsers := make([]uaaclient.User, 0)

	thirtyDaysAgo := time.Now().Truncate(24 * time.Hour).Add(-1 * 30 * 24 * time.Hour)
	thirtyDaysAgoTimestamp := thirtyDaysAgo.Unix()

	for _, user := range users {
		lastLogonTimestamp := int64(user.LastLogonTime / 1000)

		if lastLogonTimestamp >= thirtyDaysAgoTimestamp {
			activeUsers = append(activeUsers, user)
		}
	}

	return activeUsers
}

func UAAActiveUsersByOriginGauges(users []uaaclient.User) []m.Metric {
	usersByOriginCount := make(map[string]int, 0)

	for _, user := range UAAActiveUsers(users) {
		usersByOriginCount[user.Origin] += 1
	}

	metrics := make([]m.Metric, 0)
	for origin, usersCount := range usersByOriginCount {
		metrics = append(metrics, m.Metric{
			Kind:  m.Gauge,
			Time:  time.Now(),
			Name:  "uaa.active.users",
			Value: float64(usersCount),
			Tags: m.MetricTags{
				{Label: "origin", Value: origin},
			},
			Unit: "count",
		})
	}

	return metrics
}


text:
import flask
from flask import Blueprint,jsonify,request
import os.path
import urllib

from ..config.qconfig import Config
from ..libs.qhelper import Qhelper
from ..libs.qio import Qio

qengine_qmetadata = Blueprint('qengine_qmetadata', __name__)
@qengine_qmetadata.route('/question/<string:base>/<string:id>/<string:version>',methods=['GET'])
def getQuestionMetadata(base,id,version):

	config = Config()
	qhelper = Qhelper()
	qio = Qio()

	# check pass key if set
	if config.QENGINE_PASSKEY != None:
		presult = qhelper.checkPassKey(request.args.get('passKey'))
		if presult == 1:
			return jsonify({'error':'passkey is required'})
		elif presult == 2:
			return jsonify({'error':'invalid passkey format'})
		elif presult == 3:
			return jsonify({'error':'invalid passkey'})

	base = urllib.unquote(base)
	id = urllib.unquote(id)
	version = urllib.unquote(version)

	# check that question file exists first
	if qio.getQuestion(base,id,version) == False:
		badfile = {'error':'The question you requested does not exist'}
		return flask.make_response(jsonify(badfile), 404)

	# get metadata
	md = qio.getMetadata(base,id)
	if md == False:
		nometadata = {'questionmetadata':'none'}
		return jsonify(nometadata)
	else:
		return jsonify({'questionmetadata':md})


text:
package org.clapper.util.cmdline;

import java.util.Comparator;

/**
 * Used solely by <tt>UsageInfo</tt>, an instance of this class compares
 * <tt>OptionInfo</tt> items, by short option name or long option name, in
 * a case-insensitive manner.
 *
 * @see UsageInfo
 * @see OptionInfo
 */
final class OptionComparator implements Comparator<OptionInfo>
{
    private boolean ignoreCase = false;

    public OptionComparator()
    {
        // Nothing to do
    }

    public OptionComparator (boolean ignoreCase)
    {
        this.ignoreCase = ignoreCase;
    }

    public int compare (OptionInfo o1, OptionInfo o2)
    {
        String s1 = getComparisonString (o1);
        String s2 = getComparisonString (o2);

        return ignoreCase ? s1.compareToIgnoreCase (s2) : s1.compareTo (s2);
    }

    public boolean equals (Object o)
    {
        return (this.getClass().isInstance (o));
    }

    public int hashCode()                                            // NOPMD
    {
        return super.hashCode();
    }

    private String getComparisonString (OptionInfo opt)
    {
        String result = "";

        if (opt.shortOption != UsageInfo.NO_SHORT_OPTION)
            result = String.valueOf (opt.shortOption);
        else if (opt.longOption != null)
            result = opt.longOption;

        return result;
    }
}


text:
package models;

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

/**
 * A generic Wrapper-Class for a List to provide Pagination
 *
 * @author Patrick Thum, Xceptance Software Technologies GmbH, Germany
 * @param <T>
 *            the Type of the List
 */

public class PageList<T>
{
    /**
     * the complete list with all entries
     */
    private List<T> allEntrys;

    /**
     * number of entries per page
     */
    private int pageSize;

    /**
     * Default Constructor
     */
    public PageList()
    {
        this.allEntrys = new ArrayList<T>();
        this.pageSize = 0;
    }

    /**
     * Constructor to initialize the Object
     *
     * @param in
     *            the List with Entries
     * @param size
     *            the Size of Entries on one Page
     */
    public PageList(List<T> in, int size)
    {
        this.allEntrys = in;
        this.pageSize = size;
    }

    /**
     * @return the complete list which has been initialized
     */
    public List<T> getAllEntrys()
    {
        return allEntrys;
    }

    /**
     * Sets the List to handle
     *
     * @param allEntrys
     *            the List with Entries
     */
    public void setAllEntrys(List<T> allEntrys)
    {
        this.allEntrys = allEntrys;
    }

    /**
     * @return the Number of Entries on a Page
     */

    public int getPagesize()
    {
        return this.pageSize;
    }

    /**
     * Sets the Number of Entries on a Page
     *
     * @param size
     *            the Number of Entries
     */

    public void setPagesize(int size)
    {
        this.pageSize = size;
    }

    /**
     * @return the Number of Elements in the List
     */
    public int getEntryCount()
    {
        return allEntrys.size();
    }

    /**
     * @return the Number of Pages
     */
    public int getPageCount()
    {
        if (pageSize <= 0)
        { // return 1 if the number of entries on a page is below 1
            return 1;
        }

        int entrys = allEntrys.size();
        if (entrys < pageSize)
        { // return 1 if the number of entries in the list is below the number of entries on a page
            return 1;
        }
        else
        { // calculate the number of pages
            return (int) Math.ceil((entrys / new Double(pageSize)));
        }
    }

    /**
     * @param page
     *            the Page-number
     * @return a List which contains all Entries of the specified Page
     */
    public List<T> getPage(int page)
    {
        if (pageSize <= 0)
        { // the number of entries is less than 0, return all
            return allEntrys;
        }
        if (page > getPageCount())
        { // the page-number which is called is greater than the number of existing pages, return nothing
            return new ArrayList<T>();
        }
        // get the index-number of the last entry on the page
        int endIndex = (page * pageSize) - 1;
        // get the index-number of the first entry on the page
        int startIndex = endIndex - pageSize + 1;

        if (endIndex >= getEntryCount())
        { // the calculated last entry is greater than the number of existing entries
            endIndex = getEntryCount();
        }
        else
        { // the last entry exists, but the sublist takes the endIndex as EXCLUSIVE value
            endIndex += 1;
        }
        return allEntrys.subList(startIndex, endIndex);
    }
}


text:
set -e

# Script to workaround docker-machine/boot2docker OSX host volume issues: https://github.com/docker-library/mysql/issues/99

echo '* Working around permission errors locally by making sure that "mysql" uses the same uid and gid as the host volume'

TARGET_UID=$(stat -c "%u" /var/lib/mysql)
echo '-- Setting mysql user to use uid '$TARGET_UID
usermod -o -u $TARGET_UID mysql || true

TARGET_GID=$(stat -c "%g" /var/lib/mysql)
echo '-- Setting mysql group to use gid '$TARGET_GID
groupmod -o -g $TARGET_GID mysql || true

echo
echo '* Starting MySQL'
chown -R mysql:root /var/run/mysqld/

/entrypoint.sh mysqld --user=mysql --console
/docker-entrypoint.sh