text:
var noble = require('noble');
var events = require('events');
var eventEmitter = new events.EventEmitter();

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

var ble = false;
var serviceBase = ['d506' , 'a904deb947482c7f4a124842']; // 0x0000
var services = {
    ControlService                : '0001', ///< Myo info service
    MyoInfoCharacteristic         : '0101', ///< Serial number for this Myo and various parameters which
                                            ///< are specific to this firmware. Read-only attribute.
                                            ///< See myohw_fw_info_t.
    FirmwareVersionCharacteristic : '0201', ///< Current firmware version. Read-only characteristic.
                                            ///< See myohw_fw_version_t.
    CommandCharacteristic         : '0401', ///< Issue commands to the Myo. Write-only characteristic.
                                            ///< See myohw_command_t.

    ImuDataService                : '0002', ///< IMU service
    IMUDataCharacteristic         : '0402', ///< See myohw_imu_data_t. Notify-only characteristic.
    MotionEventCharacteristic     : '0502', ///< Motion event data. Indicate-only characteristic.

    ClassifierService             : '0003', ///< Classifier event service.
    ClassifierEventCharacteristic : '0103', ///< Classifier event data. Indicate-only characteristic. See myohw_pose_t.

    EmgDataService                : '0005', ///< Raw EMG data service.
    EmgData0Characteristic        : '0105', ///< Raw EMG data. Notify-only characteristic.
    EmgData1Characteristic        : '0205', ///< Raw EMG data. Notify-only characteristic.
    EmgData2Characteristic        : '0305', ///< Raw EMG data. Notify-only characteristic.
    EmgData3Characteristic        : '0405'  ///< Raw EMG data. Notify-only characteristic.
};
// Standard Bluetooth device services.
var bluetoothStandard = {
    BatteryService                : '180f', ///< Battery service
    BatteryLevelCharacteristic    : '2a19', ///< Current battery level information. Read/notify characteristic.

    DeviceService                 : '1800',
    DeviceName                    : '2a00' ///< Device name data. Read/write characteristic.
};

function format(data){
    return serviceBase[0] + data + serviceBase[1];
}

for(var k in services){
    services[k] = format(services[k]);
}

noble.on('stateChange', function (state) {
    if (state === 'poweredOn') {
        ble = true;
    } else {
        console.log('bluetooth LE down');
        ble = false;
    }
});

function startScan(callback) {
    if(ble){
        noble.startScanning(services.ControlService);
        callback(false, 'bluetooth LE up');
    }else {
        setTimeout(function () {
            startScan(callback);
        }, 100);
    }
}

function stopScan(){
    noble.stopScanning();
}

var myo = {};

myo.scan = {};
myo.scan.start = startScan;
myo.scan.stop = stopScan;
myo.connected = {};
myo.event = eventEmitter;
myo.connectedSize = function(){
    return Object.size(myo.connected);
};
myo.key = function(){
    return Object.keys(myo.connected);
};
myo.quickConnect = function(callback){
  myo.scan.start(function(err, data){
        if(err){
            callback(true, data);
        }else{
            var loop = setInterval(function(){
                if(myo.connectedSize() > 0){
                    var id = myo.key()[0];
                    if(myo.connected[id].ready) {
                        myo.scan.stop();
                        clearInterval(loop);
                        callback(false, id);
                    }
                }
            },100);
        }
    });
};

function registerUtil(peripheral, callbackMain){
    myo.connected[peripheral.id].disconnect = function(){
        peripheral.disconnect();
    };

    callbackMain();
}

function registerGeneric(GenericAccess, peripheral, callbackMain){
    GenericAccess.discoverCharacteristics([bluetoothStandard.DeviceName], function(error, characteristics) {
        if (characteristics.length > 0) {
            myo.connected[peripheral.id].generic = {};
            myo.connected[peripheral.id].generic.setName = function (data, callback) {
                characteristics[0].write(new Buffer(data, 'utf-8'), false, function (err) {
                    if (err) {
                        callback(true, err);
                    } else {
                        callback(false, data);
                    }
                });
            };

            myo.connected[peripheral.id].generic.getName = function (callback) {
                characteristics[0].read(function (err, data) {
                    if (err) {
                        callback(true, err);
                    } else {
                        var readable = data.toString('utf-8');
                        callback(false, readable);
                    }
                });
            };
            callbackMain();
        } else {
            callbackMain(true, 'characteristic not found');
        }
    });
}

function registerBattery(Battery, peripheral, callbackMain){
    Battery.discoverCharacteristics([bluetoothStandard.BatteryLevelCharacteristic], function (error, characteristics) {
        if (characteristics.length > 0) {
            myo.connected[peripheral.id].battery = function(callback) {
                var batteryChar = characteristics[0];
                batteryChar.read(function (err, data) {
                    if (err) {
                        callback(true, err);
                    } else {
                        callback(false, data.readUInt8(0));
                    }
                });
            };

            callbackMain();
        } else {
            callbackMain(true, 'characteristic not found');
        }
    });
}

function registerControl(Control, peripheral, callbackMain){
    Control.discoverCharacteristics([services.CommandCharacteristic, services.FirmwareVersionCharacteristic, services.MyoInfoCharacteristic], function (error, characteristics) {
        if (characteristics.length == 3) {
            var myoInfo = characteristics[0];
            var firmware = characteristics[1];
            var command = characteristics[2];

            myo.connected[peripheral.id].firmware = function(callback){
                 firmware.read(function(err, data){
                    if(err){
                        callback(true, data);
                    } else {
                        var hardware;
                        switch (data.readUInt16LE(6)){
                            case 0:
                                hardware = "undefined";
                                break;
                            case 1:
                                hardware = "Myo Alpha (REV-C) hardware";
                                break;
                            case 2:
                                hardware = "Myo (REV-D) hardware.";
                                break;
                            default :
                                hardware = "undefined";
                                break;
                        }
                        callback(false, {
                            major: data.readUInt16LE(0),
                            minor: data.readUInt16LE(2),
                            patch: data.readUInt16LE(4),
                            hardware_rev: hardware
                        })
                    }
                 });
            };

            myo.connected[peripheral.id].info = function(callback){
                myoInfo.read(function(err, data){
                    if (err) {
                        callback(true, err);
                    } else {
                        var unlock_pose;
                        var unlock_pose_raw = data.readUInt16LE(6);
                        switch(unlock_pose_raw){
                            case 0:
                                unlock_pose = "rest";
                                break;
                            case 1:
                                unlock_pose = "fist";
                                break;
                            case 2:
                                unlock_pose = "wave_in";
                                break;
                            case 3:
                                unlock_pose = "wave_out";
                                break;
                            case 4:
                                unlock_pose = "fingers_spread";
                                break;
                            case 5:
                                unlock_pose = "double_tap";
                                break;
                            default :
                                unlock_pose = "unknow pose";
                                break;
                        }

                        var classifier_type;
                        if(data.readUInt8(8) == 0){
                            classifier_type = "default";
                        } else {
                            classifier_type = "personalized";
                        }
                        callback(false, {
                            serial_number:data.readUInt8(0).toString()+data.readUInt8(1).toString()+data.readUInt8(2).toString()+data.readUInt8(3).toString()+data.readUInt8(4).toString()+data.readUInt8(5).toString(),
                            unlock_pose:unlock_pose,
                            active_classifier_type:classifier_type,
                            active_classifier_index:data.readUInt8(9),
                            has_custom_classifier:data.readUInt8(10),
                            stream_indicating:data.readUInt8(11),
                            sku:data.readUInt8(12)
                        });
                    }
                });
            };

            myo.connected[peripheral.id].vibrate = function(type){
                var len = 0x00;
                if(type == "light"){
                    len = 0x01;
                } else  if(type == "medium"){
                    len = 0x02;
                } else  if(type == "strong"){
                    len = 0x03;
                }
                command.write(new Buffer([0x03, 1, len]));
            };

            myo.connected[peripheral.id].vibrate2 = function(time, strength){
                var buf = new Buffer(2);
                buf.writeUInt16LE(time, 0); // Milliseconds
                var buf2 = new Buffer(1);
                buf2.writeUInt8(strength, 0); // 0 - 255
                command.write(new Buffer([0x07, 18, buf[0], buf[1], buf2[0]]));
            };

            myo.connected[peripheral.id].notify = function(){
                command.write(new Buffer([0x0b, 1, 0x00]));
            };

            myo.connected[peripheral.id].setMode = function(emg, imu, classifier, callback){
                var data = {};

                if(emg == "none"){
                    data.emg = 0x00;
                } else if(emg == "send"){
                    data.emg = 0x02;
                } else if(emg == "raw"){
                    data.emg = 0x03;
                }else{
                    data.emg = 0x02;
                }

                if(imu == "none"){
                    data.imu = 0x00;
                } else if(imu == "data"){
                    data.imu = 0x01;
                } else if(imu == "events"){
                    data.imu = 0x02;
                } else if(imu == "all"){
                    data.imu = 0x03;
                } else if(imu == "raw"){
                    data.imu = 0x04;
                } else {
                    data.imu = 0x03;
                }

                if(classifier == "disabled"){
                    data.classifier = 0x00;
                } else if(classifier == "enabled"){
                     data.classifier = 0x01;
                } else {
                    data.classifier = 0x01;
                }

                command.write(new Buffer([0x01, 3, data.emg, data.imu, data.classifier]), true, function(err){
                    if(err) console.log(err);
                    callback();
                });
            };

            myo.connected[peripheral.id].deepSleep = function(callback){
                command.write(new Buffer([0x04, 0]), true,  function(err){
                    if(err) console.log(err);
                    callback();
                });
            };

            myo.connected[peripheral.id].sleepMode = function(type, callback) {
                var mode;
                if (type == "normal") {
                    mode = 0x00;
                } else if (type == "forever") {
                    mode = 0x01;
                } else {
                    mode = 0x00;
                }
                command.write(new Buffer([0x09, 1, mode]), true,  function(err){
                    if(err) console.log(err);
                    callback();
                });
            };

            myo.connected[peripheral.id].unlock = function(type, callback){
                var mode;
                if(type == "lock"){
                    mode = 0x00;
                } else if(type == "timed"){
                    mode = 0x01;
                } else if(type == "hold"){
                    mode = 0x02;
                } else {
                    mode = 0x02;
                }
                command.write(new Buffer([0x0a, 1, mode]), true,  function(err){
                    if(err) console.log(err);
                    callback();
                });
            };
            callbackMain();
        }
    });
}

