<commit_before>var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var fs = require('fs');
var http = require('http');

var util = require('./util');

var editorevent = require('./editor_event');
var remotehostevent = require('./remotehost_event');

var filedialog= require('./js/filedialog');
var RemoteFTP = require('./js/RemoteFTP');

//-------------------------------------
// Server request logic
//-------------------------------------
var server = http.createServer();
server.on('request', function(req,res){
	console.log("REQ>"+req.url);

	var url = req.url;
	var addrs = req.url.split("?");
	if (addrs)
		url = addrs[0]; // ignore args

	if (url == '/') {
		var html = fs.readFileSync('./home.html');
		res.writeHead(200,{'Content-Type':'text/html', charaset:'UTF-8'});
		res.end(html);
	} else {
		fs.readFile('.' + url, function (err,data){
			if (err) {
				res.writeHead(404,{'Content-Type':'text/html', charaset:'UTF-8'});
				res.end("
not found
");
				return;
			}
			var ext = util.getExtention(url);
			if (ext == "css")
				res.writeHead(200,{'Content-Type':'text/css',charaset:'UTF-8'});
			else if (ext == "html" || ext == "htm")
				res.writeHead(200,{'Content-Type':'text/html',charaset:'UTF-8'});
			else if (ext == "js" || ext == "json")
				res.writeHead(200,{'Content-Type':'text/javascript',charaset:'UTF-8'});
			else
				res.writeHead(200);//,{charaset:'UTF-8'});
			res.end(data);
		}); // fs.readFile
	}
});
server.listen(8080);
console.log('Server running on localhost:8080')

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

function registerPTLEvent(socket)
{
	socket.on('ptl_launchapp', function(data) {
		console.log("ptl_launchapp:" + data.appname);

		var appcmd;
		if (data.appname == 'FXgen')
			appcmd = 'open /Applications/FXgen.app';
		else if(data.appname == 'PDI')
			appcmd = 'pdi';

		var child = exec(appcmd, function(err, stdout, stderr) {
			if (err) {
				console.log(err);
				console.log(err.code);
				console.log(err.signal);
			} else {
				console.log('stdout: ' + stdout);
				console.log('stderr: ' + stderr)
			}
		});
	});// ptl_launchapp

	filedialog.SocketEvent(socket,'homedlg');
	filedialog.SocketEvent(socket,'remotedlg');

	socket.on('registerProjectHistory', function(path){
		console.log("REGISTER_HISTORY:"+path);
		var historyFile = "project_history.json";
		fs.readFile(historyFile, function(err,data){
			var names = path.split("/");
			var name = names[names.length-1];
			console.log("ProjName="+name);
			if (err) {
				console.log('Error: ' + err);
				data = new Array();
				data.push({"name":name, "path":path});
			} else {
				data = JSON.parse(data);
				data.splice(0, 0,{"name":name, "path":path}); // Add first
			}
			data  = JSON.stringify(data);
			fs.writeFileSync(historyFile, data, 'utf8');
		});
	});

}

// socket.io setting
var io = require('socket.io').listen(server);
io.set('log level', 1);

io.sockets.on('connection', function (socket) {
	socket.emit('event', 'Server Connected.');
	console.log("[CONNECT] ID="+socket.id);

	RemoteFTP(socket);
	editorevent.registerEditorEvent(socket);
	remotehostevent.registerEditorEvent(socket);
	registerPTLEvent(socket);
});<commit_msg>beautify<commit_after>var exec = require('child_process').exec,
	spawn = require('child_process').spawn,
	fs = require('fs'),
	http = require('http'),
	util = require('./util'),
	editorevent = require('./editor_event'),
	remotehostevent = require('./remotehost_event'),
	filedialog = require('./js/filedialog'),
	RemoteFTP = require('./js/RemoteFTP');

//-------------------------------------
// Server request logic
//-------------------------------------
var server = http.createServer();
server.on('request', function (req, res) {
	"use strict";
	console.log("REQ>" + req.url);

	var url = req.url,
		addrs = req.url.split("?"),
		html,
		ext;
	if (addrs) {
		url = addrs[0]; // ignore args
	}

	if (url === '/') {
		html = fs.readFileSync('./home.html');
		res.writeHead(200, {'Content-Type': 'text/html', charaset: 'UTF-8'});
		res.end(html);
	} else {
		fs.readFile('.' + url, function (err, data) {
			if (err) {
				res.writeHead(404, {'Content-Type': 'text/html', charaset: 'UTF-8'});
				res.end("
not found
");
				return;
			}
			ext = util.getExtention(url);
			if (ext === "css") {
				res.writeHead(200, {'Content-Type': 'text/css', charaset: 'UTF-8'});
			} else if (ext === "html" || ext === "htm") {
				res.writeHead(200, {'Content-Type': 'text/html', charaset: 'UTF-8'});
			} else if (ext === "js" || ext === "json") {
				res.writeHead(200, {'Content-Type': 'text/javascript', charaset: 'UTF-8'});
			} else {
				res.writeHead(200);//,{charaset:'UTF-8'});
			}
			res.end(data);
		}); // fs.readFile
	}
});
server.listen(8080);
console.log('Server running on localhost:8080');

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

function registerPTLEvent(socket) {
	"use strict";
	socket.on('ptl_launchapp', function (data) {
		console.log("ptl_launchapp:" + data.appname);

		var appcmd, child;
		if (data.appname === 'FXgen') {
			appcmd = 'open /Applications/FXgen.app';
		} else if (data.appname === 'PDI') {
			appcmd = 'pdi';
		}
		child = exec(appcmd, function (err, stdout, stderr) {
			if (err) {
				console.log(err);
				console.log(err.code);
				console.log(err.signal);
			} else {
				console.log('stdout: ' + stdout);
				console.log('stderr: ' + stderr);
			}
		});
	});// ptl_launchapp

	filedialog.SocketEvent(socket, 'homedlg');
	filedialog.SocketEvent(socket, 'remotedlg');

	socket.on('registerProjectHistory', function (path) {
		console.log("REGISTER_HISTORY:" + path);
		var historyFile = "project_history.json";
		fs.readFile(historyFile, function (err, data) {
			var names = path.split("/"),
				name = names[names.length - 1];
			console.log("ProjName=" + name);
			if (err) {
				console.log('Error: ' + err);
				data = [];
				data.push({"name": name, "path": path});
			} else {
				data = JSON.parse(data);
				data.splice(0, 0, {"name": name, "path": path}); // Add first
			}
			data  = JSON.stringify(data);
			fs.writeFileSync(historyFile, data, 'utf8');
		});
	});

}

// socket.io setting
var io = require('socket.io').listen(server);
io.set('log level', 1);

io.sockets.on('connection', function (socket) {
	"use strict";
	socket.emit('event', 'Server Connected.');
	console.log("[CONNECT] ID=" + socket.id);

	RemoteFTP(socket);
	editorevent.registerEditorEvent(socket);
	remotehostevent.registerEditorEvent(socket);
	registerPTLEvent(socket);
});<|endoftext|>


<commit_before>var authConfig = require('../config/authConfig.js');
var yelp = require('./yelpApi.js');
var Heap = require('heap');
var utils = require('./utils.js');
var fs = require('fs');
/*
Creates an instance of Recommendation Session

@constructor
@this {RecSession}
@param {string} loc The user-input location (zip code, address, etc).
@param {string} uid The randomly generated UID for this session.
*/

var RecSession = function(loc, uid, numRecs) {
  this.location = loc;
  this.uniqueID = uid;
  this.recommendations = {};
  this.vetoes = {};
  this.numRecs = numRecs;
  this.recQueue = [];
};

/*
Gets the restaurant data from Yelp and saves it in the instance of RecSession.

@this {RecSession}
@param {callback} cb The callback to invoke with (err, data, res)
*/

RecSession.prototype.getYelpData = function(cb) {
  var yelpClient = new yelp.YelpClient(authConfig);
  var searchParams = {
    sort: 1,
    radius_filter: 5000,
    location: this.location
  };

  yelpClient.searchRestaurants(searchParams, function(err, data, res) {
    if (err) {
      console.error('Error - Yelp API returned: ', err);
    }

    this.yelpData = data;
    cb(err, data, res);
  }.bind(this));
};

/*
Builds the recommendation queue.

@param {callback} cb The callback to invoke with (recommendations)
*/
RecSession.prototype.buildRecommendation = function(cb){
  var subCallback = function(err, data, res){
    if(!err){
      this.lat = data.region.center.latitude;
      this.longi = data.region.center.longitude;
      this.recQueue = data.businesses;
      this.recQueue.sort(function(a, b){
        return utils.calculateScore(this.lat, this.longi, a) - utils.calculateScore(this.lat, this.longi, b);
      }.bind(this));

      for(var i=0;i<this.numRecs && this.recQueue.length > 0;i++){
        var current = this.recQueue.pop();
        var vetoed = false;
        if(this.vetoes[current.id]){
          vetoed = true;
        };
        for(var j=0;j++;j<current.categories.length){
          if(this.vetoes[current.categories[i]]){
            vetoed = true;
          }
        };
        if(!vetoed){
          this.recommendations[current.id] = current;
        }else{
          i --;
        }
      }

      cb(this.recommendations);
    }
  };

  this.getYelpData(subCallback.bind(this));
};
/*
Returns recs

@returns {object} Object of recommendations keyed by id.
*/
RecSession.prototype.getRecs = function(){
  return this.recommendations;
};
/*
Adds veto to session

@param {object} Takes command object of form {key: 'id'|'object', val: valueToVeto}
*/
RecSession.prototype.veto = function(command) {
  // Refactor using lodash later.
  this.vetoes[command.val] = true;
  if(command.key === 'id'){
    delete this.recommendations[command.val];
  }else{
    var keys = Object.keys(this.recommendations);
    for(var i=0;i<keys.length;i++){
      if(this.recommendations[keys[i]].categories[0].indexOf(command.val) > -1){
        delete this.recommendations[keys[i]];
      }
    }
  };
  for(var i=0;i<this.numRecs && this.recQueue.length > 0 && Object.keys(this.recommendations).length < this.numRecs;i++){
    var current = this.recQueue.pop();
    var vetoed = false;
    if(this.vetoes[current.id]){
      vetoed = true;
    };
    // First in array is food-related;
    for(var j=0;j++;j<current.categories[0].length){
      if(this.vetoes[current.categories[0][i]]){
        vetoed = true;
      }
    };
    if(!vetoed){
      this.recommendations[current.id] = current;
    }else{
      i --;
    }
  };

};
module.exports = RecSession;

module.exports.RecSession = RecSession;

// (location, uid, numRecommendations)
var testsesh = new RecSession('94103', 0, 3);
testsesh.veto({key:'id', val:'crepes-a-go-go-san-francisco-2'});
testsesh.buildRecommendation(function(recs){
  console.log(Object.keys(recs))
  testsesh.veto({key:'id', val:'so-san-francisco-4'})
  console.log(Object.keys(testsesh.getRecs()));
  testsesh.veto({key:'category', val:'asianfusion'})
  console.log(Object.keys(testsesh.getRecs()));
})
<commit_msg>Updated logs<commit_after>var authConfig = require('../config/authConfig.js');
var yelp = require('./yelpApi.js');
var Heap = require('heap');
var utils = require('./utils.js');
var fs = require('fs');
/*
Creates an instance of Recommendation Session

@constructor
@this {RecSession}
@param {string} loc The user-input location (zip code, address, etc).
@param {string} uid The randomly generated UID for this session.
*/

var RecSession = function(loc, uid, numRecs) {
  this.location = loc;
  this.uniqueID = uid;
  this.recommendations = {};
  this.vetoes = {};
  this.numRecs = numRecs;
  this.recQueue = [];
};

/*
Gets the restaurant data from Yelp and saves it in the instance of RecSession.

@this {RecSession}
@param {callback} cb The callback to invoke with (err, data, res)
*/

RecSession.prototype.getYelpData = function(cb) {
  var yelpClient = new yelp.YelpClient(authConfig);
  var searchParams = {
    sort: 1,
    radius_filter: 5000,
    location: this.location
  };

  yelpClient.searchRestaurants(searchParams, function(err, data, res) {
    if (err) {
      console.error('Error - Yelp API returned: ', err);
    }

    this.yelpData = data;
    cb(err, data, res);
  }.bind(this));
};

/*
Builds the recommendation queue.

@param {callback} cb The callback to invoke with (recommendations)
*/
RecSession.prototype.buildRecommendation = function(cb){
  var subCallback = function(err, data, res){
    if(!err){
      this.lat = data.region.center.latitude;
      this.longi = data.region.center.longitude;
      this.recQueue = data.businesses;
      this.recQueue.sort(function(a, b){
        return utils.calculateScore(this.lat, this.longi, a) - utils.calculateScore(this.lat, this.longi, b);
      }.bind(this));

      for(var i=0;i<this.numRecs && this.recQueue.length > 0;i++){
        var current = this.recQueue.pop();
        var vetoed = false;
        if(this.vetoes[current.id]){
          vetoed = true;
        };
        for(var j=0;j++;j<current.categories.length){
          if(this.vetoes[current.categories[i]]){
            vetoed = true;
          }
        };
        if(!vetoed){
          this.recommendations[current.id] = current;
        }else{
          i --;
        }
      }

      cb(this.recommendations);
    }
  };

  this.getYelpData(subCallback.bind(this));
};
/*
Returns recs

@returns {object} Object of recommendations keyed by id.
*/
RecSession.prototype.getRecs = function(){
  return this.recommendations;
};
/*
Adds veto to session

@param {object} Takes command object of form {key: 'id'|'object', val: valueToVeto}
*/
RecSession.prototype.veto = function(command) {
  // Refactor using lodash later.
  this.vetoes[command.val] = true;
  if(command.key === 'id'){
    delete this.recommendations[command.val];
  }else{
    var keys = Object.keys(this.recommendations);
    for(var i=0;i<keys.length;i++){
      if(this.recommendations[keys[i]].categories[0].indexOf(command.val) > -1){
        delete this.recommendations[keys[i]];
      }
    }
  };
  for(var i=0;i<this.numRecs && this.recQueue.length > 0 && Object.keys(this.recommendations).length < this.numRecs;i++){
    var current = this.recQueue.pop();
    var vetoed = false;
    if(this.vetoes[current.id]){
      vetoed = true;
    };
    // First in array is food-related;
    for(var j=0;j++;j<current.categories[0].length){
      if(this.vetoes[current.categories[0][i]]){
        vetoed = true;
      }
    };
    if(!vetoed){
      this.recommendations[current.id] = current;
    }else{
      i --;
    }
  };

};
module.exports = RecSession;

// // (location, uid, numRecommendations)
// var testsesh = new RecSession('94103', 0, 3);
// testsesh.veto({key:'id', val:'crepes-a-go-go-san-francisco-2'});
// testsesh.buildRecommendation(function(recs){
//   console.log(Object.keys(recs))
//   testsesh.veto({key:'id', val:'so-san-francisco-4'})
//   console.log(Object.keys(testsesh.getRecs()));
//   testsesh.veto({key:'category', val:'asianfusion'})
//   console.log(Object.keys(testsesh.getRecs()));
// })
<|endoftext|>


<commit_before>// grab the things we need
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var Email = require('./email');
var Schema = mongoose.Schema;

// create a schema
var userSchema = new Schema({
	externalEmail : { type : String, default: "None"},
	internalEmail : { type : String, default: "None"},
	accountType : { type : Number, default: 0},
	passwordHash : { type : String, default : "None" },
	firstName : { type : String, default : "None" },
	lastName : { type : String, default : "None" }
});

// custom method to add string to end of name
// you can create more important methods like name validations or formatting
// you can also do queries and find similar users
userSchema.methods.authenticate = function(checkPass) {
  // add some stuff to the users name
 bcrypt.compare(checkPass, this.passwordHash, function(err, res){
 	return res;
 });
};

userSchema.methods.generateEmail = function(callback) {
	Email.findOne({"taken" : false}, function(err, email){
		if(err){
			callback(error, false);
			return;
		}
		console.log("Find email returned : ");
		console.log(email);
		console.log("Found untaken email : ");
		console.log(email.email);
		this.internalEmail = email.email;
		Email.findOneAndUpdate({email : email.email}, {taken : true}, function(err, user){
			if(err){
				throw err;
			} else {
				console.log("Saved email as being taken");
				console.log("Returned value from update : ");
				console.log(user);
				console.log("Email in inner scope is : ");
				console.log(email);
				callback(email, true);
			}
		});

	});
}

// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);

// make this available to our users in our Node applications
module.exports = User;<commit_msg>Holy mother of fuck it's getting close now<commit_after>// grab the things we need
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var Email = require('./email');
var Schema = mongoose.Schema;

// create a schema
var userSchema = new Schema({
	externalEmail : { type : String, default: "None"},
	internalEmail : { type : String, default: "None"},
	accountType : { type : Number, default: 0},
	passwordHash : { type : String, default : "None" },
	firstName : { type : String, default : "None" },
	lastName : { type : String, default : "None" }
});

// custom method to add string to end of name
// you can create more important methods like name validations or formatting
// you can also do queries and find similar users
userSchema.methods.authenticate = function(checkPass) {
  // add some stuff to the users name
 bcrypt.compare(checkPass, this.passwordHash, function(err, res){
 	return res;
 });
};

userSchema.methods.generateEmail = function(callback) {
	Email.findOne({"taken" : false}, function(err, email){
		if(err){
			callback(error, false);
			return;
		}
		console.log("Find email returned : ");
		console.log(email);
		console.log("Found untaken email : ");
		console.log(email.email);
		this.internalEmail = email.email;
		Email.findOneAndUpdate({email : email.email}, {taken : true}, function(err, user){
			if(err){
				throw err;
			} else {
				console.log("Saved email as being taken");
				console.log("Returned value from update : ");
				console.log(user);
				console.log("Email in inner scope is : ");
				console.log(email.email);
				callback(email.email, true);
			}
		});

	});
}

// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);

// make this available to our users in our Node applications
module.exports = User;<|endoftext|>


<commit_before>
/* Diego is your little diagnostics mercenary! */
let _log = require('./log')('diego')
let os = require('./os')
let spawn = require('./spawn')

let self = {
  hire: async function (opts) {
    let log = _log.bind(null, opts)

    // privacy setting: add `export DIEGO_IS_ASLEEP` to your ~/.bashrc, ~/.zshrc etc.
    // to make sure diego never looks around.
    // note that, logs don't leave your computer unless you post them yourself on the
    // issue tracker for example, but I figured it's easy for us to provide a way
    // to turn it off
    if (process.env.DIEGO_IS_ASLEEP) {
      log('diego is asleep.')
      return
    }

    log('diego here, looking around')

    let dump = async (full, re) => {
      if (typeof re === 'undefined') {
        re = /.*/
      }

      // for our purpose, no need to worry about escaping arguments.
      let args = full.split(' ')
      let command = args.shift()
      try {
        await spawn({
          command, args, ontoken: (tok) => (re.test(tok) && log(tok))
        })
      } catch (e) { log(`${command} resisted us: ${e.message || '?'}`) }
    }

    switch (os.itch_platform()) {
      case 'windows':
        await dump('cmd.exe /c ver')
        // weirdest syntax ever, `name,` and `caption,` are separate arguments...
        await dump('wmic cpu get name, caption, maxclockspeed')
        await dump('wmic path Win32_VideoController get Name')
        break
      case 'linux':
        await dump('uname -a')
        await dump('lsb_release -a')
        await dump('lspci', /VGA compatible/)
        break
      case 'osx':
        await dump('uname -a')
        await dump('sw_vers')
        await dump('system_profiler SPHardwareDataType SPDisplaysDataType')
        break
    }

    log('diego out')
  }
}

module.exports = self
<commit_msg>let diego find cpu info on linux<commit_after>
/* Diego is your little diagnostics mercenary! */
let _log = require('./log')('diego')
let os = require('./os')
let spawn = require('./spawn')

let self = {
  hire: async function (opts) {
    let log = _log.bind(null, opts)

    // privacy setting: add `export DIEGO_IS_ASLEEP` to your ~/.bashrc, ~/.zshrc etc.
    // to make sure diego never looks around.
    // note that, logs don't leave your computer unless you post them yourself on the
    // issue tracker for example, but I figured it's easy for us to provide a way
    // to turn it off
    if (process.env.DIEGO_IS_ASLEEP) {
      log('diego is asleep.')
      return
    }

    log('diego here, looking around')

    let dump = async (full, re) => {
      if (typeof re === 'undefined') {
        re = /.*/
      }

      // for our purpose, no need to worry about escaping arguments.
      let args = full.split(' ')
      let command = args.shift()
      try {
        await spawn({
          command, args, ontoken: (tok) => (re.test(tok) && log(tok))
        })
      } catch (e) { log(`"${full}" resisted us: ${e.message || '?'}`) }
    }

    switch (os.itch_platform()) {
      case 'windows':
        await dump('cmd.exe /c ver')
        // weirdest syntax ever, `name,` and `caption,` are separate arguments...
        await dump('wmic cpu get name, caption, maxclockspeed')
        await dump('wmic path Win32_VideoController get Name')
        break
      case 'linux':
        await dump('uname -a')
        await dump('cat /proc/cpuinfo', /model name/)
        await dump('lsb_release -a')
        await dump('lspci', /VGA compatible/)
        break
      case 'osx':
        await dump('uname -a')
        await dump('sw_vers')
        await dump('system_profiler SPHardwareDataType SPDisplaysDataType')
        break
    }

    log('diego out')
  }
}

module.exports = self
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import {
	StyleSheet,
	View,
	Text,
	AppState,
	TouchableHighlight,
	ScrollView,
	Image,
	ListView,
	Animated,
	RefreshControl,
	Modal,
	Component,
	Alert,
	Navigator,
	ActivityIndicator,
} from 'react-native';
import { connect } from 'react-redux';

import TopBannerView from './banner/TopBannerView';
import WelcomeModal from './WelcomeModal';
import NavigationBarWithRouteMapper from './NavigationBarWithRouteMapper';
import FeedbackView from './FeedbackView';

// Cards
import WeatherCard from './weather/WeatherCard';
import ShuttleCard from './shuttle/ShuttleCard';
import EventCard from './events/EventCard'
import QuicklinksCard from './quicklinks/QuicklinksCard'
import NewsCard from './news/NewsCard';
import DiningCard from './dining/DiningCard';
import SearchCard from './mapsearch/SearchCard';

import YesNoCard from './survey/YesNoCard';
import MultipleChoiceCard from './survey/MultipleChoiceCard';
import IntervalCard from './survey/IntervalCard';
import TextInputCard from './survey/TextInputCard';

// actions
import { updateLocation } from '../actions/location';

// Node Modules
const GoogleAPIAvailability = require('react-native-google-api-availability-bridge');

// App Settings / Util / CSS
const AppSettings = require('../AppSettings');
const css = require('../styles/css');
const general = require('../util/general');
const logger = require('../util/logger');
const shuttle = require('../util/shuttle');

// Views
const DiningDetail = require('./dining/DiningDetail');
const DiningList = require('./dining/DiningList');

var Home = React.createClass({

	copyrightYear: new Date().getFullYear(),

	getInitialState: function() {
		return {
			initialLoad: true,
			scrollEnabled: true,
			cacheMap: false,
			refreshing:false,
			updatedGoogle: true,
		}
	},

	componentWillMount: function() {
		if (general.platformAndroid()) {
			this.updateGooglePlay();
			this.setState({cacheMap: true});
		}
	},

	componentDidMount: function() {
		logger.ga('View Loaded: Home');
	},

	updateGooglePlay: function() {
		GoogleAPIAvailability.checkGooglePlayServices((result) => {
			if(result === 'update') {
				this.setState({updatedGoogle: false})
			}
		});
	},

	render: function() {
		logger.log('Home: render');
		return this.renderScene();
	},

	renderScene: function(route, navigator, index, navState) {
		return (
			<View style={css.main_container}>
				<ScrollView contentContainerStyle={css.scroll_main} refreshControl={
					<RefreshControl refreshing={this.state.refreshing} onRefresh={this._handleRefresh} tintColor='#CCC' title='' />
				}>

					{/* WELCOME MODAL */}
					<WelcomeModal />

					{/* SPECIAL TOP BANNER */}
					<TopBannerView navigator={this.props.navigator}/>

					{/* LOAD PRIMARY CARDS */}
					{ this.getCards() }

					{/* FOOTER */}
					<View style={css.footer}>
						<TouchableHighlight style={css.footer_link} underlayColor={'rgba(200,200,200,.1)'} onPress={ () => this.gotoFeedbackForm() }>
							<Text style={css.footer_about}>Feedback</Text>
						</TouchableHighlight>
						<Text style={css.footer_spacer}>|</Text>
						<TouchableHighlight style={css.footer_link}>
							<Text style={css.footer_copyright}>© {this.copyrightYear} UC Regents</Text>
						</TouchableHighlight>
					</View>

				</ScrollView>
			</View>
		);
	},

	getCards: function() {
		var cards = [];
		var cardCounter = 0;

		// Setup Cards
		if (this.props.cards['weather'].active) {
			cards.push(<WeatherCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'weather'} />);
		}
		if (this.props.cards['shuttle'].active) {
			cards.push(<ShuttleCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'shuttle'} />);
		}
		if (this.props.cards['dining'].active) {
			cards.push(<DiningCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'dining'} />);
		}
		if (this.props.cards['events'].active) {
			cards.push(<EventCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'events'} />);
		}
		if (this.props.cards['quicklinks'].active) {
			cards.push(<QuicklinksCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'quicklinks'} />);
		}
		if (this.props.cards['news'].active) {
			cards.push(<NewsCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'news'} />);
		}
		if (this.props.cards['map'].active) {
			cards.push(<SearchCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'map'} />);
		}
		return cards;
	},

	refreshAllCards: function(refreshType) {
		if (!refreshType) {
			refreshType = 'manual';
		}

		// Refresh location
		if (this.props.locationPermission === 'authorized') {
			this.props.dispatch(updateLocation());
		}

		// Refresh cards
		if (this.refs.cards) {
			this.refs.cards.forEach(c => c.refresh());
		}
	},

	gotoFeedbackForm: function() {
		this.props.navigator.push({ id: 'FeedbackView', component: FeedbackView, title: 'Feedback' });
	},

	_handleRefresh: function() {
		this.refreshAllCards('auto');
		this.setState({refreshing: false});
	}
});

