text:
function draw() {
    var canvas = document.getElementById("canvas");
    if (canvas.getContext) {
        var ctx = canvas.getContext("2d");
    }

	if(getType() == "Organism") {
		//get values
		var commonName=getCommonName();
		var latinName=getLatinName();
		var evolutionaryTree=getEvolutionaryTree();
		var pointValue=getPointValue();
		var scale=getScale();
		var foodchainNum=getFoodchainNum();
		var artistName=getArtistName();
		var artistWebsite=getArtistWebsite();
		var dietType=getDietType();
		var climates=getClimates();
		var special=getSpecial();
		var desc=getDescription();
		var terrains= getTerrains();

		//draw
		drawTerrains(ctx, terrains);
		drawBackground(ctx, color);
		drawImage(ctx);
		drawTitle(ctx, commonName);
		drawSubtitle(ctx, latinName);
		drawDietCircle(ctx, dietType);
		drawEvolutionaryTree(ctx, evolutionaryTree);
		drawPointValue(ctx,pointValue);
		drawScale(ctx, scale);
		drawFoodchainNum(ctx, foodchainNum);
		drawArtistName(ctx, artistName);
		drawArtistWebsite(ctx, artistWebsite);
		drawCCMentions(ctx);
		drawClimate(ctx, climates);
		drawSpecial(ctx, special);
		drawDescription(ctx, desc);
	}
	else if(getType() == "Event") {
		var eventName=getEventName();
		var artistName=getArtistName();
		var artistWebsite=getArtistWebsite();
		var play=getPlay();
		var effect=getEffect();

		drawBackground(ctx, color);
		drawImage(ctx);
		drawTitle(ctx, eventName);
		drawSubtitle(ctx, "Event Card");
		drawEvolutionaryTree(ctx, "Event");
		drawArtistName(ctx, artistName);
		drawArtistWebsite(ctx, artistWebsite);
		drawSpecial(ctx, play);
		drawDescription(ctx, effect);
		drawCCMentions(ctx);
	}

	else if(getType() == "Home") {
		var homeName=getHomeName();

		drawBackground(ctx, color);
		drawImage(ctx);
		drawTitle(ctx, "Home Card");
		drawSubtitle(ctx, homeName);
		drawEvolutionaryTree(ctx, "Starter");
		drawArtistName(ctx, artistName);
		drawArtistWebsite(ctx, artistWebsite);
		drawSpecial(ctx, ["This is a HOME card. The game starts with", "each player having a HOME card played on the", "table next to each other."]);
		drawDescription(ctx, ["Home cards represent all TERRAIN", "and CLIMATE values."]);
		drawCCMentions(ctx);
    }
}

function hex2rgb(hex) { //needs to be moved to utilities.js
	if(hex.charAt(0) == "#") hex = hex.slice(1); //Remove the '#' char - if there is one.
	hex = hex.toUpperCase();
	var hex_alphabets = "0123456789ABCDEF";
	var value = new Array(3);
	var k = 0;
	var int1,int2;
	for(var i=0;i<6;i+=2) {
		int1 = hex_alphabets.indexOf(hex.charAt(i));
		int2 = hex_alphabets.indexOf(hex.charAt(i+1));
		value[k] = (int1 * 16) + int2;
		k++;
	}
	return ("rgb("+value[0]+","+value[1]+","+value[2]+")");
}

function drawBackground(context, color){
    context.fillStyle = "rgb(0,0,0)"; //draws border of card
    context.fillRect(0,0,270,410);

    var rgbColor=hex2rgb(color); //we convert to RGB, otherwise Gecko is a pain.
    context.fillStyle = rgbColor;
    context.fillRect(10, 10, 250, 390);
}

function drawImage(context){
    var image = new Image();
    image.src = getImagePath(image); //we get the path from the html input
    image.onload = function() {
        context.drawImage(image, 10, 60, 250, 153);
    };
}

function drawTitle(context, title){
    context.fillStyle = "rgb(0,0,0)"; //draw title

    var fontSize=20;
    var size=300;
    //determine font size for string (needs to be moved in a function)
    while (size>180){
        context.font = 'bold '+fontSize+'px sans-serif';
        size=Math.round(context.measureText(title).width);
        fontSize--;
    }

    context.textBaseline = 'top';
    context.fillText  (title, 15, 35-fontSize);
}

function drawSubtitle(context, subtitle){
    context.fillStyle = "rgb(0,0,0)"; //draw subtitle
    context.font         = 'italic 12px sans-serif';
    context.textBaseline = 'top';
    context.fillText(subtitle, 15, 40);
}

function drawDietCircle(context, type){
    //type 1 is photosynthetic, yellow
    //type 2 is molecular, black
    //type 3 is herbivore, green
    //type 4 is omnivore, brown
    //type 5 is carnivore, red
    switch(type){
        case "1":
            context.fillStyle = "rgb(223,192,0)";
            break;
        case "2":
            context.fillStyle = "rgb(0,0,0)";
            break;
        case "3":
            context.fillStyle = "rgb(49,159,0)";
            break;
        case "4":
            context.fillStyle = "rgb(127,59,0)";
            break;
        case "5":
		case "6":
            context.fillStyle = "rgb(255,0,0)";
            break;
    }

    context.arc(240, 30, 12, 0, Math.PI*2, true);
    context.closePath();
    context.fill();

}

function drawFoodchainNum(context, num){
    context.fillStyle = "rgb(255,255,255)";
    context.font         = 'bold 24px serif';
    context.textBaseline = 'top';
    context.fillText(num, 234, 17);
}

function drawScale(context, scale){
    context.fillStyle = "rgb(0,0,0)";
    context.font         = 'bold 24px serif';
    context.textBaseline = 'top';
    context.fillText(scale, 205, 17);
}

function drawClimate(context, climates){
    //flags indicate climate (hot, warm, cool, cold)
    //Order on card: cold, cool // warm, hot
    var climateCount=0; //this variable is used to determine whether a comma will be inserted or not
    var bottomLine=0; //this variable is used to determine if cold/cool are displayed on the lower or upper line

    context.fillStyle = "rgb(0,0,0)";
    context.font         = 'bold 12px sans-serif';
    context.textBaseline = 'top';

    if (climates & 0x1){
        context.fillText("Hot", 230, 385);
        climateCount++;
        bottomLine=1;
    }

    if (climates & 0x2){
        if (climateCount==1){
            context.fillText(",", 224, 385);
            context.fillText("Warm", 190, 385);
        } else {
            context.fillText("Warm", 220, 385);
        }
        bottomLine=1;
    }

    climateCount=0
    if (climates & 0x4){
        context.fillText("Cool", 225, 385-bottomLine*15);
        climateCount++;
    }

    if (climates & 0x8){
        if (climateCount==1){
            context.fillText(",", 218, 385-bottomLine*15);
            context.fillText("Cold", 193, 385-bottomLine*15);
        } else {
            context.fillText("Cold", 225, 385-bottomLine*15);
        }
    }
}

function drawPointValue(context, points){
    context.fillStyle = "rgb(0,0,0)";
    context.font         = 'bold 11px sans-serif';
    context.textBaseline = 'top';
    context.fillText(points+" POINTS", 195, 230);
}

function drawTerrains(context, terrains){
    var left = new Image();
    left.src = "resources/"+terrains[0]+".png";

    var center = new Image();
    center.src = "resources/"+terrains[1]+".png";

    var right = new Image();
    right.src = "resources/"+terrains[2]+".png";

    left.onload = function() {
        context.drawImage(left, 10, 345);
    };

    right.onload = function() {
        context.drawImage(right, 178, 345);
    };

    center.onload = function() {
        context.drawImage(center, 94, 345);
    };
}

function drawEvolutionaryTree(context, names){
    context.fillStyle = "rgb(9,83,168)";
    context.font         = '8px courier';
    context.textBaseline = 'top';
    size=context.measureText(names);
    context.fillText(names, 255-Math.round(size.width), 215);
}

function drawArtistName(context, artistName){
    context.fillStyle = "rgb(0,0,0)";
    context.font         = '11px sans-serif';
    context.textBaseline = 'top';
    context.fillText("Image by ", 15, 370);

    context.font         = 'italic 11px sans-serif';
    context.textBaseline = 'top';
    context.fillText(artistName, 62, 370);
}

function drawArtistWebsite(context, artistWebsite){
    context.fillStyle = "rgb(9,83,168)";
    context.font         = '11px sans-serif';
    context.textBaseline = 'top';
    context.fillText(artistWebsite, 15, 385);
}

function drawCCMentions(context){
    var image = new Image();
    image.src = "resources/creative-commons.png";
    image.onload = function() {
        context.drawImage(image, 15, 215);
    };
}

function drawSpecial(context, special){
    context.fillStyle = "rgb(0,0,0)";
    context.font         = '11px sans-serif';
    context.textBaseline = 'top';

    for (i=0;i<special.length;i++){
        context.fillText(special[i], 15, 250+i*12);
    }
}

function drawDescription(context, description){
    context.fillStyle = "rgb(0,0,0)";
    context.font         = 'italic 11px sans-serif';
    context.textBaseline = 'top';

    for (i=0;i<description.length;i++){
        context.fillText(description[i], 15, 315+i*12);
    }
}


text:
path: /portfolio/static-website
priority: 8
title: "A Personal Website"
previewImage: danielhollcraft-website.png
start: Apr 2017,
end: Present,
type: Open Source,
skills: GatsbyJS, GraphQL, React, SCSS, Serverless, S3, Amazon Web Services,
source: https://github.com/danielbh/danielhollcraft.com-gatsbyjs
mobilePreview: DanielHollcraftMobile,
desktopPreview: DanielHollcraftDesktop,
previewCaption: Daniel Hollcraft website preview,
platform: Web,
---

Created the second version of my personal website using Gatsby.js.

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Serverside_InlineCredentials
 *
 * @author Pierre - dev@nettools.ovh
 * @license MIT
 */

namespace Nettools\GoogleAPI\Clients;

/**
 * Class to interface with Google APIs server-side with clientId and clientSecret credentials
 *
 * The web app access user data with his explicit consentement, and we have to deal with accesstokens and authorization process
 */
class Serverside_InlineCredentials extends Serverside
{
    /**
     * Constructor of interface to Google APIs with server-side business
     *
     * @param string $clientid Credentials from Google Developper console
     * @param string $clientsecret Credentials from Google Developper console
     * @param string[] $scopes Array of strings with scopes (such as Google\Service\Calendar::CALENDAR_READONLY)
     * @param string[] $others Associative array of Google API config values
     */
    public function __construct($clientid, $clientsecret, $scopes, $others = array())
    {
        // credentials
        $others['clientId'] = $clientid;
        $others['clientSecret'] = $clientsecret;

        // call parent constructor with parameters defined and merged with optional ones
        parent::__construct($scopes, $others);
    }
}

?>


text:
/**
 * download
 */