function registerImu(Imu, peripheral, callbackMain){
    Imu.discoverCharacteristics([services.IMUDataCharacteristic], function (error, characteristics) {
        var imuChar = characteristics[0];
        var scaling = {
            'ORIENTATION_SCALE': 16384.0,
            'ACCELEROMETER_SCALE': 2048.0,
            'GYROSCOPE_SCALE': 16.0
        };

        myo.connected[peripheral.id].imu = function (status) {
            imuChar.notify(status, function (error) {
                if(error) console(error);
            });
        };

        imuChar.on('read', function (data) {
            var metrics = {
                orientation: {
                    w: data.readInt16LE(0) / scaling.ORIENTATION_SCALE,
                    x: data.readInt16LE(2) / scaling.ORIENTATION_SCALE,
                    y: data.readInt16LE(4) / scaling.ORIENTATION_SCALE,
                    z: data.readInt16LE(6) / scaling.ORIENTATION_SCALE
                },
                accelerometer: [
                    data.readInt16LE(8) / scaling.ACCELEROMETER_SCALE,
                    data.readInt16LE(10) / scaling.ACCELEROMETER_SCALE,
                    data.readInt16LE(12) / scaling.ACCELEROMETER_SCALE
                ],
                gyroscope: [
                    data.readInt16LE(14) / scaling.GYROSCOPE_SCALE,
                    data.readInt16LE(16) / scaling.GYROSCOPE_SCALE,
                    data.readInt16LE(18) / scaling.GYROSCOPE_SCALE
                ]
            };
            eventEmitter.emit('imu', {id: peripheral.id, metrics:metrics});
        });

        callbackMain();
    });
}

function registerClassifier(Classifier, peripheral, callbackMain){
    Classifier.discoverCharacteristics([services.ClassifierEventCharacteristic], function (error, characteristics) {
        var classifierChar = characteristics[0];
        myo.connected[peripheral.id].classifier = function (status) {
            classifierChar.notify(status, function (error) {
                if (error) console(error);
            });
        };

        classifierChar.on('read', function (data) {
            var info = {};
            switch (data.readInt8(0)){
                case 1:
                    info.event_type = "arm_synced";
                    switch (data.readInt8(1)){
                        case 1:
                            info.arm = "right";
                            break;
                        case 2:
                            info.arm = "left";
                            break;
                        default :
                            info.arm = "unknow";
                            break;
                    }
                    switch (data.readInt8(2)){
                        case 1:
                            info.x_direction = "wrist";
                            break;
                        case 2:
                            info.x_direction = "elbow";
                            break;
                        default :
                            info.x_direction = "unknow";
                            break;
                    }
                    break;
                case 2:
                    info.event_type = "arm_unsynced";
                    switch (data.readInt8(1)){
                        case 1:
                            info.arm = "right";
                            break;
                        case 2:
                            info.arm = "left";
                            break;
                        default :
                            info.arm = "unknow";
                            break;
                    }
                    switch (data.readInt8(2)){
                        case 1:
                            info.x_direction = "wrist";
                            break;
                        case 2:
                            info.x_direction = "elbow";
                            break;
                        default :
                            info.x_direction = "unknow";
                            break;
                    }
                    break;
                case 3:
                    info.event_type = "pose";
                    switch (data.readInt16LE(1)){
                        case 0:
                            info.pose = "rest";
                            break;
                        case 1:
                            info.pose = "fist";
                            break;
                        case 2:
                            info.pose = "wave_in";
                            break;
                        case 3:
                            info.pose = "wave_out";
                            break;
                        case 4:
                            info.pose = "fingers_spread";
                            break;
                        case 5:
                            info.pose = "double_tap";
                            break;
                        default :
                            info.pose = "unknow";
                            break;
                    }
                    break;
                case 4:
                    info.event_type = "unlocked";
                    break;
                case 5:
                    info.event_type = "locked";
                    break;
                case 6:
                    info.event_type = "sync_failed";
                    break;
            }
            eventEmitter.emit('classifier', {id: peripheral.id, info:info});
        });

        callbackMain();
    });
}

function registerEmg(Emg, peripheral, callbackMain){
    Emg.discoverCharacteristics([services.EmgData0Characteristic, services.EmgData1Characteristic, services.EmgData2Characteristic, services.EmgData3Characteristic], function (error, characteristics) {
        var EmgChar = characteristics;
        myo.connected[peripheral.id].emg = function (status) {
            for(var i = 0; i < 4; i++) {
                EmgChar[i].notify(status, function (error) {
                    if (error) console(error);
                });
            }
        };

        for(var i = 0; i < 4; i++) {
            EmgChar[i].on('read', function (data) {
                var objEMG = {
                    sample1: [
                        data.readInt8(0),
                        data.readInt8(1),
                        data.readInt8(2),
                        data.readInt8(3),
                        data.readInt8(4),
                        data.readInt8(5),
                        data.readInt8(6),
                        data.readInt8(7)
                    ],
                    sample2: [
                        data.readInt8(8),
                        data.readInt8(9),
                        data.readInt8(10),
                        data.readInt8(11),
                        data.readInt8(12),
                        data.readInt8(13),
                        data.readInt8(14),
                        data.readInt8(15)
                    ]
                };
                eventEmitter.emit('emg'+i, {id: peripheral.id, data:objEMG});
            });
        }

        callbackMain();
    });
}

