<commit_before>// download a survey
// must specify the site and protocol
//var uuid = require('./uuid');

function processDownload(cloudSurvey) {
    //do stuff with surveyData
   try {
    	console.log ('enter try in download');
    	var db = Ti.Database.open('ltemaDB');
    	console.log ('database opened successfuly');

    	var surveyData = cloudSurvey.survey_data;
    	console.log('THE DOWNLOAD');
    	//console.log(surveyData);
    	console.log('site and protocol: ' + cloudSurvey.site + ' ' + cloudSurvey.protocol);

    	var protocolIDResult = db.execute('SELECT protocol_id FROM protocol WHERE protocol_name =?', cloudSurvey.protocol);
    	var protocolID = protocolIDResult.fieldByName('protocol_id');
    	console.log ('protocol id : ' + protocolID);
    	var parkIDResult = db.execute('SELECT park_id FROM park WHERE park_name =?', cloudSurvey.site);
    	var parkID = parkIDResult.fieldByName('park_id');
    	console.log ('park id : ' + parkID);
    	var year = cloudSurvey.last_modified.slice(0,4);
    	console.log ('year: ' + year);

		console.log('eline 25 (download)');

		// Check if this site has been previously surveyed
		var previousID = db.execute('SELECT site_id, site_survey_guid FROM site_survey \
										WHERE protocol_id = ? \
										AND park_id = ?', protocolID, parkID);

		var prevSiteID = previousID.fieldByName('site_id');
		var prevSiteGUID = previousID.fieldByName('site_survey_guid');

		if (prevSiteGUID == null) {
			console.log('prevSiteGUID was null');
			prevSiteGUID = surveyData[0].site_guid;
			console.log('guid value: ' + prevSiteGUID);
		}

		console.log('id line 34 (download): ' + prevSiteID + ' and guid: ' + prevSiteGUID);

		if (!prevSiteID) {
			// Insert the new survey
			//var siteGUID = String(uuid.generateUUID());
			//var results = db.execute('SELECT last_insert_rowid() as siteID');

			console.log('processDownload variable list with types: ');
			console.log('siteID: ' + typeof siteID + ' as ' + siteID);
			//console.log('siteGUID: ' + typeof siteGUID + ' as ' + siteGUID);
			console.log('currentYear: ' + typeof year + ' as ' + year);
			console.log('protocolID: ' + typeof protocolID + ' as ' + protocolID);
			console.log('parkID: ' + typeof parkID + ' as ' + parkID);

			//db.execute('INSERT INTO site_survey (site_survey_guid, year, protocol_id, park_id) VALUES (?,?,?,?)', siteGUID, year, protocolID, parkID);

			console.log('after insert download line 50');

		// Get the transects associated with the survey
		} else {
			//updating existing site
			var previousID = db.execute('SELECT site_id FROM site_survey \
										WHERE site_survey_guid = ?', siteGUID);

			var siteID = previousID.fieldByName('site_id');

			//var siteID = prevSiteID;
			var siteGUID = prevSiteGUID;
			//delete existing data
			db.execute('DELETE FROM site_survey WHERE site_survey_guid = ?', siteGUID);

			console.log('(download, Else clause) siteGUID: ' + typeof siteGUID + ' as ' + siteGUID);
			//db.execute('UPDATE site_survey SET year=? WHERE site_survey_guid=?', currentYear, siteGUID);
			db.execute('INSERT INTO site_survey (site_survey_guid, year, protocol_id, park_id) VALUES (?,?,?,?)', siteGUID, year, protocolID, parkID);

			var transects = db.execute('SELECT * FROM transect WHERE site_survey_guid = ?', siteGUID);

			// Copy and associate any existing transects
			for (var i = 0; i < surveyData.length; i++) {
				var transectGUID = surveyData[i].transect_guid;
				var transectName = surveyData[i].transect_name;
				var surveyor = surveyData[i].surveyor;
				var otherSurveyors = surveyData[i].other_surveyors;
				var plotDistance = surveyData[i].plot_distance;
				var stakeOrientation = surveyData[i].stake_orientation;
				var utmZone = surveyData[i].utm_zone;
				var utmEasting = surveyData[i].utm_easting;
				var utmNorthing = surveyData[i].utm_northing;
				var tComments = surveyData[i].comments;
				var transectID = surveyData[i].transect_id;
				var transectMediaID = surveyData[i].media_id;

				db.execute('INSERT INTO transect (transect_guid, transect_name, surveyor, other_surveyors, \
					plot_distance, stake_orientation, utm_zone, utm_easting, utm_northing, comments, site_id) \
					VALUES (?,?,?,?,?,?,?,?,?,?,?) WHERE transect_guid = ?', transectGUID, transectName, surveyor, otherSurveyors,
					plotDistance, stakeOrientation, utmZone, utmEasting, utmNorthing, tComments, siteID, transectGUID);

				// Get any plots associated with the transect
				var plots = db.execute('SELECT * FROM plot WHERE transect_guid = ?', transectGUID);

				// Copy and associate any existing plots
				while (plots.isValidRow()) {
					var plotID = plots.fieldByName('plot_id');
					var plotName = plots.fieldByName('plot_name');
					var plotUtmZone = plots.fieldByName('utm_zone');
					var plotUtmEasting = plots.fieldByName('utm_easting');
					var plotUtmNorthing = plots.fieldByName('utm_northing');
					var utc = plots.fieldByName('utc');
					var stakeDeviation = plots.fieldByName('stake_deviation');
					var distanceDeviation = plots.fieldByName('distance_deviation');
					var comments = plots.fieldByName('comments');
					var plotID = plots.fieldByName('plot_id');

					db.execute('INSERT INTO plot (plot_id, plot_name, utm_zone, utm_easting, utm_northing, utc, stake_deviation, distance_deviation, \
						transect_id, comments) VALUES (?,?,?,?,?,?,?,?,?,?)', plotID, plotName, plotUtmZone, plotUtmEasting, plotUtmNorthing,
						utc, stakeDeviation, distanceDeviation, transectID, comments);

					// Get any plot observations associated with the plot
					var observations = db.execute('SELECT * FROM plot_observation WHERE plot_id = ?', plotID);

					// Copy and associate any existing plot observations
					while (observations.isValidRow()){
						var observationID = uuid.generateUUID();
						var observation = observations.fieldByName('observation');
						var groundCover = 0;
						var count = observations.fieldByName('count');
						var observationComments = observations.fieldByName('comments');

						db.execute('INSERT INTO plot_observation (observation_id, observation, ground_cover, count, comments, plot_id) \
							VALUES (?,?,?,?,?,?)', observationID, observation, groundCover, count, observationComments, plotID);

						observations.next();
					}
					plots.next();
				}
				transects.next();
			}
			//observations.close();
			//plots.close();
			//transects.close();
		}

	} catch (e){
		var errorMessage = e.message;
		Ti.App.fireEvent("app:dataBaseError", {error: errorMessage});
	} finally {
		//protocolResult.close();
		//parkResult.close();
		db.close();
		Ti.App.fireEvent("app:refreshSiteSurveys");
		$.addSiteSurveyWin.close();
	}

}

function downloadSurvey(site, protocol) {
    try {
        console.log('enter try in downloadSurvey');

        var url = "https://capstone-ltemac.herokuapp.com/download?park=" + encodeURIComponent(site) + "&protocol=" + protocol;
        alert('download url: ' + url);
        var httpClient = Ti.Network.createHTTPClient();

        httpClient.open("GET", url);

        httpClient.setRequestHeader('secret', '12345-12345-12345-12345-12345');
        httpClient.setRequestHeader('Content-Type', 'application/json');

        httpClient.onload = function() {
            //call checkLocalSurveys, pass in results
            Ti.API.info("Downloaded text: " + this.responseData);
            var returnArray = JSON.parse(this.responseData);
            processDownload(returnArray);
            alert('successful download');
        };
        httpClient.onerror = function(e) {
            Ti.API.debug("STATUS: " + this.status);
            Ti.API.debug("TEXT:   " + this.responseText);
            Ti.API.debug("ERROR:  " + e.error);
            var cloudSurveys = [];
            processDownload(cloudSurveys);
            alert('error retrieving remote data');
        };

        httpClient.send();

        console.log('leaving try downloadSurvey gracefully');
    }
    catch (e) {
        var errorMessage = e.message;
        console.log('error in checkSurveys: ' + errorMessage);
    }
}

exports.downloadSurvey = downloadSurvey;<commit_msg>progress on download.js and index<commit_after>// download a survey
// must specify the site and protocol
//var uuid = require('./uuid');