var request = require('request'),
    fs = require('fs'),
    url = require('url'),
    progress = require('request-progress'),
    mkdirp = require('mkdirp'),
    os = require('os'),
    dns = require('dns'),
    isReachable = require('is-reachable');

//get the host (http:// + IP)
var host = localStorage.getItem('host');
//save the robot model
var currentModel = "";
//save the file pattern, you can upload files more than one kind.
var currentFilePattern = '';

//upload interval object, in uploadAndSubmit function
var interval = null;
var intervalIsClosed = false;

var percentNum = 0;
var percentText;

//default URLs
//following two URLs on internet
var downloadURL = "http://download.gs-robot.com/system_package/";
var getUpdatePathURL = "http://rms.gs-robot.com/gs-rms-svr/system_packages/";
//following URLs on the robot server and you can configure it.
var restoreURL = host + ":6789/gs-robot/system/rollback";
var uploadURL = host + ":6789/gs-robot/system/update_system/";
var beginURL = host + ":5678/gs-robot/cmd/launch_system_updater";
var overURL = host + ":5678/gs-robot/cmd/shutdown_system_updater";
var urlMap = JSON.parse(localStorage.getItem('ipConfig'));

//set a flag at the first time of loading the page to use it by the refresh button
localStorage.setItem('page', "firmware");

//trigger the material modal, but now I trigger it in the function
// $('.modal-trigger').leanModal();

/**
 * ===========================================================================================
 *                                    download project
 * ===========================================================================================
 */
function downloadFile(urlData, toast) {
    var file_name = url.parse(urlData).pathname.split('/').pop();
    console.log('filename: ' + file_name);
    var out = fs.createWriteStream('./firmware_download/' + file_name);

    var downloadError = false;
    // Use request and request-progress, you can trace the
    // The options argument is optional so you can omit it
    progress(request(urlData), {
        throttle: 0,                    // Throttle the progress event to 2000ms, defaults to 1000ms
        delay: 0,                       // Only start to emit after 1000ms delay, defaults to 0ms
        lengthHeader: 'content-length'  // Length header to use, defaults to content-length
    })
        .on('progress', function (state) {
            // The state is an object that looks like this:
            // {
            //     percentage: 0.5,            // Overall percentage (between 0 to 1)
            //     speed: 554732,              // The download speed in bytes/sec
            //     size: {
            //         total: 90044871,        // The total payload size in bytes
            //         transferred: 27610959   // The transferred payload size in bytes
            //     },
            //     time: {
            //         elapsed: 36.235,        // The total elapsed seconds since the start (3 decimals)
            //         remaining: 81.403       // The remaining seconds to finish (3 decimals)
            //     }
            // }
            //console.log('progress', state);
            percentNum = toDecimal2(state.percentage * 100);
            percentText = toDecimal2(state.percentage * 100) + "%" + "  Speed: " + parseInt(state.speed / 1024) + " KB/s";
            document.getElementById('downloadProgress1').textContent = percentText;
            document.getElementById('progressDeter').setAttribute('style', "width:" + percentNum + "%");
        })
        // when error occurs program will go here
        .on('error', function (err) {
            console.log("download error: " + err);
            // when download is broken, show the push button
            showUpdateBtn();
            downloadError = true;
        })
        .on('end', function (response) {
            console.log("download end response: " + response);
            $("#firmwareProgressBar").css("visibility", "hidden");
            console.log(downloadError);
            showUpdateBtn();
            if (!downloadError) {
                // Do something after request finishes
                Materialize.toast(file_name + toast, 4000);
                Materialize.toast(file_name + " is saved in firmware_download folder!", 8000);
                document.getElementById('downloadProgress1').textContent = "100%" + "  Speed: " + "0KB/s";
                document.getElementById('progressDeter').setAttribute('style', "width:0%");
            } else {
                //if user cancel the download action, it'll break the request and delete the incomplete file
                toastError(file_name + " download failed!");
                // break the write
                out.end();
                console.log("delete file" + file_name);
                //delete file synchronously
                fs.unlinkSync('./firmware_download/' + file_name);
            }
        })
        //write the file using pipe
        .pipe(out);
}

function showUpdateBtn() {
    $("#chooseFileBtn").css('visibility', 'visible');
    $("#chooseAudioFileBtn").css('visibility', 'visible');
    // $("#uploadBtn").css('visibility', 'visible');
    // $("#uploadAudioBtn").css('visibility', 'visible');
}

function hideUpdateBtn() {
    $("#chooseFileBtn").css('visibility', 'hidden');
    $("#chooseAudioFileBtn").css('visibility', 'hidden');
    // $("#uploadBtn").css('visibility', 'hidden');
    // $("#uploadAudioBtn").css('visibility', 'hidden');
}

//to decimal, save 2 digits
function toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}

//the function is reserved
/*
 function getModelList() {
 $.ajax({
 url: getModelListURL,
 type: "GET",
 dataType: "json",
 async: false,
 success: function (data) {
 if(data.successed) {
 modelList = data;
 } else {
 console.log(data);
 toastError("Oops... Get robot list failed.");
 //Materialize.toast("Oops... Get robot list failed.", 4000);
 }
 }
 });
 }
 */

document.getElementById('download').addEventListener('click', function () {
    console.log("download");

    //check if firmware_download is existed, if not it'll create a new folder
    fs.stat('./firmware_download', function (err, stat) {
        if (err === null) {
            //folder is existed do nothing
        } else {
            mkdirp('./firmware_download', function (err) {
                console.log(err);
            });
        }
    });

    downloadSubmit();
    // selectModel('list-content');
});

function downloadSubmit() {
    hideUpdateBtn();
    isReachable(downloadURL, (err, reachable) => {
        if (reachable) {
            download();
        } else {
            showUpdateBtn();
            toastError("Please connect to the Internet first!");
            toastError(err);
        }
    });

    // $.ajax({
    //     type: "GET",
    //     url: "http://www.baidu.com",
    //     success: function (data) {
    //         download();
    //     },
    //     error: function (XMLHttpRequest, textStatus, errorThrown) {
    //         showUpdateBtn();
    //         console.log(errorThrown);
    //         console.log(textStatus);
    //         if (textStatus == 'error') {
    //             toastError("Please connect to the Internet first!");
    //         }
    //     }
    // });
}

//configure a special style of toasting a error
function toastError(string) {
    var text = "" + string + "
";
    Materialize.toast(text, 10000);
}

//download main route function
function download() {
    $("#firmwareProgressBar").css("visibility", "visible");
    currentModel = localStorage.getItem('currentModel');
    var xhr = new XMLHttpRequest();

    xhr.onload = function () {
        console.log("getPath response:" + xhr.response);
        var object = JSON.parse(xhr.response);
        if (xhr.status === 400) {
            // If session is expired, it'll sign out.
            if (object.code === "SESSION_SERVICE_CUSTOMER_SESSION_EXPIRED") {
                setTimeout(function () {
                    location.href = "signIn.html";
                }, 5000);
            }
            showUpdateBtn();
            $("#firmwareProgressBar").css("visibility", "hidden");
            toastError("Download failed (no latest update in the server)");
            toastError(object.message);
        } else {
            var object = JSON.parse(xhr.response);
            console.log(object);
            if (object.msg === "successed") {
                Materialize.toast("Get UpdatePath successfully.", 4000);

                //Create a file list of files which are downloading.
                //You can crash the download by click the delete label.
                //At the end of a line, it'll show a text of the current progress and the downloading speed.
                var ul = document.getElementById('listContainer');
                clearList();
                var li_1 = document.createElement('li');
                li_1.setAttribute('class', 'collection-item');

                var h = document.createElement('h5');
                h.textContent = "Downloading";
                li_1.appendChild(h);
                ul.appendChild(li_1);

                var li = document.createElement('li');
                li.setAttribute('class', 'collection-item');

                var div = document.createElement('div');
                div.setAttribute('id', 'list0');
                //div.textContent = files[i].name;
                div.textContent = object.data.pkg_file_url;

                var a = document.createElement('a');
                a.setAttribute('class', 'secondary-content');
                a.setAttribute('id', "downloadProgress1");
                a.textContent = "0%";

                var a_svg = document.createElement('a');
                a_svg.setAttribute('class', 'secondary-content');
                a_svg.setAttribute('id', "close1");
                a_svg.setAttribute('style', 'margin-left:20px;position:absolute;z-index:100;');

                var img = document.createElement('img');
                img.src = "css/icon/ic_cancel_black_24dp_1x.png";

                /*

                 */
                var progressDiv = document.createElement('div');
                progressDiv.setAttribute('class', 'progress');
                var subProgressDiv = document.createElement('div');
                subProgressDiv.setAttribute('class', 'determinate');
                subProgressDiv.setAttribute('id', 'progressDeter');
                subProgressDiv.setAttribute('style', 'width: 0%');
                progressDiv.appendChild(subProgressDiv);

                a_svg.appendChild(img);
                div.appendChild(a_svg);
                div.appendChild(a);
                li.appendChild(div);
                li.appendChild(progressDiv);
                ul.appendChild(li);

                document.getElementById('close1').addEventListener("click", cancelAndDelete);
                //go real download get request
                downloadFile(downloadURL + object.data.pkg_file_url, ' is downloaded !');
            } else {
                $("#firmwareProgressBar").css("visibility", "hidden");
                toastError("Oops... Get UpdatePath failed.");
            }
        }
    };
    xhr.open("GET", getUpdatePathURL + currentModel + "/latest");
    //add some header about the safe verification
    xhr.setRequestHeader("Gs-Client-Access-Key", localStorage.getItem("accessKey"));
    xhr.setRequestHeader("Gs-Client-Type", "DESKTOP_WEB");
    xhr.setRequestHeader("Gs-Language-Type", "CN");
    xhr.send(null);
}

/**
 * function to break the request by making a error, but this practice is little bit dirty.
 */
function cancelAndDelete() {
    var content = document.getElementById('listContainer');
    //This will make a error and the connection of downloading will break
    content.innerHTML = "";
    Materialize.toast("Cancel downloading!", 4000);
    $("#firmwareProgressBar").css("visibility", "hidden");
}

/**
 * ===========================================================================================
 *                                 restore the last version
 * ===========================================================================================
 */