noble.on('discover', function(peripheral) {
    //noble.stopScanning();
    eventEmitter.emit('discover', peripheral.id);

    peripheral.on('disconnect', function(){
        eventEmitter.emit('disconnect', peripheral.id);
        delete myo.connected[peripheral.id];
    });

    peripheral.on('connect', function () {
        eventEmitter.emit('connect', peripheral.id);
        myo.connected[peripheral.id] = {};
        myo.connected[peripheral.id].ready = false;

        peripheral.discoverServices([services.ControlService,services.ClassifierService, services.ImuDataService, services.EmgDataService, bluetoothStandard.BatteryService, bluetoothStandard.DeviceService], function(error, services) {

            var GenericAccess = services[0];
            var Battery = services[1];
            var Control = services[2];
            var Imu = services[3];
            var Classifier = services[4];
            var Emg = services[5];

            registerUtil(peripheral, function() {
                registerGeneric(GenericAccess, peripheral, function () {
                    registerBattery(Battery, peripheral, function () {
                        registerControl(Control, peripheral, function () {
                            registerImu(Imu, peripheral, function(){
                                registerClassifier(Classifier, peripheral, function() {
                                    registerEmg(Emg, peripheral, function() {
                                        eventEmitter.emit('ready', peripheral.id);
                                        myo.connected[peripheral.id].ready = true;
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    });

    peripheral.connect();
});

module.exports = myo;


text:
xdg-desktop-menu install polybox-polybox.directory polybox-polybox.desktop plbx-dropbox.desktop

xdg-desktop-menu install polybox-polybox.directory polybox-cnc.directory polybox-cnc.desktop CNC-gmoccapy.desktop CNC-gscreen.desktop CNC-pyvcp.desktop CNC-linuxcnc.desktop

xdg-desktop-menu install polybox-polybox.directory polybox-tools.directory polybox-tools-getmakers.desktop polybox-tools-thingiverse.desktop polybox-tools-shapeways.desktop polybox-tools-sculpteo.desktop

#xdg-desktop-menu install polybox-polybox.directory polybox-help.directory

xdg-icon-resource install --size 22 ./icon/polybox.png polybox-polybox-menu

redpajama_set_name: RedPajamaGithub


text:
"""
Unit test for Range parameters.
"""

import unittest
import param

class TestRangeParameters(unittest.TestCase):

    def test_initialization_out_of_bounds(self):
        try:
            class Q(param.Parameterized):
                q = param.Range((0, 2), bounds=(0, 1))
        except ValueError:
            pass
        else:
            raise AssertionError("No exception raised on out-of-bounds date")

    def test_set_exclusive_out_of_bounds_upper(self):
        class Q(param.Parameterized):
            q = param.Range(bounds=(0, 10), inclusive_bounds=(True, False))
        try:
            Q.q = (0, 10)
        except ValueError:
            pass
        else:
            raise AssertionError("No exception raised on out-of-bounds date")

    def test_set_exclusive_out_of_bounds_lower(self):
        class Q(param.Parameterized):
            q = param.Range(bounds=(0, 10), inclusive_bounds=(False, True))
        try:
            Q.q = (0, 10)
        except ValueError:
            pass
        else:
            raise AssertionError("No exception raised on out-of-bounds date")

    def test_set_out_of_bounds(self):
        class Q(param.Parameterized):
            q = param.Range(bounds=(0, 10))
        try:
            Q.q = (5, 11)
        except ValueError:
            pass
        else:
            raise AssertionError("No exception raised on out-of-bounds date")

    def test_get_soft_bounds(self):
        q = param.Range((1,3), bounds=(0, 10), softbounds=(1, 9))
        self.assertEqual(q.get_soft_bounds(), (1, 9))


text:
package ml.puredark.hviewer.ui.adapters;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.balysv.materialripple.MaterialRippleLayout;
import com.gc.materialdesign.views.ProgressBarDeterminate;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import ml.puredark.hviewer.R;
import ml.puredark.hviewer.beans.DownloadItemStatus;
import ml.puredark.hviewer.beans.DownloadTask;
import ml.puredark.hviewer.beans.Site;
import ml.puredark.hviewer.beans.Tag;
import ml.puredark.hviewer.beans.Video;
import ml.puredark.hviewer.http.ImageLoader;
import ml.puredark.hviewer.ui.dataproviders.ListDataProvider;

public class DownloadingTaskAdapter extends RecyclerView.Adapter<DownloadingTaskAdapter.DownloadTaskViewHolder> {
    private final static int VIEW_TYPE_DOWNLOADING = 1;
    private final static int VIEW_TYPE_DOWNLOADED = 2;
    private Context context;
    private ListDataProvider<DownloadTask> mProvider;
    private OnItemClickListener mItemClickListener;

    public DownloadingTaskAdapter(Context context, ListDataProvider<DownloadTask> mProvider) {
        this.mProvider = mProvider;
        setHasStableIds(false);
        this.context = context;
    }

    @Override
    public DownloadTaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_DOWNLOADING) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_download_task, parent, false);
            return new DownloadingTaskViewHolder(v);
        } else if (viewType == VIEW_TYPE_DOWNLOADED) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_collection, parent, false);
            return new DownloadedTaskViewHolder(v);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(DownloadTaskViewHolder viewHolder, int position) {
        DownloadTask task = mProvider.getItem(position);
        checkSiteFlags(viewHolder, task.collection.site);
        if (viewHolder instanceof DownloadingTaskViewHolder) {
            DownloadingTaskViewHolder holder = (DownloadingTaskViewHolder) viewHolder;
            if(!task.collection.cover.equals(holder.ivCover.getTag())) {
                holder.ivCover.setTag(holder.ivCover);
                ImageLoader.loadImageFromUrl(context, holder.ivCover, task.collection.cover, null);
            }
            holder.tvTitle.setText(task.collection.title);
            holder.tvUploader.setText(task.collection.uploader);
            holder.tvCategory.setText(task.collection.category);
            holder.rbRating.setRating(task.collection.rating);
            holder.tvSubmittime.setText(task.collection.datetime);
            int percent = 0;
            if (task.collection.videos != null && task.collection.videos.size() > 0) {
                for (Video video : task.collection.videos) {
                    if (video.status == DownloadItemStatus.STATUS_DOWNLOADING) {
                        percent = video.percent;
                        break;
                    } else if (video.status == DownloadItemStatus.STATUS_WAITING && percent == 0) {
                        percent = video.percent;
                    }
                }
                holder.tvCount.setText(task.getDownloadedVideoCount() + "/" + task.collection.videos.size());
            } else {
                int size = (task.collection.pictures != null) ? task.collection.pictures.size() : 0;
                holder.tvCount.setText(task.getDownloadedPictureCount() + "/" + size);
                percent = Math.round(((float) task.getDownloadedPictureCount() * 100 / size));
            }
            holder.tvPercentage.setText(percent + "%");
            holder.progressBar.setProgress(percent);
            int resID = R.drawable.ic_play_arrow_primary_dark;
            switch (task.status) {
                case DownloadTask.STATUS_PAUSED:
                    resID = R.drawable.ic_play_arrow_primary_dark;
                    break;
                case DownloadTask.STATUS_GETTING:
                    resID = R.drawable.ic_pause_primary_dark;
                    break;
                case DownloadTask.STATUS_IN_QUEUE:
                    resID = R.drawable.ic_next_download_primary_dark;
                    break;
            }
            holder.btnStartPause.setImageResource(resID);
        } else if (viewHolder instanceof DownloadedTaskViewHolder) {
            DownloadedTaskViewHolder holder = (DownloadedTaskViewHolder) viewHolder;
            if(!task.collection.cover.equals(holder.ivCover.getTag())) {
                holder.ivCover.setTag(holder.ivCover);
                ImageLoader.loadImageFromUrl(context, holder.ivCover, task.collection.cover, null);
            }
            holder.tvTitle.setText(task.collection.title);
            holder.tvUploader.setText(task.collection.uploader);
            holder.tvCategory.setText(task.collection.category);
            CollectionTagAdapter adapter = (CollectionTagAdapter) holder.rvTags.getAdapter();
            if (adapter != null) {
                adapter.getDataProvider().clear();
                if (task.collection.tags != null)
                    adapter.getDataProvider().addAll(task.collection.tags);
            }
            holder.rbRating.setRating(task.collection.rating);
            holder.tvSubmittime.setText(task.collection.datetime);
        }
    }

    private void checkSiteFlags(DownloadTaskViewHolder holder, Site site) {
        if (site.hasFlag(Site.FLAG_NO_COVER)) {
            holder.layoutCover.setVisibility(View.GONE);
        }
        if (site.hasFlag(Site.FLAG_NO_TITLE)) {
            holder.tvTitle.setVisibility(View.GONE);
            if (holder.rvTags != null) {
                holder.rvTags.setLayoutManager(new StaggeredGridLayoutManager(3, OrientationHelper.HORIZONTAL));
            }
        }
        if (site.hasFlag(Site.FLAG_NO_RATING)) {
            holder.rbRating.setVisibility(View.GONE);
        }
        if (site.hasFlag(Site.FLAG_NO_TAG) && holder.rvTags != null) {
            holder.tvTitle.setMaxLines(2);
            holder.rvTags.setVisibility(View.GONE);
            holder.rvTags.setAdapter(
                    new CollectionTagAdapter(new ListDataProvider<>(new ArrayList()))
            );
        }
    }

    @Override
    public int getItemCount() {
        return (mProvider == null) ? 0 : mProvider.getCount();
    }

    @Override
    public long getItemId(int position) {
        return (mProvider == null) ? 0 : mProvider.getItem(position).getId();
    }

    @Override
    public int getItemViewType(int position) {
        DownloadTask task = mProvider.getItem(position);
        return (task.status == DownloadTask.STATUS_COMPLETED) ? VIEW_TYPE_DOWNLOADED : VIEW_TYPE_DOWNLOADING;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mItemClickListener = listener;
    }

    public ListDataProvider getDataProvider() {
        return mProvider;
    }

    public void setDataProvider(ListDataProvider mProvider) {
        this.mProvider = mProvider;
    }

    public interface OnItemClickListener {
        void onItemClick(View v, int position);

        boolean onItemLongClick(View v, int position);
    }

    class DownloadTaskViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.ripple_layout)
        MaterialRippleLayout rippleLayout;
        @BindView(R.id.layout_cover)
        RelativeLayout layoutCover;
        @BindView(R.id.iv_cover)
        ImageView ivCover;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.tv_uploader)
        TextView tvUploader;
        @BindView(R.id.tv_category)
        TextView tvCategory;
        @BindView(R.id.rv_tags)
        @Nullable
        RecyclerView rvTags;
        @BindView(R.id.rb_rating)
        RatingBar rbRating;
        @BindView(R.id.tv_submittime)
        TextView tvSubmittime;

        DownloadTaskViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }

    class DownloadingTaskViewHolder extends DownloadTaskViewHolder {
        @BindView(R.id.tv_count)
        TextView tvCount;
        @BindView(R.id.btn_start_pause)
        ImageView btnStartPause;
        @BindView(R.id.tv_percentage)
        TextView tvPercentage;
        @BindView(R.id.progress_bar)
        ProgressBarDeterminate progressBar;

        DownloadingTaskViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);

            view.setOnClickListener(v -> {
                if (mItemClickListener != null && getAdapterPosition() >= 0 && getAdapterPosition() < getItemCount())
                    mItemClickListener.onItemClick(v, getAdapterPosition());
            });
            view.setOnLongClickListener(v -> mItemClickListener != null && getAdapterPosition() >= 0 && getAdapterPosition() < getItemCount()
                    && mItemClickListener.onItemLongClick(v, getAdapterPosition()));
            rippleLayout.setOnClickListener(v -> {
                if (mItemClickListener != null && getAdapterPosition() >= 0)
                    mItemClickListener.onItemClick(v, getAdapterPosition());
            });
            rippleLayout.setOnLongClickListener(v -> mItemClickListener != null && getAdapterPosition() >= 0 && getAdapterPosition() < getItemCount()
                    && mItemClickListener.onItemLongClick(v, getAdapterPosition()));
        }

    }

    class DownloadedTaskViewHolder extends DownloadTaskViewHolder {

        DownloadedTaskViewHolder(View view) {
            super(view);
            rvTags.setAdapter(
                    new CollectionTagAdapter(
                            new ListDataProvider<>(
                                    new ArrayList<Tag>()
                            )
                    )
            );
            view.setOnClickListener(v -> {
                if (mItemClickListener != null && getAdapterPosition() >= 0 && getAdapterPosition() < getItemCount())
                    mItemClickListener.onItemClick(v, getAdapterPosition());
            });
            view.setOnLongClickListener(v -> mItemClickListener != null && getAdapterPosition() >= 0 && getAdapterPosition() < getItemCount()
                    && mItemClickListener.onItemLongClick(v, getAdapterPosition()));
            rippleLayout.setOnClickListener(v -> {
                if (mItemClickListener != null && getAdapterPosition() >= 0)
                    mItemClickListener.onItemClick(v, getAdapterPosition());
            });
            rippleLayout.setOnLongClickListener(v -> mItemClickListener != null && getAdapterPosition() >= 0 && getAdapterPosition() < getItemCount()
                    && mItemClickListener.onItemLongClick(v, getAdapterPosition()));
        }

    }

}


text:
package org.codehaus.groovy.runtime;

public class RangeInfo {
    public final int from;
    public final int to;
    public final boolean reverse;

    public RangeInfo(int from, int to, boolean reverse) {
        this.from = from;
        this.to = to;
        this.reverse = reverse;
    }
}


text:
package com.perforce.p4java.option.server;

import java.util.List;

import com.perforce.p4java.core.file.DiffType;
import com.perforce.p4java.exception.OptionsException;
import com.perforce.p4java.exception.P4JavaError;
import com.perforce.p4java.option.Options;
import com.perforce.p4java.server.IServer;

/**
 * Options class for the different options that can be specified when running a
 * describe on a changelist
 */
public class DescribeOptions extends Options {

	/**
	 * Options:
	 */
	public static final String OPTIONS_SPECS = null;

	private boolean outputShelvedDiffs = false;
	private DiffType type = null;

	/**
	 * Default constructor.
	 */
	public DescribeOptions() {
		super();
	}

	/**
	 * Strings-based constructor; see 'p4 help [command]' for possible options.
	 *

	 *
	 * WARNING: you should not pass more than one option or argument in each
	 * string parameter. Each option or argument should be passed-in as its own
	 * separate string parameter, without any spaces between the option and the
	 * option value (if any).
	 *

	 *
	 * NOTE: setting options this way always bypasses the internal options
	 * values, and getter methods against the individual values corresponding to
	 * the strings passed in to this constructor will not normally reflect the
	 * string's setting. Do not use this constructor unless you know what you're
	 * doing and / or you do not also use the field getters and setters.
	 *
	 * @see com.perforce.p4java.option.Options#Options(String...)
	 */
	public DescribeOptions(String... options) {
		super(options);
	}

	/**
	 * Create a changelist describe options
	 *
	 * @param type
	 */
	public DescribeOptions(DiffType type) {
		this(type, false);
	}

	/**
	 * Create a changelist describe options
	 *
	 * @param type
	 * @param outputShelvedDiffs
	 */
	public DescribeOptions(DiffType type, boolean outputShelvedDiffs) {
		this.type = type;
		this.outputShelvedDiffs = outputShelvedDiffs;
	}

	/**
	 * @return the type
	 */
	public DiffType getType() {
		return this.type;
	}

	/**
	 * @param type
	 *            the type to set
	 */
	public DescribeOptions setType(DiffType type) {
		this.type = type;
		return this;
	}

	/**
	 * @return the showShelvedDiffs
	 */
	public boolean isOutputShelvedDiffs() {
		return this.outputShelvedDiffs;
	}

	/**
	 * @param showShelvedDiffs
	 *            the showShelvedDiffs to set
	 */
	public DescribeOptions setOutputShelvedDiffs(boolean showShelvedDiffs) {
		this.outputShelvedDiffs = showShelvedDiffs;
		return this;
	}

	/**
	 * @see com.perforce.p4java.option.Options#processOptions(com.perforce.p4java.server.IServer)
	 */
	public List<String> processOptions(IServer server) throws OptionsException {
		throw new P4JavaError("Unimplemented method");
	}
}


text:
#ifndef GrVkVaryingHandler_DEFINED
#define GrVkVaryingHandler_DEFINED

#include "src/gpu/glsl/GrGLSLVarying.h"

class GrVkVaryingHandler : public GrGLSLVaryingHandler {
public:
    GrVkVaryingHandler(GrGLSLProgramBuilder* program) : INHERITED(program) {}

    typedef GrGLSLVaryingHandler::VarArray VarArray;

private:
    void onFinalize() override;

    friend class GrVkPipelineStateBuilder;

    using INHERITED = GrGLSLVaryingHandler;
};

#endif


text:
package com.prolificinteractive.materialcalendarview;

import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckedTextView;

/**
 * Display one day of a {@linkplain MaterialCalendarView}
 */
public class DayView extends CheckedTextView {

	private CalendarDay date = new CalendarDay();
	private int selectionColor = Color.GRAY;

	private final int fadeTime;

	public DayView(Context context) {
		this(context, null);
	}

	public DayView(Context context, AttributeSet attrs) {
		super(context, attrs);

		fadeTime = getResources().getInteger(
				android.R.integer.config_shortAnimTime);

		setSelectionColor(this.selectionColor);

		setGravity(Gravity.CENTER);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
			setTextAlignment(TEXT_ALIGNMENT_CENTER);
		}

		if (isInEditMode()) {
			setText("99");
		}
	}

	public void setDay(boolean flag, CalendarDay date) {
		this.date = date;
		if (flag) {
			int num = date.getWeekOfYear();
			num = num - 9;
			if (num < 1 || num > 19)
				setText("");
			else {
				setText(num + "");
				setTextColor(Color.parseColor("#0b9ede"));
				setTextSize(16);
				setEnabled(false);
			}

		} else {
			setText(String.valueOf(date.getDay()));
		}
	}

	public void setSelectionColor(int color) {
		this.selectionColor = color;
		setBackgroundDrawable(generateBackground(color, fadeTime));
	}

	public CalendarDay getDate() {
		return date;
	}

	@Override
	public void setEnabled(boolean enabled) {
		super.setEnabled(enabled);
	}

	protected void setupSelection(boolean showOtherDates, boolean inRange,
			boolean inMonth) {
		boolean enabled = inMonth && inRange;
		setEnabled(enabled);
		setVisibility(enabled || showOtherDates ? View.VISIBLE : View.INVISIBLE);
	}

	public static Drawable generateBackground(int color, int fadeTime) {
		StateListDrawable drawable = new StateListDrawable();
		drawable.setExitFadeDuration(fadeTime);
		drawable.addState(new int[] { android.R.attr.state_checked },
				generateCircleDrawable(color));
		if (Build.VERSION.SDK_INT >= 21) {
			drawable.addState(new int[] { android.R.attr.state_pressed },
					generateRippleDrawable(color));
		} else {
			drawable.addState(new int[] { android.R.attr.state_pressed },
					generateCircleDrawable(color));
		}
		drawable.addState(new int[] {},
				generateCircleDrawable(Color.TRANSPARENT));
		return drawable;
	}

	public static Drawable generateCircleDrawable(final int color) {
		ShapeDrawable drawable = new ShapeDrawable(new OvalShape());
		drawable.setShaderFactory(new ShapeDrawable.ShaderFactory() {
			@Override
			public Shader resize(int width, int height) {
				return new LinearGradient(0, 0, 0, 0, color, color,
						Shader.TileMode.REPEAT);
			}
		});
		return drawable;
	}

	public static Drawable generateRippleDrawable(final int color) {
		ColorStateList list = ColorStateList.valueOf(color);
		Drawable mask = generateCircleDrawable(Color.WHITE);
		return new RippleDrawable(list, null, mask);
	}
}


text:
import { SymbolScreenshotsService } from '../services/symbol-screenshots/symbol-screenshots.service';
import { Injectable, Renderer2, RendererFactory2 } from '@angular/core';
import { translate3d, assignGlobalCursor, CursorState, CursorStateType } from 'cd-utils/css';
import { AssetsService } from '../services/assets/assets.service';
import { DEFAULT_UNITS, DIV_TAG } from 'cd-common/consts';
import { getElementBaseStyles } from 'cd-common/utils';
import { DragItemType } from './dnd-utils';
import { IPoint } from 'cd-utils/geometry';
import * as cd from 'cd-interfaces';

// CSS defined in /src/styles/ghost.scss
const enum GhostCSSClass {
  Default = 'dnd-ghost',
  Surface = 'surface',
  Tree = 'tree',
  Image = 'image',
  Thumbnail = 'thumbnail',
  SymbolThumb = 'symbol-thumbnail',
}

const MAX_IMAGE_HEIGHT = 112;
const MAX_IMAGE_WIDTH = 240;
const MAX_SYMBOL_WIDTH = 110;
const MAX_SYMBOL_HEIGHT = 72;
const BORDER_RADIUS = 'var(--cd-border-radius-1)';
const OFFSCREEN_POSITION = -10000;
const DATA_LABEL = 'data-label';

/**
 * The DND Ghost service is responsible for visualizing the drag item
 */
@Injectable({ providedIn: 'root' })
export class DndGhostService {
  private _dragType: DragItemType = DragItemType.Default;
  protected _ghostIds: string[] = [];
  private _cursorState: CursorStateType = CursorState.Default;
  private _renderer: Renderer2;
  private _ghostElem?: HTMLElement;

  private _initalWidth = 0;
  private _initalHeight = 0;
  private _width = 0;
  private _height = 0;
  private _offsetX = 0;
  private _offsetY = 0;

  constructor(
    protected rendererFactory: RendererFactory2,
    private _imageAssetService: AssetsService,
    private _symScreenshotService: SymbolScreenshotsService
  ) {
    this._renderer = rendererFactory.createRenderer(null, null);
  }

  setSize(renderer: Renderer2, ghost: HTMLElement, width: number, height: number) {
    const w = Math.round(width);
    const h = Math.round(height);
    renderer.setStyle(ghost, 'width', w + DEFAULT_UNITS);
    renderer.setStyle(ghost, 'height', h + DEFAULT_UNITS);
    this._initalWidth = w;
    this._initalHeight = h;
  }

  assignGhostType(renderer: Renderer2, ghost: HTMLElement, dragType: DragItemType) {
    renderer.addClass(ghost, GhostCSSClass.Default);
    this._dragType = dragType;
    if (dragType === DragItemType.TreeNode) return renderer.addClass(ghost, GhostCSSClass.Tree);
  }

  setPosition(_renderer: Renderer2, ghost: HTMLElement, x: number, y: number) {
    ghost.style.transform = translate3d(x, y);
  }

  setRoundedCorners(renderer: Renderer2, ghost: HTMLElement) {
    renderer.setStyle(ghost, 'border-radius', BORDER_RADIUS);
  }

  createGhost(
    ids: string[],
    width: number,
    height: number,
    dragType: DragItemType,
    label = '',
    roundCorners = false
  ) {
    const { _renderer } = this;
    const ghost = _renderer.createElement(DIV_TAG);
    this.setSize(_renderer, ghost, width, height);
    if (label) _renderer.setAttribute(ghost, DATA_LABEL, label);
    this.setPosition(_renderer, ghost, OFFSCREEN_POSITION, OFFSCREEN_POSITION);
    this.assignGhostType(_renderer, ghost, dragType);
    if (roundCorners) this.setRoundedCorners(_renderer, ghost);
    _renderer.appendChild(document.body, ghost);
    this._ghostElem = ghost;
    this._ghostIds = ids;
  }

  set globalCursor(value: CursorStateType) {
    if (value === this._cursorState) return;
    this._cursorState = value;
    assignGlobalCursor(value);
  }

  urlForAsset(asset: cd.IProjectAsset, thumbnail: boolean): string | undefined {
    if (!asset?.urls) return;
    return thumbnail
      ? asset.urls[cd.AssetSizes.BigThumbnailXHDPI]
      : asset.urls[cd.AssetSizes.Original];
  }

  setImageForSymbol(id: string, thumbnail: boolean) {
    const { _renderer, _ghostElem } = this;
    if (!_ghostElem) return;
    const item = this._symScreenshotService.screenshotForId(id);
    const url = item && item.url;
    if (!url) return;
    if (thumbnail) {
      this.setSize(_renderer, _ghostElem, MAX_SYMBOL_WIDTH, MAX_SYMBOL_HEIGHT);
      _renderer.addClass(_ghostElem, GhostCSSClass.SymbolThumb);
    }

    this.assignImage(_renderer, _ghostElem, url);
  }

  setAsImageThumbnail(assetId: string) {
    const { _renderer, _ghostElem } = this;
    if (!_ghostElem) return;
    const asset = this._imageAssetService.getAssetForId(assetId);
    const url = this.urlForAsset(asset, true);
    if (!url) return;
    this.setSize(_renderer, _ghostElem, MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
    _renderer.addClass(_ghostElem, GhostCSSClass.Thumbnail);
    this.assignImage(_renderer, _ghostElem, url);
  }

  setAssetPanelImage(assetId: string, element: cd.PropertyModel, width: number, height: number) {
    const backgroundSize = getElementBaseStyles(element)?.objectFit;
    this.setAsImage(assetId, width, height, backgroundSize);
  }

  setAsImage(assetId: string, width: number, height: number, backgroundSize = cd.ObjectFit.Cover) {
    const { _renderer, _ghostElem } = this;
    if (!_ghostElem) return;
    const asset = this._imageAssetService.getAssetForId(assetId);
    const url = this.urlForAsset(asset, false);

    if (width && height) {
      this.setSize(_renderer, _ghostElem, width, height);
      _renderer.setStyle(_ghostElem, 'background-size', backgroundSize);
    }

    if (!url) return;
    this.assignImage(_renderer, _ghostElem, url);
  }

  assignImage(renderer: Renderer2, ghost: HTMLElement, url: string) {
    renderer.setStyle(ghost, 'background-image', `url(${url})`);
    renderer.addClass(ghost, GhostCSSClass.Image);
  }

  moveGhost({ x, y }: IPoint) {
    if (!this._ghostElem) return;
    const { _offsetX, _offsetY } = this;
    this.setPosition(this._renderer, this._ghostElem, x + _offsetX, y + _offsetY);
  }

  updateGhostSize(bounds: cd.IRect | undefined, initalOffset: IPoint, _zoom?: number) {
    const { _ghostElem, _initalWidth, _dragType, _initalHeight } = this;
    if (!_ghostElem) return;
    if (!bounds || _dragType === DragItemType.TreeNode) return; // Ignore for tree nodes
    const { width, height } = bounds;
    if (width === this._width && height === this._height) return;
    _ghostElem.style.width = width + DEFAULT_UNITS;
    _ghostElem.style.height = height + DEFAULT_UNITS;
    _ghostElem.classList.remove(GhostCSSClass.Thumbnail);
    // Adjust the cursor position based on ratio from new dimensions
    if (_initalHeight !== height && _initalWidth !== width) {
      this._offsetX = initalOffset.x - (initalOffset.x * width) / _initalWidth;
      this._offsetY = initalOffset.y - (initalOffset.y * height) / _initalHeight;
    }

    this._width = width;
    this._height = height;
  }

  resetGhost() {
    this.globalCursor = CursorState.Default;
    if (!this._ghostElem) return;
    this._renderer.removeChild(document.body, this._ghostElem);
    this._ghostElem = undefined;
    this._ghostIds = [];
    this._offsetX = 0;
    this._offsetY = 0;
    this._initalWidth = 0;
    this._initalHeight = 0;
    this._width = 0;
    this._height = 0;
  }
}


text:
<?php

namespace Deicer\Query\Exception;

use LogicException as SplException;
use Deicer\Query\Exception\ExceptionInterface;

/**
 * Deicer Invalid Query Interface Exception
 *
 * @category   Deicer
 * @package    Query
 * @subpackage Exception
 * @version    $id$
 * @copyright  2013 Alex Butucea <alex826@gmail.com>
 * @author     Alex Butucea <alex826@gmail.com>
 * @license    The MIT License (MIT) {@link http://opensource.org/licenses/MIT}
 */
class InvalidQueryInterfaceException extends SplException implements ExceptionInterface
{
}


text:
/*
Language: DOS .bat
Author: Alexander Makarov (http://rmcreative.ru/)
*/

function(hljs) {
  return {
    case_insensitive: true,
    defaultMode: {
      keywords: {
        flow: 'if else goto for in do call exit not exist errorlevel defined equ neq lss leq gtr geq',
        keyword: 'shift cd dir echo setlocal endlocal set pause copy',
        stream: 'prn nul lpt3 lpt2 lpt1 con com4 com3 com2 com1 aux',
        winutils: 'ping net ipconfig taskkill xcopy ren del'
      },
      contains: [
        {
          className: 'envvar', begin: '%%[^ ]'
        },
        {
          className: 'envvar', begin: '%[^ ]+?%'
        },
        {
          className: 'envvar', begin: '![^ ]+?!'
        },
        {
          className: 'number', begin: '\\b\\d+',
          relevance: 0
        },
        {
          className: 'comment',
          begin: '@?rem', end: '$'
        }
      ]
    }
  };
}


text:
extern crate comctl32;
use comctl32::*;
#[inline(never)] fn bb<T>(_: T) {}
#[test] #[cfg(target_env = "msvc")]
fn functions_msvc() {
    bb(DPA_Clone);
    bb(DPA_CreateEx);
    bb(DPA_DestroyCallback);
    bb(DPA_EnumCallback);
    bb(DPA_GetPtrIndex);
    bb(DPA_Grow);
    bb(DPA_LoadStream);
    bb(DPA_Merge);
    bb(DPA_SaveStream);
    bb(DSA_DeleteItem);
    bb(DSA_DestroyCallback);
    bb(DSA_GetItem);
    bb(DSA_SetItem);
    bb(FlatSB_EnableScrollBar);
    bb(FlatSB_GetScrollInfo);
    bb(FlatSB_GetScrollPos);
    bb(FlatSB_GetScrollProp);
    bb(FlatSB_GetScrollRange);
    bb(FlatSB_SetScrollInfo);
    bb(FlatSB_SetScrollPos);
    bb(FlatSB_SetScrollProp);
    bb(FlatSB_SetScrollRange);
    bb(FlatSB_ShowScrollBar);
    bb(InitializeFlatSB);
    bb(UninitializeFlatSB);
}
#[test]
fn functions() {
    bb(AddMRUStringW);
    // bb(CreateMRUListW);
    bb(CreateMappedBitmap);
    bb(CreatePropertySheetPage);
    bb(CreatePropertySheetPageA);
    bb(CreatePropertySheetPageW);
    bb(CreateStatusWindow);
    bb(CreateStatusWindowA);
    bb(CreateStatusWindowW);
    bb(CreateToolbarEx);
    bb(CreateUpDownControl);
    bb(DPA_Create);
    bb(DPA_DeleteAllPtrs);
    bb(DPA_DeletePtr);
    bb(DPA_Destroy);
    bb(DPA_GetPtr);
    bb(DPA_InsertPtr);
    bb(DPA_Search);
    bb(DPA_SetPtr);
    bb(DPA_Sort);
    bb(DSA_Create);
    bb(DSA_DeleteAllItems);
    bb(DSA_Destroy);
    bb(DSA_GetItemPtr);
    bb(DSA_InsertItem);
    bb(DefSubclassProc);
    bb(DestroyPropertySheetPage);
    bb(DrawInsert);
    bb(DrawStatusText);
    bb(DrawStatusTextA);
    bb(DrawStatusTextW);
    bb(EnumMRUListW);
    bb(FreeMRUList);
    bb(GetEffectiveClientRect);
    bb(GetMUILanguage);
    bb(ImageList_Add);
    bb(ImageList_AddIcon);
    bb(ImageList_AddMasked);
    bb(ImageList_BeginDrag);
    bb(ImageList_Copy);
    bb(ImageList_Create);
    bb(ImageList_Destroy);
    bb(ImageList_DragEnter);
    bb(ImageList_DragLeave);
    bb(ImageList_DragMove);
    bb(ImageList_DragShowNolock);
    bb(ImageList_Draw);
    bb(ImageList_DrawEx);
    bb(ImageList_DrawIndirect);
    bb(ImageList_Duplicate);
    bb(ImageList_EndDrag);
    bb(ImageList_GetBkColor);
    bb(ImageList_GetDragImage);
    bb(ImageList_GetIcon);
    bb(ImageList_GetIconSize);
    bb(ImageList_GetImageCount);
    bb(ImageList_GetImageInfo);
    bb(ImageList_LoadImage);
    bb(ImageList_LoadImageA);
    bb(ImageList_LoadImageW);
    bb(ImageList_Merge);
    bb(ImageList_Read);
    bb(ImageList_Remove);
    bb(ImageList_Replace);
    bb(ImageList_ReplaceIcon);
    bb(ImageList_SetBkColor);
    bb(ImageList_SetDragCursorImage);
    bb(ImageList_SetIconSize);
    bb(ImageList_SetImageCount);
    bb(ImageList_SetOverlayImage);
    bb(InitCommonControls);
    bb(InitCommonControlsEx);
    bb(InitMUILanguage);
    bb(LBItemFromPt);
    bb(MakeDragList);
    bb(MenuHelp);
    bb(PropertySheet);
    bb(PropertySheetA);
    bb(PropertySheetW);
    bb(RemoveWindowSubclass);
    bb(SetWindowSubclass);
    bb(ShowHideMenuCtl);
    bb(Str_SetPtrW);
    bb(_TrackMouseEvent);
}


text:
module Omniship
  module DHLGM
    module Track
      class Error < TrackError
        NOT_FOUND_RESPONSE = "400"
        def initialize(root)
          if root.xpath("track/error/code/text()").to_s == NOT_FOUND_RESPONSE
            self.code = NOT_FOUND
          end

          super(root.xpath("track/error/description/text()").to_s)
        end
      end
    end
  end
end


text:
class CVirtualMachine;

class CScopedVmPauser
{
public:
	           CScopedVmPauser(CVirtualMachine&);
	virtual    ~CScopedVmPauser();

private:
	CVirtualMachine&    m_virtualMachine;
	bool                m_paused = false;
};


text:
/*
 * Register all the grabbing devices.
 *
 * This file is part of Libav.
 *
 * Libav is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * Libav is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Libav; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "config.h"
#include "libavformat/avformat.h"
#include "avdevice.h"

#define REGISTER_OUTDEV(X,x) { \
          extern AVOutputFormat ff_##x##_muxer; \
          if(CONFIG_##X##_OUTDEV)  av_register_output_format(&ff_##x##_muxer); }
#define REGISTER_INDEV(X,x) { \
          extern AVInputFormat ff_##x##_demuxer; \
          if(CONFIG_##X##_INDEV)   av_register_input_format(&ff_##x##_demuxer); }
#define REGISTER_INOUTDEV(X,x)  REGISTER_OUTDEV(X,x); REGISTER_INDEV(X,x)

void avdevice_register_all(void)
{
    static int initialized;

    if (initialized)
        return;
    initialized = 1;

    /* devices */
    REGISTER_INOUTDEV (ALSA, alsa);
    REGISTER_INDEV    (BKTR, bktr);
    REGISTER_INDEV    (DV1394, dv1394);
    REGISTER_INDEV    (FBDEV, fbdev);
    REGISTER_INDEV    (JACK, jack);
    REGISTER_INOUTDEV (OSS, oss);
    REGISTER_INDEV    (PULSE, pulse);
    REGISTER_INOUTDEV (SNDIO, sndio);
    REGISTER_INDEV    (V4L2, v4l2);
#if FF_API_V4L
    REGISTER_INDEV    (V4L, v4l);
#endif
    REGISTER_INDEV    (VFWCAP, vfwcap);
    REGISTER_INDEV    (X11_GRAB_DEVICE, x11_grab_device);

    /* external libraries */
    REGISTER_INDEV    (LIBCDIO, libcdio);
    REGISTER_INDEV    (LIBDC1394, libdc1394);
}


text:
//********************************************************************
//*
//* Warning: This file was generated by ecore4CPP Generator
//*
//********************************************************************

#ifndef UML_STRINGEXPRESSION_HPP
#define UML_STRINGEXPRESSION_HPP

#include <map>

#include <memory>
#include <string>
// forward declarations
template<class T, class ... U> class Subset;

class AnyObject;
typedef std::shared_ptr<AnyObject> Any;

//*********************************
// generated Includes
#include <map> // used for Persistence
#include <vector> // used for Persistence
namespace persistence
{
	namespace interfaces
	{
		class XLoadHandler; // used for Persistence
		class XSaveHandler; // used for Persistence
	}
}

namespace uml
{
	class umlFactory;
}

//Forward Declaration for used types
namespace uml
{
	class Comment;
	class Dependency;
	class Namespace;
	class Package;
	class Slot;
	class TemplateBinding;
	class TemplateParameter;
	class TemplateSignature;
	class Type;
	class ValueSpecificationAction;
}

// namespace macro header include
#include "uml/uml.hpp"

// base class includes
#include "uml/Expression.hpp"
#include "uml/TemplateableElement.hpp"

// enum includes
#include "uml/VisibilityKind.hpp"

//*********************************
namespace uml
{
	/*!
	A StringExpression is an Expression that specifies a String value that is derived by concatenating a sequence of operands with String values or a sequence of subExpressions, some of which might be template parameters.

From package UML::Values.

	*/

	class UML_API StringExpression: virtual public Expression, virtual public TemplateableElement
	{
		public:
 			StringExpression(const StringExpression &) {}

		protected:
			StringExpression(){}
			//Additional constructors for the containments back reference
			StringExpression(std::weak_ptr<uml::Namespace> par_namespace);

			//Additional constructors for the containments back reference
			StringExpression(std::weak_ptr<uml::Element> par_owner);

			//Additional constructors for the containments back reference
			StringExpression(std::weak_ptr<uml::StringExpression> par_owningExpression);

			//Additional constructors for the containments back reference
			StringExpression(std::weak_ptr<uml::Package> par_owningPackage);

			//Additional constructors for the containments back reference
			StringExpression(std::weak_ptr<uml::Slot> par_owningSlot);

			//Additional constructors for the containments back reference
			StringExpression(std::weak_ptr<uml::TemplateParameter> par_owningTemplateParameter);

			//Additional constructors for the containments back reference
			StringExpression(std::weak_ptr<uml::ValueSpecificationAction> par_valueSpecificationAction);

		public:
			virtual std::shared_ptr<ecore::EObject> copy() const = 0;

			//destructor
			virtual ~StringExpression() {}

			//*********************************
			// Operations
			//*********************************
			/*!
			All the operands of a StringExpression must be LiteralStrings
			operand->forAll (oclIsKindOf (LiteralString))
			*/

			virtual bool operands(Any diagnostics,std::shared_ptr<std::map < Any, Any>> context) = 0;
			/*!
			If a StringExpression has sub-expressions, it cannot have operands and vice versa (this avoids the problem of having to define a collating sequence between operands and subexpressions).
			if subExpression->notEmpty() then operand->isEmpty() else operand->notEmpty() endif
			*/

			virtual bool subexpressions(Any diagnostics,std::shared_ptr<std::map < Any, Any>> context) = 0;

			//*********************************
			// Attribute Getters & Setters
			//*********************************

			//*********************************
			// Reference Getters & Setters
			//*********************************
			/*!
			The StringExpression of which this StringExpression is a subExpression.

From package UML::Values.

			*/

			virtual std::weak_ptr<uml::StringExpression> getOwningExpression() const = 0;
			/*!
			The StringExpression of which this StringExpression is a subExpression.

From package UML::Values.

			*/

			virtual void setOwningExpression(std::weak_ptr<uml::StringExpression>) = 0;
			/*!
			The StringExpressions that constitute this StringExpression.

From package UML::Values.

			*/

			virtual std::shared_ptr<Subset<uml::StringExpression, uml::Element>> getSubExpression() const = 0;

			//*********************************
			// Union Reference Getters
			//*********************************
			/*!
			Specifies the Namespace that owns the NamedElement.

From package UML::CommonStructure.

			*/

			virtual std::weak_ptr<uml::Namespace> getNamespace() const = 0;
			/*!
			The Elements owned by this Element.

From package UML::CommonStructure.

			*/

			virtual std::shared_ptr<Union<uml::Element>> getOwnedElement() const = 0;
			/*!
			The Element that owns this Element.

From package UML::CommonStructure.

			*/

			virtual std::weak_ptr<uml::Element> getOwner() const = 0;

			//*********************************
			// Container Getter
			//*********************************
			virtual std::shared_ptr<ecore::EObject> eContainer() const = 0;

			//*********************************
			// Persistence Functions
			//*********************************
			virtual void load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) = 0;
			virtual void resolveReferences(const int featureID, std::vector<std::shared_ptr<ecore::EObject> > references) = 0;
			virtual void save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const = 0;

		protected:
			//*********************************
			// Attribute Members
			//*********************************

			//*********************************
			// Reference Members
			//*********************************
			/*!
			The StringExpression of which this StringExpression is a subExpression.

From package UML::Values.

			*/

			std::weak_ptr<uml::StringExpression> m_owningExpression;
			/*!
			The StringExpressions that constitute this StringExpression.

From package UML::Values.

			*/

			mutable std::shared_ptr<Subset<uml::StringExpression, uml::Element>> m_subExpression;
	};
}
#endif /* end of include guard: UML_STRINGEXPRESSION_HPP */


text:
class BrowserInstantController;
class GURL;
class InstantService;
class Profile;

namespace content {
class WebContents;
}

// InstantController drives Chrome Instant, i.e., the browser implementation of
// the Embedded Search API (see http://dev.chromium.org/embeddedsearch).
//
// In extended mode, InstantController maintains and coordinates an InstantTab.
// An InstantTab instance points to the currently active tab, if it supports the
// Embedded Search API. InstantTab is backed by a WebContents and it does not
// own that WebContents.
//
// InstantController is owned by Browser via BrowserInstantController.
class InstantController : public InstantTab::Delegate {
 public:
  explicit InstantController(BrowserInstantController* browser);
  ~InstantController() override;

  // The search mode in the active tab has changed. Bind |instant_tab_| if the
  // |new_mode| reflects an Instant search results page.
  void SearchModeChanged(const SearchMode& old_mode,
                         const SearchMode& new_mode);

  // The user switched tabs. Bind |instant_tab_| if the newly active tab is an
  // Instant search results page.
  void ActiveTabChanged();

  // Used by BrowserInstantController to notify InstantController about the
  // instant support change event for the active web contents.
  void InstantSupportChanged(InstantSupportState instant_support);

  // Resets list of debug events.
  void ClearDebugEvents();

  // See comments for |debug_events_| below.
  const std::list<std::pair<int64_t, std::string>>& debug_events() {
    return debug_events_;
  }

 private:
  friend class InstantExtendedManualTest;
  friend class InstantTestBase;

  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest, ExtendedModeIsOn);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest, MostVisited);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest, ProcessIsolation);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest, UnrelatedSiteInstance);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest, OnDefaultSearchProviderChanged);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest,
                           AcceptingURLSearchDoesNotNavigate);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest, AcceptingJSSearchDoesNotRunJS);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest,
                           ReloadSearchAfterBackReloadsCorrectQuery);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest, KeyboardTogglesVoiceSearch);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest, HomeButtonAffectsMargin);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest, SearchReusesInstantTab);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest,
                           SearchDoesntReuseInstantTabWithoutSupport);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest,
                           TypedSearchURLDoesntReuseInstantTab);
  FRIEND_TEST_ALL_PREFIXES(InstantExtendedTest,
                           DispatchMVChangeEventWhileNavigatingBackToNTP);

  // Overridden from InstantTab::Delegate:
  // TODO(shishir): We assume that the WebContent's current RenderViewHost is
  // the RenderViewHost being created which is not always true. Fix this.
  void InstantSupportDetermined(const content::WebContents* contents,
                                bool supports_instant) override;
  void InstantTabAboutToNavigateMainFrame(const content::WebContents* contents,
                                          const GURL& url) override;

  // Adds a new event to |debug_events_| and also DVLOG's it. Ensures that
  // |debug_events_| doesn't get too large.
  void LogDebugEvent(const std::string& info) const;

  // If the active tab is an Instant search results page, sets |instant_tab_| to
  // point to it. Else, deletes any existing |instant_tab_|.
  void ResetInstantTab();

  // Sends theme info and most visited items to the Instant tab.
  void UpdateInfoForInstantTab();

  // Returns the InstantService for the browser profile.
  InstantService* GetInstantService() const;

  BrowserInstantController* const browser_;

  // The instance of InstantTab maintained by InstantController.
  std::unique_ptr<InstantTab> instant_tab_;

  // The search model mode for the active tab.
  SearchMode search_mode_;

  // List of events and their timestamps, useful in debugging Instant behaviour.
  mutable std::list<std::pair<int64_t, std::string>> debug_events_;

  DISALLOW_COPY_AND_ASSIGN(InstantController);
};