function processDownload(cloudSurvey) {
    //do stuff with surveyData
    // expected fields: site, site_survey_guid, year, protocol_id, park_id, exported, transect_guid, transect_name, surveyor, other_surveyors, plot_distance,
    //   stake_orientation, utm_zone, utm_easting, utm_northing, comments, flickr_id, plot_guid, plot_name,
   try {
    	console.log ('enter try in download');
    	var db = Ti.Database.open('ltemaDB');
    	console.log ('database opened successfuly');

    	var surveyData = cloudSurvey.survey_data;
    	console.log('THE DOWNLOAD');
    	//console.log(surveyData);
    	console.log('site and protocol: ' + cloudSurvey.site + ' ' + cloudSurvey.protocol);

    	var protocolIDResult = db.execute('SELECT protocol_id FROM protocol WHERE protocol_name =?', cloudSurvey.protocol);
    	var protocolID = protocolIDResult.fieldByName('protocol_id');
    	console.log ('protocol id : ' + protocolID);
    	var parkIDResult = db.execute('SELECT park_id FROM park WHERE park_name =?', cloudSurvey.site);
    	var parkID = parkIDResult.fieldByName('park_id');
    	console.log ('park id : ' + parkID);
    	var year = cloudSurvey.last_modified.slice(0,4);
    	console.log ('year: ' + year);

		console.log('line 25 (download)');

		// Check if this site has been previously surveyed
		var previousID = db.execute('SELECT site_survey_guid FROM site_survey \
										WHERE protocol_id = ? \
										AND park_id = ?', protocolID, parkID);

		var prevSiteGUID = previousID.fieldByName('site_survey_guid');

		if (prevSiteGUID == null) {
			console.log('prevSiteGUID was null');
			prevSiteGUID = surveyData[0].site_guid;
			console.log('guid value: ' + prevSiteGUID);
		}

		console.log('id line 34 (download): ' + prevSiteID + ' and guid: ' + prevSiteGUID);

		if (!prevSiteID) {
			// Insert the new survey
			//var siteGUID = String(uuid.generateUUID());
			//var results = db.execute('SELECT last_insert_rowid() as siteID');

			console.log('processDownload variable list with types: ');
			console.log('siteID: ' + typeof siteID + ' as ' + siteID);
			//console.log('siteGUID: ' + typeof siteGUID + ' as ' + siteGUID);
			console.log('currentYear: ' + typeof year + ' as ' + year);
			console.log('protocolID: ' + typeof protocolID + ' as ' + protocolID);
			console.log('parkID: ' + typeof parkID + ' as ' + parkID);

			//db.execute('INSERT INTO site_survey (site_survey_guid, year, protocol_id, park_id) VALUES (?,?,?,?)', siteGUID, year, protocolID, parkID);

			console.log('after insert download line 50');

		// Get the transects associated with the survey
		} else {
			//var siteID = prevSiteID;
			var siteGUID = prevSiteGUID;
			//delete existing data
			db.execute('DELETE FROM site_survey WHERE site_survey_guid = ?', siteGUID);

			console.log('(download, Else clause) siteGUID: ' + typeof siteGUID + ' as ' + siteGUID);
			//db.execute('UPDATE site_survey SET year=? WHERE site_survey_guid=?', currentYear, siteGUID);
			db.execute('INSERT INTO site_survey (site_survey_guid, year, protocol_id, park_id) VALUES (?,?,?,?)', siteGUID, year, protocolID, parkID);

			var transects = db.execute('SELECT * FROM transect WHERE site_survey_guid = ?', siteGUID);

			// Copy and associate any existing transects
			var cloudTransects = surveyData.transects;
			for (var i = 0; i < cloudTransects.length; i++) {
				var siteGUID_FK = cloudTransect[i].site_survey_guid;
				if (siteGUID_FK == siteGUID) {
					continue;
				}
				var transectGUID = cloudTransects[i].transect_guid;
				var transectName = cloudTransects[i].transect_name;
				var surveyor = cloudTransects[i].surveyor;
				var otherSurveyors = cloudTransects[i].other_surveyors;
				var plotDistance = cloudTransects[i].plot_distance;
				var stakeOrientation = cloudTransects[i].stake_orientation;
				var utmZone = cloudTransects[i].utm_zone;
				var utmEasting = cloudTransects[i].utm_easting;
				var utmNorthing = cloudTransects[i].utm_northing;
				var tComments = cloudTransects[i].comments;
				var transectFlickrID = cloudTransects[i].flickr_id;

				db.execute('INSERT INTO transect (transect_guid, transect_name, surveyor, other_surveyors, \
					plot_distance, stake_orientation, utm_zone, utm_easting, utm_northing, comments, site_guid, flickr_id) \
					VALUES (?,?,?,?,?,?,?,?,?,?,?)', transectGUID, transectName, surveyor, otherSurveyors,
					plotDistance, stakeOrientation, utmZone, utmEasting, utmNorthing, tComments, siteGUID);

				// Get any plots associated with the transect
				var plots = db.execute('SELECT * FROM plot WHERE transect_guid = ?', transectGUID);

				// Copy and associate any existing plots
				var cloudPlots = surveyData.plots;
				for (var j = 0; j < cloudPlots.length; j++) {
					var transectGUID_FK = cloudPlots[j].transect_guid;
					if (transectGUID_FK != transectGUID) {
						continue;
					}
					var plotGUID = cloudPlots[j].plot_guid;
					var plotName = cloudPlots[j].plot_name;
					var plotUtmZone = cloudPlots[j].utm_zone;
					var plotUtmEasting = cloudPlots[j].utm_easting;
					var plotUtmNorthing = cloudPlots[j].utm_northing;
					var utc = cloudPlots[j].utc;
					var stakeDeviation = cloudPlots[j].stake_deviation;
					var distanceDeviation = cloudPlots[j].distance_deviation;
					var plotComments = cloudPlots[j].comments;
					var plotFlickrID = cloudPlots[j].flickr_id;

					db.execute('INSERT INTO plot (plot_id, plot_name, utm_zone, utm_easting, utm_northing, utc, stake_deviation, distance_deviation, \
						transect_guid, comments, flickr_id) VALUES (?,?,?,?,?,?,?,?,?,?,?)', plotID, plotName, plotUtmZone, plotUtmEasting, plotUtmNorthing,
						utc, stakeDeviation, distanceDeviation, transectGUID, plotComments, plotFlickrID);

					// Copy and associate any existing plot observations
					var plotObservations = surveyData.plot_observations;
					for (var k = 0; k < plotObservations.length; k++) {
						var plotGUID_FK = plotObservations[k].plot_guid;
						if (plotGUID_FK != plotGUID) {
							continue;
						}
						var observationGUID = plotObservations[k].plot_observation_guid;
						var observation = plotObservations[k].observation;
						var groundCover = 0;
						var count = plotObservations[k].count;
						var observationComments = plotObservations[k].comments;
						var plobsFlickrID = plotObservations[k].flickr_id;
						var speciesCode = plotObservations[k].species_code;

						db.execute('INSERT INTO plot_observation (observation_id, observation, ground_cover, count, comments, plot_guid, flickr_id, species_code) \
							VALUES (?,?,?,?,?,?,?,?)', observationID, observation, groundCover, count, observationComments, plotGUID, plobsFlickrID, speciesCode);

					}
				}
			}
		}

	} catch (e){
		var errorMessage = e.message;
		Ti.App.fireEvent("app:dataBaseError", {error: errorMessage});
	} finally {
		db.close();
		Ti.App.fireEvent("app:refreshSiteSurveys");
	}

}

function downloadSurvey(site, protocol) {
    try {
        console.log('enter try in downloadSurvey');

        var url = "https://capstone-ltemac.herokuapp.com/download?park=" + encodeURIComponent(site) + "&protocol=" + protocol;
        alert('download url: ' + url);
        var httpClient = Ti.Network.createHTTPClient();

        httpClient.open("GET", url);

        httpClient.setRequestHeader('secret', '12345-12345-12345-12345-12345');
        httpClient.setRequestHeader('Content-Type', 'application/json');

        httpClient.onload = function() {
            //call checkLocalSurveys, pass in results
            Ti.API.info("Downloaded text: " + this.responseData);
            var returnArray = JSON.parse(this.responseData);
            processDownload(returnArray);
            alert('successful download');
        };
        httpClient.onerror = function(e) {
            Ti.API.debug("STATUS: " + this.status);
            Ti.API.debug("TEXT:   " + this.responseText);
            Ti.API.debug("ERROR:  " + e.error);
            var cloudSurveys = [];
            processDownload(cloudSurveys);
            alert('error retrieving remote data');
        };

        httpClient.send();

        console.log('leaving try downloadSurvey gracefully');
    }
    catch (e) {
        var errorMessage = e.message;
        console.log('error in checkSurveys: ' + errorMessage);
    }
}

exports.downloadSurvey = downloadSurvey;<|endoftext|>


<commit_before>// download a survey
// must specify the site and protocol
//var uuid = require('./uuid');

function processDownload(cloudSurvey) {
    //do stuff with surveyData
    // expected fields: site, site_survey_guid, year, protocol_id, park_id, exported, transect_guid, transect_name, surveyor, other_surveyors, plot_distance,
    //   stake_orientation, utm_zone, utm_easting, utm_northing, comments, flickr_id, plot_guid, plot_name,
   try {
    	console.log ('enter try in download');
    	var db = Ti.Database.open('ltemaDB');
    	console.log ('database opened successfuly');

    	var surveyData = cloudSurvey.survey_data;
    	console.log('THE DOWNLOAD');
    	//console.log(surveyData);
    	console.log('site and protocol: ' + cloudSurvey.site + ' ' + cloudSurvey.protocol);

    	var protocolIDResult = db.execute('SELECT protocol_id FROM protocol WHERE protocol_name =?', cloudSurvey.protocol);
    	var protocolID = protocolIDResult.fieldByName('protocol_id');
    	console.log ('protocol id : ' + protocolID);
    	var parkIDResult = db.execute('SELECT park_id FROM park WHERE park_name =?', cloudSurvey.site);
    	var parkID = parkIDResult.fieldByName('park_id');
    	console.log ('park id : ' + parkID);
    	var year = cloudSurvey.last_modified.slice(0,4);
    	console.log ('year: ' + year);

		console.log('line 25 (download)');

		// Check if this site has been previously surveyed
		var previousID = db.execute('SELECT site_survey_guid FROM site_survey \
										WHERE protocol_id = ? \
										AND park_id = ?', protocolID, parkID);

		var prevSiteGUID = previousID.fieldByName('site_survey_guid');

		if (prevSiteGUID == null) {
			console.log('prevSiteGUID was null');
			prevSiteGUID = surveyData[0].site_guid;
			console.log('guid value: ' + prevSiteGUID);
		}

		console.log('id line 34 (download): ' + prevSiteID + ' and guid: ' + prevSiteGUID);

		if (!prevSiteID) {
			// Insert the new survey
			//var siteGUID = String(uuid.generateUUID());
			//var results = db.execute('SELECT last_insert_rowid() as siteID');

			console.log('processDownload variable list with types: ');
			console.log('siteID: ' + typeof siteID + ' as ' + siteID);
			//console.log('siteGUID: ' + typeof siteGUID + ' as ' + siteGUID);
			console.log('currentYear: ' + typeof year + ' as ' + year);
			console.log('protocolID: ' + typeof protocolID + ' as ' + protocolID);
			console.log('parkID: ' + typeof parkID + ' as ' + parkID);

			//db.execute('INSERT INTO site_survey (site_survey_guid, year, protocol_id, park_id) VALUES (?,?,?,?)', siteGUID, year, protocolID, parkID);

			console.log('after insert download line 50');

		// Get the transects associated with the survey
		} else {
			//var siteID = prevSiteID;
			var siteGUID = prevSiteGUID;
			//delete existing data
			db.execute('DELETE FROM site_survey WHERE site_survey_guid = ?', siteGUID);

			console.log('(download, Else clause) siteGUID: ' + typeof siteGUID + ' as ' + siteGUID);
			//db.execute('UPDATE site_survey SET year=? WHERE site_survey_guid=?', currentYear, siteGUID);
			db.execute('INSERT INTO site_survey (site_survey_guid, year, protocol_id, park_id) VALUES (?,?,?,?)', siteGUID, year, protocolID, parkID);

			var transects = db.execute('SELECT * FROM transect WHERE site_survey_guid = ?', siteGUID);

			// Copy and associate any existing transects
			var cloudTransects = surveyData.transects;
			for (var i = 0; i < cloudTransects.length; i++) {
				var siteGUID_FK = cloudTransect[i].site_survey_guid;
				if (siteGUID_FK == siteGUID) {
					continue;
				}
				var transectGUID = cloudTransects[i].transect_guid;
				var transectName = cloudTransects[i].transect_name;
				var surveyor = cloudTransects[i].surveyor;
				var otherSurveyors = cloudTransects[i].other_surveyors;
				var plotDistance = cloudTransects[i].plot_distance;
				var stakeOrientation = cloudTransects[i].stake_orientation;
				var utmZone = cloudTransects[i].utm_zone;
				var utmEasting = cloudTransects[i].utm_easting;
				var utmNorthing = cloudTransects[i].utm_northing;
				var tComments = cloudTransects[i].comments;
				var transectFlickrID = cloudTransects[i].flickr_id;

				db.execute('INSERT INTO transect (transect_guid, transect_name, surveyor, other_surveyors, \
					plot_distance, stake_orientation, utm_zone, utm_easting, utm_northing, comments, site_guid, flickr_id) \
					VALUES (?,?,?,?,?,?,?,?,?,?,?)', transectGUID, transectName, surveyor, otherSurveyors,
					plotDistance, stakeOrientation, utmZone, utmEasting, utmNorthing, tComments, siteGUID);

				// Get any plots associated with the transect
				var plots = db.execute('SELECT * FROM plot WHERE transect_guid = ?', transectGUID);

				// Copy and associate any existing plots
				var cloudPlots = surveyData.plots;
				for (var j = 0; j < cloudPlots.length; j++) {
					var transectGUID_FK = cloudPlots[j].transect_guid;
					if (transectGUID_FK != transectGUID) {
						continue;
					}
					var plotGUID = cloudPlots[j].plot_guid;
					var plotName = cloudPlots[j].plot_name;
					var plotUtmZone = cloudPlots[j].utm_zone;
					var plotUtmEasting = cloudPlots[j].utm_easting;
					var plotUtmNorthing = cloudPlots[j].utm_northing;
					var utc = cloudPlots[j].utc;
					var stakeDeviation = cloudPlots[j].stake_deviation;
					var distanceDeviation = cloudPlots[j].distance_deviation;
					var plotComments = cloudPlots[j].comments;
					var plotFlickrID = cloudPlots[j].flickr_id;

					db.execute('INSERT INTO plot (plot_id, plot_name, utm_zone, utm_easting, utm_northing, utc, stake_deviation, distance_deviation, \
						transect_guid, comments, flickr_id) VALUES (?,?,?,?,?,?,?,?,?,?,?)', plotID, plotName, plotUtmZone, plotUtmEasting, plotUtmNorthing,
						utc, stakeDeviation, distanceDeviation, transectGUID, plotComments, plotFlickrID);

    					// Copy and associate any existing plot observations
					var plotObservations = surveyData.plot_observations;
					for (var k = 0; k < plotObservations.length; k++) {
						var plotGUID_FK = plotObservations[k].plot_guid;
						if (plotGUID_FK != plotGUID) {
							continue;
						}
						var observationGUID = plotObservations[k].plot_observation_guid;
						var observation = plotObservations[k].observation;
						var groundCover = 0;
						var count = plotObservations[k].count;
						var observationComments = plotObservations[k].comments;
						var plobsFlickrID = plotObservations[k].flickr_id;
						var speciesCode = plotObservations[k].species_code;

						db.execute('INSERT INTO plot_observation (observation_id, observation, ground_cover, count, comments, plot_guid, flickr_id, species_code) \
							VALUES (?,?,?,?,?,?,?,?)', observationID, observation, groundCover, count, observationComments, plotGUID, plobsFlickrID, speciesCode);

					}
				}
			}
		}

	} catch (e){
		var errorMessage = e.message;
		Ti.App.fireEvent("app:dataBaseError", {error: errorMessage});
	} finally {
		db.close();
		Ti.App.fireEvent("app:refreshSiteSurveys");
	}

}