function mapStateToProps(state, props) {
	return {
		cards: state.cards,
		locationPermission: state.location.permission
	};
}

module.exports = connect(mapStateToProps)(Home);
<commit_msg>Fixed some formatting<commit_after>'use strict';

import React from 'react';
import {
	StyleSheet,
	View,
	Text,
	AppState,
	TouchableHighlight,
	ScrollView,
	Image,
	ListView,
	Animated,
	RefreshControl,
	Modal,
	Component,
	Alert,
	Navigator,
	ActivityIndicator,
} from 'react-native';
import { connect } from 'react-redux';

import TopBannerView from './banner/TopBannerView';
import WelcomeModal from './WelcomeModal';
import NavigationBarWithRouteMapper from './NavigationBarWithRouteMapper';
import FeedbackView from './FeedbackView';

// Cards
import WeatherCard from './weather/WeatherCard';
import ShuttleCard from './shuttle/ShuttleCard';
import EventCard from './events/EventCard'
import QuicklinksCard from './quicklinks/QuicklinksCard'
import NewsCard from './news/NewsCard';
import DiningCard from './dining/DiningCard';
import SearchCard from './mapsearch/SearchCard';

import YesNoCard from './survey/YesNoCard';
import MultipleChoiceCard from './survey/MultipleChoiceCard';
import IntervalCard from './survey/IntervalCard';
import TextInputCard from './survey/TextInputCard';