#endif  // CHROME_BROWSER_UI_SEARCH_INSTANT_CONTROLLER_H_


text:
{% extends "v2/modules/gsoc/form_base.html" %}
{% comment %}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
{% endcomment %}

{% block synchronous_scripts %}
  <script type='text/javascript' src="/tiny_mce/tiny_mce.js"></script>
  {{ block.super }}
{% endblock synchronous_scripts %}

{% block dependencies %}
  [
    dep.uniform,
    dep.counter,
    null,
    function () {
      jQuery("select, input:radio, input:file, input:checkbox").uniform();
      jQuery("#abstract").counter({
        goal: 500
      });
      tinyMCE.init(melange.tinyMceConfig(["melange-public_info-textarea"],
                                         "advanced"));
    },
  ]
{% endblock dependencies %}


text:
<?php

/**
 * Google Cloud Storage Read Client - Implements only the methods required to
 * read bytes from GCS using stream wrappers. For a fully fledged client
 * to access Google Cloud Storage you should consult the Google API client.
 *
 */

namespace google\appengine\ext\cloud_storage_streams;

/**
 * Google Cloud Storage Client for reading objects.
 */
final class CloudStorageReadClient extends CloudStorageClient {
  // Buffer for storing data.
  private $read_buffer;

  // Position in the read buffer where we are currently
  private $buffer_read_position = 0;