function downloadSurvey(site, protocol) {
    try {
        console.log('enter try in downloadSurvey');

        var url = "https://capstone-ltemac.herokuapp.com/download?park=" + encodeURIComponent(site) + "&protocol=" + protocol;
        alert('download url: ' + url);
        var httpClient = Ti.Network.createHTTPClient();

        httpClient.open("GET", url);

        httpClient.setRequestHeader('secret', '12345-12345-12345-12345-12345');
        httpClient.setRequestHeader('Content-Type', 'application/json');

        httpClient.onload = function() {
            //call checkLocalSurveys, pass in results
            Ti.API.info("Downloaded text: " + this.responseData);
            var returnArray = JSON.parse(this.responseData);
            processDownload(returnArray);
            alert('successful download');
        };
        httpClient.onerror = function(e) {
            Ti.API.debug("STATUS: " + this.status);
            Ti.API.debug("TEXT:   " + this.responseText);
            Ti.API.debug("ERROR:  " + e.error);
            var cloudSurveys = [];
            processDownload(cloudSurveys);
            alert('error retrieving remote data');
        };

        httpClient.send();

        console.log('leaving try downloadSurvey gracefully');
    }
    catch (e) {
        var errorMessage = e.message;
        console.log('error in checkSurveys: ' + errorMessage);
    }
}

exports.downloadSurvey = downloadSurvey;<commit_msg>progress on download, updated for new blob format including media<commit_after>// download a survey
// must specify the site and protocol

function processDownload(cloudSurvey) {
    //do stuff with cloudSurvey
    // expected fields: site, protocol, date_surveyed, last_modified, version_no, exported,
    //   survey_data {transects[], plots[], plot_observations[], media[], survey_meta}

   try {
    	console.log ('enter try in download');
    	var db = Ti.Database.open('ltemaDB');

    	var surveyData = cloudSurvey.survey_data;
    	var surveyMeta = surveyData.survey_meta;
		var cloudMedia = surveyData.media;
		var cloudTransects = surveyData.transects;
    	var cloudPlots = surveyData.plots;
		var plotObservations = surveyData.plot_observations;
    	//console.log('THE DOWNLOAD');
    	//console.log(surveyData);
    	console.log('THE DOWNLOAD SITE AND PROTOCOL');
    	console.log('site and protocol: ' + cloudSurvey.site + ' ' + cloudSurvey.protocol);

    	/*
    	var protocolIDResult = db.execute('SELECT protocol_id FROM protocol WHERE protocol_name =?', cloudSurvey.protocol);
    	var protocolID = protocolIDResult.fieldByName('protocol_id');
    	console.log ('protocol id : ' + protocolID);

    	var parkIDResult = db.execute('SELECT park_id FROM park WHERE park_name =?', cloudSurvey.site);
    	var parkID = parkIDResult.fieldByName('park_id');
    	console.log ('park id : ' + parkID);
	    */

	    var protocolID = surveyMeta.protocol_id;
	    var parkID = surveyMeta.park_id;

		// Check if this site has been previously surveyed
		var previousID = db.execute('SELECT site_survey_guid FROM site_survey \
										WHERE protocol_id = ? \
										AND park_id = ?', protocolID, parkID);

		var prevSiteGUID = previousID.fieldByName('site_survey_guid');
		var cloudSiteSurveyGUID = surveyMeta.site_survey_guid;

		var siteSurveyGUID = prevSiteGUID;
		if (siteSurveyGUID != cloudSiteSurveyGUID) {
			console.log('old siteSurvey differs from cloud. Setting siteSurveyGUID to cloud value');
			siteSurveyGUID = cloudSiteSurveyGUID;
		}

		console.log('siteSurveyGUID line 47 (download): ' + siteSurveyGUID);

    	// compare dates between old and cloud data
		var oldDate = db.execute('SELECT year FROM site_survey WHERE site_survey_guid = ?', siteSurveyGUID);
		var oldYear = oldDate.fieldByName('year');
		var cloudYear = cloudSurvey.last_modified.slice(0,4);
    	console.log ('old year, new year: ' + oldYear + ', ' + cloudYear);

    	var year = oldDate;
    	if (cloudYear >= oldYear) {
    		year = cloudYear;
    		console.log ('updated year: ', year);
    	}

    	var cloudVersion = cloudSurvey.version_no;
    	var deviceVersionQuery = db.execute('SELECT version_no FROM site_survey WHERE site_survey_guid = ?', siteSurveyGUID);
		var deviceVersion = deviceVersionQuery.fieldByName('version_no');

		if (deviceVersion >= cloudVersion) {
			// Inform user that device version is newer and don't change database'
			alert('version on DEVICE is newer!\n old is ' + deviceVersion + ' new is ' + cloudVersion);

		} else {
			//Insert the updated survey
			alert('version on CLOUD is newer!\n old is ' + deviceVersion + ' new is ' + cloudVersion);

			var siteGUID = prevSiteGUID;
			//delete existing data
			db.execute('DELETE FROM site_survey WHERE site_survey_guid = ?', siteGUID);

			console.log('(download, Else clause) siteGUID: ' + typeof siteGUID + ' as ' + siteGUID);
			//db.execute('UPDATE site_survey SET year=? WHERE site_survey_guid=?', currentYear, siteGUID);
			db.execute('INSERT INTO site_survey (site_survey_guid, year, protocol_id, park_id) VALUES (?,?,?,?)', siteGUID, year, protocolID, parkID);

			// Copy and associate any existing transects media and id's'
			for (var i = 0; i < cloudMedia.length; i++) {
				var oldMediaID = cloudMedia[i].media_id;
				var flickrID = cloudMedia[i].flickr_id;

				// insert flickr_id and extract auto-incremented media_id and store in media blob
				db.execute('INSERT INTO media (flickr_id) VALUES (?);', flickrID);
				var results = db.execute('SELECT last_insert_rowid() as mediaID');
				var newMediaID = results.fieldByName('mediaID');

				cloudMedia[i].new_media_id = newMediaID;
			}

			// Copy and associate any existing transects
			for (var i = 0; i < cloudTransects.length; i++) {
				var siteGUID_FK = cloudTransect[i].site_survey_guid;
				if (siteGUID_FK == siteGUID) {
					continue;
				}
				var transectGUID = cloudTransects[i].transect_guid;
				var transectName = cloudTransects[i].transect_name;
				var surveyor = cloudTransects[i].surveyor;
				var otherSurveyors = cloudTransects[i].other_surveyors;
				var plotDistance = cloudTransects[i].plot_distance;
				var stakeOrientation = cloudTransects[i].stake_orientation;
				var utmZone = cloudTransects[i].utm_zone;
				var utmEasting = cloudTransects[i].utm_easting;
				var utmNorthing = cloudTransects[i].utm_northing;
				var tComments = cloudTransects[i].comments;
				var transectOldMediaID = cloudTransects[i].media_id;

				// use old media id from cloud to map to new media id
				var transectNewMediaID = null;
				for (var m = 0; m < cloudMedia.length; i++) {
					if (transectOldMediaID == cloudMedia[m].media_id) {
						transectNewMediaID = cloudMedia[m].new_media_id;
						//remove this row to save time for future iterations
						cloudMedia.splice(m, 1);
						break;
					}
				}

				db.execute('INSERT INTO transect (transect_guid, transect_name, surveyor, other_surveyors, \
					plot_distance, stake_orientation, utm_zone, utm_easting, utm_northing, comments, site_guid, media_id) \
					VALUES (?,?,?,?,?,?,?,?,?,?,?,?)', transectGUID, transectName, surveyor, otherSurveyors,
					plotDistance, stakeOrientation, utmZone, utmEasting, utmNorthing, tComments, siteGUID, transectNewMediaID);

				// Copy and associate any existing plots
				for (var j = 0; j < cloudPlots.length; j++) {
					var transectGUID_FK = cloudPlots[j].transect_guid;
					if (transectGUID_FK != transectGUID) {
						continue;
					}
					var plotGUID = cloudPlots[j].plot_guid;
					var plotName = cloudPlots[j].plot_name;
					var plotUtmZone = cloudPlots[j].utm_zone;
					var plotUtmEasting = cloudPlots[j].utm_easting;
					var plotUtmNorthing = cloudPlots[j].utm_northing;
					var utc = cloudPlots[j].utc;
					var stakeDeviation = cloudPlots[j].stake_deviation;
					var distanceDeviation = cloudPlots[j].distance_deviation;
					var plotComments = cloudPlots[j].comments;
					var plotMediaID = cloudPlots[j].media_id;

					// use old media id from cloud to map to new media id
					var plotNewMediaID = null;
					for (var m = 0; m < cloudMedia.length; i++) {
						if (plotOldMediaID == cloudMedia[m].media_id) {
							plotNewMediaID = cloudMedia[m].new_media_id;
							//remove this row to save time for future iterations
							cloudMedia.splice(m, 1);
							break;
						}
					}

					db.execute('INSERT INTO plot (plot_guid, plot_name, utm_zone, utm_easting, utm_northing, utc, stake_deviation, distance_deviation, \
						transect_guid, comments, media_id) VALUES (?,?,?,?,?,?,?,?,?,?,?)', plotGUID, plotName, plotUtmZone, plotUtmEasting, plotUtmNorthing,
						utc, stakeDeviation, distanceDeviation, transectGUID, plotComments, plotNewMediaID);

					// Copy and associate any existing plot observations
					for (var k = 0; k < plotObservations.length; k++) {
						var plotGUID_FK = plotObservations[k].plot_guid;
						if (plotGUID_FK != plotGUID) {
							continue;
						}
						var observationGUID = plotObservations[k].plot_observation_guid;
						var observation = plotObservations[k].observation;
						var groundCover = 0;
						var count = plotObservations[k].count;
						var observationComments = plotObservations[k].comments;
						var plotObsOldMediaID = plotObservations[k].media_id;
						var speciesCode = plotObservations[k].species_code;

						// use old media id from cloud to map to new media id
						var plotObsNewMediaID = null;
						for (var m = 0; m < cloudMedia.length; i++) {
							if (plotObsOldMediaID == cloudMedia[m].media_id) {
								plotObsNewMediaID = cloudMedia[m].new_media_id;
								//remove this row to save time for future iterations
								cloudMedia.splice(m, 1);
								break;
							}
						}

						db.execute('INSERT INTO plot_observation (observation_guid, observation, ground_cover, count, comments, plot_guid, media_id, species_code) \
							VALUES (?,?,?,?,?,?,?,?)', observationGUID, observation, groundCover, count, observationComments, plotGUID, plotObsNewMediaID, speciesCode);

					}
				}
			}
		}

	} catch (e){
		var errorMessage = e.message;
		Ti.App.fireEvent("app:dataBaseError", {error: errorMessage});
	} finally {
		db.close();
		Ti.App.fireEvent("app:refreshSiteSurveys");
	}

}