// actions
import { updateLocation } from '../actions/location';

// Node Modules
const GoogleAPIAvailability = require('react-native-google-api-availability-bridge');

// App Settings / Util / CSS
const AppSettings = require('../AppSettings');
const css = require('../styles/css');
const general = require('../util/general');
const logger = require('../util/logger');
const shuttle = require('../util/shuttle');

// Views
const DiningDetail = require('./dining/DiningDetail');
const DiningList = require('./dining/DiningList');

var Home = React.createClass({

	copyrightYear: new Date().getFullYear(),

	getInitialState() {
		return {
			initialLoad: true,
			scrollEnabled: true,
			cacheMap: false,
			refreshing:false,
			updatedGoogle: true,
		}
	},

	componentWillMount() {
		if (general.platformAndroid()) {
			this.updateGooglePlay();
			this.setState({cacheMap: true});
		}
	},

	componentDidMount() {
		logger.ga('View Loaded: Home');
	},

	updateGooglePlay() {
		GoogleAPIAvailability.checkGooglePlayServices((result) => {
			if(result === 'update') {
				this.setState({ updatedGoogle: false });
			}
		});
	},

	render() {
		logger.log('Home: render');
		return this.renderScene();
	},

	renderScene(route, navigator, index, navState) {
		return (
			<View style={css.main_container}>
				<ScrollView contentContainerStyle={css.scroll_main} refreshControl={
					<RefreshControl refreshing={this.state.refreshing} onRefresh={this._handleRefresh} tintColor='#CCC' title='' />
				}>

					{/* WELCOME MODAL */}
					<WelcomeModal />

					{/* SPECIAL TOP BANNER */}
					<TopBannerView navigator={this.props.navigator}/>

					{/* LOAD PRIMARY CARDS */}
					{ this.getCards() }

					{/* FOOTER */}
					<View style={css.footer}>
						<TouchableHighlight style={css.footer_link} underlayColor={'rgba(200,200,200,.1)'} onPress={ () => this.gotoFeedbackForm() }>
							<Text style={css.footer_about}>Feedback</Text>
						</TouchableHighlight>
						<Text style={css.footer_spacer}>|</Text>
						<TouchableHighlight style={css.footer_link}>
							<Text style={css.footer_copyright}>© {this.copyrightYear} UC Regents</Text>
						</TouchableHighlight>
					</View>

				</ScrollView>
			</View>
		);
	},

	getCards() {
		var cards = [];
		var cardCounter = 0;

		// Setup Cards
		if (this.props.cards['weather'].active) {
			cards.push(<WeatherCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'weather'} />);
		}
		if (this.props.cards['shuttle'].active) {
			cards.push(<ShuttleCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'shuttle'} />);
		}
		if (this.props.cards['dining'].active) {
			cards.push(<DiningCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'dining'} />);
		}
		if (this.props.cards['events'].active) {
			cards.push(<EventCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'events'} />);
		}
		if (this.props.cards['quicklinks'].active) {
			cards.push(<QuicklinksCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'quicklinks'} />);
		}
		if (this.props.cards['news'].active) {
			cards.push(<NewsCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'news'} />);
		}
		if (this.props.cards['map'].active) {
			cards.push(<SearchCard navigator={this.props.navigator} ref={(c) => this.cards ? this.cards.push(c) : this.cards = [c]} key={'map'} />);
		}
		return cards;
	},

	refreshAllCards(refreshType) {
		if (!refreshType) {
			refreshType = 'manual';
		}

		// Refresh location
		if (this.props.locationPermission === 'authorized') {
			this.props.dispatch(updateLocation());
		}

		// Refresh cards
		if (this.refs.cards) {
			this.refs.cards.forEach(c => c.refresh());
		}
	},

	gotoFeedbackForm() {
		this.props.navigator.push({ id: 'FeedbackView', component: FeedbackView, title: 'Feedback' });
	},

	_handleRefresh() {
		this.refreshAllCards('auto');
		this.setState({refreshing: false});
	}
});