  // Position in the object where the current block starts from
  private $object_block_start_position = 0;

  // Next position to read from when this buffer is finished.
  private $next_read_position = 0;

  // Overall size of the object in GCS
  private $object_total_length;

  // ETag of the object as it was first read.
  private $object_etag;

  // We have reached the end of the file while reading it.
  private $eof = false;

  // When we first read the file we partially complete the stat_result that
  // we then return in calls to stat()
  private $stat_result = [];

  // Metadata for the object as it was first read.
  private $metadata = [];

  // Content-Type for the object as it was first read.
  private $content_type;

  // HTTP status codes that indicate that there is an object to read, and we
  // need to process the response.
  private static $valid_status_codes = [HttpResponse::OK,
                                        HttpResponse::PARTIAL_CONTENT,
                                        HttpResponse::RANGE_NOT_SATISFIABLE];

  // Client for caching the results of GCS reads.
  private $memcache_client;

  public function __construct($bucket, $object, $context) {
    parent::__construct($bucket, $object, $context);
    $this->memcache_client = new \Memcache();
  }

  public function __destruct() {
    parent::__destruct();
  }

  // Initialize is called when opening the stream. We will try and retrieve
  // the first chunk of the file during this stage, to validate that
  // - it exists
  // - the app has the ACL to access it.
  public function initialize() {
    return $this->fillReadBuffer(0);
  }