document.getElementById('rollback').addEventListener('click', restore);
function restore() {
    currentModel = localStorage.getItem('currentModel');
    $("#firmwareProgressBar").css("visibility", "visible");
    beginURL = host + urlMap[currentModel].start_updater_api;
    restoreURL = host + urlMap[currentModel].rollback_api;

    if (beginURL != "") {
        //check the begin url whether reachable
        $.ajax({
            type: "GET",
            url: beginURL,
            success: function (data) {
                console.log(beginURL);
                //request rollback
                request.get({url: beginURL}, function (err, httpResponse, body) {
                    setTimeout(function () {
                        $.ajax({
                            url: restoreURL,
                            type: "GET",
                            success: function (data) {
                                console.log("rollback response: " + data);
                                var object = JSON.parse(data);
                                if (object.successed) {
                                    $("#firmwareProgressBar").css("visibility", "hidden");
                                    Materialize.toast("Rollback successfully!", 8000);
                                } else {
                                    $("#firmwareProgressBar").css("visibility", "hidden");
                                    toastError("Oops... Rollback failed!");
                                    //Materialize.toast("Oops... Rollback failed!", 4000);
                                }
                            }
                        });
                    }, 4000);
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("check connection response:" + errorThrown);
                console.log("check connection response:" + textStatus);
                $("#firmwareProgressBar").css("visibility", "hidden");
                toastError("Please connect to the robot WI-FI first!");
            }
        });
    } else {
        $("#firmwareProgressBar").css("visibility", "hidden");
        toastError("You can't rollback now. Robot is not ready.");
    }
}

//获得指定目录下的所有文件
function getAllFiles(root) {
    var result = [], files = fs.readdirSync(root);
    files.forEach(function (file) {
        var pathname = root + "/" + file
            , stat = fs.lstatSync(pathname);
        if (stat === undefined) return;

        // 不是文件夹就是文件
        if (!stat.isDirectory()) {
            result.push(pathname);
            // 递归自身
        } else {
            result = result.concat(getAllFiles(pathname))
        }
    });
    return result;
}

/**
 * ===========================================================================================
 *                                         Upload
 * ===========================================================================================
 */
var filesForm;
//show selected files in a list
$('input[type=file]').change(function () {
    currentModel = localStorage.getItem('currentModel');
    //get the uploadForm
    var form = document.forms["uploadForm"];
    if (currentFilePattern === 'firmware') {
        filesForm = form['file'];
    }
    if (currentFilePattern === 'audio') {
        filesForm = form['audioFile'];
    }
    if (filesForm.files.length > 0) {
        $("#uploadBtn").css("background-color", "#2196F3");
        // $("#uploadAudioBtn").css("background-color", "#2196F3");
        $("#uploadBtn").css("color", "#FFFFFF");
        // $("#uploadAudioBtn").css("color", "#FFFFFF");
        var files = filesForm.files;
        var ul = document.getElementById('listContainer');

        clearList();

        //create a upload list with a progress text
        var li_1 = document.createElement('li');
        li_1.setAttribute('class', 'collection-item');
        var h = document.createElement('h5');
        h.textContent = "Uploading ---> updating";
        li_1.appendChild(h);
        ul.appendChild(li_1);

        //support multiple files
        for (var i = 0; i < files.length; i++) {
            var li = document.createElement('li');
            li.setAttribute('class', 'collection-item');
            var div = document.createElement('div');
            div.setAttribute('id', 'list' + i);
            div.textContent = files[i].name;
            var a = document.createElement('a');
            a.setAttribute('class', 'secondary-content');
            a.setAttribute('id', "progress" + (i + 1));
            var a1 = document.createElement('a');
            a1.textContent = " SIZE: " + parseInt(files[i].size / 1024) + "KB";
            a.textContent = "0%";

            div.appendChild(a);
            div.appendChild(a1);
            li.appendChild(div);
            ul.appendChild(li);
        }
    } else {
        alert("Please choose a file.");
    }
});

document.getElementById("chooseFileBtn").addEventListener('click', function () {
    currentModel = localStorage.getItem('currentModel');
    currentFilePattern = 'firmware';
    document.getElementById('fileID').click();
});

// document.getElementById("chooseAudioFileBtn").addEventListener('click', function () {
//     currentModel = localStorage.getItem('currentModel');
//     currentFilePattern = 'audio';
//     document.getElementById('audioFileID').click();
// });

//reserved function for canceling and deleting the uploading file
function cancelChooseFile() {
    var content = document.getElementById('list0');
    //when upload this will trigger a error and break the XHR
    content.innerHTML = "";
    toastError("Please choose file again", 4000);
    $("#uploadBtn").css("background-color", "#DFDFDF");
    $("#uploadBtn").css("color", "#9F9F9F");
}

function clearList() {
    var list = document.getElementById('listContainer');
    list.innerHTML = "";
}

var canUpload = true;
function uploadAndSubmit() {
    var intervalTime;
    event.preventDefault();
    $('#uploadBtn').addClass('disabled');
    // $('#uploadAudioBtn').addClass('disabled');

    currentModel = localStorage.getItem('currentModel');
    $("#firmwareProgressBar").css("visibility", "visible");
    var object = JSON.parse(localStorage.getItem('ipConfig'));
    beginURL = host + object[currentModel].start_updater_api;
    if (currentFilePattern === 'firmware') {
        uploadURL = host + object[currentModel].update_api;
    }
    if (currentFilePattern === 'audio') {
        uploadURL = host + object[currentModel].update_audio_api;
    }

    console.log(canUpload);
    if (beginURL != "") {
        //use ajax to check the internet connectivity
        if (canUpload) {
            $.ajax({
                type: "GET",
                url: beginURL,
                success: function (data) {
                    canUpload = false;
                    console.log("start response " + data);
                    //use request
                    request.get({url: beginURL}, function (err, httpResponse, body) {
                        console.log("start response: " + httpResponse);
                        console.log("start error: " + err);
                        $("#firmwareProgressBar").css("visibility", "visible");
                        var object = JSON.parse(body);
                        console.log(object);
                        intervalTime = 0;
                        //setTimeout(function() {
                        //ask for upload file every 3 seconds a time
                        interval = setInterval(function () {
                            intervalTime += 1;
                            if (intervalTime > 5) {
                                clearInterval(interval);
                            }
                            if (object.successed) {
                                var form = document.forms["uploadForm"];
                                var fileName;
                                if (currentFilePattern === 'firmware') {
                                    fileName = $("[name='file']#fileID").val().split('\\').pop();
                                }
                                if (currentFilePattern === 'audio') {
                                    fileName = $("[name='audioFile']#audioFileID").val().split('\\').pop();
                                }

                                console.log("fileName: " + fileName);
                                $("#firmwareProgressBar").css("visibility", "visible");
                                if (filesForm.files.length > 0) {

                                    // 寻找表单域中的 <input type="file" ... /> 标签
                                    var file = filesForm.files[0];

                                    //var formData = new FormData();
                                    //
                                    //for(var i=0;i<files.length;i++) {
                                    //  var file = files[i];
                                    //  formData.append(file.name, file);
                                    //}

                                    var xhr = new XMLHttpRequest();
                                    (xhr.upload || xhr).addEventListener('progress', function (e) {
                                        var done = e.position || e.loaded;
                                        var total = e.totalSize || e.total;
                                        if (total != 0 && !intervalIsClosed) {
                                            console.log("clearInterval-------------------");
                                            clearInterval(interval);
                                            intervalIsClosed = true;
                                        }
                                        console.log('xhr progress: ' + Math.round(done / total * 100) + '%');
                                        //example update the progress data
                                        //$('#progress1').textContent = Math.round(done / total * 100) + '%';
                                        document.getElementById('progress1').textContent = Math.round(done / total * 100) + '%';
                                        if (done === total) {
                                            document.getElementById('progress1').textContent = "Decompressing and installing";
                                        }
                                    });
                                    // 请求完成时建立一个处理程序。
                                    xhr.onload = function () {
                                        canUpload = true;
                                        console.log("update response status: " + xhr.status);
                                        console.log("update response: " + xhr.response);
                                        var object = JSON.parse(xhr.response);

                                        $('#uploadBtn').removeClass('disabled');
                                        // $('#uploadAudioBtn').removeClass('disabled');

                                        clearInterval(interval);
                                        if (object.successed) {
                                            setTimeout(function() {
                                                document.getElementById('progress1').textContent = "Update complete";
                                                Materialize.toast("Update successfully", 4000);
                                                Materialize.toast("If you want to use the updated features, please restart your robot.", 10000);
                                                $("#firmwareProgressBar").css("visibility", "hidden");
                                                intervalIsClosed = false;
                                                return false;
                                            },60000);
                                        } else {
                                            document.getElementById('progress1').textContent = "Update failed";
                                            toastError("Update failed " + object.msg, 20000);
                                            $("#firmwareProgressBar").css("visibility", "hidden");
                                            console.log(xhr.response);
                                            return false;
                                        }
                                    };
                                    xhr.onerror = function () {
                                        canUpload = true;
                                        $("#firmwareProgressBar").css("visibility", "hidden");
                                    };
                                    console.log(uploadURL + file.name);
                                    xhr.open("POST", uploadURL + file.name);
                                    xhr.send(file);
                                } else {
                                    alert("Please choose a file.");
                                    $("#uploadBtn").css("background-color", "#DFDFDF");
                                    // $("#uploadAudioBtn").css("background-color", "#DFDFDF");
                                    $("#uploadBtn").css("color", "#9F9F9F");
                                    // $("#uploadAudioBtn").css("color", "#9F9F9F");
                                }
                            }
                        }, 3000);
                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    canUpload = true;
                    console.log("check connection response: " + textStatus);
                    $('#uploadBtn').removeClass('disabled');
                    // $('#uploadAudioBtn').removeClass('disabled');

                    $("#firmwareProgressBar").css("visibility", "hidden");
                    if (textStatus == 'error') {
                        toastError("Please connect to the robot WI-FI first!", 10000);
                    }
                }
            });
        }
    } else {
        $("#firmwareProgressBar").css("visibility", "hidden");
        toastError("You can't update now. Robot is not ready.");
    }
}

/**
 * ===========================================================================================
 *                                          Go back
 * ===========================================================================================
 */
function firmwareBack() {
    clearInterval(interval);
    intervalIsClosed = true;
    //control the event binding
    codeBackEventSum = 1;
    console.log('back from firmware');

    currentModel = localStorage.getItem('currentModel');
    console.log(currentModel);
    $("#firmwareProgressBar").css("visibility", "visible");
    var object = JSON.parse(localStorage.getItem('ipConfig'));
    console.log(object);
    overURL = host + object[currentModel].stop_updater_api;
    $.ajax({
        url: overURL,
        type: "GET",
        success: function (data) {
            console.log(data);
        }
    });

    //just replace the content1's content
    $('#content1').fadeOut('fast', function () {
        $(this).load('selectModule.html #content1', function () {
            localStorage.setItem('page', 'select');
            // if($('#backBtn1').length) {
            //     document.getElementById('backBtn1').setAttribute('id','backBtn');
            // }
            $('#titleText').text("FUNCTION SELECTION");
            checkReachable();
            document.getElementById('mapModule').addEventListener('click', goMapModule);
            document.getElementById('firmwareModule').addEventListener('click', goFirmwareModule);
            // document.getElementById('backBtn').removeEventListener('click',false);
            $(this).fadeIn('fast');
        });
    });
}

//binding so many times will occur horrible error, use eventSum var control the binding
if (codeBackEventSum === 0) {
    console.log(mapBackEventSum);
    if (mapBackEventSum) {
        document.getElementById('backBtn').removeEventListener('click', mapBack);
    }
    document.getElementById('backBtn').addEventListener('click', firmwareBack);
}

document.getElement


text:
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>nl.big-o</groupId>
  <artifactId>atlas</artifactId>
  <packaging>jar</packaging>
  <version>0.2.0</version>
  <name>atlas</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <junit.version>4.13.1</junit.version>
    <kryo.version>5.0.1</kryo.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.esotericsoftware</groupId>
      <artifactId>kryo</artifactId>
      <version>${kryo.version}</version>
    </dependency>

  </dependencies>

  <build>

    <plugins>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <executable>java</executable>
          <mainClass>atlas.CityIndex</mainClass>
        </configuration>
      </plugin>

      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.2.4</version>
        <configuration>
          <createDependencyReducedPom>true</createDependencyReducedPom>
          <filters>
            <filter>
              <artifact>*:*</artifact>
              <excludes>
                <exclude>META-INF/*.SF</exclude>
                <exclude>META-INF/*.DSA</exclude>
                <exclude>META-INF/*.RSA</exclude>
              </excludes>
            </filter>
          </filters>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>atlas.Atlas</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>

    </plugins>

  </build>

</project>


text:
from typing import Union

from pytorch_lightning.loggers.base import DummyLogger
from pytorch_lightning.utilities import rank_zero_info
from pytorch_lightning.utilities.exceptions import MisconfigurationException

class DebuggingConnector:
    def __init__(self, trainer):
        self.trainer = trainer

    def on_init_start(
        self,
        limit_train_batches,
        limit_val_batches,
        limit_test_batches,
        limit_predict_batches,
        val_check_interval,
        overfit_batches,
        fast_dev_run,
    ):
        if not isinstance(fast_dev_run, (bool, int)):
            raise MisconfigurationException(
                f"fast_dev_run={fast_dev_run} is not a valid configuration. It should be either a bool or an int >= 0"
            )

        if isinstance(fast_dev_run, int) and (fast_dev_run < 0):
            raise MisconfigurationException(
                f"fast_dev_run={fast_dev_run} is not a valid configuration. It should be >= 0."
            )

        self.trainer.fast_dev_run = fast_dev_run
        fast_dev_run = int(fast_dev_run)

        # set fast_dev_run=True when it is 1, used while logging
        if fast_dev_run == 1:
            self.trainer.fast_dev_run = True

        if fast_dev_run:
            limit_train_batches = fast_dev_run
            limit_val_batches = fast_dev_run
            limit_test_batches = fast_dev_run
            limit_predict_batches = fast_dev_run
            self.trainer.fit_loop.max_steps = fast_dev_run
            self.trainer.num_sanity_val_steps = 0
            self.trainer.fit_loop.max_epochs = 1
            val_check_interval = 1.0
            self.trainer.check_val_every_n_epoch = 1
            self.trainer.logger = DummyLogger()

            rank_zero_info(
                "Running in fast_dev_run mode: will run a full train,"
                f" val, test and prediction loop using {fast_dev_run} batch(es)."
            )

        self.trainer.limit_train_batches = _determine_batch_limits(limit_train_batches, "limit_train_batches")
        self.trainer.limit_val_batches = _determine_batch_limits(limit_val_batches, "limit_val_batches")
        self.trainer.limit_test_batches = _determine_batch_limits(limit_test_batches, "limit_test_batches")
        self.trainer.limit_predict_batches = _determine_batch_limits(limit_predict_batches, "limit_predict_batches")
        self.trainer.val_check_interval = _determine_batch_limits(val_check_interval, "val_check_interval")
        self.trainer.overfit_batches = _determine_batch_limits(overfit_batches, "overfit_batches")
        self.determine_data_use_amount(self.trainer.overfit_batches)

    def determine_data_use_amount(self, overfit_batches: float) -> None:
        """Use less data for debugging purposes"""
        if overfit_batches > 0:
            self.trainer.limit_train_batches = overfit_batches
            self.trainer.limit_val_batches = overfit_batches
            self.trainer.limit_test_batches = overfit_batches

def _determine_batch_limits(batches: Union[int, float], name: str) -> Union[int, float]:
    if 0 <= batches <= 1:
        return batches
    if batches > 1 and batches % 1.0 == 0:
        return int(batches)
    raise MisconfigurationException(
        f"You have passed invalid value {batches} for {name}, it has to be in [0.0, 1.0] or an int."
    )


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * @type {DOMFileSystem}
 */
var fileSystem = null;

/**
 * Map of opened files, from a openRequestId to filePath
 * .
 * @type {Object.<number, string>}
 */
var openedFiles = {};

/**
 * @type {string}
 * @const
 */
var TESTING_TEXT = 'We are bytes at the 5th GB of the file!';

/**
 * @type {number}
 * @const
 */
var TESTING_TEXT_OFFSET = 5 * 1000 * 1000 * 1000;

/**
 * Metadata for a testing file with 6GB file size.
 * @type {Object}
 * @const
 */
var TESTING_6GB_FILE = Object.freeze({
  isDirectory: false,
  name: '6gb.txt',
  size: 6 * 1024 * 1024 * 1024,
  modificationTime: new Date(2014, 1, 25, 7, 36, 12)
});

/**
 * Requests opening a file at filePath. Further file operations
 * will be associated with the requestId
 *
 * @param {OpenFileRequestedOptions} options Options.
 * @param {function()} onSuccess Success callback.
 * @param {function(string)} onError Error callback.
 */
function onOpenFileRequested(options, onSuccess, onError) {
  if (options.fileSystemId != test_util.FILE_SYSTEM_ID) {
    onError('INVALID_OPERATION');  // enum ProviderError.
    return;
  }

  if (options.mode != 'READ') {
    onError('ACCESS_DENIED');  // enum ProviderError.
    return;
  }

  if (options.filePath != '/' + TESTING_6GB_FILE.name) {
    onError('NOT_FOUND');  // enum ProviderError.
    return;
  }

  openedFiles[options.requestId] = options.filePath;
  onSuccess();
}

/**
 * Requests closing a file previously opened with openRequestId.
 *
 * @param {CloseFileRequestedOptions} options Options.
 * @param {function()} onSuccess Success callback.
 * @param {function(string)} onError Error callback.
 */
function onCloseFileRequested(options, onSuccess, onError) {
  if (options.fileSystemId != test_util.FILE_SYSTEM_ID ||
      !openedFiles[options.openRequestId]) {
    onError('INVALID_OPERATION');  // enum ProviderError.
    return;
  }

  delete openedFiles[options.openRequestId];
  onSuccess();
}

/**
 * Requests reading contents of a file, previously opened with
 * openRequestId.
 *
 * @param {ReadFileRequestedOptions} options Options.
 * @param {function(ArrayBuffer, boolean)} onSuccess Success callback with a
 *     chunk of data, and information if more data will be provided later.
 * @param {function(string)} onError Error callback.
 */
function onReadFileRequested(options, onSuccess, onError) {
  var filePath = openedFiles[options.openRequestId];
  if (options.fileSystemId != test_util.FILE_SYSTEM_ID || !filePath) {
    onError('INVALID_OPERATION');  // enum ProviderError.
    return;
  }

  if (filePath == '/' + TESTING_6GB_FILE.name) {
    if (options.offset < TESTING_TEXT_OFFSET ||
        options.offset >= TESTING_TEXT_OFFSET + TESTING_TEXT.length) {
      console.error('Reading from a wrong location in the file!');
      onError('FAILED');  // enum ProviderError.
      return;
    }

    var buffer = TESTING_TEXT.substr(
        options.offset - TESTING_TEXT_OFFSET, options.length);
    var reader = new FileReader();
    reader.onload = function(e) {
      onSuccess(e.target.result, false /* hasMore */);
    };
    reader.readAsArrayBuffer(new Blob([buffer]));
    return;
  }

  onError('INVALID_OPERATION');  // enum ProviderError.
}

/**
 * Sets up the tests. Called once per all test cases. In case of a failure,
 * the callback is not called.
 *
 * @param {function()} callback Success callback.
 */
function setUp(callback) {
  chrome.fileSystemProvider.onGetMetadataRequested.addListener(
      test_util.onGetMetadataRequestedDefault);

  test_util.defaultMetadata['/' + TESTING_6GB_FILE.name] =
      TESTING_6GB_FILE;

  chrome.fileSystemProvider.onOpenFileRequested.addListener(
      onOpenFileRequested);
  chrome.fileSystemProvider.onReadFileRequested.addListener(
      onReadFileRequested);
  chrome.fileSystemProvider.onCloseFileRequested.addListener(
      onCloseFileRequested);

  test_util.mountFileSystem(callback);
}

/**
 * Runs all of the test cases, one by one.
 */
function runTests() {
  chrome.test.runTests([
    // Read contents of a new file, which is 6GB in size. Such size does not
    // fit in a 32bit int nor in size_t (unsigned). It should be safe to assume,
    // that if 6GB are supported, then there is no 32bit bottle neck, and the
    // next one would be 64bit. File System Provider API should support files
    // with size greater or equal to 2^53.
    function readBigFileSuccess() {
      var onTestSuccess = chrome.test.callbackPass();
      test_util.fileSystem.root.getFile(
          TESTING_6GB_FILE.name,
          {create: false},
          function(fileEntry) {
            fileEntry.file(function(file) {
              // Read 10 bytes from the 5th GB.
              var fileSlice =
                  file.slice(TESTING_TEXT_OFFSET,
                             TESTING_TEXT_OFFSET + TESTING_TEXT.length);
              var fileReader = new FileReader();
              fileReader.onload = function(e) {
                var text = fileReader.result;
                chrome.test.assertEq(TESTING_TEXT, text);
                onTestSuccess();
              };
              fileReader.onerror = function(e) {
                chrome.test.fail(fileReader.error.name);
              };
              fileReader.readAsText(fileSlice);
            },
            function(error) {
              chrome.test.fail(error.name);
            });
          },
          function(error) {
            chrome.test.fail(error.name);
          });
    }
  ]);
}

// Setup and run all of the test cases.
setUp(runTests);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Shared
{
    public static class Util
    {
        public static bool In(this string value, params string[] stringValues)
        {
            foreach (string otherValue in stringValues)
                if (String.Compare(value, otherValue) == 0)
                    return true;

            return false;
        }
    }
}


text:
"""Utility commands to cycle active objects in pymol.

Adds cycler types to pymol:
    pdbdircycler          - Cycles through all pdbs in a given directory.
    pdbdircyclerlite      - Cycles through all pdbs in a given directory, loading one object at a time.
    pdblistfilecycler     - Cycles through all pdbs listed in a file.
    pdblistfilecyclerlite - Cycles through all pdbs listed in a file, loading one object at a time.
    objcycler             - Cycles though all objects.

Adds cycler commands:
    set_cycler_command    - Sets command run on each cycler iteration. Use to init object representation in lite cyclers.
"""

import logging
logger = logging.getLogger("Cycler")

from pymol import cmd,viewing
import os,re

from glob import glob
from os import path

# ashworth
# minimal general classes to support convenient "list mode" behavior in pymol (left/right arrows cycle through list)
# the 'Lite' classes use the LoadDeleteCycler instead of the EnableCycler, in order that only a single pdb from the list is loaded into memory at any given time. These 'Lite' versions are preferable for large numbers of pdbs that would exceed system memory if loaded all at once.

####################################################################################################
# relates paths to object names in a way that matches the result of cmd.load
def objname(objpath):
    return re.sub( r'(\.pdb|\.pdb.gz)$', '', path.basename(objpath))

# base class cycler for enable/disable behavior, with all objects (pdbs) preloaded
class EnableCycler(object):
    def __init__(self):
        self.current_index = 0
        self.auto_zoom = False
        self.onload_command = None

    def iter(self,by=1):
        #enabled = cmd.get_names('objects',enabled_only=1)[0]

        choices = self.choices()
        l = len(choices)

        assert self.current_index < l
        next_object = (self.current_index + by) % l

        cmd.disable(objname(choices[self.current_index]))

        self.current_index = next_object
        cmd.enable(objname(choices[self.current_index]))
        if self.auto_zoom:
            cmd.zoom(objname(choices[self.current_index]))

        if self.onload_command:
            logging.debug("onload_command: %s", self.onload_command)
            cmd.do(self.onload_command)

        cmd.replace_wizard('message',choices[self.current_index])

    def choices(self):
        raise NotImplementedError("EnableCycler.choices")

# base class cycler for load/delete behavior (to be employed when there are too many pdbs to hold in memory all at once)
class LoadDeleteCycler(object):
    def __init__(self):
        self.auto_zoom = False
        self.onload_command = None

    def iter(self,by=1):
        loaded = cmd.get_names('objects')[0]
        choices = self.choices()
        l = len(choices)
        next_file = 0
        for i in range(l):
            if objname(choices[i]) == loaded:
                next_file = choices[ (i+by) % l ]
                break
        cmd.delete('all')
        if not os.path.exists(next_file):
            raise ValueError("Can not locate file: %s" % next_file)
        cmd.load(next_file)
        if self.auto_zoom:
            cmd.zoom()

        if self.onload_command:
            logging.debug("onload_command: %s", self.onload_command)
            cmd.do(self.onload_command)

        cmd.replace_wizard('message',next_file)

    def choices(self):
        raise NotImplementedError("EnableCycler.choices")

####################################################################################################
# cycler over all pdbs in directory
class PDBDirCycler(EnableCycler):
    def __init__(self,target_dir='.'):
        super(PDBDirCycler, self).__init__()
        self.pdbs = glob(path.join(target_dir, "*.pdb*"))
        self.loadpdbs()
    def loadpdbs(self):
        for pdb in self.pdbs:
            cmd.load(pdb)
            cmd.disable(objname(pdb))
        cmd.enable(objname(self.pdbs[0]))
    def choices(self):
        return self.pdbs

class PDBDirCyclerLite(LoadDeleteCycler):
    def __init__(self,target_dir='.'):
        super(PDBDirCyclerLite, self).__init__()
        self.pdbs = [ f for f in os.listdir(target_dir) if re.search('.pdb.*$',f) ]
        pdb = self.pdbs[0]
        cmd.load(pdb)
    def choices(self):
        return self.pdbs

####################################################################################################
# cycler over pdbs in list file
class PDBListFileCycler(EnableCycler):
    def __init__(self,list_file):
        super(PDBListFileCycler, self).__init__()
        self.pdbs = [ l.strip() for l in open(list_file) ]
        self.loadpdbs()
    def loadpdbs(self):
        for pdb in self.pdbs:
            cmd.load(pdb)
            cmd.disable(objname(pdb))
        cmd.enable(objname(self.pdbs[0]))
    def choices(self):
        return self.pdbs

class PDBListFileCyclerLite(LoadDeleteCycler):
    def __init__(self,list_file):
        super(PDBListFileCyclerLite, self).__init__()
        self.pdbs = [ l.strip() for l in open(list_file) ]
        pdb = self.pdbs[0]
        cmd.load(pdb)
    def choices(self):
        return self.pdbs

####################################################################################################
# cycler over all PyMOL objects (including new ones)
class ObjectCycler(EnableCycler):
    def __init__(self):
        super(ObjectCycler, self).__init__()
        cmd.disable('all')
        cmd.enable( cmd.get_names('objects')[0] )
    def choices(self):
        return cmd.get_names('objects')

####################################################################################################
def prev_pdb():
    viewing.cycler.iter(-1)
def next_pdb():
    viewing.cycler.iter(1)

def spawnPDBDirCycler(target_dir='.',lite=False):
    if lite: viewing.cycler = PDBDirCyclerLite(target_dir)
    else: viewing.cycler = PDBDirCycler(target_dir)
    cmd.set_key('left',prev_pdb)
    cmd.set_key('right',next_pdb)

def spawnPDBListFileCycler(list_file,lite=False):
    if lite: viewing.cycler = PDBListFileCyclerLite(list_file)
    else: viewing.cycler = PDBListFileCycler(list_file)
    cmd.set_key('left',prev_pdb)
    cmd.set_key('right',next_pdb)

def spawnObjectCycler():
    viewing.cycler = ObjectCycler()
    cmd.set_key('left',prev_pdb)
    cmd.set_key('right',next_pdb)

def setCyclerOnloadCommand(command_string):
    if command_string[0] == '"' or command_string[0] == "'":
        command_string = command_string[1:-1]
    if viewing.cycler:
        logging.debug("Setting cycler onload_command: %s", command_string)
        viewing.cycler.onload_command = command_string

cmd.extend( 'pdbdircycler', lambda dir='.': spawnPDBDirCycler('.',False) )
cmd.extend( 'pdbdircyclerlite', lambda dir='.': spawnPDBDirCycler('.',True) )
cmd.extend( 'pdblistfilecycler', lambda file: spawnPDBListFileCycler(file,False) )
cmd.extend( 'pdblistfilecyclerlite', lambda file: spawnPDBListFileCycler(file,True) )

cmd.extend( 'objcycler', spawnObjectCycler )
cmd.extend( 'set_cycler_command', setCyclerOnloadCommand )

# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4


text:
from __future__ import unicode_literals, division, absolute_import
from builtins import *  # noqa pylint: disable=unused-import, redefined-builtin

import logging

from flexget import plugin
from flexget.event import event

try:
    from flexget.plugins.filter.series import remove_series_episode
except ImportError:
    raise plugin.DependencyError(issued_by='series_remove', missing='series',
                                 message='series_forget plugin need series plugin to work')

log = logging.getLogger('series_forget')

class OutputSeriesRemove(object):
    schema = {'type': 'boolean'}

    def on_task_output(self, task, config):
        if not config:
            return
        for entry in task.accepted:
            if 'series_name' in entry and 'series_id' in entry:
                try:
                    remove_series_episode(entry['series_name'], entry['series_id'])
                    log.info('Removed episode `%s` from series `%s` download history.' %
                             (entry['series_id'], entry['series_name']))
                except ValueError:
                    log.debug('Series (%s) or id (%s) unknown.' % (entry['series_name'], entry['series_id']))

@event('plugin.register')
def register_plugin():
    plugin.register(OutputSeriesRemove, 'series_remove', api_ver=2)


text:
$(function() {
    var slideOptions = {
        duration: 300,
        easing: "easeOutCubic"
    }

    // $parents = $('.menu-item-has-children');

    $('#top-nav').on('click', '.disclose', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var targetDeg = 0;
        var $icon = $(e.target);
        var $parent = $icon.closest('li');
        if ($parent.hasClass('has-children')) {
            $child = $parent.children('ul.sub-menu').first();
            if ($child.is(":visible")) {
                $parent.find('ul.sub-menu').velocity("slideUp", slideOptions);
                $parent.find('.disclose').velocity({
                    'rotateZ': '0deg'
                }, slideOptions);
            } else {
                $child.velocity("slideDown", slideOptions);
                $icon.velocity({
                    rotateZ: '180deg'
                }, slideOptions);
            }

        }
    });

    var $menu = jQuery(".nav-list").first();

    var resize = function() {
        if ($(window).width() < 768) {
            $menu.hide();
        } else {
            $menu.show()
        }
    }

    var lastResize = Date.now();

    $(window).resize(function() {
        if (Date.now() < lastResize + 100) return;
        resize();
        lastResize = Date.now();
    })

    var $menuIcon = jQuery('#menu-icon')
    $menuIcon.click(function() {
        if ($menu.is(":visible")) {
            $menu.velocity("slideUp", slideOptions);
            $menu.find('ul').velocity("slideUp", slideOptions);
            $menu.find('.disclose').velocity({
                'rotateZ': '0deg'
            }, 0);
        } else {
            $menu.velocity("slideDown", slideOptions);
        }
    });

    resize();

});


text:
#include "platform.h"

#include <sys/mman.h> // mmap()
#include <unistd.h> // close(), getpagesize(), lseek()

char *map_file_on_offset(tar_fle *tar_file, int *new_offset) {
    /* Maps only a specific part of the file
     * to memory: current offset. f can only be
     * accessed with the correct file-based offset
     */
    char *f;

    // Use native mmap() on POSIX-systems
    const int pgsize = sysconf(_SC_PAGESIZE);
    *new_offset = (((tar_file->curpos/pgsize)+1)*pgsize)-pgsize;

    f = (char *) mmap(0, pgsize, PROT_READ, MAP_PRIVATE,
                      tar_file->fd, *new_offset);

    if (f == MAP_FAILED) {
        return NULL;
    }
    return f;
}

void unmap_file(char *f, tar_fle *tar_file) {
    /* unmap the file from memory */
    munmap(f, sysconf(_SC_PAGESIZE));
}

int tar_close(tar_fle *tar_file) {
    return close(tar_file->fd);
}

int fd_get_offset(int fd) {
    return lseek(fd, 0, SEEK_CUR);
}

int fd_set_offset(int fd, int offset) {
    return lseek(fd, offset, SEEK_SET);
}

int fd_read(int fd, void *buffer, int count) {
    return read(fd, buffer, count);
}


text:
var Army_UnitTest = Class.create();
Army_UnitTest.prototype = Object.extendsObject(AbstractAjaxProcessor, {
	initialize: function(expected, evaluator, args, id, title, assertion) {
		var source, method;
		if (arguments.length == 1 && arguments[0] != null && typeof(arguments[0]) === "object") {
			evaluator = expected.evaluator;
			id = expected.id;
			source = expected.source;
			method = expected.method;
			args = expected.args;
			if (typeof(args) === "undefined")
				args = expected.data;
			title = expected.title;
			assertion = expected.assertion;
			expected = expected.expected;
		}
		if (typeof(evaluator) !== "function") {
			if (typeof(evaluator) == "undefined") {
				if (typeof(source) == "undefined") {
					if (typeof(method) == "undefined")
						throw "Evaluator function or source and method must be defined.";
					throw "Evaluator source must be defined if method is defined and evaluator function is not defined.";
				}
				if (typeof(method) == "undefined")
					throw "Evaluator method must be defined if source is defined and evaluator function is not defined.";
				if (source === null)
					throw "Source object cannot be null if evaluator function is not defined.";
				if (typeof(method) !== "string")
					throw "Method must be a string which names the method (function) to invoke on the source object.";
				if (method.length == 0)
					throw "Method cannot be empty.";
				var f = source[method];
				if (typeof(f) !== "function")
					throw "Source object does not contain a function named \"" + method + "\".";
			} else {
				if (evaluator == null)
					throw "Evaluator cannot be null.";
				throw "Evaluator must be a function.";
			}
		}
		if (typeof(assertion) != "function") {
			if (typeof(assertion) != "undefined") {
				if (assertion !== null)
					throw "Assertion cannot be null.";
				throw "Assertion must be a function if it is defined.";
			}
			assertion = function(expected, actual) { return this.areEqual(expected, actual); }
		}
		this._evaluator = evaluator;
		this._assertion = assertion;
		this._expected = expected;
		if (typeof(args) === "undefined")
			this._args = [];
		else if (args === null)
			this._args = [null];
		else
			this._args = (new ArrayUtil()).ensureArray(args);
		this._title = Army_UnitTest.ensureString(title);
		if (typeof(id) === "undefined" || id === null) {
			if (this._title.length > 0)
				this._id = this._title + " created on " + Date.now();
			else {
				this._id = "Test created on " + Date.now();
				this._title = this._id;
			}
		} else {
			this._id = id;
			if (this._title.length == 0)
				this._title = Army_UnitTest.ensureString(this._id);
		}
		this._source = source;
		this._method = method;
	},

	getExpected: function() { return this._expected; },
	getArgs: function() { return this._args; },
	getTitle: function() { return this._title; },
	getId: function() { return this._id; },
	getSource: function() { return this._source; },
	getMethod: function() { return this._method; },
	duplicateWithArgs: function(expected, args) {
		return new Army_UnitTest(expected, this._evaluator, args, this._id, this._title, this._assertion);
	},
	evaluate: function(resultId) {
		var assertion = this._assertion;
		if (typeof(assertion) != "undefined")
			assertion = function(expected, actual) { return this.areEqual(expected, actual); }
		var evaluator = this._evaluator;
		if (typeof(evaluator) != "undefined")
			evaluator = function() { return this._source.apply(this._source, Army_ArrayUtil.__toArgArray(arguments)); }
		return new Army_UnitTest.TestResult(this, evaluator, assertion, resultId);
	},
	type: 'Army_UnitTest'
});
Army_UnitTest.isNil = function(value) { return (typeof(value) === "undefined" || value === null); };
Army_UnitTest.isFunction = function(value) { return (typeof(value) === "function"); };
Army_UnitTest.isNilOrFunction = function(value) {
	var t = typeof(value);
	return (t == "function" || t == "undefined" || value === null);
};
Army_UnitTest.ensureString = function(value) {
	var t = typeof(value)
	if (t === "undefined" || value === null)
		return "";
	if (t == "string")
		return value;
	if (t != "object")
		return value.toString();
	return JSON.stringify(value);
};
Army_UnitTest.getTypeName = function(obj, functionAsProto) {
	var t = typeof(obj)

	if (obj === null)
		return null;

	var proto;
	if (t === "object")
		proto = Object.getPrototypeOf(obj);
	else if (t === "function" && functionAsProto)
		proto = obj;
	else
		return t;

	for (var p = proto; typeof(p) != "undefined" && p != null; p = p.__proto__) {
		if (typeof(p.type) === "string" && p.type.length > 0)
			return p.type;
		if (typeof(p.constructor) === "function" && typeof(p.constructor.name) === "string" && p.constructor.name.length > 0)
			return p.constructor.name;
	}

	var re = /^\[((object\s+)?([^\]]+)?)\]/;
	var name = t;
	var m = null;
	try {
		name = Object.toString.call(obj);
		m = re.exec(name)
	} catch (e) { }
	if (m !== null) {
		if (typeof(m[3]) !== "undefined") {
			if (m[3] !== "Object")
				return m[3];
			name = m[3];
		} else if (typeof(m[2]) !== "undefined")
			name = m[2];
		else if (typeof(m[1]) !== "undefined")
			name = m[1];
	}
	for (var p = proto; typeof(p) != "undefined" && p != null; p = p.__proto__) {
		m = null;
		try { m = re.exec(Object.toString.call(p)); } catch (e) { }
		if (m != null && typeof(m[3] !== "undefined"))
			return m[3];
	}

	return name;
}
Army_UnitTest.TestResult = Class.create();
Army_UnitTest.TestResult.prototype = Object.extendsObject(AbstractAjaxProcessor, {
	initialize: function(unitTest, evaluator, assertion, id) {
		if (Army_UnitTest.getTypeName(unitTest) !== Army_UnitTest.prototype.type)
			throw "Argument must be a " + Army_UnitTest.prototype.type + " object.";
		var t = typeof(evaluator);
		if (t === "undefined")
			throw "Evaluator must be a defined.";
		if (t !== "function")
			throw "Evaluator must be a function.";
		t = typeof(assertion);
		if (t === "undefined")
			throw "Assertion must be a defined.";
		if (t !== "function")
			throw "Assertion must be a function.";
		this.expectedValue = unitTest.getExpected();
		this.expectedType = Army_UnitTest.getTypeName(this.expectedValue);
		this.testId = unitTest.getId();
		this.resultId = Army_UnitTest.ensureString(id);
		if (this.resultId.length == 0)
			this.resultId = testId;
		this.title = unitTest.getTitle();
		this.source = unitTest.getSource();
		this.method = unitTest.getMethod();
		var contextObj = {
			expected = this.expected,
			testId = this.testId,
			resultId = this.resultId,
			title = this.title,
			source = this.source,
			method = this.method,
			isNil: Army_UnitTest.isNil,
			isFunction: Army_UnitTest.isFunction,
			isNilOrFunction: Army_UnitTest.isNilOrFunction,
			ensureString: Army_UnitTest.ensureString,
			getTypeName: Army_UnitTest.getTypeName,
		};
		this.started = Date.now();
		try {
			this.actualValue = evaluator.call(contextObj, unitTest.getArgs());
			this.completed = Date.now();
			this.evaluationCompleted = true;
			this.assertionOutput = assertion.call(contextObj, this._expected, this._actual);
			this.success = (this._assertionOutput == true);
		} catch (e) {
			if (typeof(this.completed) === "undefined")
				this.completed = Date.now();
			this.error = e;
			if (typeof(this._evaluationCompleted) === "undefined")
				this.evaluationCompleted = false;
			this.success = false;
		}
		if (typeof(contextObj.message) === "undefined" || contextObj.message === null) {
			if (typeof(this.error) === "undefined")
				this.message = (this.success) ? "Succeeded" : "Failed";
			else
				this.message = Army_UnitTest.ensureString(this.error);
		} else
			this.message = Army_UnitTest.ensureString(contextObj.message);
		this.actualType = Army_UnitTest.getTypeName(this.actualValue);
	},
	type: 'Army_UnitTest.TestResult'
});
Army_UnitTest.evaluate = function(unitTestArr) {
	var testArr = (new Army_ArrayUtil(unitTestArr)).filter(function(v) { return (Army_UnitTest.getTypeName(v) === Army_UnitTest.prototype.type && typeof(v.evaluator) === "function"); }
	var results = [];
	if (testArr.length == 0)
		testArr.push(new Army_UnitTest("Array", function() { }, [], "Warning", "Empty Test Warning", function() {
			this.message = "No tests were found.";
			return false;
		}));
	return testArr.map(function(test, index, arr) {
		var id = test.getId();
		var getDup = function(s, idx) {
			return arr.reduce(function(p, c, i) {
				if (i.getId() == this.id && i < this.index)
					return p + 1;
				return p;
			}, 0, { id: s, index: idx });
		}
		if (getDup(id, index) > 0) {
			var n = 1;
			var s = id;
			do {
				id = s + "_" + n;
				n++;
			} while (getDup(id, index) > 0);
		}
		return test.evaluate(id);
	});
}


text:
// Copyright (c) 2011, David J. Pearce (djp@ecs.vuw.ac.nz)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//    * Redistributions of source code must retain the above copyright
//      notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//    * Neither the name of the <organization> nor the
//      names of its contributors may be used to endorse or promote products
//      derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package wyrw.core;

import java.util.List;

import wyautl.core.Automaton;
import wyrw.util.AbstractActivation;

/**
 *

 * A rewrite rule which may increase the overall size of the automaton. Such
 * rules are more complex to handle than reduction rules, simply because they
 * can easily lead to infinite rewriting cycles. Such a cycle occurs when an
 * inference rule generates a new fact which is then immediately eliminated via
 * a reduction rule.
 *

 *
 *

 * Inference rules are generally less frequently occuring, and should be
 * considered as more expensive from a performance perspective.  The
 * following illustrates a very simple rule system:
 *

 *
 *

 * reduce LessThan[Num(int x), Num(int y)]:
 *   => True, if x < y
 *   => False
 *
 * reduce And{Bool b, BExpr... xs}:
 *    => False, if b == False
 *    => True, if |xs| == 0
 *    => And (xs)
 *
 * infer And{LessThan[Expr e1, Expr e2] l1,
 *           LessThan[Expr e3, Expr e4] l2,
 *           BExpr... bs}:
 *    => And (bs ++ LessThan[e1,e4]), if e2 == e3
 *

 *
 *

 * The key challenge with this system is that, unless inference rules are
 * handled with care, an infinite loop can easily occur. For example, the
 * expression 1 < x && x < 2 can lead to an infinite loop where
 * 1 < 2 is continually being infered, and then immediately reduced
 * to true and eliminated from the conjunction.
 *

 *

 * To deal with the issue of infinite loops, the system requires that inferences
 * rules are only considered to have "fired" if, after full reduction, the
 * automaton remains in a different state from before the rule was activated.
 * This requires some considerable care to implement correctly.
 *

 *
 * @author David J. Pearce
 *
 */
public interface InferenceRule extends RewriteRule {

	/**
	 * Probe a given root to see whether or not this rule could be applied to
	 * it. If it can, the corresponding activation record(s) are added to the
	 * list. Note that, under no circumstances is this function permitted to
	 * modify the automaton.
	 *
	 * @param automaton
	 *            Automaton to probe.
	 * @param root
	 *            --- The automaton root that this rewrite is working off.
	 * @param target
	 *            State to use as the target for the probe.
	 * @param activations
	 *            List of activations onto which to add any which are discovered
	 *            during the probe.
	 *
	 * @return
	 */
	public void probe(Automaton automaton, int root, int target, List<Inference.Activation> activations);

	/**
	 *

	 * Apply this rule to a given automaton for a given root using the given
	 * continuation state. The application may or may not actually modify the
	 * automaton and this is indicated by the return value.
	 *

	 *

	 * After a successful rule application, a new tree root will be
	 * returned which represents the updated state. This root may equal some
	 * existing root, or may be a completely new root. Whilst new states may be
	 * added to the automaton, states which existed prior to
	 * apply() being called cannot be removed (even if they become
	 * unreachable). Thus, a separate call is required to place the automaton
	 * into a compacted state.
	 *

	 *

	 * After an unsuccessful rule application, the automaton should be
	 * left in an identical state as before apply() was called.
	 * This means any temporary states added during apply() must be
	 * removed from the automaton.
	 *

	 *
	 * @param automaton
	 *            --- The automaton to be rewritten.
	 * @param root
	 *            --- The automaton root that this rewrite is working off.
	 * @param state
	 *            --- Data required by the rewrite to perform the rewrite. This
	 *            may be null if no such data is required.
	 *
	 * @return The state that was rewritten to. Using this, and state[0], you
	 *         can determine which state was rewritten from, and which was
	 *         rewritten to. In the case of an unsuccessful rewrite, then K_Void
	 *         is returned (-1).
	 */
	public int apply(Automaton automaton, int root, int[] state);
}


text:
require "spec_helper"

describe VraptorScaffold do
end


text:
Verifies that generated lazy loading value holders disallow protected property direct read
--FILE--
<?php

require_once __DIR__ . '/init.php';

class Kitchen
{
    protected $sweets;
}

$factory = new \ProxyManager\Factory\LazyLoadingValueHolderFactory($configuration);

$proxy = $factory->createProxy(Kitchen::class, function (& $wrapped, $proxy, $method, array $parameters, & $initializer) {
    $initializer = null;
    $wrapped     = new Kitchen();
});

$proxy->sweets;
?>
--EXPECTF--
%SFatal error: Cannot access protected property %s::$sweets in %s on line %d


text:
VALUE ExceptionClass;

VALUE exception_initialize(VALUE vSelf, VALUE vMessage)
{
    Check_Type(vMessage, T_STRING);
    rb_iv_set(vSelf, "@message", vMessage);

    return vSelf;
}

VALUE exception_inspect(VALUE vSelf)
{
    VALUE vCode, vMsg;
    char sMsg[200];

    vCode = rb_iv_get(vSelf, "@code");
    vMsg = rb_iv_get(vSelf, "@message");
    sprintf(sMsg, "#<AerospikeNative::Exception: @code=%d, @message=\"%s\">", NUM2INT(vCode), StringValueCStr(vMsg));

    return rb_str_new2(sMsg);
}

void define_exception()
{
    ExceptionClass = rb_define_class_under(AerospikeNativeClass, "Exception", rb_eStandardError);
    rb_define_method(ExceptionClass, "initialize", exception_initialize, 1);
    rb_define_method(ExceptionClass, "inspect", exception_inspect, 0);
    rb_define_attr(ExceptionClass, "code", 1, 0);
    rb_define_attr(ExceptionClass, "message", 1, 0);

    rb_define_const(ExceptionClass, "ERR_CLIENT_ABORT", INT2FIX(AEROSPIKE_ERR_CLIENT_ABORT));
    rb_define_const(ExceptionClass, "ERR_INVALID_HOST", INT2FIX(AEROSPIKE_ERR_INVALID_HOST));
    rb_define_const(ExceptionClass, "NO_MORE_RECORDS", INT2FIX(AEROSPIKE_NO_MORE_RECORDS));
    rb_define_const(ExceptionClass, "ERR_PARAM", INT2FIX(AEROSPIKE_ERR_PARAM));
    rb_define_const(ExceptionClass, "ERR_CLIENT", INT2FIX(AEROSPIKE_ERR_CLIENT));
    rb_define_const(ExceptionClass, "OK", INT2FIX(AEROSPIKE_OK));
    rb_define_const(ExceptionClass, "ERR_SERVER", INT2FIX(AEROSPIKE_ERR_SERVER));
    rb_define_const(ExceptionClass, "ERR_RECORD_NOT_FOUND", INT2FIX(AEROSPIKE_ERR_RECORD_NOT_FOUND)); // 2

    rb_define_const(ExceptionClass, "ERR_RECORD_EXISTS", INT2FIX(AEROSPIKE_ERR_RECORD_EXISTS)); // 5
    rb_define_const(ExceptionClass, "ERR_BIN_EXISTS", INT2FIX(AEROSPIKE_ERR_BIN_EXISTS)); // 6

    rb_define_const(ExceptionClass, "ERR_TIMEOUT", INT2FIX(AEROSPIKE_ERR_TIMEOUT)); // 9

    rb_define_const(ExceptionClass, "ERR_RECORD_TOO_BIG", INT2FIX(AEROSPIKE_ERR_RECORD_TOO_BIG)); // 13
    rb_define_const(ExceptionClass, "ERR_RECORD_BUSY", INT2FIX(AEROSPIKE_ERR_RECORD_BUSY));
}

void raise_aerospike_exception(int iCode, char* sMessage)
{
    VALUE vException;

    vException = rb_exc_new2(ExceptionClass, sMessage);
    rb_iv_set(vException, "@code", INT2FIX(iCode));
    rb_exc_raise(vException);
}


text:
package transports_test

import (
	"github.com/matiasinsaurralde/transports/marshalers"
	// "github.com/matiasinsaurralde/transports/marshalers/protos"

	"net/http"
	"net/url"
	"strings"
	"testing"
)

var request http.Request

func init() {

	url, _ := url.Parse("http://whatismyip.akamai.com/")

	request = http.Request{
		Method: "GET",
		URL:    url,
		Proto:  "HTTP/1.0",
	}
}

func TestProtobufHttpRequestMarshal(t *testing.T) {
	var marshaler transports.Marshaler
	marshaler = transports.ProtobufMarshaler{}
	var i interface{}
	i = request
	_, err := marshaler.Marshal(&i)
	if err != nil {
		t.Fatal("Can't marshal HttpRequest")
	}
}

func TestProtobufHttpResponseMarshal(t *testing.T) {
	var marshaler transports.Marshaler
	marshaler = transports.ProtobufMarshaler{}
	var i interface{}
	i = request
	_, err := marshaler.Marshal(&i)
	if err != nil {
		t.Fatal("Can't marshal HttpResponse")
	}
}

func TestProtobufUnsupportedType(t *testing.T) {
	var marshaler transports.Marshaler
	marshaler = transports.ProtobufMarshaler{}

	var v UnknownType
	v = UnknownType{"Value"}

	var i interface{}
	i = v

	_, err := marshaler.Marshal(&i)

	exists := strings.Index(err.Error(), transports.MarshalerTypeNotSupportedError)

	if exists < 0 {
		t.Fatal("Unsupported type doesn't break the Protobuf marshaler")
	}
}

func TestProtobufNilInput(t *testing.T) {
	var marshaler transports.Marshaler
	marshaler = transports.ProtobufMarshaler{}
	_, err := marshaler.Marshal(nil)

	if strings.Index(err.Error(), transports.MarshalerNilTypeError) < 0 {
		t.Fatal("Nil type doesn't break the Protobuf marshaler")
	}
}


text:
module.exports = process.env.BONESCRIPT_COV ?
    require('./src-cov/index') :
    require('./src/index');


text:
import httpretty

from formspree import settings
from formspree.app import DB
from formspree.forms.models import Form
from formspree_test_case import FormspreeTestCase

class RateLimitingTestCase(FormspreeTestCase):
    @httpretty.activate
    def test_rate_limiting_on_form_posts(self):
        httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json')

        # confirm a form
        self.client.post('/alice@example.com',
            headers={'referer': 'http://somewhere.com'},
            data={'name': 'john'}
        )
        form = Form.query.filter_by(host='somewhere.com', email='alice@example.com').first()
        form.confirmed = True
        DB.session.add(form)
        DB.session.commit()

        # submit form many times
        replies = []
        for _ in range(1000):
            r = self.client.post('/alice@example.com',
                headers={'referer': 'http://somewhere.com'},
                data={'name': 'attacker'}
            )
            replies.append(r.status_code)

        limit = int(settings.RATE_LIMIT.split(' ')[0])

        # the number of submissions should not be more than the rate limit
        form = Form.query.filter_by(host='somewhere.com', email='alice@example.com').first()
        self.assertLess(form.counter, limit)

        # should have gotten some 302 and then many 429 responses
        self.assertLessEqual(replies.count(302), limit)
        self.assertGreaterEqual(replies.count(429), 900-limit)


text:
module SubdomainHelper
  def switch_to_subdomain(subdomain)
    # lvh.me always resolves to 127.0.0.1
    hostname = subdomain ? "#{subdomain}.lvh.me" : "lvh.me"
    Capybara.app_host = "http://#{hostname}"
  end

  def switch_to_main_domain
    switch_to_subdomain nil
  end
end

RSpec.configure do |config|
  config.include SubdomainHelper, type: :feature
end

Capybara.configure do |config|
  config.always_include_port = true
end


text:
/*!
 * \file
 *                toolbox Prox
 *
 *                by Jean-Paul Chièze
 *
 *
 *                File mexgrouputils.h
 * \brief Contains miscellaneous functions for group structs in mex files */

#ifndef MEXGROUPUTILS_H
#define MEXGROUPUTILS_H

#include <mex.h>
#include <typeinfo>
#include <stdlib.h>
#include <iostream>
#ifndef MATLAB_MEX_FILE
#define MATLAB_MEX_FILE
#endif
#include <groups-graph.h>

typedef StructNodeElem<double> NodeElem;

void mexCgroupsToMatlab(std::vector<NodeElem *> *gstruct,mxArray* mxgstruct) {
  int i = 0;
  mwSize cdims[1];
  for(std::vector<NodeElem *>::iterator it = gstruct->begin();it != gstruct->end();it++, i++) {
    cdims[0] = 4;
    mxArray* mxnode = mxCreateCellArray((mwSize)1,cdims);
    NodeElem *node = *it;
    cdims[0] = node->vars->size();
    mxArray* vars = mxCreateNumericArray((mwSize)1,(const mwSize*)cdims,mxINT32_CLASS,mxREAL);
    memcpy(mxGetPr(vars),node->vars->data(),cdims[0] * sizeof(int));
    cdims[0] = node->children->size();
    mxArray* children = mxCreateNumericArray((mwSize)1,cdims,mxINT32_CLASS,mxREAL);
    memcpy(mxGetPr(children),node->children->data(),cdims[0] * sizeof(int));
    cdims[0] = 1;
    mxArray * mxnum = mxCreateNumericArray((mwSize)1,cdims,mxINT32_CLASS,mxREAL);
    int *pnum = reinterpret_cast<int *>(mxGetPr(mxnum));
    *pnum = node->node_num;
    mxSetCell(mxnode,0,mxnum);
    mxSetCell(mxnode,1,mxCreateDoubleScalar(node->weight));
    mxSetCell(mxnode,2,vars);
    mxSetCell(mxnode,3,children);
    mxSetCell(mxgstruct,(mwSize)i,mxnode);
  }
  del_gstruct(gstruct);

}
#define MEX_TRY(x) try{ x } catch(char const *_e) {mexErrMsgTxt(_e);}

std::vector<NodeElem *> *mexMatlabToCgroups(const mxArray *mxgstruct) {
  std::vector<NodeElem *> *gstruct = new std::vector<NodeElem *>;
  const mwSize* dims=mxGetDimensions(mxgstruct);
  for(unsigned int i = 0;i < *dims; i++) {
    mxArray *m_node = mxGetCell(mxgstruct,(mwIndex) i);
    int num_node = mxGetScalar(mxGetCell(m_node,0));
    float weight = mxGetScalar(mxGetCell(m_node,1));
    mxArray *mxvars = mxGetCell(m_node,2);
    int *pvars = reinterpret_cast<int *>(mxGetPr(mxvars));
    mxArray *mxchildren = mxGetCell(m_node,3);
    int *pchildren = reinterpret_cast<int *>(mxGetPr(mxchildren));
    const mwSize* tmpdims=mxGetDimensions(mxvars);
    std::vector<int> *vars = new std::vector<int>;
    for(unsigned int j= 0;j < *tmpdims;j++) vars->push_back(*(pvars+j));
    tmpdims = mxGetDimensions(mxchildren);
    std::vector<int> *children = new std::vector<int>;
    for(unsigned int j= 0;j < *tmpdims;j++) children->push_back(*(pchildren+j));
    NodeElem *node = new NodeElem(num_node,weight,vars,children);
    gstruct->push_back(node);
  }
  return gstruct;
}
template <> inline mxArray* createMatrix<int>(int m, int n) {
   return mxCreateNumericMatrix(static_cast<mwSize>(m),
         static_cast<mwSize>(n),mxINT32_CLASS,mxREAL);
};

template<typename T> mxArray *makeVector(Vector<T> *v) {
  mxArray *mxvect = createMatrix<T>(1,v->n());
  T *pv = reinterpret_cast<T*>(mxGetPr(mxvect));
  memcpy(pv,v->rawX(),v->n() * sizeof(T));
  return mxvect;
}

#endif // MEXGROUPUTILS_H


text:
import copy
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter, SimpleRouter
from rest_framework.authtoken import views as rf_views
from sensor_net import views
from views import NetworkListViewSet, NodeListViewSet, NodeDetailViewSet, \
                    ReadingListViewSet, ReadingDetailViewSet, SensorListViewSet, SensorDetailViewSet,\
                    AlertLogViewSet, AlertViewSet

__all__ = ["BulkRouter"]

class BulkRouter(DefaultRouter):
    routes = copy.deepcopy(SimpleRouter.routes)
    routes[0].mapping.update({
        'put': 'bulk_update',
        'patch': 'partial_bulk_update',
        'delete': 'bulk_destroy',
    })

router = BulkRouter(trailing_slash=False)
router.register(r'networks', NetworkListViewSet)
router.register(r'nodes', NodeListViewSet)
#router.register(r'node/create', NodeDetailViewSet)
router.register(r'readings', ReadingListViewSet)
router.register(r'sensors', SensorListViewSet)
router.register(r'reading/create', ReadingDetailViewSet)
router.register(r'alert-logs', AlertLogViewSet)
#router.register(r'alerts', AlertViewSet) #TODO figure out why this is failing

urlpatterns = [

    # url(r'^$', TemplateView.as_view(template_name='sensor_net/network.html')),
    url(r'^$', views.network, name='network'),
    url(r'^api/v1/docs/', include('rest_framework_swagger.urls')),
    url(r'^api/v1/', include(router.urls)),
    url(r'^api/token-auth', rf_views.obtain_auth_token),
    url(r'^nodes/$', views.nodes, name='nodes'),
    url(r'^sensors/$', views.all_sensors, name='all_sensors'),
    url(r'^nodes/node/(?P<nodeslug>.*)/$', views.individual_node, name='individual_node'),
    url(r'^sensors/sensor/(?P<nodeslug>.*)/$', views.individual_sensor, name='individual_sensor'),
    url(r'^historical/$', views.historical, name='historical'),
    url(r'^dashboard/$', views.dashboard, name='dashboard'),

    # Begin partial views
    url(r'^dashboard/recent-readings/$', views.recent_readings, name='recent_readings'),
    url(r'^dashboard/recent-alerts/$', views.recent_alerts, name='recent_alerts'),
    url(r'^dashboard/door-status/$', views.door_status, name='door_status'),
    url(r'^dashboard/light-meter/$', views.light_meter, name='light_meter'),
   # url(r'^reading/create/$', views.post_reading, name='post_reading')
]


text:
package de.chefkoch.api.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import de.chefkoch.api.serialize.BooleanAsIntAdapter;
import de.chefkoch.api.serialize.IntegerAsStringAdapter;
import de.chefkoch.api.serialize.RuntimeTypeAdapterFactoryHelper;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;

/**
 * Created by christophwidulle on 25.09.15.
 */
public class CkApiClient {

    private Retrofit retrofit;
    private RecipeApiModule recipeApiModule;
    private final Map<String, String> headers = new ConcurrentHashMap<>();

    public CkApiClient() {
        initWithBaseUrl("http://api.chefkoch.de/v2/");
    }

    private void initWithBaseUrl(String url) {

        final OkHttpClient client = new OkHttpClient();
        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                Request.Builder builder = chain.request().newBuilder();
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
                return chain.proceed(builder.build());
            }
        });
        final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
                .registerTypeAdapterFactory(RuntimeTypeAdapterFactoryHelper.getNotificationRuntimeTypeAdapterFactory())
                .registerTypeAdapter(Boolean.class, new BooleanAsIntAdapter()).registerTypeAdapter(Integer.class, new IntegerAsStringAdapter())
                .registerTypeAdapter(int.class, new IntegerAsStringAdapter())
                .create();

        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        recipeApiModule = retrofit.create(RecipeApiModule.class);
    }

    public void updateBaseUrl(String url) {
        initWithBaseUrl(url);
    }

    public void addHeader(String key, String value) {
        this.headers.put(key, value);
    }

    public RecipeApiModule recipe() {
        return recipeApiModule;
    }
}