function mapStateToProps(state, props) {
	return {
		cards: state.cards,
		locationPermission: state.location.permission
	};
}

module.exports = connect(mapStateToProps)(Home);
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function () {
  var usedModels = {
    "AbstractDAO":true,
    "AbstractDAOView":true,
    "Action":true,
    "ActionButtonCView2":true,
    "Arg":true,
    "Calc":true,
    "foam.apps.calc.CalcSpeechView":true,
    "foam.apps.calc.CalcView":true,
    "foam.apps.calc.CalcButton":true,
    "foam.apps.calc.Fonts":true,
    "Constant":true,
    "CountExpr":true,
    "DAOController":true,
    "DAOListView":true,
    "DOMValue":true,
    "DetailView":true,
    "foam.input.touch.DragGesture":true,
    "Expr":true,
    "foam.input.touch.Gesture":true,
    "foam.input.touch.GestureManager":true,
    "foam.input.touch.GestureTarget":true,
    "foam.apps.calc.History":true,
    "foam.apps.calc.HistoryCitationView":true,
    "foam.input.touch.InputPoint": true,
    "Interface":true,
    "foam.apps.calc.MainButtonsView":true,
    "Message":true,
    "Method":true,
    "Model":true,
    "foam.apps.calc.NumberFormatter":true,
    "foam.input.touch.PinchTwistGesture":true,
    "foam.ui.layout.PositionedDOMViewTrait":true,
    "foam.ui.layout.PositionedViewTrait":true,
    "Property":true,
    "PropertyView":true,
    "Relationship":true,
    "foam.input.touch.ScrollGesture":true,
    "foam.apps.calc.SecondaryButtonsView":true,
    "SimpleValue":true,
    "foam.input.touch.TapGesture":true,
    "Template":true,
    "foam.apps.calc.TertiaryButtonsView":true,
    "foam.input.touch.TouchManager":true,
    "View":true,
    "WindowHashValue":true,
    "foam.core.bootstrap.ModelFileDAO":true,
    "foam.graphics.AbstractCViewView":true,
    "foam.graphics.ActionButtonCView":true,
    "foam.graphics.CView":true,
    "foam.graphics.CViewView":true,
    "foam.graphics.Circle":true,
    "foam.graphics.PositionedCViewView":true,
    "foam.html.Element":true,
    "foam.i18n.ChromeMessagesBuilder":true,
    "foam.i18n.ChromeMessagesExtractor":true,
    "foam.i18n.GlobalController":true,
    "foam.i18n.MessagesBuilder":true,
    "foam.i18n.Visitor":true,
    "foam.patterns.ChildTreeTrait":true,
    "foam.ui.SlidePanel":true,
    "foam.ui.Window":true,
    "foam.ui.animated.Label":true,
    "foam.ui.md.Flare":true,
    "foam.ui.md.Halo":true
  };

  var class_ = CLASS;

  GLOBAL.CLASS = function(m) {
    var id = m.package ? m.package + '.' + m.name : m.name;
    if ( usedModels[id] ) class_(m);
  };

  var aevalTemplate_ = aevalTemplate;

  GLOBAL.aevalTemplate = function(t, model) {
    return aconstant(t.code ? t.code : function() { return ''; }) ;
  };
})();
<commit_msg>Add foam.ui.FoamTagView to acalc's Opt.js optimizations.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function () {
  var usedModels = {
    "AbstractDAO":true,
    "AbstractDAOView":true,
    "Action":true,
    "ActionButtonCView2":true,
    "Arg":true,
    "Calc":true,
    "foam.apps.calc.CalcSpeechView":true,
    "foam.apps.calc.CalcView":true,
    "foam.apps.calc.CalcButton":true,
    "foam.apps.calc.Fonts":true,
    "Constant":true,
    "CountExpr":true,
    "DAOController":true,
    "DAOListView":true,
    "DOMValue":true,
    "DetailView":true,
    "foam.input.touch.DragGesture":true,
    "Expr":true,
    "foam.input.touch.Gesture":true,
    "foam.input.touch.GestureManager":true,
    "foam.input.touch.GestureTarget":true,
    "foam.apps.calc.History":true,
    "foam.apps.calc.HistoryCitationView":true,
    "foam.input.touch.InputPoint": true,
    "Interface":true,
    "foam.apps.calc.MainButtonsView":true,
    "Message":true,
    "Method":true,
    "Model":true,
    "foam.apps.calc.NumberFormatter":true,
    "foam.input.touch.PinchTwistGesture":true,
    "foam.ui.layout.PositionedDOMViewTrait":true,
    "foam.ui.layout.PositionedViewTrait":true,
    "Property":true,
    "PropertyView":true,
    "Relationship":true,
    "foam.input.touch.ScrollGesture":true,
    "foam.apps.calc.SecondaryButtonsView":true,
    "SimpleValue":true,
    "foam.input.touch.TapGesture":true,
    "Template":true,
    "foam.apps.calc.TertiaryButtonsView":true,
    "foam.input.touch.TouchManager":true,
    "View":true,
    "WindowHashValue":true,
    "foam.core.bootstrap.ModelFileDAO":true,
    "foam.graphics.AbstractCViewView":true,
    "foam.graphics.ActionButtonCView":true,
    "foam.graphics.CView":true,
    "foam.graphics.CViewView":true,
    "foam.graphics.Circle":true,
    "foam.graphics.PositionedCViewView":true,
    "foam.html.Element":true,
    "foam.i18n.ChromeMessagesBuilder":true,
    "foam.i18n.ChromeMessagesExtractor":true,
    "foam.i18n.GlobalController":true,
    "foam.i18n.MessagesBuilder":true,
    "foam.i18n.Visitor":true,
    "foam.patterns.ChildTreeTrait":true,
    "foam.ui.SlidePanel":true,
    "foam.ui.Window":true,
    "foam.ui.animated.Label":true,
    "foam.ui.md.Flare":true,
    "foam.ui.md.Halo":true,
    "foam.ui.FoamTagView":true
  };

  var class_ = CLASS;

  GLOBAL.CLASS = function(m) {
    var id = m.package ? m.package + '.' + m.name : m.name;
    if ( usedModels[id] ) class_(m);
  };

  var aevalTemplate_ = aevalTemplate;

  GLOBAL.aevalTemplate = function(t, model) {
    return aconstant(t.code ? t.code : function() { return ''; }) ;
  };
})();
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function () {
  var usedModels = {
    "ArrayProperty": true,
    "BooleanProperty": true,
    "DateProperty": true,
    "DateTimeProperty": true,
    "DocumentationProperty": true,
    "EMailProperty": true,
    "FactoryProperty": true,
    "FloatProperty": true,
    "FunctionProperty": true,
    "IntProperty": true,
    "ModelProperty": true,
    "ReferenceArrayProperty": true,
    "ReferenceProperty": true,
    "StringArrayProperty": true,
    "StringProperty": true,
    "URLProperty": true,
    "ViewFactoryProperty": true,
    "ViewProperty": true,
    "AbstractDAO":true,
    "foam.core.types.DAOProperty":true,
    "foam.dao.ProxyDAO":false,
    "foam.dao.FutureDAO":false,
    "Action":true,
    "ActionButtonCView2":true,
    "Arg":true,
    "Calc":true,
    "foam.apps.calc.CalcSpeechView":true,
    "foam.apps.calc.CalcView":true,
    "foam.apps.calc.CalcButton":true,
    "foam.apps.calc.Fonts":true,
    "Constant":true,
    "CountExpr":true,
    "DAOController":true,
    "foam.ui.DAOListView":true,
    "DOMValue":true,
    "foam.ui.DetailView":false,
    "foam.input.touch.DragGesture":true,
    "Expr":true,
    "foam.input.touch.Gesture":true,
    "foam.input.touch.GestureManager":true,
    "foam.input.touch.GestureTarget":true,
    "foam.apps.calc.History":true,
    "foam.apps.calc.HistoryCitationView":true,
    "foam.input.touch.InputPoint": true,
    "Interface":true,
    "foam.apps.calc.MainButtonsView":true,
    "Message":true,
    "Method":true,
    "Model":true,
    "foam.apps.calc.NumberFormatter":true,
    "foam.input.touch.PinchTwistGesture":true,
    "foam.ui.layout.PositionedDOMViewTrait":true,
    "foam.ui.layout.PositionedViewTrait":true,
    "Property":true,
    "foam.ui.PropertyView":true,
    "foam.ui.AsyncLoadingView":true,
    "Relationship":true,
    "foam.input.touch.ScrollGesture":true,
    "foam.apps.calc.SecondaryButtonsView":true,
    "SimpleValue":true,
    "foam.input.touch.TapGesture":true,
    "Template":true,
    "foam.apps.calc.TertiaryButtonsView":true,
    "foam.input.touch.TouchManager":true,
    "foam.ui.View":true,
    "foam.ui.SimpleView":true,
    "foam.ui.BaseView":true,
    "foam.ui.HTMLViewTrait":true,
    "foam.ui.HTMLPropertyViewTrait":true,
    "foam.ui.LeafDataView":true,
    "foam.ui.DAODataViewTrait":true,
    "foam.ui.DestructiveDataView":true,
    "foam.ui.AbstractDAOView":true,
    "foam.core.bootstrap.ModelFileDAO":true,
    "foam.graphics.AbstractCViewView":true,
    "foam.graphics.ActionButtonCView":true,
    "foam.graphics.CView":true,
    "foam.graphics.CViewView":true,
    "foam.graphics.Circle":true,
    "foam.graphics.PositionedCViewView":true,
    "foam.html.Element":true,
    "foam.i18n.IdGenerator":true,
    "foam.i18n.ChromeMessagesInjector":true,
    "foam.i18n.GlobalController":true,
    "foam.i18n.MessagesExtractor":true,
    "foam.i18n.Visitor":true,
    "foam.patterns.ChildTreeTrait":true,
    "foam.ui.SlidePanel":true,
    "foam.ui.Window":true,
    "foam.ui.animated.Label":true,
    "foam.ui.md.Flare":true,
    "foam.ui.md.Halo":true,
    "foam.ui.FoamTagView":true
  };

  var class_ = CLASS;

  GLOBAL.CLASS = function(m) {
    var id = m.package ? m.package + '.' + m.name : m.name;
    if ( usedModels[id] ) class_(m);
  };

  var aevalTemplate_ = aevalTemplate;

  GLOBAL.aevalTemplate = function(t, model) {
    return aconstant(t.code ? t.code : function() { return ''; }) ;
  };
})();
<commit_msg>Opt.js acalc changes to omit webgl<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function () {
  var usedModels = {
    "ArrayProperty": true,
    "BooleanProperty": true,
    "DateProperty": true,
    "DateTimeProperty": true,
    "DocumentationProperty": true,
    "EMailProperty": true,
    "FactoryProperty": true,
    "FloatProperty": true,
    "FunctionProperty": true,
    "IntProperty": true,
    "ModelProperty": true,
    "ReferenceArrayProperty": true,
    "ReferenceProperty": true,
    "StringArrayProperty": true,
    "StringProperty": true,
    "URLProperty": true,
    "ViewFactoryProperty": true,
    "ViewProperty": true,
    "AbstractDAO":true,
    "foam.core.types.DAOProperty":true,
    "foam.dao.ProxyDAO":false,
    "foam.dao.FutureDAO":false,
    "Action":true,
    "ActionButtonCView2":true,
    "Arg":true,
    "Calc":true,
    "foam.apps.calc.CalcSpeechView":true,
    "foam.apps.calc.CalcView":true,
    "foam.apps.calc.CalcButton":true,
    "foam.apps.calc.Fonts":true,
    "Constant":true,
    "CountExpr":true,
    "DAOController":true,
    "foam.ui.DAOListView":true,
    "DOMValue":true,
    "foam.ui.DetailView":false,
    "foam.input.touch.DragGesture":true,
    "Expr":true,
    "foam.input.touch.Gesture":true,
    "foam.input.touch.GestureManager":true,
    "foam.input.touch.GestureTarget":true,
    "foam.apps.calc.History":true,
    "foam.apps.calc.HistoryCitationView":true,
    "foam.input.touch.InputPoint": true,
    "Interface":true,
    "foam.apps.calc.MainButtonsView":true,
    "Message":true,
    "Method":true,
    "Model":true,
    "foam.apps.calc.NumberFormatter":true,
    "foam.input.touch.PinchTwistGesture":true,
    "foam.ui.layout.PositionedDOMViewTrait":true,
    "foam.ui.layout.PositionedViewTrait":true,
    "Property":true,
    "foam.ui.PropertyView":true,
    "foam.ui.AsyncLoadingView":true,
    "Relationship":true,
    "foam.input.touch.ScrollGesture":true,
    "foam.apps.calc.SecondaryButtonsView":true,
    "SimpleValue":true,
    "foam.input.touch.TapGesture":true,
    "Template":true,
    "foam.apps.calc.TertiaryButtonsView":true,
    "foam.input.touch.TouchManager":true,
    "foam.ui.View":true,
    "foam.ui.SimpleView":true,
    "foam.ui.BaseView":true,
    "foam.ui.HTMLViewTrait":true,
    "foam.ui.HTMLPropertyViewTrait":true,
    "foam.ui.LeafDataView":true,
    "foam.ui.DAODataViewTrait":true,
    "foam.ui.DestructiveDataView":true,
    "foam.ui.AbstractDAOView":true,
    "foam.core.bootstrap.ModelFileDAO":true,
    "foam.graphics.AbstractCViewView":true,
    "foam.graphics.ActionButtonCView":true,
    "foam.graphics.CView":true,
    "foam.graphics.CViewView":true,
    "foam.graphics.Circle":true,
    "foam.graphics.PositionedCViewView":true,
    "foam.graphics.webgl.CViewGLView":false,
    "foam.graphics.webgl.GLView":false,
    "foam.graphics.webgl.GLViewView":false,
    "foam.html.Element":true,
    "foam.i18n.IdGenerator":true,
    "foam.i18n.ChromeMessagesInjector":true,
    "foam.i18n.GlobalController":true,
    "foam.i18n.MessagesExtractor":true,
    "foam.i18n.Visitor":true,
    "foam.patterns.ChildTreeTrait":true,
    "foam.ui.SlidePanel":true,
    "foam.ui.Window":true,
    "foam.ui.animated.Label":true,
    "foam.ui.md.Flare":true,
    "foam.ui.md.Halo":true,
    "foam.ui.FoamTagView":true
  };

  var class_ = CLASS;

  GLOBAL.CLASS = function(m) {
    var id = m.package ? m.package + '.' + m.name : m.name;
    if ( usedModels[id] ) class_(m);
  };

  var aevalTemplate_ = aevalTemplate;

  GLOBAL.aevalTemplate = function(t, model) {
    return aconstant(t.code ? t.code : function() { return ''; }) ;
  };
})();
<|endoftext|>