  /**
   * Read at most $count_bytes from the file.
   * If we have reached the end of the buffered amount, and there is more
   * data in the file then retreive more bytes from storage.
   */
  public function read($count_bytes) {
    // If we have data in the read_buffer then use it.
    $readBuffer_size = strlen($this->read_buffer);
    $bytes_available = $readBuffer_size - $this->buffer_read_position;

    // If there are no more bytes available then get some.
    if ($bytes_available === 0 && !$this->eof) {
      // If we know the object size, check it first.
      $object_bytes_read = $this->object_block_start_position +
                           $this->buffer_read_position;
      if ($object_bytes_read === $this->object_total_length ||
          !isset($this->next_read_position)) {
        $this->eof = true;
        return false;
      }
      if (!$this->fillReadBuffer($this->next_read_position)) {
        return false;
      }
      // Re-calculate the number of bytes we can serve.
      $readBuffer_size = strlen($this->read_buffer);
      $bytes_available = $readBuffer_size - $this->buffer_read_position;
    }

    if ($bytes_available > 0) {
      $bytes_to_read = min($bytes_available, $count_bytes);
      $current_buffer_position = $this->buffer_read_position;
      $this->buffer_read_position += $bytes_to_read;

      return substr($this->read_buffer,
                    $current_buffer_position,
                    $bytes_to_read);
    }

    return false;
  }