function downloadSurvey(site, protocol) {
    try {
        console.log('enter try in downloadSurvey');

        var url = "https://capstone-ltemac.herokuapp.com/download?park=" + encodeURIComponent(site) + "&protocol=" + protocol;
        alert('download url: ' + url);
        var httpClient = Ti.Network.createHTTPClient();

        httpClient.open("GET", url);

        httpClient.setRequestHeader('secret', '12345-12345-12345-12345-12345');
        httpClient.setRequestHeader('Content-Type', 'application/json');

        httpClient.onload = function() {
            //call checkLocalSurveys, pass in results
            Ti.API.info("Downloaded text: " + this.responseData);
            var returnArray = JSON.parse(this.responseData);
            processDownload(returnArray);
            alert('successful download');
        };
        httpClient.onerror = function(e) {
            Ti.API.debug("STATUS: " + this.status);
            Ti.API.debug("TEXT:   " + this.responseText);
            Ti.API.debug("ERROR:  " + e.error);
            var cloudSurveys = [];
            processDownload(cloudSurveys);
            alert('error retrieving remote data');
        };

        httpClient.send();

        console.log('leaving try downloadSurvey gracefully');
    }
    catch (e) {
        var errorMessage = e.message;
        console.log('error in checkSurveys: ' + errorMessage);
    }
}

exports.downloadSurvey = downloadSurvey;<|endoftext|>


<commit_before>var _ = require('underscore');

var resource = function(input){
  this.input = input;
  var that = this;
  // make "this" for all input methods refer to this resource object
  // instead of the input object
  _.each(input, function(v, k){
    if (_.isFunction(v)){
      input[k] = _.bind(v, that);
    }
  });
}

resource.prototype.HEAD = function(req, res){
  var r = this;
  // 405 if GET isn't defined.
  checkMethodAllowed('GET', r, req, res)
  if (res.done) return;

  if (_.isFunction(this.input.HEAD)){
    setResource(req);
    fetch(this, req, res, function(err){
      if (!err){
        r.input.HEAD(req, res);
      }
    });
  } else {
    // don't allow write() to occur
    res.write = function(){};
    // don't allow end() to take params
    res.origEnd = res.end;
    res.end = function(){
      res.origEnd();
    };
    this.GET(req, res);  // note that we call our own GET
  }
}

resource.prototype.OPTIONS = function(req, res){
  setResource(req);
  var r = this;
  fetch(this, req, res, function(err){
    if (!err){
      if (_.isFunction(r.input.OPTIONS)){
        return r.input.OPTIONS(req, res)
      }
      setAllowHeader(r.input, req, res);
      res.writeHead(204);
      res.end();
    }
  });

}

var getMethodHandler = function(methodName){
  return function(req, res){
    setResource(req);
    var r = this;
    fetch(this, req, res, function(err){
      if (!err){
        checkMethodAllowed(methodName, r, req, res)
        if (res.done) return;

        r.input[methodName](req, res);
      }
    });
  }
}

var supportedMethods = [
  'GET'
  , 'POST'
  , 'PUT'
  , 'DELETE'
  , 'COPY'
  , 'LOCK'
  , 'MKCOL'
  , 'MOVE'
  , 'PROPFIND'
  , 'PROPPATCH'
  , 'UNLOCK'
  , 'REPORT'
  , 'MKACTIVITY'
  , 'CHECKOUT'
  , 'MERGE'
  , 'M-SEARCH'
  , 'NOTIFY'
  , 'SUBSCRIBE'
  , 'UNSUBSCRIBE'
  , 'PATCH'
]

_.each(supportedMethods, function(method){
  resource.prototype[method] = getMethodHandler(method);
});

exports.resource = resource

var setResource = function(req){
  req.resource = req.resource || {};
}

var checkMethodAllowed = function(method, r, req, res){
  if (!_.isFunction(r.input[method])){
    handle405(r, req, res);
  }
}

var fetch = function(r, req, res, onDone){
  if (_.isFunction(r.input.fetch)){
    var onFetch = function(err, val){
      if (err){
        handle404(r, req, res);
        onDone(true);
      } else {
        req.resource.fetched = val;
        onDone();
      }
    }
    r.input.fetch(req, onFetch);
  } else {
    onDone();
  }
}

var handle405 = function(r, req, res){
  if (_.isFunction(r.handle405)){
    r.handle405(req, res);
  } else {
    setAllowHeader(r.input, req, res);
    res.writeHead(405);
    res.end();
  }
  res.done = true;
};
var handle404 = function(r, req, res){
  if (_.isFunction(r.handle404)){
    r.handle404(req, res);
  } else {
    res.writeHead(404);
    res.end();
  }
  res.done = true;
};

setAllowHeader = function(obj, req, res){
  res.setHeader('Allow', allowHeader(obj));
};

var allowHeader = function(obj){
  var methods = getMethods(obj);
  var additionalMethods = ['OPTIONS']
  if (_.isFunction(obj.GET)){
    additionalMethods.push('HEAD');
  }
  methods = _.union(additionalMethods, methods);
  return methods.join(",");
};

var getMethods = function(handler){
  var moduleMethods = _.functions(handler);
  var retval = _.intersection(moduleMethods, serverSupportedMethods);
  return retval;
};

var serverSupportedMethods = ["GET", "POST",
                              "PUT", "DELETE",
                              "HEAD", "OPTIONS"];
<commit_msg>updated resource to do "input" method binding at call time, instead of at construction.<commit_after>var _ = require('underscore');

var resource = function(input){
  this.input = input;
};

resource.prototype.HEAD = function(req, res){
  var r = this;
  // 405 if GET isn't defined.
  checkMethodAllowed('GET', r, req, res);
  if (res.done) return;

  if (_.isFunction(r.input.HEAD)){
    setResource(req);
    fetch(r, req, res, function(err){
      if (!err){
        r.input.HEAD.apply(r, [req, res]);
      }
    });
  } else {
    // don't allow write() to occur
    res.write = function(){};
    // don't allow end() to take params
    res.origEnd = res.end;
    res.end = function(){
      res.origEnd();
    };
    r.GET(req, res);  // note that we call our own GET
  }
};

resource.prototype.OPTIONS = function(req, res){
  setResource(req);
  var r = this;
  fetch(r, req, res, function(err){
    if (!err){
      if (_.isFunction(r.input.OPTIONS)){
        return r.input.OPTIONS.apply(r, [req, res]);
      }
      setAllowHeader(r.input, req, res);
      res.writeHead(204);
      res.end();
    }
  });

};

var getMethodHandler = function(methodName){
  return function(req, res){
    setResource(req);
    var r = this;   // TODO WTF is this?
    fetch(r, req, res, function(err){
      if (!err){
        checkMethodAllowed(methodName, r, req, res);
        if (res.done) return;
        r.input[methodName].apply(r, [req, res]);
      }
    });
  };
};

var supportedMethods = [
  'GET',
  'POST',
  'PUT',
  'DELETE',
  'COPY',
  'LOCK',
  'MKCOL',
  'MOVE',
  'PROPFIND',
  'PROPPATCH',
  'UNLOCK',
  'REPORT',
  'MKACTIVITY',
  'CHECKOUT',
  'MERGE',
  'M-SEARCH',
  'NOTIFY',
  'SUBSCRIBE',
  'UNSUBSCRIBE',
  'PATCH'
];

_.each(supportedMethods, function(method){
  resource.prototype[method] = getMethodHandler(method);
});

exports.resource = resource;

var setResource = function(req){
  req.resource = req.resource || {};
};

var checkMethodAllowed = function(method, r, req, res){
  if (!_.isFunction(r.input[method])){
    handle405(r, req, res);
  }
};

var fetch = function(r, req, res, onDone){
  if (_.isFunction(r.input.fetch)){
    var onFetch = function(err, val){
      if (err){
        handle404(r, req, res);
        onDone(true);
      } else {
        req.resource.fetched = val;
        onDone();
      }
    };
    r.input.fetch.apply(r, [req, onFetch]);
  } else {
    onDone();
  }
};

var handle405 = function(r, req, res){
  if (_.isFunction(r.handle405)){
    r.handle405(req, res);
  } else {
    setAllowHeader(r.input, req, res);
    res.writeHead(405);
    res.end();
  }
  res.done = true;
};
var handle404 = function(r, req, res){
  if (_.isFunction(r.handle404)){
    r.handle404(req, res);
  } else {
    res.writeHead(404);
    res.end();
  }
  res.done = true;
};

setAllowHeader = function(obj, req, res){
  res.setHeader('Allow', allowHeader(obj));
};

var allowHeader = function(obj){
  var methods = getMethods(obj);
  var additionalMethods = ['OPTIONS'];
  if (_.isFunction(obj.GET)){
    additionalMethods.push('HEAD');
  }
  methods = _.union(additionalMethods, methods);
  return methods.join(",");
};

var getMethods = function(handler){
  var moduleMethods = _.functions(handler);
  var retval = _.intersection(moduleMethods, serverSupportedMethods);
  return retval;
};

var serverSupportedMethods = ["GET", "POST",
                              "PUT", "DELETE",
                              "HEAD", "OPTIONS"];
<|endoftext|>


<commit_before>var type_mapping = [
  '',
  'double_value',
  'float_value',
  'int32_value',
  'int64_value',
  'uint32_value',
  'uint64_value',
  'sint32_value',
  'sint64_value',
  'fixed32_value',
  'fixed64_value',
  'sfixed32_value',
  'sfixed64_value',
  'bool_value',
  'string_value',
  'bytes_value'
];

module.exports = getResponseArray;

function copy(src)  {
  var dst = new ArrayBuffer((src.byteLength || src.length));
  new Uint8Array(dst).set(new Uint8Array(src));
  return dst;
}

function mapValues(value, ret, fn) {
  ret = ret || [];

  if (value.type < 16) {
      ret.push(value[type_mapping[value.type]]);
  } else {
    switch (value.type) {
      case 16: // OPERATION
      break;

      case 17: // ERROR
        fn(new Error(value.string_value));
        return null;
      break;

      case 18: // SHAPE_HANDLE
        ret.push({ id: value.uint32_value });
      break;

      case 19: // FLOAT_BUFFER
        ret.push(new Float32Array(copy(value.bytes_value)));
      break;

      case 20: // DOUBLE_BUFFER
        ret.push(new Float64Array(copy(value.bytes_value)));
      break;

      case 21: // OBJECT
        var l = value.item.length;
        var pack = {};

        for (var i=0; i<l; i++) {
          var subvalue = value.item[i];
          var collected = mapValues(subvalue, [], fn);
          if (collected) {
            pack[subvalue.string_value] = collected[0];
          }
        }
        ret.push(pack);

      break;

      case 22: // UINT32_BUFFER
        ret.push(new Uint32Array(copy(value.bytes_value)));
      break;
    }
  }
  return ret;
}