<commit_before>(function (Popcorn) {

   /* Salt Popcorn plugin - as simple and essential as salt
    *
    * Adds the ability to show and hide arbitrary divs according to video timing.
    *
    * @param {Object} options
    *
    * Required parameters: start, end, target.
    *
    * start: the time in seconds when the div should be made visible
    * end: the time in seconds when the visible div should be made invisible
    * target: Is the ID of the element where whose visibility will be toggled. Display style is maintained.
    *
    * Optional parameters
    *
    *   has_reveal: "true" setting causes children elements to be progressively revealed
    *   reveal_timeout: time (in milliseconds) to delay between revealing elements. Default 100.
    *
    * Thanks to @Matt Lindeboom - github/mmlindeboom for the core approach to the progressive reveal option
    *
    * Example:
    *
    *   var p = Popcorn('#video')
    *
    *   // Simple salt
    *   .salt({
    *     start: 5, // seconds
    *     end: 15, // seconds
    *     target: 'textdiv' //id of div to show/hide
    *   })
    *
    */

  Popcorn.plugin( "salt" , {
    manifest: {
        about: {
            name: "Salt Popcorn Plugin",
            version: "0.1",
            author: "Susan E. McGregor (@susanemcg)",
            website: "github/susanemcg"
        },
        options: {
            start: {
              elem: "input",
              type: "number",
              label: "Start"
            },
            end: {
              elem: "input",
              type: "number",
              label: "End"
            },
            target: "div-id",
            has_reveal: {
              elem: "input",
              type: "string",
              label: "hasReveal"
            },
            reveal_timeout:{
              elem: "input",
              type: "number",
              label: "duration"
            }

        }
    },

    _setup : function( options ) {
        var targetDiv = Popcorn.dom.find( options.target );

        if ( targetDiv ){
          //get the div element and save a reference to it
          options._container = targetDiv;
          var targetCSS = targetDiv.currentStyle || getComputedStyle(targetDiv,null);
          //remember its original display type
          options._displayType = targetCSS.display;
          //hide it
          options._container.style.display = "none";

        }
     },

    start: function( event, options ){

      if ( options.has_reveal == "true" ) {

        //if reveal option is set, create references to div and display style...
        var revealDiv = options._container;
        var redisplayType = options._displayType;

        //because we may need to adjust them in the case of a "handText" instance
        if( ( options._container.className ).indexOf( 'handText' ) != -1 ) {
            revealDiv = options._container.children[0];
            revealCSS = revealDiv.currentStyle || getComputedStyle(revealDiv,null);
            redisplayType = revealCSS.display;

        }

        //make the main/parent container visible
        options._container.style.display = options._displayType;

        //but loop through and hide its children...
        for(var i = 0; i < revealDiv.children.length; i++){
          revealDiv.children[i].style.display = "none";
          var delay = options.reveal_timeout ? Number(options.reveal_timeout) : 100;

            //while also setting a timeout for revealing them.
            (function (elem, display_style){
              setTimeout( function () { elem.style.display = display_style;}, delay*i);
            })(revealDiv.children[i], redisplayType);
        }

      } else {

       //display div with original display type
        options._container.style.display = options._displayType;

      }
    },

    end: function( event, options ){
      //hide it when it's all over
       options._container.style.display = "none";
     },

   _teardown: function( options ) {
      var targetDiv = Popcorn.dom.find( options.target );
      if ( targetDiv ) {
        targetDiv.removeChild( options._container );
      }
    }
  });

})(Popcorn);<commit_msg>Adjusted salt plugin to better support progressive-reveal on webfonts text. Expects pipes in text to define each chunk.<commit_after>(function (Popcorn) {

   /* Salt Popcorn plugin - as simple and essential as salt
    *
    * Adds the ability to show and hide arbitrary divs according to video timing.
    *
    * @param {Object} options
    *
    * Required parameters: start, end, target.
    *
    * start: the time in seconds when the div should be made visible
    * end: the time in seconds when the visible div should be made invisible
    * target: Is the ID of the element where whose visibility will be toggled. Display style is maintained.
    *
    * Optional parameters
    *
    *   has_reveal: "true" setting causes children elements to be progressively revealed
    *   reveal_timeout: time (in milliseconds) to delay between revealing elements. Default 100.
    *
    * Thanks to @Matt Lindeboom - github/mmlindeboom for the core approach to the progressive reveal option
    *
    * Example:
    *
    *   var p = Popcorn('#video')
    *
    *   // Simple salt
    *   .salt({
    *     start: 5, // seconds
    *     end: 15, // seconds
    *     target: 'textdiv' //id of div to show/hide
    *   })
    *
    */

  Popcorn.plugin( "salt" , {
    manifest: {
        about: {
            name: "Salt Popcorn Plugin",
            version: "0.1",
            author: "Susan E. McGregor (@susanemcg)",
            website: "github/susanemcg"
        },
        options: {
            start: {
              elem: "input",
              type: "number",
              label: "Start"
            },
            end: {
              elem: "input",
              type: "number",
              label: "End"
            },
            target: "div-id",
            has_reveal: {
              elem: "input",
              type: "string",
              label: "hasReveal"
            },
            reveal_timeout:{
              elem: "input",
              type: "number",
              label: "duration"
            }

        }
    },

    _setup : function( options ) {
        var targetDiv = Popcorn.dom.find( options.target );

        if ( targetDiv ){
          //get the div element and save a reference to it
          options._container = targetDiv;
          var targetCSS = targetDiv.currentStyle || getComputedStyle(targetDiv,null);
          //remember its original display type
          options._displayType = targetCSS.display;
          //hide it
          options._container.style.display = "none";

        }
     },

    start: function( event, options ){

      if ( options.has_reveal == "true" ) {

        //if reveal option is set, create references to div and display style...
        var revealDiv = options._container;
        var redisplayType = options._displayType;

        //because we may need to adjust them in the case of a "handText" instance
        if( ( options._container.className ).indexOf( 'handText' ) != -1 ) {
            revealDiv = options._container.children[0];
            revealCSS = revealDiv.currentStyle || getComputedStyle(revealDiv,null);
            redisplayType = revealCSS.display;

        }else if( ( options._container.className ).indexOf( 'revealWrap' ) == -1 ){
        //this means we're dealing with "normal" text. segments to be revealed successively should be pipe-separated
        //we check for the "revealWrap" class in case the user rewinds. without this check, the text will
        //be "divided" twice, leaving it all jammed up together.

          var revealContents = revealDiv.textContent;
          var revealArray = revealContents.split("|");
          revealDiv.innerHTML = "";
          revealDiv.className = "revealWrap";

          for (var p=0; p<revealArray.length; p++){
            var wrapperDiv = document.createElement("div");
            wrapperDiv.className = "revealWrap";
            wrapperDiv.innerHTML = revealArray[p];
            revealDiv.appendChild(wrapperDiv);
          }

        }

        //make the main/parent container visible
        options._container.style.display = options._displayType;

        //but loop through and hide its children...
        for(var i = 0; i < revealDiv.children.length; i++){
          revealDiv.children[i].style.display = "none";
          var delay = options.reveal_timeout ? Number(options.reveal_timeout) : 100;

            //while also setting a timeout for revealing them.
            (function (elem, display_style){
              setTimeout( function () { elem.style.display = display_style;}, delay*i);
            })(revealDiv.children[i], redisplayType);
        }

      } else {

       //display div with original display type
        options._container.style.display = options._displayType;

      }
    },

    end: function( event, options ){
      //hide it when it's all over
       options._container.style.display = "none";
     },

   _teardown: function( options ) {
      var targetDiv = Popcorn.dom.find( options.target );
      if ( targetDiv ) {
        targetDiv.removeChild( options._container );
      }
    }
  });

})(Popcorn);<|endoftext|>