  /**
   * Returns true if we have read to the end of file, false otherwise.
   */
  public function eof() {
    return $this->eof;
  }

  /**
   * Seek within the current file. We expect the upper layers of PHP to convert
   * SEEK_CUR to SEEK_SET.
   */
  public function seek($offset, $whence) {
    if ($whence == SEEK_END) {
      if (isset($this->object_total_length)) {
        $whence = SEEK_SET;
        $offset = $this->object_total_length + $offset;
      } else {
        trigger_error("Unable to seek from end for objects with unkonwn size",
                      E_USER_WARNING);
        return false;
      }
    }

    if ($whence != SEEK_SET) {
      trigger_error(sprintf("Unsupported seek mode: %d", $whence),
                    E_USER_WARNING);
      return false;
    }
    // If we know the size, then make sure they are only seeking within it.
    if (isset($this->object_total_length) &&
        $offset >= $this->object_total_length) {
      return false;
    }
    if ($offset < 0) {
      return false;
    }
    // Clear EOF and work it out next time they read.
    $this->eof = false;

    // Check if we can seek inside the current buffer
    $buffer_end = $this->object_block_start_position +
                  strlen($this->read_buffer);
    if ($this->object_block_start_position <= $offset &&
        $offset < $buffer_end) {
      $this->buffer_read_position = $offset -
          $this->object_block_start_position;
    } else {
      $this->read_buffer = "";
      $this->buffer_read_position = 0;
      $this->next_read_position = $offset;
    }
    return true;
  }

  /**
   * Return our stat buffer, if we have one.
   */
  public function stat() {
    if (!empty($this->stat_result)) {
      return $this->stat_result;
    } else {
      return false;
    }
  }

  /**
   * Having tell() at this level in the stack seems bonkers.
   */
  public function tell() {
    return $this->buffer_read_position + $this->object_block_start_position;
  }

  public function getMetaData() {
    return $this->metadata;
  }

  public function getContentType() {
    return $this->content_type;
  }

  /**
   * Override the makeHttpRequest function so we can implement caching.
   * If caching is enabled then we try and retrieve a matching request for the
   * object name and range from memcache.
   * If we find a result in memcache, and optimistic caching is enabled then
   * we return that result immediately without checking if the object has
   * changed in GCS. Otherwise, we will issue a 'If-None-Match' request with
   * the ETag of the object to ensure it is still current.
   *
   * Optimisitic caching is best suited when the application is soley updating
   * objects in cloud storage, as the cache can be invalidated when the object
   * is updated by the application.
   */
  protected function makeHttpRequest($url, $method, $headers, $body = null) {
    if (!$this->context_options['enable_cache']) {
      return parent::makeHttpRequest($url, $method, $headers, $body);
    }

    $cache_key = sprintf(parent::MEMCACHE_KEY_FORMAT, $url, $headers['Range']);
    $cache_obj = $this->memcache_client->get($cache_key);
    if (false !== $cache_obj) {
      if ($this->context_options['enable_optimistic_cache']) {
        return $cache_obj;
      } else {
        $cache_etag = $this->getHeaderValue('ETag', $cache_obj['headers']);
        if (array_key_exists('If-Match', $headers)) {
          // We will perform a If-None-Match to validate the cache object, only
          // if it has the same ETag value as what we are asking for.
          if ($headers['If-Match'] === $cache_etag) {
            unset($headers['If-Match']);
          } else {
            // We are asking for a different object that what is in the cache.
            $cache_etag = null;
          }
        }
      }
      if (isset($cache_etag)) {
        $headers['If-None-Match'] = $cache_etag;
      }
    }

    $result = parent::makeHttpRequest($url, $method, $headers, $body);

    if (false === $result) {
      return false;
    }
    $status_code = $result['status_code'];
    if (HttpResponse::NOT_MODIFIED === $result['status_code']) {
      return $cache_obj;
    }
    if (in_array($status_code, self::$valid_status_codes)) {
      $this->memcache_client->set($cache_key, $result, 0,
          $this->context_options['read_cache_expiry_seconds']);
    }
    return $result;
  }

  /**
   * Fill our internal buffer with data, by making a http request to Google
   * Cloud Storage.
   */
  private function fillReadBuffer($read_position) {
    $headers = $this->getOAuthTokenHeader(parent::READ_SCOPE);
    if ($headers === false) {
      trigger_error("Unable to acquire OAuth token.", E_USER_WARNING);
      return false;
    }

    $end_range = $read_position + parent::DEFAULT_READ_SIZE - 1;
    $range = $this->getRangeHeader($read_position, $end_range);
    $headers = array_merge($headers, $range);

    // If we have an ETag from the first read then use it to ensure we are
    // retrieving the same object.
    if (isset($this->object_etag)) {
      $headers["If-Match"] = $this->object_etag;
    }

    $http_response = $this->makeHttpRequest($this->url,
                                            "GET",
                                            $headers);

    if ($http_response === false) {
      trigger_error("Unable to connect to Google Cloud Storage Service.",
                    E_USER_WARNING);
      return false;
    }

    $status_code = $http_response['status_code'];
    if ($status_code === HttpResponse::NOT_FOUND) {
      return false;
    }
    if ($status_code === HttpResponse::PRECONDITION_FAILED) {
      trigger_error("Object content has changed.", E_USER_WARNING);
      return false;
    }

    if (!in_array($status_code, self::$valid_status_codes)) {
      trigger_error($this->getErrorMessage($status_code,
                                           $http_response['body']),
                    E_USER_WARNING);
      return false;
    }

    $this->read_buffer = $http_response['body'];
    $this->buffer_read_position = 0;
    $this->object_block_start_position = $read_position;

    // If we got the complete object in the response then use the
    // Content-Length
    if ($status_code == HttpResponse::OK) {
      $content_length = $this->getHeaderValue('Content-Length',
                                              $http_response['headers']);
      assert(isset($content_length));
      $this->object_total_length = intval($content_length);
      $this->next_read_position = null;
    } else if ($status_code == HttpResponse::RANGE_NOT_SATISFIABLE) {
      // We've read past the end of the object ... no more data.
      $this->read_buffer = "";
      $this->eof = true;
      $this->next_read_position = null;
      if (!isset($this->object_total_length)) {
        $this->object_total_length = 0;
      }
    } else {
      $content_range = $this->getHeaderValue('Content-Range',
                                             $http_response['headers']);
      assert(isset($content_range));
      if (preg_match(parent::CONTENT_RANGE_REGEX, $content_range, $m) === 1) {
        $this->next_read_position = intval($m[2]) + 1;
        $this->object_total_length = intval($m[3]);
      }
    }

    $this->metadata = self::extractMetaData($http_response['headers']);

    $this->content_type = $this->getHeaderValue('Content-Type',
                                                $http_response['headers']);

    $this->object_etag =
        $this->getHeaderValue('ETag', $http_response['headers']);

    if (empty($this->stat_result)) {
      $stat_args = ['size' => $this->object_total_length,
                    'mode' => parent::S_IFREG];

      $last_modified = $this->getHeaderValue('Last-Modified',
                                             $http_response['headers']);
      if (isset($last_modified)) {
        $unix_time = strtotime($last_modified);
        if ($unix_time !== false) {
          $stat_args["mtime"] = $unix_time;
        }
      }
      $this->stat_result = $this->createStatArray($stat_args);
    }

    return true;
  }
}