function getResponseArray(obj, fn) {
  var ret = [];

  var l = obj.value.length;
  for (var i=0; i<l; i++) {
    if (mapValues(obj.value[i], ret, fn) === null) {
      return;
    }
  }

  fn && fn(null, (ret.length > 1) ? ret : ret[0]);
}
<commit_msg>attach response to error<commit_after>var type_mapping = [
  '',
  'double_value',
  'float_value',
  'int32_value',
  'int64_value',
  'uint32_value',
  'uint64_value',
  'sint32_value',
  'sint64_value',
  'fixed32_value',
  'fixed64_value',
  'sfixed32_value',
  'sfixed64_value',
  'bool_value',
  'string_value',
  'bytes_value'
];

module.exports = getResponseArray;

function copy(src)  {
  var dst = new ArrayBuffer((src.byteLength || src.length));
  new Uint8Array(dst).set(new Uint8Array(src));
  return dst;
}

function mapValues(obj, value, ret, fn) {
  ret = ret || [];

  if (value.type < 16) {
      ret.push(value[type_mapping[value.type]]);
  } else {
    switch (value.type) {
      case 16: // OPERATION
      break;

      case 17: // ERROR
        var error = new Error(value.string_value);
        console.error(value.string_value);
        error.responseObject = obj;
        fn(error);
        return null;
      break;

      case 18: // SHAPE_HANDLE
        ret.push({ id: value.uint32_value });
      break;

      case 19: // FLOAT_BUFFER
        ret.push(new Float32Array(copy(value.bytes_value)));
      break;

      case 20: // DOUBLE_BUFFER
        ret.push(new Float64Array(copy(value.bytes_value)));
      break;

      case 21: // OBJECT
        var l = value.item.length;
        var pack = {};

        for (var i=0; i<l; i++) {
          var subvalue = value.item[i];
          var collected = mapValues(obj, subvalue, [], fn);
          if (collected) {
            pack[subvalue.string_value] = collected[0];
          }
        }
        ret.push(pack);

      break;

      case 22: // UINT32_BUFFER
        ret.push(new Uint32Array(copy(value.bytes_value)));
      break;
    }
  }
  return ret;
}

function getResponseArray(obj, fn) {
  var ret = [];

  var l = obj.value.length;
  for (var i=0; i<l; i++) {
    if (mapValues(obj, obj.value[i], ret, fn) === null) {
      return;
    }
  }

  fn && fn(null, (ret.length > 1) ? ret : ret[0]);
}
<|endoftext|>


<commit_before>// Description:
//   Example scripts for you to examine and try out.
//
// Notes:
//   They are commented out by default, because most of them are pretty silly and
//   wouldn't be useful and amusing enough for day to day huboting.
//   Uncomment the ones you want to try and experiment with.
//
//   These are from the scripting documentation: https://github.com/github/hubot/blob/master/docs/scripting.md

var exec = require('child_process').exec,
    executeCmd = (cmd) => {
      var promise = new Promise((resolve, reject) => {
        exec(cmd, (error, stdout, stderr) => {
          if (error !== null) {
            console.log('exec error: ' + error);
            return reject(error);
          }
          return resolve(stdout);
        });
      });
      return promise;
    };

module.exports = (robot) => {
  robot.respond(/open the (.*) door/i, (res) => {
    var doorType = res.match[1];
    return res.send("Opening " + doorType + " door");
  });
  robot.respond(/show images/i, (res) => {
    executeCmd('docker images')
    .then((stdout) => {
      return res.send(stdout);
    }).catch((err) => {
      return res.send(err);
    })
  });
  robot.respond(/running containers/i, (res) => {
    executeCmd('docker ps')
    .then((stdout) => {
      return res.send(stdout);
    }).catch((err) => {
      return res.send(err);
    })
  });
  robot.respond(/stop (.*)/i, (res) => {
    var container = res.match[1];
    executeCmd('docker stop ' + container)
    .then((stdout) => {
      return res.send("The container " + stdout.trim() + " is now stopped.");
    }).catch((err) => {
      return res.send(err);
    })
  });
  robot.respond(/run (.*) as (.*)/i, (res) => {
    var image = res.match[1],
        name = res.match[2];
    executeCmd('docker run -d -p 80:80 --name ' + name + ' ' + image)
    .then((stdout) => {
      return res.send("Now running " + image + " as " + name + ".");
    }).catch((err) => {
      return res.send(err);
    })
  });
};
<commit_msg>Updated help for container script<commit_after>// Description:
//   Example scripts for you to examine and try out.
//
// Commands:
//   show images
//   running containers
//   run <image_name> as <container_name>
//   stop <container_name>
//
// Notes:
//   They are commented out by default, because most of them are pretty silly and
//   wouldn't be useful and amusing enough for day to day huboting.
//   Uncomment the ones you want to try and experiment with.
//
//   These are from the scripting documentation: https://github.com/github/hubot/blob/master/docs/scripting.md

var exec = require('child_process').exec,
    executeCmd = (cmd) => {
      var promise = new Promise((resolve, reject) => {
        exec(cmd, (error, stdout, stderr) => {
          if (error !== null) {
            console.log('exec error: ' + error);
            return reject(error);
          }
          return resolve(stdout);
        });
      });
      return promise;
    };

module.exports = (robot) => {
  robot.respond(/show images/i, (res) => {
    executeCmd('docker images')
    .then((stdout) => {
      return res.send(stdout);
    }).catch((err) => {
      return res.send(err);
    })
  });
  robot.respond(/running containers/i, (res) => {
    executeCmd('docker ps')
    .then((stdout) => {
      return res.send(stdout);
    }).catch((err) => {
      return res.send(err);
    })
  });
  robot.respond(/stop (.*)/i, (res) => {
    var container = res.match[1];
    executeCmd('docker stop ' + container)
    .then((stdout) => {
      return res.send("The container " + stdout.trim() + " is now stopped.");
    }).catch((err) => {
      return res.send(err);
    })
  });
  robot.respond(/run (.*) as (.*)/i, (res) => {
    var image = res.match[1],
        name = res.match[2];
    executeCmd('docker run -d -p 80:80 --name ' + name + ' ' + image)
    .then((stdout) => {
      return res.send("Now running " + image + " as " + name + ".");
    }).catch((err) => {
      return res.send(err);
    })
  });
};
<|endoftext|>


<commit_before>//= require baseline
//= require plugins/jquery.zebraStripe.js