text:
require 'spec_helper'

describe Spree::BillingIntegration::Pagseguro::Checkout do
  context "redirect_url" do
    let(:payment_method) { create(:pagseguro_checkout) }
    let(:order) { create(:order_with_line_items) }

    # TODO Test with invalid credentials
    # expect {
    #   payment_method.redirect_url(order)
    # }.to raise_error(PagSeguro::Errors::Unauthorized, "Credentials provided (e-mail and token) failed to authenticate")

    it "should return checkout url given valid credentials (see README)" do
      expect { payment_method.redirect_url(order) }.not_to raise_error
      expect(payment_method.redirect_url(order)).to start_with('https://pagseguro.uol.com.br/v2')
    end
  end

end


text:
namespace py = pybind11;

using namespace hpmc;

using namespace hpmc::detail;

namespace hpmc
    {
//! Export the base HPMCMono integrators
void export_union_convex_polyhedron(py::module& m)
    {
    export_IntegratorHPMCMono<ShapeUnion<ShapeSpheropolyhedron>>(
        m,
        "IntegratorHPMCMonoConvexPolyhedronUnion");
    export_ComputeFreeVolume<ShapeUnion<ShapeSpheropolyhedron>>(
        m,
        "ComputeFreeVolumeConvexPolyhedronUnion");
    export_ComputeSDF<ShapeUnion<ShapeSpheropolyhedron>>(m,
                                                         "ComputeSDFConvexSpheropolyhedronUnion");
    export_UpdaterMuVT<ShapeUnion<ShapeSpheropolyhedron>>(m,
                                                          "UpdaterMuVTConvexSpheropolyhedronUnion");
    export_UpdaterClusters<ShapeUnion<ShapeSpheropolyhedron>>(
        m,
        "UpdaterClustersConvexSpheropolyhedronUnion");

    export_ExternalFieldInterface<ShapeUnion<ShapeSpheropolyhedron>>(
        m,
        "ExternalFieldConvexPolyhedronUnion");
    export_LatticeField<ShapeUnion<ShapeSpheropolyhedron>>(
        m,
        "ExternalFieldLatticeConvexPolyhedronUnion");
    export_ExternalFieldComposite<ShapeUnion<ShapeSpheropolyhedron>>(
        m,
        "ExternalFieldCompositeConvexPolyhedronUnion");
    export_ExternalFieldWall<ShapeUnion<ShapeSpheropolyhedron>>(m, "WallConvexPolyhedronUnion");
    export_UpdaterExternalFieldWall<ShapeUnion<ShapeSpheropolyhedron>>(
        m,
        "UpdaterExternalFieldWallConvexPolyhedronUnion");

#ifdef ENABLE_HIP

    export_IntegratorHPMCMonoGPU<ShapeUnion<ShapeSpheropolyhedron>>(
        m,
        "IntegratorHPMCMonoConvexPolyhedronUnionGPU");
    export_ComputeFreeVolumeGPU<ShapeUnion<ShapeSpheropolyhedron>>(
        m,
        "ComputeFreeVolumeConvexPolyhedronUnionGPU");
    export_UpdaterClustersGPU<ShapeUnion<ShapeSpheropolyhedron>>(
        m,
        "UpdaterClustersConvexSpheropolyhedronUnionGPU");

#endif
    }

    } // namespace hpmc