text:
<?php
/**
 * @author    MyBB Group
 * @version   2.0.0
 * @package   mybb/core
 * @license   http://www.mybb.com/licenses/bsd3 BSD-3
 */

namespace MyBB\Core\Permissions;

use Illuminate\Database\DatabaseManager;
use MyBB\Core\Database\Models\ContentClass;
use MyBB\Core\Database\Models\Role;
use Illuminate\Contracts\Cache\Repository as CacheRepository;
use MyBB\Core\Database\Models\User;
use MyBB\Core\Exceptions\PermissionImplementInterfaceException;
use MyBB\Core\Exceptions\PermissionInvalidContentException;
use MyBB\Core\Permissions\Interfaces\InheritPermissionInterface;
use MyBB\Core\Permissions\Interfaces\PermissionInterface;

class PermissionChecker
{
	// Constants used as permission value
	const NEVER = -1;
	const NO = 0;
	const YES = 1;

	/**
	 * @var CacheRepository
	 */
	private $cache;

	/**
	 * @var DatabaseManager
	 */
	private $db;

	/**
	 * @var ContentClass
	 */
	private $classModel;

	/**
	 * @var array
	 */
	private $permissions;

	/**
	 * @var array
	 */
	private $unviewableIds;

	/**
	 * @var Role
	 */
	private $guestRole;

	/**
	 * @param CacheRepository $cache
	 * @param DatabaseManager $db
	 * @param ContentClass    $classModel
	 */
	public function __construct(CacheRepository $cache, DatabaseManager $db, ContentClass $classModel)
	{
		$this->cache = $cache;
		$this->db = $db;
		$this->classModel = $classModel;
	}

	/**
	 * Get an array of unviewable ids for the registered content type
	 *
	 * @param string $content
	 * @param User   $user
	 *
	 * @return array
	 *
	 * @throws PermissionInvalidContentException
	 * @throws PermissionImplementInterfaceException
	 */
	public function getUnviewableIdsForContent($content, User $user = null)
	{
		$concreteClass = $this->classModel->getClass($content);

		if ($concreteClass == null) {
			throw new PermissionInvalidContentException($content);
		}

		if (!($concreteClass instanceof PermissionInterface)) {
			throw new PermissionImplementInterfaceException($content);
		}

		if ($this->unviewableIds[$content] != null) {
			return $this->unviewableIds[$content];
		}

		$models = $concreteClass::all();

		$unviewable = [];
		foreach ($models as $model) {
			if (!$this->hasPermission($content, $model->getContentId(), $concreteClass::getViewablePermission(), $user)
			) {
				$unviewable[] = $model->getContentId();
			}
		}

		$this->unviewableIds[$content] = $unviewable;

		return $unviewable;
	}

	/**
	 * Checks whether the specified user has the specified permission
	 *
	 * @param string       $content
	 * @param int          $contentID
	 * @param array|string $permission
	 * @param User         $user
	 *
	 * @return bool
	 *
	 * @throws PermissionInvalidContentException
	 * @throws PermissionImplementInterfaceException
	 */
	public function hasPermission($content, $contentID, $permission, User $user = null)
	{
		// TODO: Permissions should use the new Guard system in Laravel.
		return true;
//		$concreteClass = $this->classModel->getClass($content);
//
//		if ($concreteClass == null) {
//			throw new PermissionInvalidContentException($content);
//		}
//
//		if (!($concreteClass instanceof PermissionInterface)) {
//			throw new PermissionImplementInterfaceException($content);
//		}
//
//		if ($user == null) {
//			$user = app('auth.driver')->user();
//		}
//
//		// Handle the array case
//		if (is_array($permission)) {
//			foreach ($permission as $perm) {
//				$hasPermission = $this->hasPermission($content, $contentID, $perm, $user);
//
//				// No need to check more permissions
//				if (!$hasPermission) {
//					return false;
//				}
//			}
//
//			return true;
//		}
//
//		// We already calculated the permissions for this user, no need to recheck all roles
//		if (isset($this->permissions[$content][$contentID][$user->getKey()][$permission])) {
//			return $this->permissions[$content][$contentID][$user->getKey()][$permission];
//		}
//
//		// Handle special cases where no role has been set
//		$roles = $user->roles;
//		if ($roles->count() == 0) {
//			if ($user->exists) {
//				// User saved? Something is wrong, attach the registered role
//				$registeredRole = Role::where('role_slug', '=', 'user')->first();
//				$user->roles()->attach($registeredRole->id, ['is_display' => 1]);
//				$roles = [$registeredRole];
//			} else {
//				// Guest
//				if ($this->guestRole == null) {
//					$this->guestRole = Role::where('role_slug', '=', 'guest')->first();
//				}
//				$roles = [$this->guestRole];
//			}
//		}
//
//		// Assume "No" by default
//		$isAllowed = false;
//		foreach ($roles as $role) {
//			$hasPermission = $this->getPermissionForRole($role, $permission, $content, $contentID);
//
//			// If we never want to grant the permission we can skip all other roles. But don't forget to cache it
//			if ($hasPermission == PermissionChecker::NEVER) {
//				$isAllowed = false;
//				break;
//			} // Override our "No" assumption - but don't return yet, we may have a "Never" permission later
//			elseif ($hasPermission == PermissionChecker::YES) {
//				$isAllowed = true;
//			}
//		}
//
//		// No parent? No need to do anything else here
//		if (($concreteClass instanceof InheritPermissionInterface)
//			&& $concreteClass::find($contentID)->getParent() != null
//		) {
//			// If we have a positive permission but need to check parents for negative values do so here
//			if ($isAllowed && in_array($permission, $concreteClass::getNegativeParentOverrides())) {
//				$isAllowed = $this->hasPermission(
//					$content,
//					$concreteClass::find($contentID)->getParent()->getContentId(),
//					$permission,
//					$user
//				);
//			}
//
//			// Do the same for negative permissions with parent positives
//			if (!$isAllowed && in_array($permission, $concreteClass::getPositiveParentOverrides())) {
//				$isAllowed = $this->hasPermission(
//					$content,
//					$concreteClass::find($contentID)->getParent()->getContentId(),
//					$permission,
//					$user
//				);
//			}
//		}
//
//		// Don't forget to cache the permission for this call
//		$this->permissions[$content][$contentID][$user->getKey()][$permission] = $isAllowed;
//
//		return $isAllowed;
	}

	/**
	 * Check whether a specific Role has the specified permission
	 *
	 * @param Role        $role       The role to check
	 * @param string      $permission The permission to check
	 * @param string|null $content    If the permission is related to some content (eg forum) this string specifies the
	 *                                type of text
	 * @param int|null    $contentID  If $content is set this specifies the ID of the content to check
	 *
	 * @return PermissionChecker::NEVER|NO|YES
	 */
	public function getPermissionForRole(Role $role, $permission, $content = null, $contentID = null)
	{
		// Permissions associated with user/groups are saved without content
		// (all permissions are associated with groups anyways)
		if ($content == 'user' || $content == 'usergroup') {
			$content = null;
			$contentID = null;
		}

		if ($this->hasCache($role, $permission, $content, $contentID)) {
			return $this->getCache($role, $permission, $content, $contentID);
		}

		// Get the value if we have one otherwise the devault value
		$permissionValues = $this->db->table('permissions')
			->where('permission_name', '=', $permission)
			->where('content_name', '=', $content)
			->leftJoin('permission_role', function ($join) use ($role, $content, $contentID) {
				$join->on('permission_id', '=', 'id')
					->where('role_id', '=', $role->id);

				if ($content != null && $contentID != null) {
					$join->where('content_id', '=', $contentID);
				}
			})
			->first(['value', 'default_value']);

		// If the permission doesn't exist return "Never" to break all loops but don't cache it as it may be added later
		if ($permissionValues == null) {
			return static::NEVER;
		}

		// We have a content value so we can save that as permission
		if ($permissionValues->value !== null) {
			$this->putCache($role, $permission, $content, $contentID, $permissionValues->value);

			return $permissionValues->value;
		}

		// We have a content permission without a specific value
		// Now we need to check whether this role has a content permission (#122)
		// Unfortunately Laravel doesn't have a subwhere for joins so we can't add it to the query above
		if ($content != null && $contentID != null) {
			$contentValues = $this->db->table('permissions')
				->where('permission_name', '=', $permission)
				->where('content_name', '=', $content)
				->leftJoin('permission_role', function ($join) use ($role, $content, $contentID) {
					$join->on('permission_id', '=', 'id')
						->where('role_id', '=', $role->id)
						->where('content_id', '=', 0);
				})
				->first(['value']);

			if ($contentValues != null && $contentValues->value !== null) {
				$this->putCache($role, $permission, $content, $contentID, $contentValues->value);

				return $contentValues->value;
			}

		}

		$this->putCache($role, $permission, $content, $contentID, $permissionValues->default_value);

		return $permissionValues->default_value;
	}

	/**
	 * @param Role        $role
	 * @param string      $permission
	 * @param string|null $content
	 * @param int|null    $contentID
	 *
	 * @return bool
	 */
	private function hasCache(Role $role, $permission, $content, $contentID)
	{
		return $this->getCache($role, $permission, $content, $contentID) != null;
	}

	/**
	 * @param Role        $role
	 * @param string      $permission
	 * @param string|null $content
	 * @param int|null    $contentID
	 *
	 * @return mixed
	 */
	private function getCache(Role $role, $permission, $content, $contentID)
	{
		return $this->cache->get("permission.{$role->role_slug}.{$permission}.{$content}.{$contentID}");
	}

	/**
	 * @param Role         $role
	 * @param string       $permission
	 * @param string|null  $content
	 * @param int|null     $contentID
	 * @param NEVER|NO|YES $value
	 */
	private function putCache(Role $role, $permission, $content, $contentID, $value)
	{
		$this->cache->forever("permission.{$role->role_slug}.{$permission}.{$content}.{$contentID}", $value);
	}
}