<commit_before>angular.module('ionic.ui.tabs', ['ionic.service.view', 'ngSanitize'])

/**
 * @description
 *
 * The Tab Controller renders a set of pages that switch based on taps
 * on a tab bar. Modelled off of UITabBarController.
 */

.run(['$ionicViewService', function($ionicViewService) {
  // set that the tabs directive should not animate when transitioning
  // to it. Instead, the children <ion-tab> directives would animate
  $ionicViewService.disableRegisterByTagName('tabs');
}])

.controller('$ionicTabs', ['$scope', '$ionicViewService', function($scope, $ionicViewService) {
  var _this = this;

  $scope.tabCount = 0;
  $scope.selectedIndex = -1;
  $scope.$enableViewRegister = false;

  angular.extend(this, ionic.controllers.TabBarController.prototype);

  ionic.controllers.TabBarController.call(this, {
    controllerChanged: function(oldC, oldI, newC, newI) {
      $scope.controllerChanged && $scope.controllerChanged({
        oldController: oldC,
        oldIndex: oldI,
        newController: newC,
        newIndex: newI
      });
    },
    tabBar: {
      tryTabSelect: function() {},
      setSelectedItem: function(index) {},
      addItem: function(item) {}
    }
  });

  this.add = function(tabScope) {
    tabScope.tabIndex = $scope.tabCount;
    this.addController(tabScope);
    if(tabScope.tabIndex === 0) {
      this.select(0);
    }
    $scope.tabCount++;
  };

  function controllerByTabIndex(tabIndex) {
    for (var x=0; x<_this.controllers.length; x++) {
      if (_this.controllers[x].tabIndex === tabIndex) {
        return _this.controllers[x];
      }
    }
  }

  this.select = function(tabIndex, emitChange) {
    if(tabIndex !== $scope.selectedIndex) {

      $scope.selectedIndex = tabIndex;
      $scope.activeAnimation = $scope.animation;
      _this.selectController(tabIndex);

      var viewData = {
        type: 'tab',
        typeIndex: tabIndex
      };

      var tabController = controllerByTabIndex(tabIndex);
      if (tabController) {
        viewData.title = tabController.title;
        viewData.historyId = tabController.$historyId;
        viewData.url = tabController.url;
        viewData.uiSref = tabController.viewSref;
        viewData.navViewName = tabController.navViewName;
        viewData.hasNavView = tabController.hasNavView;
      }

      if(emitChange) {
        $scope.$emit('viewState.changeHistory', viewData);
      }
    } else if(emitChange) {
      var currentView = $ionicViewService.getCurrentView();
      if (currentView) {
        $ionicViewService.goToHistoryRoot(currentView.historyId);
      }
    }
  };

  $scope.controllers = this.controllers;

  $scope.tabsController = this;

}])

.directive('ionTabs', ['$ionicViewService', function($ionicViewService) {
  return {
    restrict: 'E',
    replace: true,
    scope: true,
    transclude: true,
    controller: '$ionicTabs',
    template: '
<ion-tab-controller-bar></ion-tab-controller-bar>
',
    compile: function(element, attr, transclude, tabsCtrl) {
      return function link($scope, $element, $attr) {

        var tabs = $element[0].querySelector('.tabs');

        $scope.tabsType = $attr.tabsType || 'tabs-positive';
        $scope.tabsStyle = $attr.tabsStyle;
        $scope.animation = $attr.animation;

        $scope.animateNav = $scope.$eval($attr.animateNav);
        if($scope.animateNav !== false) {
          $scope.animateNav = true;
        }

        $attr.$observe('tabsStyle', function(val) {
          if(tabs) {
            angular.element(tabs).addClass($attr.tabsStyle);
          }
        });

        $attr.$observe('tabsType', function(val) {
          if(tabs) {
            angular.element(tabs).addClass($attr.tabsType);
          }
        });

        $scope.$watch('activeAnimation', function(value) {
          $element.addClass($scope.activeAnimation);
        });
        transclude($scope, function(cloned) {
          $element.prepend(cloned);
        });

      };
    }
  };
}])

// Generic controller directive
.directive('ionTab', ['$ionicViewService', '$rootScope', '$parse', '$interpolate', function($ionicViewService, $rootScope, $parse, $interpolate) {
  return {
    restrict: 'E',
    require: '^ionTabs',
    scope: true,
    transclude: 'element',
    compile: function(element, attr, transclude) {

      return function link($scope, $element, $attr, tabsCtrl) {
        var childScope, childElement;

        $ionicViewService.registerHistory($scope);

        $scope.title = $attr.title;
        $scope.icon = $attr.icon;
        $scope.iconOn = $attr.iconOn;
        $scope.iconOff = $attr.iconOff;
        $scope.viewSref = $attr.uiSref;
        $scope.url = $attr.href;
        if($scope.url && $scope.url.indexOf('#') === 0) {
          $scope.url = $scope.url.replace('#', '');
        }

        // Should we hide a back button when this tab is shown
        $scope.hideBackButton = $scope.$eval($attr.hideBackButton);

        if($scope.hideBackButton !== true) {
          $scope.hideBackButton = false;
        }

        // Whether we should animate on tab change, also impacts whether we
        // tell any parent nav controller to animate
        $scope.animate = $scope.$eval($attr.animate);

        var badgeGet = $parse($attr.badge);
        $scope.$watch(badgeGet, function(value) {
          $scope.badge = value;
        });

        $attr.$observe('badgeStyle', function(value) {
          $scope.badgeStyle = value;
        });

        var leftButtonsGet = $parse($attr.leftButtons);
        $scope.$watch(leftButtonsGet, function(value) {
          $scope.leftButtons = value;
          if($scope.doesUpdateNavRouter) {
            $scope.$emit('viewState.leftButtonsChanged', $scope.rightButtons);
          }
        });

        var rightButtonsGet = $parse($attr.rightButtons);
        $scope.$watch(rightButtonsGet, function(value) {
          $scope.rightButtons = value;
        });

        tabsCtrl.add($scope);

        function cleanupChild() {
          if(childElement) {
            childElement.remove();
            childElement = null;
          }
          if(childScope) {
            childScope.$destroy();
            childScope = null;
          }
        }

        $scope.$watch('isVisible', function(value) {
          if (value) {
            cleanupChild();
            childScope = $scope.$new();
            transclude(childScope, function(clone) {
              clone.addClass('view');
              clone.removeAttr('title');
              childElement = clone;
              $element.parent().append(childElement);
            });
            $scope.$broadcast('tab.shown');
          } else if (childScope) {
            $scope.$broadcast('tab.hidden');
            cleanupChild();
          }
        });

        // on link, check if it has a nav-view in it
        transclude($scope.$new(), function(clone) {
          var navViewEle = clone[0].getElementsByTagName("ion-nav-view");
          $scope.hasNavView = (navViewEle.length > 0);
          if($scope.hasNavView) {
            // this tab has a ui-view
            $scope.navViewName = navViewEle[0].getAttribute('name');
            if( $ionicViewService.isCurrentStateNavView( $scope.navViewName ) ) {
              // this tab's ui-view is the current one, go to it!
              tabsCtrl.select($scope.tabIndex);
            }
          }
        });

        var unregister = $rootScope.$on('$stateChangeSuccess', function(value){
          if( $ionicViewService.isCurrentStateNavView($scope.navViewName) &&
              $scope.tabIndex !== tabsCtrl.selectedIndex) {
            tabsCtrl.select($scope.tabIndex);
          }
        });

        $scope.$on('$destroy', unregister);

      };
    }
  };
}])