text:
using namespace glm;

ParticleEmitter::ParticleEmitter(glm::vec3 position, const Model* parent)
	: mpParent(parent), mPosition(position)
{
}

// This is a point emitter, nothing is random
// As a small extra task, you could create derived classes
// for more interesting emitters such as line emitters or circular emitters
// In these cases, you would sample a random point on these shapes
glm::vec3 ParticleEmitter::GetRandomPosition()
{
	// @TODO 7 - Position from Parented Emitter
	//
	// Return the position where the particle is emitted.
	// If the emitter is parented, the position is relative to its parent

	vec3 position = this->mPosition;
	if(this->mpParent != NULL) {
		position += vec3(this->mpParent->GetWorldMatrix()[3]); //translation component
	}
	return position;
}

glm::vec3 ParticleEmitter::GetAsteroidRandomPosition()
{
    float maxRadius = 30;
    float randomX = GetRandomFloat(-maxRadius, maxRadius);
    randomX = ParticleEmitter::clampValue(randomX);

    float randomY = GetRandomFloat(0, maxRadius);
    randomY = ParticleEmitter::clampValue(randomY);

    float randomZ = GetRandomFloat(-maxRadius, maxRadius);
    randomZ = ParticleEmitter::clampValue(randomZ);

    vec3 position = vec3(randomX, randomY, randomZ);

    return position;
}

// used to correct asteroids initial point
float ParticleEmitter::clampValue(float f) {
    if(f < 0) {
        f = clamp(f, f, f+10);
    } else {
        f = clamp(f, f-10, f);
    }
    return f;
}

float ParticleEmitter::GetRandomFloat(float min, float max)
{
    float value = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
    return min + value*(max - min);
}