$(function () {
  var
    headingOffsets,
    navHeight = $('#nav').height(),
    $currentHeading = $('#current_heading'),
    $navLinks =
      $('#nav_menu')
        .modal({ open: false })
        // scroll the modal to the current heading
        .on('modal:opened', function (event) {
          $(this).scrollTop($navLinks.eq($currentHeading.data('nav-link-index')).offset().top);
        })
        .find('a[href^="#"]');

  if ($navLinks.length) {
    $(window)
      // set the heading offsets array on load and resize
      .on('load', function () {
        function setHeadingOffets() {
          headingOffsets = $navLinks.toArray().map(function(navLink) {
              return document.getElementById(navLink.getAttribute('href').substr(1)).offsetTop;
            });

          $(window).trigger('scroll');
        }

        $(window).on('resize', setHeadingOffets);

        setHeadingOffets();
      })
      // set the current heading on scroll
      .on('scroll', function () {
        try {
          var navLinkIndex = headingOffsets.findIndex(function (offsetTop) {
              return offsetTop > document.documentElement.scrollTop + navHeight;
            }) - 1;

          // if no offset is greater than the document's scroll top, the index will be -2
          if (navLinkIndex === -2) {
            // set it to -1 to get the last heading
            navLinkIndex = -1;
          }

          $currentHeading
            .data('nav-link-index', navLinkIndex)
            .html($navLinks.eq(navLinkIndex).html());
        } catch (ignore) {}
      });

    // close the nav links modal when a link is clicked
    $navLinks
      .on('click', function () {
        $(this).trigger('modal:close');
      });

    // jump to previous and next headings
    $('#nav .fa-chevron-circle-up')
      .on('click', function () {
        $navLinks.eq($currentHeading.data('nav-link-index') - 1).get(0).click();
      });

    $('#nav .fa-chevron-circle-down')
      .on('click', function () {
        $navLinks.eq($currentHeading.data('nav-link-index') + 1).get(0).click();
      });
  }

  $(document)
    // close FAQs when clicking outside of them
    .on('click', function (event) {
      if (!$(event.target).closest('.faq, [data-footnote]').length) {
        $('.faq:not([hidden])').trigger('accessibleToggle:hide');
      }
    })
    // close FAQs with Esc
    .on('keyup', function (event) {
      if (event.keyCode === 27) {
        $('.faq:not([hidden])').trigger('accessibleToggle:hide');
      }
    });

  // change anchor text to heading number if it exists
  $('.default-layout #main a[href]').each(function () {
    try {
      var number = $($(this).attr('href').match(/(#.+)$/).pop()).data('heading');

      if (number) {
        this.innerHTML = number;
      }
    } catch (e) {}
  });

  // toggle FAQs by clicking their headings
  $('aside.faq').accessibleToggle({ hidden: true, parent: '#main' });

  // zebra stripe all army list table bodies that don't contain another army list table
  $('table.army-list:not(:has(table.army-list)) > tbody').zebraStripe();
});<commit_msg>scrollspy fix for mobile<commit_after>//= require baseline
//= require plugins/jquery.zebraStripe.js

$(function () {
  var
    headingOffsets,
    navHeight = $('#nav').height(),
    $currentHeading = $('#current_heading'),
    $navLinks =
      $('#nav_menu')
        .modal({ open: false })
        // scroll the modal to the current heading
        .on('modal:opened', function (event) {
          $(this).scrollTop($navLinks.eq($currentHeading.data('nav-link-index')).offset().top);
        })
        .find('a[href^="#"]');

  function setHeadingOffets() {
    headingOffsets = $navLinks.toArray().map(function(navLink) {
        return document.getElementById(navLink.getAttribute('href').substr(1)).offsetTop;
      });

    $(window).trigger('scroll');
  }

  if ($navLinks.length) {
    $(window)
      // set the heading offsets array on load and resize
      .on('resize', setHeadingOffets)
      // set the current heading on scroll
      .on('scroll', function () {
        try {
          var navLinkIndex = headingOffsets.findIndex(function (offsetTop) {
              return offsetTop > document.documentElement.scrollTop + navHeight;
            }) - 1;

          // if no offset is greater than the document's scroll top, the index will be -2
          if (navLinkIndex === -2) {
            // set it to -1 to get the last heading
            navLinkIndex = -1;
          }

          $currentHeading
            .data('nav-link-index', navLinkIndex)
            .html($navLinks.eq(navLinkIndex).html());
        } catch (ignore) {}
      });

    setHeadingOffets();

    // close the nav links modal when a link is clicked
    $navLinks
      .on('click', function () {
        $(this).trigger('modal:close');
      });

    // jump to previous and next headings
    $('#nav .fa-chevron-circle-up')
      .on('click', function () {
        $navLinks.eq($currentHeading.data('nav-link-index') - 1).get(0).click();
      });

    $('#nav .fa-chevron-circle-down')
      .on('click', function () {
        $navLinks.eq($currentHeading.data('nav-link-index') + 1).get(0).click();
      });
  }

  $(document)
    // close FAQs when clicking outside of them
    .on('click', function (event) {
      if (!$(event.target).closest('.faq, [data-footnote]').length) {
        $('.faq:not([hidden])').trigger('accessibleToggle:hide');
      }
    })
    // close FAQs with Esc
    .on('keyup', function (event) {
      if (event.keyCode === 27) {
        $('.faq:not([hidden])').trigger('accessibleToggle:hide');
      }
    });

  // change anchor text to heading number if it exists
  $('.default-layout #main a[href]').each(function () {
    try {
      var number = $($(this).attr('href').match(/(#.+)$/).pop()).data('heading');

      if (number) {
        this.innerHTML = number;
      }
    } catch (e) {}
  });

  // toggle FAQs by clicking their headings
  $('aside.faq').accessibleToggle({ hidden: true, parent: '#main' });

  // zebra stripe all army list table bodies that don't contain another army list table
  $('table.army-list:not(:has(table.army-list)) > tbody').zebraStripe();
});
<|endoftext|>


<commit_before>var getDb = require('../lib/db').getDb;
var async = require('async');

module.exports = function getBadgeModel (key) {
  var BadgeCategory = require('./badge-category')(key);
  var Image = require('./image')(key);

  function setCriteria(criteria, callback) {
    var criteriaIds = [];
    const badgeId = this.id;

    async.each(criteria, function(criterion, innerCallback) {
      criterion.badgeId = badgeId;
      Criteria.put(criterion, function(err, result) {
        if (err)
          return innerCallback(err);

        if (result.insertId) {
          criteriaIds.push(result.insertId);
        }
        else {
          criteriaIds.push(result.row.id);
        }

        return innerCallback();
      });
    },
    function(err) {
      const deleteQuery = {
        badgeId: {
          value: badgeId,
          op: '='
        },
        id: criteriaIds.map(function(criterionId) {
          return {
            op: '!=',
            value: criterionId
          };
        })
      };

      Criteria.del(deleteQuery, function(err) {
        return callback(err);
      });
    });
  }

  function setCategories(categories, callback) {
    const badgeId = this.id;

    if (!Array.isArray(categories))
      categories = [categories];

    Category.del({badgeId: badgeId}, function (err) {
      if (err)
        return callback(err);

      const stream = Category.createWriteStream();

      stream.on('error', function (err) {
        callback(err);
        callback = function () {};
      });

      stream.on('close', function () {
        callback(null);
      });

      categories.forEach(function (categoryId, pos) {
        // Filter out empty and duplicate values
        if (isNaN(parseInt(categoryId)) || categories.indexOf(categoryId) !== pos)
          return;

        stream.write({badgeId: badgeId, categoryId: categoryId});
      });

      stream.end();
    });
  }

  function createCopy(overrides, callback) {
    var badge = JSON.parse(JSON.stringify(this));

    for (var property in overrides) {
      badge[property] = overrides[property];
    }

    delete badge.id;

    var criteria = badge.criteria;
    criteria.forEach(function(criterion) {
      delete criterion.badgeId;
      delete criterion.id;
    });

    delete badge.criteria;
    badge.created = new Date();
    delete badge.lastUpdated;
    if (badge.image && (badge.image.id !== null)) {
      var newImage = { mimetype: badge.image.mimetype,
                       data: badge.image.data ? new Buffer(badge.image.data) : null,
                       url: badge.image.url };
      Image.put(newImage, function (err, result) {
        if (err)
          return callback(err);
        putBadge(result.insertId);
      });
    }
    else {
      putBadge();
    }

    function putBadge(newImageId) {
      if (newImageId !== null)
        badge.imageId = newImageId;

      delete badge.image;
      Badge.put(badge, function (err, result) {
        if (err)
          return callback(err);

        Badge.getOne({ id: result.insertId }, function(err, row) {
          if (err)
            return callback(err);

          row.setCriteria(criteria, function(err) {
            callback(err, row);
          });
        });
      });
    }
  }

  function deleteBadge(callback) {
    const badgeId = this.id;

    Criteria.del({ badgeId: badgeId }, function (err) {
      if (err)
        return callback(err);

      Badge.del({ id: badgeId }, function (err) {
        return callback(err);
      });
    });
  }

  var db = getDb(key);

  var Criteria = db.table('criteria', {
    fields:
      ['id',
       'description',
       'badgeId',
       'required',
       'note']
  });

  var Category = db.table('_badgeCategory', {
    fields: ['badgeId', 'categoryId']
  });

  var Badge = db.table('badge', {
    fields:
      ['id',
       'name',
       'status',
       'description',
       'issuerUrl',
       'earnerDescription',
       'consumerDescription',
       'tags',
       'rubricUrl',
       'timeValue',
       'timeUnits',
       'limit',
       'multiClaimCode',
       'unique',
       'published',
       'imageId',
       'studioShape',
       'studioBackground',
       'studioTextType',
       'studioTextContents',
       'studioIcon',
       'studioColor',
       'created',
       'lastUpdated',
       'system',
       'issuer',
       'program',
       'badgeType'],
    relationships: {
      criteria: {
        type: 'hasMany',
        local: 'id',
        foreign: { table: 'criteria', key: 'badgeId' }
      },
      categories: {
        type: 'hasMany',
        local: 'id',
        foreign: { table: 'badgeCategory', key: 'id' },
        via: { table: '_badgeCategory', local: 'badgeId', foreign: 'categoryId' }
      },
      image: {
        type: 'hasOne',
        local: 'imageId',
        foreign: { table: 'image', key: 'id' },
        optional: true
      }
    },
    methods: {
      setCriteria: setCriteria,
      setCategories: setCategories,
      createCopy: createCopy,
      del: deleteBadge
    }
  });

  return Badge;
};

<commit_msg>Making sure categories are copied<commit_after>var getDb = require('../lib/db').getDb;
var async = require('async');

module.exports = function getBadgeModel (key) {
  var BadgeCategory = require('./badge-category')(key);
  var Image = require('./image')(key);

  function setCriteria(criteria, callback) {
    var criteriaIds = [];
    const badgeId = this.id;

    async.each(criteria, function(criterion, innerCallback) {
      criterion.badgeId = badgeId;
      Criteria.put(criterion, function(err, result) {
        if (err)
          return innerCallback(err);

        if (result.insertId) {
          criteriaIds.push(result.insertId);
        }
        else {
          criteriaIds.push(result.row.id);
        }

        return innerCallback();
      });
    },
    function(err) {
      const deleteQuery = {
        badgeId: {
          value: badgeId,
          op: '='
        },
        id: criteriaIds.map(function(criterionId) {
          return {
            op: '!=',
            value: criterionId
          };
        })
      };

      Criteria.del(deleteQuery, function(err) {
        return callback(err);
      });
    });
  }

  function setCategories(categories, callback) {
    const badgeId = this.id;

    if (!Array.isArray(categories))
      categories = [categories];

    Category.del({badgeId: badgeId}, function (err) {
      if (err)
        return callback(err);

      const stream = Category.createWriteStream();

      stream.on('error', function (err) {
        callback(err);
        callback = function () {};
      });

      stream.on('close', function () {
        callback(null);
      });

      categories.forEach(function (categoryId, pos) {
        // Filter out empty and duplicate values
        if (isNaN(parseInt(categoryId)) || categories.indexOf(categoryId) !== pos)
          return;

        stream.write({badgeId: badgeId, categoryId: categoryId});
      });

      stream.end();
    });
  }

  function createCopy(overrides, callback) {
    var badge = JSON.parse(JSON.stringify(this));

    for (var property in overrides) {
      badge[property] = overrides[property];
    }

    delete badge.id;

    var criteria = badge.criteria;
    criteria.forEach(function(criterion) {
      delete criterion.badgeId;
      delete criterion.id;
    });

    delete badge.criteria;

    var categories = (badge.categories || []).map(function (category) {
      return category.id;
    });

    delete badge.categories;

    badge.created = new Date();
    delete badge.lastUpdated;
    if (badge.image && (badge.image.id !== null)) {
      var newImage = { mimetype: badge.image.mimetype,
                       data: badge.image.data ? new Buffer(badge.image.data) : null,
                       url: badge.image.url };
      Image.put(newImage, function (err, result) {
        if (err)
          return callback(err);
        putBadge(result.insertId);
      });
    }
    else {
      putBadge();
    }

    function putBadge(newImageId) {
      if (newImageId !== null)
        badge.imageId = newImageId;

      delete badge.image;
      Badge.put(badge, function (err, result) {
        if (err)
          return callback(err);

        Badge.getOne({ id: result.insertId }, function(err, row) {
          if (err)
            return callback(err);

          async.series([
            row.setCriteria.bind(row, criteria),
            row.setCategories.bind(row, categories)
          ], function (err) {
            callback(err, row);
          });
        });
      });
    }
  }

  function deleteBadge(callback) {
    const badgeId = this.id;

    Criteria.del({ badgeId: badgeId }, function (err) {
      if (err)
        return callback(err);

      Badge.del({ id: badgeId }, function (err) {
        return callback(err);
      });
    });
  }

  var db = getDb(key);

  var Criteria = db.table('criteria', {
    fields:
      ['id',
       'description',
       'badgeId',
       'required',
       'note']
  });

  var Category = db.table('_badgeCategory', {
    fields: ['badgeId', 'categoryId']
  });

  var Badge = db.table('badge', {
    fields:
      ['id',
       'name',
       'status',
       'description',
       'issuerUrl',
       'earnerDescription',
       'consumerDescription',
       'tags',
       'rubricUrl',
       'timeValue',
       'timeUnits',
       'limit',
       'multiClaimCode',
       'unique',
       'published',
       'imageId',
       'studioShape',
       'studioBackground',
       'studioTextType',
       'studioTextContents',
       'studioIcon',
       'studioColor',
       'created',
       'lastUpdated',
       'system',
       'issuer',
       'program',
       'badgeType'],
    relationships: {
      criteria: {
        type: 'hasMany',
        local: 'id',
        foreign: { table: 'criteria', key: 'badgeId' }
      },
      categories: {
        type: 'hasMany',
        local: 'id',
        foreign: { table: 'badgeCategory', key: 'id' },
        via: { table: '_badgeCategory', local: 'badgeId', foreign: 'categoryId' }
      },
      image: {
        type: 'hasOne',
        local: 'imageId',
        foreign: { table: 'image', key: 'id' },
        optional: true
      }
    },
    methods: {
      setCriteria: setCriteria,
      setCategories: setCategories,
      createCopy: createCopy,
      del: deleteBadge
    }
  });

  return Badge;
};

<|endoftext|>


<commit_before>
/*!
 * Module dependencies
 */

var mongoose = require('mongoose');
var QueryPlugin = require('mongoose-query');

var Schema = mongoose.Schema;
/**
 * Build schema
 */
var BuildSchema = new Schema({

  name: {type: String, required: true },
  uuid: {type: String },
  v_ctrl: {type: String, enum: ['git','SVN', 'CSV']},
  repository: [
    new Schema({
      url: { type: String }
    })
  ],
  commitId: {type: String }, //sha-1
  branch: { type: String },
  compiledBy: {type: String, enum: ['CI', 'manual']},
  changeId: {type: String}, // e.g. when gerrit build
  pullRequest: {type: String}, // e.g. when github
  meta_info: {
    compiler: {type: String},
    version: {type: String},
    machine: {type: String},
  },
  file: {
    //buffer limit 16MB when attached to document!
    name: { type: String },
    data: { type: Buffer },
    size: { type: Number }
  },
  location: [
    new Schema({
      url: {type: String }, // fs://... or http://... or ftp://... or sft://...
      auth: {
        usr: { type: String },
        pwd: { type: String }
      },
    })
  ],
  // build target device
  target: {
    type: { type: String, enum: ['simulate','hardware'], required: true},
    os: { type: String, enum: ['win32', 'win64', 'linux32', 'linux64', 'mbedOS', 'unknown'] },
    simulator: {
      bt: {type: String},
      network: {type: String},
    },
    hw: {
      vendor: { type: String },
      platform: {type: String},
      rev: { type: String },
      rf: {
        // ??
      }
    }
  }
});

/**
 * Build plugin
 */
BuildSchema.plugin( QueryPlugin ); //install QueryPlugin

/**
 * Add your
 * - pre-save hooks
 * - validations
 * - virtuals
 */

/*
BuildSchema.path('location').validate(function (value, respond) {
    if( value.length === 0 ) respond(false);
    else  respond(true);
 }, '{PATH} missing');

BuildSchema.pre('validate', true, function (next, done) {

  if( this.target.type === 'simulate' ){
      next();
  } else if( this.target.type === 'hardware' ){
    if( this.target.hw ) next();
    else next( 'target missing' );
  } else {
    next( 'target missing' );
  }
 }, '{PATH}: invalid');
*/

/**
 * Methods
 */

BuildSchema.method({

});

/**
 * Statics
 */

BuildSchema.static({

});

/**
 * Register
 */
mongoose.model('Build', BuildSchema);
<commit_msg>Update build schema (#7)<commit_after>
/*!
 * Module dependencies
 */
// native modules
var crypto = require('crypto');

// 3rd party modules
var mongoose = require('mongoose');
var QueryPlugin = require('mongoose-query');

function checksum (str, algorithm, encoding) {
    return crypto
        .createHash(algorithm || 'sha1')
        .update(str, 'binary')
        .digest(encoding || 'hex')
}

var Schema = mongoose.Schema;

/**
 * Build schema
 */
var BuildSchema = new Schema({
  name: {type: String, required: true },
  type: { type: String, enum: ['cliapp', 'unittest']},
  cre: {
    user: {type: String},
    time: {type: Date, default: Date.now},
  },
  mod: {
    user: {type: String},
    time: {type: Date, default: Date.now},
  },
  uuid: { type: String },
  vcs: [
    new Schema({
      name: { type: String },
      type: { type: String, enum: ['git','SVN', 'CSV'] }, //version control system
      url: { type: String },
      commitId: { type: String },
      clean_wa: { type: Boolean },
      branch: { type: String },
    })
  ],
  compiledBy: { type: String, enum: ['CI', 'manual'] },
  changeId: {type: String}, // e.g. when gerrit build
  pullRequest: {type: String}, // e.g. when github
  meta_info: {
    compiler: {type: String},
    version: {type: String},
    machine: {type: String},
  },
  file: {
    //buffer limit 16MB when attached to document!
    name: { type: String },
    data: { type: Buffer },
    size: { type: Number },
    sha1: { type: String },
    sha256: { type: String }
  },
  location: [
    new Schema({
      url: {type: String }, // fs://... or http://... or ftp://... or sft://...
      auth: {
        usr: { type: String },
        pwd: { type: String }
      },
    })
  ],
  issues: [
    new Schema({
      time: {type: Date, default: Date.now},
      type: { type: String, enum: ['github', 'jira'] },
      url: { type: String }
    })
  ],
  // build target device
  target: {
    type: { type: String, enum: ['simulate','hardware'], default: 'hardware'},
    os: { type: String, enum: ['win32', 'win64', 'linux32', 'linux64', 'mbedOS', 'unknown'] },
    simulator: {
      bt: { type: String },
      network: { type: String },
    },
    hw: {
      vendor: { type: String },
      platform: {type: String},
      rev: { type: String },
      rf: {
        // ??
      }
    }
  }
});

/**
 * Build plugin
 */
BuildSchema.plugin( QueryPlugin ); //install QueryPlugin

/**
 * Add your
 * - pre-save hooks
 * - validations
 * - virtuals
 */

/*
BuildSchema.path('location').validate(function (value, respond) {
    if( value.length === 0 ) respond(false);
    else  respond(true);
 }, '{PATH} missing');
 */

BuildSchema.pre('validate', true, function (next, done) {

  if( this.build && this.build.data ) {
    this.build.size = this.build.data.length;
    this.build.sha1 = checksum(this.build.data, 'sha1');
    this.build.sha256 = checksum(this.build.data, 'sha256');
  }
  if( this.target.type === 'simulate' ){
    if( this.target.simulator ) next();
    else next('simulator missing');
  } else if( this.target.type === 'hardware' ){
    if( this.target.hw ) next();
    else next( 'target missing' );
  } else {
    next( 'target missing' );
  }
 }, '{PATH}: invalid');

/**
 * Methods
 */
//BuildSchema.method({});

/**
 * Statics
 */
//BuildSchema.static({});

/**
 * Register
 */
mongoose.model('Build', BuildSchema);
<|endoftext|>


<commit_before>
var popoverVisible = undefined;

function Documents(renderer) {
	var me = this;

	var documents = [];
	for (var i = 0; i < $documents.length; i++) {
		documents[i] = new Document($documents[i], i, renderer);
	}

	me.setPosition = function (f) {
		for (var i = 0; i < documents.length; i++) documents[i].setPosition(f);
	}

	me.moveToPosition = function (f, duration) {
		for (var i = 0; i < documents.length; i++) documents[i].moveToPosition(f, 500, (documents.length-i)*1);
	}

	me.updateResultMarkers = function (show) {
		for (var i = 0; i < documents.length; i++) documents[i].updateResultMarker(show);
	}

	$(document).click(function(e) {
		if (popoverVisible !== undefined) {
			$('.thumb').popover('hide')
			popoverVisible = undefined
		}
	});

	return me;
}

function Document(data, index, renderer) {
	var me = this;
	var thumbId = data.t.charAt(0);
	var imageUrl = 'style/thumb'+thumbId+'-transparent.png';
	var color = qualityToColor(data.qualitySum);

	function startReader(index, data, viewObject) {
	}

	var viewObject = renderer.drawImage(imageUrl, 'thumb', color);

	var thumbs = [];
	for (var i = 0; i < data.c; i++) {
		var t = data.t.charAt(i);
		var color = qualityToColor(data.quality[i]);
		thumbs.push('

');
	}

	viewObject.popover({
		title:'Unterrichtung des Parlaments '+data.title,
		html:true,
		content:thumbs.join('')+'
',
		trigger:'manual'
	});

	viewObject.click(viewObject, function (e) {
		//startReader(index, data, viewObject);

		$('.thumb').popover('hide');
		if (popoverVisible !== viewObject) {
			popoverVisible = viewObject;
			viewObject.popover('show');
		}
		e.preventDefault();
		return false;
	});

	me.setPosition = function (f) {
		var pos = f(index, data);
		renderer.setPosition(viewObject, pos.x, pos.y);
	}

	me.moveToPosition = function (f, duration, delay) {
		var pos = f(index, data);
		renderer.moveToPosition(viewObject, pos.x, pos.y, duration, delay);
	}

	me.updateResultMarker = function (show) {
		if (!show || (data.resultCount > 0)) {
			viewObject.animate({opacity:1}, 250);
		} else {
			viewObject.animate({opacity:0.2}, 250);
		}
	}

	return me;
}

function qualityToColor(v) {
	// rot, gelb, grün
	var r = Math.round((v < 1 ? 1 : 2-v)*255);
	var g = Math.round((v < 1 ? v : 1  )*255);
	var b = 0;
	return 'rgb('+r+','+g+','+b+')';
}

function Renderer(target) {
	var me = this;

	me.drawImage = function (url, className, backgroundColor) {
		var div = $('

');
		//var img = $('');
		//div.append(img);
		target.append(div);
		return div;
	}

	me.setPosition = function (obj, x, y) {
		obj.css({left:x, top:y})
	}

	me.moveToPosition = function (obj, x, y, duration, delay) {
		if (Modernizr.csstransforms) {
			obj.transition({left:x+'px', top:y+'px', duration:duration, delay:delay, easing:'in-out'})
		} else {
			obj.animate({left:x, top:y}, duration, 'smooth')
		}
	}

	me.click = function (obj, f) {
		obj.click(f);
	}

	return me;
}

$.easing.smooth = function(p) {
	return p < 0.5 ?
		Math.pow( p * 2, 3) / 2 :
		1 - Math.pow( p * -2 + 2, 3 ) / 2;
}<commit_msg>adding title directly to element, more gracefully downgradeable<commit_after>
var popoverVisible = undefined;

function Documents(renderer) {
	var me = this;

	var documents = [];
	for (var i = 0; i < $documents.length; i++) {
		documents[i] = new Document($documents[i], i, renderer);
	}

	me.setPosition = function (f) {
		for (var i = 0; i < documents.length; i++) documents[i].setPosition(f);
	}

	me.moveToPosition = function (f, duration) {
		for (var i = 0; i < documents.length; i++) documents[i].moveToPosition(f, 500, (documents.length-i)*1);
	}

	me.updateResultMarkers = function (show) {
		for (var i = 0; i < documents.length; i++) documents[i].updateResultMarker(show);
	}

	$(document).click(function(e) {
		if (popoverVisible !== undefined) {
			$('.thumb').popover('hide')
			popoverVisible = undefined
		}
	});

	return me;
}

function Document(data, index, renderer) {
	var me = this;
	var thumbId = data.t.charAt(0);
	var imageUrl = 'style/thumb'+thumbId+'-transparent.png';
	var color = qualityToColor(data.qualitySum);

	function startReader(index, data, viewObject) {
	}

	var viewObject = renderer.drawImage(imageUrl, 'thumb', color, 'Unterrichtung des Parlaments '+data.title_);

	var thumbs = [];
	for (var i = 0; i < data.c; i++) {
		var t = data.t.charAt(i);
		var color = qualityToColor(data.quality[i]);
		thumbs.push('

');
	}

	viewObject.popover({
		html:true,
		content:thumbs.join('')+'
',
		trigger:'manual',
		placement:'bottom'
	});
	});

	viewObject.click(viewObject, function (e) {
		//startReader(index, data, viewObject);

		$('.thumb').popover('hide');
		if (popoverVisible !== viewObject) {
			popoverVisible = viewObject;
			viewObject.popover('show');
		}
		e.preventDefault();
		return false;
	});

	me.setPosition = function (f) {
		var pos = f(index, data);
		renderer.setPosition(viewObject, pos.x, pos.y);
	}

	me.moveToPosition = function (f, duration, delay) {
		var pos = f(index, data);
		renderer.moveToPosition(viewObject, pos.x, pos.y, duration, delay);
	}

	me.updateResultMarker = function (show) {
		if (!show || (data.resultCount > 0)) {
			viewObject.animate({opacity:1}, 250);
		} else {
			viewObject.animate({opacity:0.2}, 250);
		}
	}

	return me;
}

function qualityToColor(v) {
	// rot, gelb, grün
	var r = Math.round((v < 1 ? 1 : 2-v)*255);
	var g = Math.round((v < 1 ? v : 1  )*255);
	var b = 0;
	return 'rgb('+r+','+g+','+b+')';
}

function Renderer(target) {
	var me = this;

	me.drawImage = function (url, className, backgroundColor, title) {
		var div = $('

');
		//var img = $('');
		//div.append(img);
		target.append(div);
		return div;
	}

	me.setPosition = function (obj, x, y) {
		obj.css({left:x, top:y})
	}

	me.moveToPosition = function (obj, x, y, duration, delay) {
		if (Modernizr.csstransforms) {
			obj.transition({left:x+'px', top:y+'px', duration:duration, delay:delay, easing:'in-out'})
		} else {
			obj.animate({left:x, top:y}, duration, 'smooth')
		}
	}

	me.click = function (obj, f) {
		obj.click(f);
	}

	return me;
}

$.easing.smooth = function(p) {
	return p < 0.5 ?
		Math.pow( p * 2, 3) / 2 :
		1 - Math.pow( p * -2 + 2, 3 ) / 2;
}<|endoftext|>


<commit_before><commit_msg>fix Faq.js<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

require('./dbbs').setup();
require('./rest/subscriber/adapter.js').clearTimeouts();
var connect = require('connect');
var program = require('commander');
var html = require('./html/controller');
var rest = require('./rest/controller');
var fs = require('fs');
var profile_mod = require('./rest/profile/controller');
var packet_mod = require('./rest/packet/controller');
// var session = require('./session');
var prof = profile_mod();
var pack = packet_mod();

program
  .version(process.env.SERVER_VERSION)
  .option('-p, --port [tcp port]', 'Specify a listening port')
  .option('-a, --address [ip address]', 'Specify a listening ip address')
  .option('-c, --config [config file]', 'Specify a configuration file')
  .option('-b, --base [base html dir]', 'Specify a base dir for static files')
  .option('-d, --database [database file]', 'Specify a database file')
  .option('-t, --test', 'Run server in test mode')
  .parse(process.argv);

var port = program.port || process.env.PORT || 3000;
var ip = program.address || process.env.ADDRESS || '127.0.0.1';
var config = program.config || process.env.CONFIG || './config';
var htmlbase = program.base || process.env.BASE || __dirname;
var database = program.database || process.env.DATABASE || './dbbs';

var app = connect();

// Note - it would be nice if this could be refactored to a connect functor
html.serve(app, connect, { base: htmlbase, content: require(config)});

if(program.test) {
  fs.createWriteStream('temp','utf8');
}

// What are these global variables for? ... globals are bad!
// Also, it appears to be providing some sort of application functionality;
// however, this is a top-level composition. There should only being argument
// handling and service initialization at this point.

var profileId = 0;
var profileList = [];

var packetId = 0;
var packetList = [];
function findById(source, id){
  for (var i = 0; i < source.length; i++){
    if(source[i].id === id){
      return i;
    }
  }
  throw "couldnt find object with id: " + id;
}

app
  .use(connect.json())
  .use('/api',
       rest(require(database), {profile: prof.module, packet: pack.module})
      )
  // We should refactor this into a generic resource not found handler.
  // Definitions should be really be in this file (index.js)
  .use(function(req, res) {
    res.writeHead('404');
    res.end('');
  })
  .listen(port, ip);

console.log('Server started on: %s:%d', ip, port);
<commit_msg>removed old stub<commit_after>#!/usr/bin/env node

require('./dbbs').setup();
require('./rest/subscriber/adapter.js').clearTimeouts();
var connect = require('connect');
var program = require('commander');
var html = require('./html/controller');
var rest = require('./rest/controller');
var fs = require('fs');
var profile_mod = require('./rest/profile/controller');
var packet_mod = require('./rest/packet/controller');
// var session = require('./session');
var prof = profile_mod();
var pack = packet_mod();

program
  .version(process.env.SERVER_VERSION)
  .option('-p, --port [tcp port]', 'Specify a listening port')
  .option('-a, --address [ip address]', 'Specify a listening ip address')
  .option('-c, --config [config file]', 'Specify a configuration file')
  .option('-b, --base [base html dir]', 'Specify a base dir for static files')
  .option('-d, --database [database file]', 'Specify a database file')
  .option('-t, --test', 'Run server in test mode')
  .parse(process.argv);

var port = program.port || process.env.PORT || 3000;
var ip = program.address || process.env.ADDRESS || '127.0.0.1';
var config = program.config || process.env.CONFIG || './config';
var htmlbase = program.base || process.env.BASE || __dirname;
var database = program.database || process.env.DATABASE || './dbbs';

var app = connect();

// Note - it would be nice if this could be refactored to a connect functor
html.serve(app, connect, { base: htmlbase, content: require(config)});

if(program.test) {
  fs.createWriteStream('temp','utf8');
}

app
  .use(connect.json())
  .use('/api',
       rest(require(database), {profile: prof.module, packet: pack.module})
      )
  // We should refactor this into a generic resource not found handler.
  // Definitions should be really be in this file (index.js)
  .use(function(req, res) {
    res.writeHead('404');
    res.end('');
  })
  .listen(port, ip);

console.log('Server started on: %s:%d', ip, port);
<|endoftext|>


<commit_before><commit_msg>revoke Run.js's ability to turn off after turning on<commit_after><|endoftext|>


<commit_before><commit_msg>修复缓存KEY设置错误<commit_after><|endoftext|>


<commit_before>function camxes_preprocessing(input) {
	if (!(typeof input.valueOf() === 'string'))
		return "ERROR: Wrong input type.";
	input = input.replace(/’/gm,"'");
	input = input.replace(/([0-9])\.([0-9])/gm,"$1 pi $2");
	input = input.replace(/0/gm,"no");
	input = input.replace(/1/gm,"pa");
	input = input.replace(/2/gm,"re");
	input = input.replace(/3/gm,"ci");
	input = input.replace(/4/gm,"vo");
	input = input.replace(/5/gm,"mu");
	input = input.replace(/6/gm,"xa");
	input = input.replace(/7/gm,"ze");
	input = input.replace(/8/gm,"bi");
	input = input.replace(/9/gm,"so");
	// --- //
	input = input.replace(/[áàâä]/g,"A");
	input = input.replace(/[éèêë]/g,"E");
	input = input.replace(/[íìîïĭị]/g,"I");
	input = input.replace(/[óòôö]/g,"O");
	input = input.replace(/[úùûüŭụw]/g,"U");
	input = input.replace(/[ýỳŷÿ]/g,"Y");
	// --- //
	input = input.replace(/sh/igm,"c");
	input = input.replace(/zh/igm,"j");
	input = input.replace(/ch/igm,"tc");
	input = input.replace(/kh/igm,"x");
	// --- //
	input = input.replace(/ı/igm,"i");
	input = input.replace(/ʃ/igm,"c");
	input = input.replace(/ʒ/igm,"j");
	input = input.replace(/ɛ/gm,"e");
	input = input.replace(/[Ɛɛ́ɛ̀ɛ̂ɛ̈]/gm,"E");
        input = input.replace(/ə/igm,"y");
        input = input.replace(/ŋ/igm,"ng");
	// --- //
	input = input.replace(/([cfkpstx])([bdgjvz])/igm,"$1y$2");
	input = input.replace(/([bdgjvz])([cfkpstx])/igm,"$1y$2");
	// --- //
	var a = {"Ё":"IO","Й":"I","Ц":"TS","У":"U","К":"K","Е":"E","Н":"N","Г":"G","Ш":"C","Щ":"C","З":"Z","Х":"X","Ъ":"Y","Ь":"'","ё":"io","й":"i","ц":"ts","у":"u","к":"k","е":"e","н":"n","г":"g","ш":"c","щ":"c","з":"z","х":"x","ъ":"y","ь":"'","Ф":"F","Ы":"Y","В":"V","А":"a","П":"P","Р":"R","О":"O","Л":"L","Д":"D","Ж":"J","Э":"E","ф":"f","ы":"y","в":"v","а":"a","п":"p","р":"r","о":"o","л":"l","д":"d","ж":"j","э":"e","Я":"IA","Ч":"TC","С":"S","М":"M","И":"I","Т":"T","Б":"B","Ю":"IU","я":"ia","ч":"tc","с":"s","м":"m","и":"i","т":"t","б":"b","ю":"iu"};
	function transliterate(word){
  	return word.split('').map(function (char) {
    return a[char] || char;
  	}).join("");
	}
	input = transliterate(input);
	// --- //
	input = input.replace(/\(|\)|«|»|—|:/gm,"");
	return input;
}

module.exports.preprocessing = camxes_preprocessing;

<commit_msg>interpuncts support<commit_after>function camxes_preprocessing(input) {
	if (!(typeof input.valueOf() === 'string'))
		return "ERROR: Wrong input type.";
	input = input.replace(/’/gm,"'");
	input = input.replace(/·/gm,".");
	input = input.replace(/([0-9])\.([0-9])/gm,"$1 pi $2");
	input = input.replace(/0/gm,"no");
	input = input.replace(/1/gm,"pa");
	input = input.replace(/2/gm,"re");
	input = input.replace(/3/gm,"ci");
	input = input.replace(/4/gm,"vo");
	input = input.replace(/5/gm,"mu");
	input = input.replace(/6/gm,"xa");
	input = input.replace(/7/gm,"ze");
	input = input.replace(/8/gm,"bi");
	input = input.replace(/9/gm,"so");
	// --- //
	input = input.replace(/[áàâä]/g,"A");
	input = input.replace(/[éèêë]/g,"E");
	input = input.replace(/[íìîïĭị]/g,"I");
	input = input.replace(/[óòôö]/g,"O");
	input = input.replace(/[úùûüŭụw]/g,"U");
	input = input.replace(/[ýỳŷÿ]/g,"Y");
	// --- //
	input = input.replace(/sh/igm,"c");
	input = input.replace(/zh/igm,"j");
	input = input.replace(/ch/igm,"tc");
	input = input.replace(/kh/igm,"x");
	// --- //
	input = input.replace(/ı/igm,"i");
	input = input.replace(/ʃ/igm,"c");
	input = input.replace(/ʒ/igm,"j");
	input = input.replace(/ɛ/gm,"e");
	input = input.replace(/[Ɛɛ́ɛ̀ɛ̂ɛ̈]/gm,"E");
        input = input.replace(/ə/igm,"y");
        input = input.replace(/ŋ/igm,"ng");
	// --- //
	input = input.replace(/([cfkpstx])([bdgjvz])/igm,"$1y$2");
	input = input.replace(/([bdgjvz])([cfkpstx])/igm,"$1y$2");
	// --- //
	var a = {"Ё":"IO","Й":"I","Ц":"TS","У":"U","К":"K","Е":"E","Н":"N","Г":"G","Ш":"C","Щ":"C","З":"Z","Х":"X","Ъ":"Y","Ь":"'","ё":"io","й":"i","ц":"ts","у":"u","к":"k","е":"e","н":"n","г":"g","ш":"c","щ":"c","з":"z","х":"x","ъ":"y","ь":"'","Ф":"F","Ы":"Y","В":"V","А":"a","П":"P","Р":"R","О":"O","Л":"L","Д":"D","Ж":"J","Э":"E","ф":"f","ы":"y","в":"v","а":"a","п":"p","р":"r","о":"o","л":"l","д":"d","ж":"j","э":"e","Я":"IA","Ч":"TC","С":"S","М":"M","И":"I","Т":"T","Б":"B","Ю":"IU","я":"ia","ч":"tc","с":"s","м":"m","и":"i","т":"t","б":"b","ю":"iu"};
	function transliterate(word){
  	return word.split('').map(function (char) {
    return a[char] || char;
  	}).join("");
	}
	input = transliterate(input);
	// --- //
	input = input.replace(/\(|\)|«|»|—|:/gm,"");
	return input;
}

module.exports.preprocessing = camxes_preprocessing;

<|endoftext|>


<commit_before><commit_msg>Use braces for non-returning event handlers<commit_after><|endoftext|>