.directive('ionTabControllerBar', function() {
  return {
    restrict: 'E',
    require: '^ionTabs',
    transclude: true,
    replace: true,
    scope: true,
    template: '
' +
      '<ion-tab-controller-item icon-title="{{c.title}}" icon="{{c.icon}}" icon-on="{{c.iconOn}}" icon-off="{{c.iconOff}}" badge="c.badge" badge-style="c.badgeStyle" active="c.isVisible" index="$index" ng-repeat="c in controllers"></ion-tab-controller-item>' +
    '
',
    link: function($scope, $element, $attr, tabsCtrl) {
      $element.addClass($scope.tabsType);
      $element.addClass($scope.tabsStyle);
    }
  };
})

.directive('ionTabControllerItem', ['$window', function($window) {
  return {
    restrict: 'E',
    replace: true,
    require: '^ionTabs',
    scope: {
      iconTitle: '@',
      icon: '@',
      iconOn: '@',
      iconOff: '@',
      badge: '=',
      badgeStyle: '=',
      active: '=',
      tabSelected: '@',
      index: '='
    },
    link: function(scope, element, attrs, tabsCtrl) {
      if(attrs.icon) {
        scope.iconOn = scope.iconOff = attrs.icon;
      }

      scope.selectTab = function() {
        tabsCtrl.select(scope.index, true);
      };
    },
    template:
      '' +
        '{{badge}}' +
        '' +
        '' +
        '' +
        '' +
      ''
  };
}]);

<commit_msg>fix iconOn/iconOff showing in tabs<commit_after>angular.module('ionic.ui.tabs', ['ionic.service.view', 'ngSanitize'])

/**
 * @description
 *
 * The Tab Controller renders a set of pages that switch based on taps
 * on a tab bar. Modelled off of UITabBarController.
 */

.run(['$ionicViewService', function($ionicViewService) {
  // set that the tabs directive should not animate when transitioning
  // to it. Instead, the children <ion-tab> directives would animate
  $ionicViewService.disableRegisterByTagName('tabs');
}])

.controller('$ionicTabs', ['$scope', '$ionicViewService', function($scope, $ionicViewService) {
  var _this = this;

  $scope.tabCount = 0;
  $scope.selectedIndex = -1;
  $scope.$enableViewRegister = false;

  angular.extend(this, ionic.controllers.TabBarController.prototype);

  ionic.controllers.TabBarController.call(this, {
    controllerChanged: function(oldC, oldI, newC, newI) {
      $scope.controllerChanged && $scope.controllerChanged({
        oldController: oldC,
        oldIndex: oldI,
        newController: newC,
        newIndex: newI
      });
    },
    tabBar: {
      tryTabSelect: function() {},
      setSelectedItem: function(index) {},
      addItem: function(item) {}
    }
  });

  this.add = function(tabScope) {
    tabScope.tabIndex = $scope.tabCount;
    this.addController(tabScope);
    if(tabScope.tabIndex === 0) {
      this.select(0);
    }
    $scope.tabCount++;
  };

  function controllerByTabIndex(tabIndex) {
    for (var x=0; x<_this.controllers.length; x++) {
      if (_this.controllers[x].tabIndex === tabIndex) {
        return _this.controllers[x];
      }
    }
  }

  this.select = function(tabIndex, emitChange) {
    if(tabIndex !== $scope.selectedIndex) {

      $scope.selectedIndex = tabIndex;
      $scope.activeAnimation = $scope.animation;
      _this.selectController(tabIndex);

      var viewData = {
        type: 'tab',
        typeIndex: tabIndex
      };

      var tabController = controllerByTabIndex(tabIndex);
      if (tabController) {
        viewData.title = tabController.title;
        viewData.historyId = tabController.$historyId;
        viewData.url = tabController.url;
        viewData.uiSref = tabController.viewSref;
        viewData.navViewName = tabController.navViewName;
        viewData.hasNavView = tabController.hasNavView;
      }

      if(emitChange) {
        $scope.$emit('viewState.changeHistory', viewData);
      }
    } else if(emitChange) {
      var currentView = $ionicViewService.getCurrentView();
      if (currentView) {
        $ionicViewService.goToHistoryRoot(currentView.historyId);
      }
    }
  };

  $scope.controllers = this.controllers;

  $scope.tabsController = this;

}])

.directive('ionTabs', ['$ionicViewService', function($ionicViewService) {
  return {
    restrict: 'E',
    replace: true,
    scope: true,
    transclude: true,
    controller: '$ionicTabs',
    template: '
<ion-tab-controller-bar></ion-tab-controller-bar>
',
    compile: function(element, attr, transclude, tabsCtrl) {
      return function link($scope, $element, $attr) {

        var tabs = $element[0].querySelector('.tabs');

        $scope.tabsType = $attr.tabsType || 'tabs-positive';
        $scope.tabsStyle = $attr.tabsStyle;
        $scope.animation = $attr.animation;

        $scope.animateNav = $scope.$eval($attr.animateNav);
        if($scope.animateNav !== false) {
          $scope.animateNav = true;
        }

        $attr.$observe('tabsStyle', function(val) {
          if(tabs) {
            angular.element(tabs).addClass($attr.tabsStyle);
          }
        });

        $attr.$observe('tabsType', function(val) {
          if(tabs) {
            angular.element(tabs).addClass($attr.tabsType);
          }
        });

        $scope.$watch('activeAnimation', function(value) {
          $element.addClass($scope.activeAnimation);
        });
        transclude($scope, function(cloned) {
          $element.prepend(cloned);
        });

      };
    }
  };
}])

// Generic controller directive
.directive('ionTab', ['$ionicViewService', '$rootScope', '$parse', '$interpolate', function($ionicViewService, $rootScope, $parse, $interpolate) {
  return {
    restrict: 'E',
    require: '^ionTabs',
    scope: true,
    transclude: 'element',
    compile: function(element, attr, transclude) {

      return function link($scope, $element, $attr, tabsCtrl) {
        var childScope, childElement;

        $ionicViewService.registerHistory($scope);

        $scope.title = $attr.title;
        $scope.icon = $attr.icon;
        $scope.iconOn = $attr.iconOn;
        $scope.iconOff = $attr.iconOff;
        $scope.viewSref = $attr.uiSref;
        $scope.url = $attr.href;
        if($scope.url && $scope.url.indexOf('#') === 0) {
          $scope.url = $scope.url.replace('#', '');
        }

        // Should we hide a back button when this tab is shown
        $scope.hideBackButton = $scope.$eval($attr.hideBackButton);

        if($scope.hideBackButton !== true) {
          $scope.hideBackButton = false;
        }

        // Whether we should animate on tab change, also impacts whether we
        // tell any parent nav controller to animate
        $scope.animate = $scope.$eval($attr.animate);

        var badgeGet = $parse($attr.badge);
        $scope.$watch(badgeGet, function(value) {
          $scope.badge = value;
        });

        $attr.$observe('badgeStyle', function(value) {
          $scope.badgeStyle = value;
        });

        var leftButtonsGet = $parse($attr.leftButtons);
        $scope.$watch(leftButtonsGet, function(value) {
          $scope.leftButtons = value;
          if($scope.doesUpdateNavRouter) {
            $scope.$emit('viewState.leftButtonsChanged', $scope.rightButtons);
          }
        });

        var rightButtonsGet = $parse($attr.rightButtons);
        $scope.$watch(rightButtonsGet, function(value) {
          $scope.rightButtons = value;
        });

        tabsCtrl.add($scope);

        function cleanupChild() {
          if(childElement) {
            childElement.remove();
            childElement = null;
          }
          if(childScope) {
            childScope.$destroy();
            childScope = null;
          }
        }

        $scope.$watch('isVisible', function(value) {
          if (value) {
            cleanupChild();
            childScope = $scope.$new();
            transclude(childScope, function(clone) {
              clone.addClass('view');
              clone.removeAttr('title');
              childElement = clone;
              $element.parent().append(childElement);
            });
            $scope.$broadcast('tab.shown');
          } else if (childScope) {
            $scope.$broadcast('tab.hidden');
            cleanupChild();
          }
        });

        // on link, check if it has a nav-view in it
        transclude($scope.$new(), function(clone) {
          var navViewEle = clone[0].getElementsByTagName("ion-nav-view");
          $scope.hasNavView = (navViewEle.length > 0);
          if($scope.hasNavView) {
            // this tab has a ui-view
            $scope.navViewName = navViewEle[0].getAttribute('name');
            if( $ionicViewService.isCurrentStateNavView( $scope.navViewName ) ) {
              // this tab's ui-view is the current one, go to it!
              tabsCtrl.select($scope.tabIndex);
            }
          }
        });

        var unregister = $rootScope.$on('$stateChangeSuccess', function(value){
          if( $ionicViewService.isCurrentStateNavView($scope.navViewName) &&
              $scope.tabIndex !== tabsCtrl.selectedIndex) {
            tabsCtrl.select($scope.tabIndex);
          }
        });

        $scope.$on('$destroy', unregister);

      };
    }
  };
}])

.directive('ionTabControllerBar', function() {
  return {
    restrict: 'E',
    require: '^ionTabs',
    transclude: true,
    replace: true,
    scope: true,
    template: '
' +
      '<ion-tab-controller-item icon-title="{{c.title}}" icon="{{c.icon}}" icon-on="{{c.iconOn}}" icon-off="{{c.iconOff}}" badge="c.badge" badge-style="c.badgeStyle" active="c.isVisible" index="$index" ng-repeat="c in controllers"></ion-tab-controller-item>' +
    '
',
    link: function($scope, $element, $attr, tabsCtrl) {
      $element.addClass($scope.tabsType);
      $element.addClass($scope.tabsStyle);
    }
  };
})

.directive('ionTabControllerItem', ['$window', function($window) {
  return {
    restrict: 'E',
    replace: true,
    require: '^ionTabs',
    scope: {
      iconTitle: '@',
      icon: '@',
      iconOn: '@',
      iconOff: '@',
      badge: '=',
      badgeStyle: '=',
      active: '=',
      tabSelected: '@',
      index: '='
    },
    link: function(scope, element, attrs, tabsCtrl) {
      if(attrs.icon) {
        scope.iconOn = scope.iconOff = attrs.icon;
      }

      scope.selectTab = function() {
        tabsCtrl.select(scope.index, true);
      };
    },
    template:
      '' +
        '{{badge}}' +
        '' +
        '' +
        '' +
        '' +
      ''
  };
}]);

<|endoftext|>


<commit_before>import $ from 'jquery';
import _ from 'underscore';
import moment from 'moment';
import twemoji from 'twemoji';
import { capitalize } from '../../../utils/string';
import { setTimeagoInterval } from '../../../utils/';
import app from '../../../app';
import loadTemplate from '../../../utils/loadTemplate';
import BaseVw from '../../baseVw';

export default class extends BaseVw {
  constructor(options = {}) {
    if (!options.model) {
      throw new Error('Please provide a model.');
    }

    super({
      ...options,
      initialState: {
        showAvatar: true,
        showTimestampLine: true,
        showAsRead: false,
        ...options.initialState,
      },
    });

    this.listenTo(this.model, 'change', () => this.render());
    this.timeAgoInterval = setTimeagoInterval(this.model.get('timestamp'), () => {
      const timeAgo = moment(this.model.get('timestamp')).fromNow();
      if (timeAgo !== this.renderedTimeAgo) this.render();
    });
  }

  className() {
    return 'convoMessage';
  }

  remove() {
    this.timeAgoInterval.cancel();
    super.remove();
  }

  render() {
    let message = this.model.get('message');

    // Give any links the emphasis color.
    const $msgHtml = $(`<div>${message}</div>`);

    $msgHtml.find('a')
      .addClass('clrTEm');

    // Convert any unicode emoji characters to images via Twemoji
    message = twemoji.parse($msgHtml.html(),
      icon => (`../imgs/emojis/72X72/${icon}.png`));

    loadTemplate('modals/orderDetail/convoMessage.html', (t) => {
      this.$el.html(t({
        ...this.model.toJSON(),
        ...this._state,
        moment,
        message,
        capitalize,
        ownGuid: app.profile.id,
      }));
    });

    return this;
  }
}
<commit_msg>lint fix<commit_after>import $ from 'jquery';
import moment from 'moment';
import twemoji from 'twemoji';
import { capitalize } from '../../../utils/string';
import { setTimeagoInterval } from '../../../utils/';
import app from '../../../app';
import loadTemplate from '../../../utils/loadTemplate';
import BaseVw from '../../baseVw';

export default class extends BaseVw {
  constructor(options = {}) {
    if (!options.model) {
      throw new Error('Please provide a model.');
    }

    super({
      ...options,
      initialState: {
        showAvatar: true,
        showTimestampLine: true,
        showAsRead: false,
        ...options.initialState,
      },
    });

    this.listenTo(this.model, 'change', () => this.render());
    this.timeAgoInterval = setTimeagoInterval(this.model.get('timestamp'), () => {
      const timeAgo = moment(this.model.get('timestamp')).fromNow();
      if (timeAgo !== this.renderedTimeAgo) this.render();
    });
  }

  className() {
    return 'convoMessage';
  }

  remove() {
    this.timeAgoInterval.cancel();
    super.remove();
  }

  render() {
    let message = this.model.get('message');

    // Give any links the emphasis color.
    const $msgHtml = $(`<div>${message}</div>`);

    $msgHtml.find('a')
      .addClass('clrTEm');

    // Convert any unicode emoji characters to images via Twemoji
    message = twemoji.parse($msgHtml.html(),
      icon => (`../imgs/emojis/72X72/${icon}.png`));

    loadTemplate('modals/orderDetail/convoMessage.html', (t) => {
      this.$el.html(t({
        ...this.model.toJSON(),
        ...this._state,
        moment,
        message,
        capitalize,
        ownGuid: app.profile.id,
      }));
    });

    return this;
  }
}
<|endoftext|>


<commit_before>import {BrowserWindow, app, globalShortcut} from 'electron'
import {showDevTools, skipSecondaryDevtools} from '../shared/local-debug.desktop'

let devToolsState = showDevTools

function setupDevToolsExtensions () {
  if (__DEV__ && process.env.KEYBASE_LOCAL_DEBUG) {
    if (process.env.KEYBASE_DEV_TOOL_EXTENSIONS) {
      process.env.KEYBASE_DEV_TOOL_EXTENSIONS.split(',').forEach(p => {
        BrowserWindow.addDevToolsExtension(p)
      })
    }
  }
}

function setupOpenDevtools () {
  globalShortcut.register('CommandOrControl+Alt+k+b', () => {
    devToolsState = !devToolsState
    BrowserWindow.getAllWindows().map(bw => {
      if (devToolsState) {
        bw.webContents.openDevTools()
      } else {
        bw.webContents.closeDevTools()
      }
    })
  })
}

function cleanupOpenDevtools () {
  globalShortcut.unregister('CommandOrControl+Alt+k+b')
}

export default function () {
  app.on('ready', () => {
    setupDevToolsExtensions()
    setupOpenDevtools()
  })

  app.on('will-quit', () => {
    cleanupOpenDevtools()
  })

  if (showDevTools) {
    app.on('browser-window-created', (e, win) => {
      win = win || BrowserWindow.getFocusedWindow()

      if (win) {
        win.webContents.addListener('did-navigate', () => {
          if (!skipSecondaryDevtools || win.webContents.getURL().indexOf('renderer/index.html') !== -1) {
            win.openDevTools()
          }
        })
      }
    })
  }
}
<commit_msg>Don't compare for each window, just once beforehand<commit_after>import {BrowserWindow, app, globalShortcut} from 'electron'
import {showDevTools, skipSecondaryDevtools} from '../shared/local-debug.desktop'

let devToolsState = showDevTools

function setupDevToolsExtensions () {
  if (__DEV__ && process.env.KEYBASE_LOCAL_DEBUG) {
    if (process.env.KEYBASE_DEV_TOOL_EXTENSIONS) {
      process.env.KEYBASE_DEV_TOOL_EXTENSIONS.split(',').forEach(p => {
        BrowserWindow.addDevToolsExtension(p)
      })
    }
  }
}

function setupOpenDevtools () {
  globalShortcut.register('CommandOrControl+Alt+k+b', () => {
    devToolsState = !devToolsState
    if (devToolsState) {
      BrowserWindow.getAllWindows().map(bw => bw.webContents.openDevTools())
    } else {
      BrowserWindow.getAllWindows().map(bw => bw.webContents.closeDevTools())
    })
  })
}

function cleanupOpenDevtools () {
  globalShortcut.unregister('CommandOrControl+Alt+k+b')
}

export default function () {
  app.on('ready', () => {
    setupDevToolsExtensions()
    setupOpenDevtools()
  })

  app.on('will-quit', () => {
    cleanupOpenDevtools()
  })

  if (showDevTools) {
    app.on('browser-window-created', (e, win) => {
      win = win || BrowserWindow.getFocusedWindow()

      if (win) {
        win.webContents.addListener('did-navigate', () => {
          if (!skipSecondaryDevtools || win.webContents.getURL().indexOf('renderer/index.html') !== -1) {
            win.openDevTools()
          }
        })
      }
    })
  }
}
<|endoftext|>


<commit_before>import React from "react";
import { Case } from "../src/containers/Case/Case";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import getMuiTheme from "material-ui/styles/getMuiTheme";
const muiTheme = getMuiTheme({});
import { mountWithIntl } from "../src/helpers/intl-enzyme-test-helper.js";
import caseData from "./case_data.json";
import intlProps from "../src/helpers/intl-props-test-helper.js";
import afterPromises from "../src/helpers/afterPromises";

let fetchMock = require("fetch-mock");

fetchMock.get(
  process.env.REACT_APP_API_URL + "/case/123",
  JSON.stringify({ data: caseData })
);
fetchMock.get(
  "https://d3im063erkq9w4.cloudfront.net/Italy.svg",
  JSON.stringify({ data: caseData })
);

function setup() {
  const props = {
    intl: intlProps,
    params: { nodeID: 123 }
  };

  const enzymeWrapper = mountWithIntl(
    <MuiThemeProvider muiTheme={muiTheme}>
      <Case {...props} />
    </MuiThemeProvider>
  );
  return {
    props,
    enzymeWrapper
  };
}

describe("containers", () => {
  describe("Case", () => {
    it("should render proper data for case", function(done) {
      const { enzymeWrapper } = setup();
      afterPromises(done, () => {
        // console.error(enzymeWrapper.debug());
        expect(enzymeWrapper.find(".sub-heading").length).toBe(1);
        expect(enzymeWrapper.find("h2.case-title").text()).toBe(
          "Agenda 21 Locale (Province of Forli-Cesena, Italy)"
        );
      });
    });
  });
});
<commit_msg>factor out env var for less brittle tests<commit_after>import React from "react";
import { Case } from "../src/containers/Case/Case";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import getMuiTheme from "material-ui/styles/getMuiTheme";
const muiTheme = getMuiTheme({});
import { mountWithIntl } from "../src/helpers/intl-enzyme-test-helper.js";
import caseData from "./case_data.json";
import intlProps from "../src/helpers/intl-props-test-helper.js";
import afterPromises from "../src/helpers/afterPromises";

let fetchMock = require("fetch-mock");

fetchMock.get(
  process.env.REACT_APP_API_URL + "/case/123",
  JSON.stringify({ data: caseData })
);
fetchMock.get(
  process.env.REACT_APP_ASSETS_URL + "Italy.svg",
  JSON.stringify({ data: caseData })
);

function setup() {
  const props = {
    intl: intlProps,
    params: { nodeID: 123 }
  };

  const enzymeWrapper = mountWithIntl(
    <MuiThemeProvider muiTheme={muiTheme}>
      <Case {...props} />
    </MuiThemeProvider>
  );
  return {
    props,
    enzymeWrapper
  };
}

describe("containers", () => {
  describe("Case", () => {
    it("should render proper data for case", function(done) {
      const { enzymeWrapper } = setup();
      afterPromises(done, () => {
        // console.error(enzymeWrapper.debug());
        expect(enzymeWrapper.find(".sub-heading").length).toBe(1);
        expect(enzymeWrapper.find("h2.case-title").text()).toBe(
          "Agenda 21 Locale (Province of Forli-Cesena, Italy)"
        );
      });
    });
  });
});
<|endoftext|>