<commit_before>const slapp = require('./slapp.js').get();
const verbose = require('./verbose.js');
var kv = require('beepboop-persist')();

// Simple logging function
function _(obj){
  var str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
  console.log(str);
}

var current_help_text = verbose.HELP_TEXT;
var current_welcome_text = verbose.WELCOME_TEXT;

/**
 * This function initializes the bot messages
 */
function init(){
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:'help.md',
    },
    function(err,res){
    	if (!err) {
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        current_help_text = fileBody;
      }
      else{
        current_help_text = verbose.HELP_TEXT;
      }
  });
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:'welcome.md',
    },
    function(err,res){
      if (!err) {
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        current_welcome_text = fileBody;
      }
      else {
        current_welcome_text=verbose.WELCOME_TEXT;
      }
  });
}
  // kv.get("msgHelp",function(err,result){
  //   if(err){
  //     _("error while loading help message from the kv");
  //     current_help_text = verbose.HELP_TEXT;
  //   }
  //   else if(result)
  //     current_help_text = result;
  //   else{
  //     current_help_text = verbose.HELP_TEXT;
  //   }
  // });
  // kv.get("msgWelcome",function(err,result){
  //   if(err){
  //     _("error while loading welcome message from the kv");
  //     current_welcome_text = verbose.WELCOME_TEXT;
  //   }
  //   else if(result)
  //     current_welcome_text = result;
  //   else{
  //     current_welcome_text = verbose.WELCOME_TEXT;
  //   }
  // });
}

//Behaviour of the bot when he is mentioned or mesages with DM
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(current_help_text)
});

// response to the user joining the slack team
slapp.event('team_join', (msg) => {
  slapp.client.im.open({ token: msg.meta.bot_token,  user: msg.body.event.user.id }, (err, data) => {
    msg.say({ channel: data.channel.id, text:current_welcome_text })
  })
})
// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'Anytime :full_moon_with_face:'
  ])
})

// Catch every direct message to the bot and answer it with the help text
slapp.message('.*','direct_message', (msg) => {
  msg.say(current_help_text);
})
// Catch every message mentioning the bot and answer it with the help text
slapp.message('.*', 'direct_mention', (msg) => {
  slapp.client.im.open({ token: msg.meta.bot_token,  user: msg.body.event.user }, (err, data) => {
    msg.say({ channel: data.channel.id, text:current_help_text})
  })
})
// Handler of the slash command
slapp.command('/messages','(.*)', (msg, text, value)  => {
  slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.user_id}, (err, data) => {
    if( data.user.is_admin){
      _("text")
      _(text)
      var strtokens = text.split(" ");
      var cmd = strtokens[0];
      var val = text.replace(cmd+' ','');
      _("val")
      _(val)
      if(!text)
        msg.respond("Options for /messages: \n" +
                "\`printHelp\` prints the current help message.\n" +
                "\`printWelcome\` prints the current welcome message.\n" +
                "\`setHelp [ARG]\`  sets [ARG] as the new help message.\n" +
                "\`setWelcome [ARG]\` sets [ARG] as the new welcome message.\n" +
                "\`defaultHelp \`  sets the help message to the default value.\n" +
                "\`defaultWelcome \` sets the welcome message to the default value.\n"
              );
      else if(cmd == 'printHelp')
        printHelp(msg);
      else if(cmd == 'printWelcome')
        printWelcome(msg);
      else if(cmd == 'setHelp')
        setHelp(msg,val);
      else if(cmd == 'setWelcome')
        setWelcome(msg,val);
      else if(cmd == 'defaultHelp')
        defaultHelp(msg);
      else if(cmd == 'defaultWelcome')
        defaultWelcome(msg);
      else
        msg.respond("Please use /messages to print the available options.");
    }
    else {
      msg.respond("Sorry, you're not an admin.");
    }
  })
})
/**
 * Prints the current help message
 * @param {object} msg the slash command message sent by slapp
 */
function printHelp(msg){
  msg.respond(current_help_text);
}
/**
 * Prints the current welcome message
 * @param {object} msg the slash command message sent by slapp
 */
function printWelcome(msg){
  msg.respond(current_welcome_text);
}
/**
 * Sets the current help message to the default one
 * @param {object} msg the slash command message sent by slapp
 * @param {object} val the value sent with the command
 */
function setHelp(msg,val){
  current_help_text = val;
  msg.respond("New help message set");
  kv.set("msgHelp",val,function(err){
    if(err){
      _("error setting msgHelp in the kv");
      _(err);
      }
  });
}
/**
 * Sets the current welcome message to the default one
 * @param {object} msg the slash command message sent by slapp
 * @param {object} val the value sent with the command
 */
function setWelcome(msg,val){
  msg.respond("New welcome message set");
  current_welcome_text = val;
  kv.set("msgWelcome",val,function(err){
    if(err){
      _("error setting msgWelcome in the kv");
      _(err);
      }
  });
}
/**
 * Sets the current help message to the default one
 * @param {object} msg the slash command message sent by slapp
 */
function defaultHelp(msg){

  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:'help.md',
    },
    function(err,res){
    	if (!err) {
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        current_help_text = fileBody;
        msg.respond("Help set to Default from the github file");
      }
      else{
        current_help_text = verbose.HELP_TEXT;
        msg.respond("Coudn't read from github. Help set to default from the hard-coded string");
      }
  });
}
/**
 * Sets the current welcome message to the default one
 * @param {object} msg the slash command message sent by slapp
 */
function defaultWelcome(msg){
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:'welcome.md',
    },
    function(err,res){
      if (!err) {
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        current_welcome_text = fileBody;
        msg.respond("Welcome set to Default from the github file");
      }
      else {
        current_welcome_text=verbose.WELCOME_TEXT;
        msg.respond("Coudn't read from github. Welcome set to default from the hard-coded string");
      }
  });
}
module.exports = {
  init:init
}
<commit_msg>bracket fix<commit_after>const slapp = require('./slapp.js').get();
const verbose = require('./verbose.js');
var kv = require('beepboop-persist')();

// Simple logging function
function _(obj){
  var str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
  console.log(str);
}

var current_help_text = verbose.HELP_TEXT;
var current_welcome_text = verbose.WELCOME_TEXT;

/**
 * This function initializes the bot messages
 */
function init(){
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:'help.md',
    },
    function(err,res){
    	if (!err) {
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        current_help_text = fileBody;
      }
      else{
        current_help_text = verbose.HELP_TEXT;
      }
  });
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:'welcome.md',
    },
    function(err,res){
      if (!err) {
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        current_welcome_text = fileBody;
      }
      else {
        current_welcome_text=verbose.WELCOME_TEXT;
      }
  });
}
  // kv.get("msgHelp",function(err,result){
  //   if(err){
  //     _("error while loading help message from the kv");
  //     current_help_text = verbose.HELP_TEXT;
  //   }
  //   else if(result)
  //     current_help_text = result;
  //   else{
  //     current_help_text = verbose.HELP_TEXT;
  //   }
  // });
  // kv.get("msgWelcome",function(err,result){
  //   if(err){
  //     _("error while loading welcome message from the kv");
  //     current_welcome_text = verbose.WELCOME_TEXT;
  //   }
  //   else if(result)
  //     current_welcome_text = result;
  //   else{
  //     current_welcome_text = verbose.WELCOME_TEXT;
  //   }
  // });
//}

//Behaviour of the bot when he is mentioned or mesages with DM
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(current_help_text)
});

// response to the user joining the slack team
slapp.event('team_join', (msg) => {
  slapp.client.im.open({ token: msg.meta.bot_token,  user: msg.body.event.user.id }, (err, data) => {
    msg.say({ channel: data.channel.id, text:current_welcome_text })
  })
})
// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'Anytime :full_moon_with_face:'
  ])
})

// Catch every direct message to the bot and answer it with the help text
slapp.message('.*','direct_message', (msg) => {
  msg.say(current_help_text);
})
// Catch every message mentioning the bot and answer it with the help text
slapp.message('.*', 'direct_mention', (msg) => {
  slapp.client.im.open({ token: msg.meta.bot_token,  user: msg.body.event.user }, (err, data) => {
    msg.say({ channel: data.channel.id, text:current_help_text})
  })
})
// Handler of the slash command
slapp.command('/messages','(.*)', (msg, text, value)  => {
  slapp.client.users.info({token:msg.meta.bot_token,user:msg.body.user_id}, (err, data) => {
    if( data.user.is_admin){
      _("text")
      _(text)
      var strtokens = text.split(" ");
      var cmd = strtokens[0];
      var val = text.replace(cmd+' ','');
      _("val")
      _(val)
      if(!text)
        msg.respond("Options for /messages: \n" +
                "\`printHelp\` prints the current help message.\n" +
                "\`printWelcome\` prints the current welcome message.\n" +
                "\`setHelp [ARG]\`  sets [ARG] as the new help message.\n" +
                "\`setWelcome [ARG]\` sets [ARG] as the new welcome message.\n" +
                "\`defaultHelp \`  sets the help message to the default value.\n" +
                "\`defaultWelcome \` sets the welcome message to the default value.\n"
              );
      else if(cmd == 'printHelp')
        printHelp(msg);
      else if(cmd == 'printWelcome')
        printWelcome(msg);
      else if(cmd == 'setHelp')
        setHelp(msg,val);
      else if(cmd == 'setWelcome')
        setWelcome(msg,val);
      else if(cmd == 'defaultHelp')
        defaultHelp(msg);
      else if(cmd == 'defaultWelcome')
        defaultWelcome(msg);
      else
        msg.respond("Please use /messages to print the available options.");
    }
    else {
      msg.respond("Sorry, you're not an admin.");
    }
  })
})
/**
 * Prints the current help message
 * @param {object} msg the slash command message sent by slapp
 */
function printHelp(msg){
  msg.respond(current_help_text);
}
/**
 * Prints the current welcome message
 * @param {object} msg the slash command message sent by slapp
 */
function printWelcome(msg){
  msg.respond(current_welcome_text);
}
/**
 * Sets the current help message to the default one
 * @param {object} msg the slash command message sent by slapp
 * @param {object} val the value sent with the command
 */
function setHelp(msg,val){
  current_help_text = val;
  msg.respond("New help message set");
  kv.set("msgHelp",val,function(err){
    if(err){
      _("error setting msgHelp in the kv");
      _(err);
      }
  });
}
/**
 * Sets the current welcome message to the default one
 * @param {object} msg the slash command message sent by slapp
 * @param {object} val the value sent with the command
 */
function setWelcome(msg,val){
  msg.respond("New welcome message set");
  current_welcome_text = val;
  kv.set("msgWelcome",val,function(err){
    if(err){
      _("error setting msgWelcome in the kv");
      _(err);
      }
  });
}
/**
 * Sets the current help message to the default one
 * @param {object} msg the slash command message sent by slapp
 */
function defaultHelp(msg){

  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:'help.md',
    },
    function(err,res){
    	if (!err) {
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        current_help_text = fileBody;
        msg.respond("Help set to Default from the github file");
      }
      else{
        current_help_text = verbose.HELP_TEXT;
        msg.respond("Coudn't read from github. Help set to default from the hard-coded string");
      }
  });
}
/**
 * Sets the current welcome message to the default one
 * @param {object} msg the slash command message sent by slapp
 */
function defaultWelcome(msg){
  github.get().repos.getContent({
      owner:"NeuroTechX",
      repo:"ntx_slack_archive",
      path:'welcome.md',
    },
    function(err,res){
      if (!err) {
        var b64fileBody = res.content;
        var bufBody = new Buffer(b64fileBody, 'base64')
        var fileBody = bufBody.toString();
        current_welcome_text = fileBody;
        msg.respond("Welcome set to Default from the github file");
      }
      else {
        current_welcome_text=verbose.WELCOME_TEXT;
        msg.respond("Coudn't read from github. Welcome set to default from the hard-coded string");
      }
  });
}
module.exports = {
  init:init
}
<|endoftext|>


<commit_before>define(['esri/InfoTemplate'], function (InfoTemplate) {

    return {
        mapOptions: {
            extentJson: {
                "xmin": 30236013.176644534,
                "ymin": 1976510.339413753,
                "xmax": 30272702.950221367,
                "ymax": 1988568.2806257235,
                "spatialReference": {
                    "wkid": 102100
                }
            },
            basemap: "osm"
                //minZoom: 4,
                //isScrollWheelZoom: true,
                //nav: false,
                //logo: false,
                //wrapAround180: true,
                //showLabels: true
        },

        /*
         *operation layers,belize restaurants layer
         */
        layers: {
            belizeMapService: {
                url: 'http://localhost:6080/arcgis/rest/services/BelizeEdit/MapServer',
                title: 'Restaurants',
                options: {
                    id: 'Restaurants',
                    opacity: 1.0,
                    visible: false
                }
            }
        },

        // Add config parameters for each map widget you want to include
        // The map reference will get appended to the options
        // To accept default options just pass empty object {}
        // NOTE: to change the position of these widgets, make changes in map.css
        widgets: {
            legend: {
                id:"map-legend",
            },
            scalebar: {

            },
            homeButton: {

            },
            locateButton: {

            },
            layerList: {

            },
            bookMarks: {

            },
            geocoder: {
                autoComplete: true,
                arcgisGeocoder: {
                    placeholder: 'Address or Location'
                },
                'class': 'geocoder'
            }
        },

        portalUrl: 'http://www.arcgis.com'
    };
});
<commit_msg>change the POI service URL to featureserver,which can enbale data edits and target the data on the enterprise geodatabase.<commit_after>define(['esri/InfoTemplate'], function (InfoTemplate) {

    return {
        mapOptions: {
            extentJson: {
                "xmin": 30236013.176644534,
                "ymin": 1976510.339413753,
                "xmax": 30272702.950221367,
                "ymax": 1988568.2806257235,
                "spatialReference": {
                    "wkid": 102100
                }
            },
            basemap: "osm"
                //minZoom: 4,
                //isScrollWheelZoom: true,
                //nav: false,
                //logo: false,
                //wrapAround180: true,
                //showLabels: true
        },

        /*
         *operation layers,belize restaurants layer
         */
        layers: {
            belizeMapService: {
                url: 'http://localhost:6080/arcgis/rest/services/BelizeEdit/FeatureServer',
                title: 'Restaurants',
                options: {
                    id: 'Restaurants',
                    opacity: 1.0,
                    visible: false
                }
            }
        },

        // Add config parameters for each map widget you want to include
        // The map reference will get appended to the options
        // To accept default options just pass empty object {}
        // NOTE: to change the position of these widgets, make changes in map.css
        widgets: {
            legend: {
                id:"map-legend",
            },
            scalebar: {

            },
            homeButton: {

            },
            locateButton: {

            },
            layerList: {

            },
            bookMarks: {

            },
            geocoder: {
                autoComplete: true,
                arcgisGeocoder: {
                    placeholder: 'Address or Location'
                },
                'class': 'geocoder'
            }
        },

        portalUrl: 'http://www.arcgis.com'
    };
});
<|endoftext|>


<commit_before>var React = require('react');
var GoogleChartLoader = require('./GoogleChartLoader');
var DEFAULT_COLORS = require('../constants/DEFAULT_CHART_COLORS');

var Chart = React.createClass({
	chart: null,
	wrapper: null,
	hidden_columns: [],
	data_table: [],
	getInitialState: function() {
		return {
		};
	},
	componentDidMount: function(){
	    var self = this;

	    GoogleChartLoader.init().then(function(){
	      self.drawChart();
	    });
	},

	componentDidUpdate: function(){
		if (GoogleChartLoader.is_loaded){
			this.drawChart();
		};
  	},

	getDefaultProps: function() {
		return {
			chartType : 'LineChart',
			graph_id: 'graph',
			rows: [],
			columns: [],
			options: {
				chart: {
					title: 'Chart Title',
					subtitle: 'Subtitle'
				},
				hAxis: {title: 'X Label'},
				vAxis: {title: 'Y Label'},
				width: '400px',
				height: '300px'

	      	},
	      	chartEvents : [],
	      	data: null,
	      	onSelect: null,
	        legend_toggle: false
	    };
	},

	render: function() {
		return React.DOM.div({id: this.props.graph_id, style: {height: this.props.height, width:this.props.width}});
	},
	build_data_table : function() {

		var data_table = new google.visualization.DataTable();
		for (var i = 0 ; i < this.props.columns.length; i++) {
			data_table.addColumn(this.props.columns[i].type, this.props.columns[i].label);
		}

		if (this.props.rows.length > 0) {
			data_table.addRows(this.props.rows);
		}
		return data_table;
	},

	drawChart: function() {

		if (this.props.data !== null ) {
			if (this.props.data.length === 0 ) {
				// Initialized. Do nothing and wait for data
				return;
			}

			this.data_table = this.props.data;
		}
		else if (this.props.columns.length === 0) {
			return;
		}
		else {
			this.data_table = this.build_data_table();
		}

		this.wrapper = new google.visualization.ChartWrapper({
			chartType: this.props.chartType,
			dataTable: this.data_table,
			options : this.props.options,
			containerId: this.props.graph_id
		});

		this.data_table = this.wrapper.getDataTable();

        var self = this;

        google.visualization.events.addOneTimeListener(this.wrapper, 'ready', function() {
        	self.chart = self.wrapper.getChart();
        	self.listen_to_chart_events.call(this);
        });

        if (this.props.legend_toggle) {
        	google.visualization.events.addListener(this.wrapper, 'select', function() { self.default_chart_select.call(this); });
        }
        if (this.props.onSelect !== null) {
        	google.visualization.events.addListener(this.wrapper, 'select', function() { self.props.onSelect(self, self.chart.getSelection()); });
        }
        self.wrapper.draw();

    },
    listen_to_chart_events: function() {

    	var self = this;
    	var event_data;
  		for (var i = 0; i < this.props.chartEvents.length; i++) {
  			if (this.props.chartEvents[i].eventName === 'ready') {
  				this.props.chartEvents[i].callback(this);
  			}
  			else {
  				var callback = self.props.chartEvents[i].callback;
  				google.visualization.events.addListener(this.chart, this.props.chartEvents[i].eventName, function(){ callback(self); });
  			}

		}

    },

    default_chart_select: function() {
		var selection = this.chart.getSelection();
	    // if selection length is 0, we deselected an element
	    if (selection.length > 0) {
	        // if row is undefined, we clicked on the legend
	        if (selection[0].row == null) {
	        	var column = selection[0].column;
	        	this.toggle_points(column);
	        }
	    }
    },

    build_empty_column: function(index) {

    	return {
			label: this.data_table.getColumnLabel(index),
            type: this.data_table.getColumnType(index),
            calc: function () {
                return null;
            }
		};
    },

    build_column_from_src: function(index) {
    	return {
			label: this.data_table.getColumnLabel(index),
			type: this.data_table.getColumnType(index),
			sourceColumn: index
		};
    },

    toggle_points: function(column) {

		//Need to show legend !!

    	var view = new google.visualization.DataView(this.wrapper.getDataTable());
    	var column_count = view.getNumberOfColumns();
    	var colors = [],
    		columns = [],
			empty_columns = [],
			column_hidden,
			empty_column,
			column_from_src;

		for (var i = 0; i < column_count; i++) {

			// If user clicked on legend
			if (i === column ) {

				column_hidden = (typeof this.hidden_columns[i] !== 'undefined');

				//User wants to hide values
				if (!column_hidden ) {
					// Null out the values of the column
					empty_column =  this.build_empty_column(i);
					columns.push(empty_column);

					this.hidden_columns[i] = { color : this.get_column_color(i-1) };
					colors.push('#CCCCCC');
				}
				//User wants to show values
				else {
					column_from_src = this.build_column_from_src(i);
    				columns.push(column_from_src);

    				var previous_color = this.hidden_columns[i].color;
    				delete this.hidden_columns[i];
    				colors.push(previous_color);
				}
			}
			else if (typeof this.hidden_columns[i] !== 'undefined') {
				empty_column =  this.build_empty_column(i);
				columns.push(empty_column);
				colors.push('#CCCCCC');
			}
			else {
				column_from_src = this.build_column_from_src(i);
    			columns.push(column_from_src);

					if (i !== 0) {
						colors.push(this.get_column_color(i-1));
					}
			}
		}

		view.setColumns(columns);
    	this.props.options.colors = colors;

    	this.chart.draw(view, this.props.options);
    },

    get_column_color: function(column_index) {
    	if (this.props.options.colors) {
			if (this.props.options.colors[column_index]) {
				return this.props.options.colors[column_index];
			}
		}
		else {
			if (typeof DEFAULT_COLORS[column_index] !== 'undefined') {
				return DEFAULT_COLORS[column_index];
			}
			else {
				return DEFAULT_COLORS[0];
			}

		}
    }

});

module.exports = Chart;<commit_msg>fix graph to be unique id<commit_after>var React = require('react');
var GoogleChartLoader = require('./GoogleChartLoader');
var DEFAULT_COLORS = require('../constants/DEFAULT_CHART_COLORS');

var uniqueId = 0;
var generateUniqueId = function() {
    uniqueId++;
    return "reactgooglegraph" + uniqueId;
};

var Chart = React.createClass({
	chart: null,
	wrapper: null,
	hidden_columns: [],
	data_table: [],
	getInitialState: function() {
		return {
            graph_id: this.props.graph_id || generateUniqueId()
		};
	},
	componentDidMount: function(){
	    var self = this;

	    GoogleChartLoader.init().then(function(){
	      self.drawChart();
	    });
	},

	componentDidUpdate: function(){
		if (GoogleChartLoader.is_loaded){
			this.drawChart();
		};
  	},

	getDefaultProps: function() {
		return {
			chartType : 'LineChart',
			rows: [],
			columns: [],
			options: {
				chart: {
					title: 'Chart Title',
					subtitle: 'Subtitle'
				},
				hAxis: {title: 'X Label'},
				vAxis: {title: 'Y Label'},
				width: '400px',
				height: '300px'

	      	},
	      	chartEvents : [],
	      	data: null,
	      	onSelect: null,
	        legend_toggle: false
	    };
	},

	render: function() {
		return React.DOM.div({id: this.state.graph_id, style: {height: this.props.height, width:this.props.width}});
	},
	build_data_table : function() {

		var data_table = new google.visualization.DataTable();
		for (var i = 0 ; i < this.props.columns.length; i++) {
			data_table.addColumn(this.props.columns[i].type, this.props.columns[i].label);
		}

		if (this.props.rows.length > 0) {
			data_table.addRows(this.props.rows);
		}
		return data_table;
	},

	drawChart: function() {

		if (this.props.data !== null ) {
			if (this.props.data.length === 0 ) {
				// Initialized. Do nothing and wait for data
				return;
			}

			this.data_table = this.props.data;
		}
		else if (this.props.columns.length === 0) {
			return;
		}
		else {
			this.data_table = this.build_data_table();
		}

		this.wrapper = new google.visualization.ChartWrapper({
			chartType: this.props.chartType,
			dataTable: this.data_table,
			options : this.props.options,
			containerId: this.state.graph_id
		});

		this.data_table = this.wrapper.getDataTable();

        var self = this;

        google.visualization.events.addOneTimeListener(this.wrapper, 'ready', function() {
        	self.chart = self.wrapper.getChart();
        	self.listen_to_chart_events.call(this);
        });

        if (this.props.legend_toggle) {
        	google.visualization.events.addListener(this.wrapper, 'select', function() { self.default_chart_select.call(this); });
        }
        if (this.props.onSelect !== null) {
        	google.visualization.events.addListener(this.wrapper, 'select', function() { self.props.onSelect(self, self.chart.getSelection()); });
        }
        self.wrapper.draw();

    },
    listen_to_chart_events: function() {

    	var self = this;
    	var event_data;
  		for (var i = 0; i < this.props.chartEvents.length; i++) {
  			if (this.props.chartEvents[i].eventName === 'ready') {
  				this.props.chartEvents[i].callback(this);
  			}
  			else {
  				var callback = self.props.chartEvents[i].callback;
  				google.visualization.events.addListener(this.chart, this.props.chartEvents[i].eventName, function(){ callback(self); });
  			}

		}

    },

    default_chart_select: function() {
		var selection = this.chart.getSelection();
	    // if selection length is 0, we deselected an element
	    if (selection.length > 0) {
	        // if row is undefined, we clicked on the legend
	        if (selection[0].row == null) {
	        	var column = selection[0].column;
	        	this.toggle_points(column);
	        }
	    }
    },

    build_empty_column: function(index) {

    	return {
			label: this.data_table.getColumnLabel(index),
            type: this.data_table.getColumnType(index),
            calc: function () {
                return null;
            }
		};
    },

    build_column_from_src: function(index) {
    	return {
			label: this.data_table.getColumnLabel(index),
			type: this.data_table.getColumnType(index),
			sourceColumn: index
		};
    },

    toggle_points: function(column) {

		//Need to show legend !!

    	var view = new google.visualization.DataView(this.wrapper.getDataTable());
    	var column_count = view.getNumberOfColumns();
    	var colors = [],
    		columns = [],
			empty_columns = [],
			column_hidden,
			empty_column,
			column_from_src;

		for (var i = 0; i < column_count; i++) {

			// If user clicked on legend
			if (i === column ) {

				column_hidden = (typeof this.hidden_columns[i] !== 'undefined');

				//User wants to hide values
				if (!column_hidden ) {
					// Null out the values of the column
					empty_column =  this.build_empty_column(i);
					columns.push(empty_column);

					this.hidden_columns[i] = { color : this.get_column_color(i-1) };
					colors.push('#CCCCCC');
				}
				//User wants to show values
				else {
					column_from_src = this.build_column_from_src(i);
    				columns.push(column_from_src);

    				var previous_color = this.hidden_columns[i].color;
    				delete this.hidden_columns[i];
    				colors.push(previous_color);
				}
			}
			else if (typeof this.hidden_columns[i] !== 'undefined') {
				empty_column =  this.build_empty_column(i);
				columns.push(empty_column);
				colors.push('#CCCCCC');
			}
			else {
				column_from_src = this.build_column_from_src(i);
    			columns.push(column_from_src);

					if (i !== 0) {
						colors.push(this.get_column_color(i-1));
					}
			}
		}

		view.setColumns(columns);
    	this.props.options.colors = colors;

    	this.chart.draw(view, this.props.options);
    },

    get_column_color: function(column_index) {
    	if (this.props.options.colors) {
			if (this.props.options.colors[column_index]) {
				return this.props.options.colors[column_index];
			}
		}
		else {
			if (typeof DEFAULT_COLORS[column_index] !== 'undefined') {
				return DEFAULT_COLORS[column_index];
			}
			else {
				return DEFAULT_COLORS[0];
			}

		}
    }

});

module.exports = Chart;
<|endoftext|>


<commit_before>
freeflowComponent.prototype.resize = function (ele) {

    var _this = this;

    this.resizeEvents = this.resizeEvents || [];

    $(ele).resizable({
        stop : function (event, ui) {
            var tab = $(ui.element).attr('tab');
            var layer = $(ui.element).attr('layer');

            /* json */
            _this.data.layers[layer].w = ui.size.width;
            _this.data.layers[layer].h = ui.size.height;

            /* set to input */
            $('.ff_w_input[tab=' + tab + ']').val(ui.size.width);
            $('.ff_h_input[tab=' + tab + ']').val(ui.size.height);

            _this.resizeEventTrigger({
                size : ui.size,
                tab : tab,
                layer : layer
            });
        }
    });
}
freeflowComponent.prototype.addResizeEvent = function (fn) {
    this.resizeEvents.push(fn);
};
freeflowComponent.prototype.resizeEventTrigger = function (options) {
    for (var i = 0; i < this.resizeEvents.length; i++) {
        this.resizeEvents[0](options);
    }
};
freeflowComponent.prototype.stopReize = function (ele) {
    $(ele).resizable('destroy');
}

var resize = function (_this) {
    this.prototype = {
        initialize : function () {
            this.resizeEvents = [];
        },
        new : function (layer, tab) {
            var self = this;

            $(layer).resizable({
                stop : function (event, ui) {
                    var tab = $(ui.element).attr('tab');
                    var layer = $(ui.element).attr('layer');

                    /* json */
                    _this.data.layers[layer].w = ui.size.width;
                    _this.data.layers[layer].h = ui.size.height;

                    /* set to input */
                    $('.ff_w_input[tab=' + tab + ']').val(ui.size.width);
                    $('.ff_h_input[tab=' + tab + ']').val(ui.size.height);

                    self.onResize({
                        size : ui.size,
                        tab : tab,
                        layer : layer
                    });
                }
            });
        },
        onResize : function (options) {
            for (var i = 0; i < this.resizeEvents.length; i++) {
                this.resizeEvents[0](options);
            }
        },
        addResizeEvent : function (fn) {
            this.resizeEvents.push(fn);
        }
    };

    return this.prototype;
}<commit_msg>stop resize of unselected layer<commit_after>
freeflowComponent.prototype.resize = function (ele) {

    var _this = this;

    this.resizeEvents = this.resizeEvents || [];

    $(ele).resizable({
        stop : function (event, ui) {
            var tab = $(ui.element).attr('tab');
            var layer = $(ui.element).attr('layer');

            /* json */
            _this.data.layers[layer].w = ui.size.width;
            _this.data.layers[layer].h = ui.size.height;

            /* set to input */
            $('.ff_w_input[tab=' + tab + ']').val(ui.size.width);
            $('.ff_h_input[tab=' + tab + ']').val(ui.size.height);

            _this.resizeEventTrigger({
                size : ui.size,
                tab : tab,
                layer : layer
            });
        }
    });
}
freeflowComponent.prototype.addResizeEvent = function (fn) {
    this.resizeEvents.push(fn);
};
freeflowComponent.prototype.resizeEventTrigger = function (options) {
    for (var i = 0; i < this.resizeEvents.length; i++) {
        this.resizeEvents[0](options);
    }
};
freeflowComponent.prototype.stopReize = function (ele) {
    $(ele).resizable('destroy');
}

var resize = function (_this) {
    this.prototype = {
        initialize : function () {
            this.resizeEvents = [];
        },
        new : function (layer, tab) {
            var self = this;

            $('.ff_layer[tab=' + tab + ']').resizable('destroy');

            $(layer).resizable({
                stop : function (event, ui) {
                    var tab = $(ui.element).attr('tab');
                    var layer = $(ui.element).attr('layer');

                    /* json */
                    _this.data.layers[layer].w = ui.size.width;
                    _this.data.layers[layer].h = ui.size.height;

                    /* set to input */
                    $('.ff_w_input[tab=' + tab + ']').val(ui.size.width);
                    $('.ff_h_input[tab=' + tab + ']').val(ui.size.height);

                    self.onResize({
                        size : ui.size,
                        tab : tab,
                        layer : layer
                    });
                }
            });
        },
        onResize : function (options) {
            for (var i = 0; i < this.resizeEvents.length; i++) {
                this.resizeEvents[0](options);
            }
        },
        addResizeEvent : function (fn) {
            this.resizeEvents.push(fn);
        }
    };

    return this.prototype;
}<|endoftext|>


<commit_before>'use strict'

const sourcemaps = require('gulp-sourcemaps')
const concat = require('gulp-concat')
const footer = require('gulp-footer')
const uglify = require('gulp-uglify')
const flatten = require('gulp-flatten')
const rev = require('gulp-rev')
const util = require('gulp-util')
const filenames = require('gulp-filenames')

exports.dep = ['bundle:app']
exports.fn = function (gulp, paths, mode, done) {
  return gulp.src([paths.src + 'jspm_packages/system.js',
      paths.src + 'app-bundle.conf.js'], { base: '.' })
    .pipe(!mode.production ? sourcemaps.init({loadMaps: true}) : util.noop())
    .pipe(concat('app-bootstrap.js'))
    .pipe(footer('\nSystem.import(\'app/splash\').catch(console.error.bind(console));\nSystem.import(\'aurelia-bootstrapper\').catch(console.error.bind(console));'))
    .pipe(uglify({mangle: mode.production}))
    .pipe(flatten())
    .pipe(mode.production ? rev() : util.noop())
    .pipe(filenames('bootstrapjs'))
    .pipe(!mode.production ? sourcemaps.write('.', {
      mapSources: function (sourcePath) {
        var truncatedSourcePath = sourcePath.substr(sourcePath.indexOf('/') + 1)
        util.log('SourcePath within source map truncated to:', util.colors.cyan(truncatedSourcePath))
        return truncatedSourcePath
      }
    }) : util.noop())
    .pipe(gulp.dest(paths.wwwroot))
}
<commit_msg>Add systemjs polyfills to support older browsers.<commit_after>'use strict'

const sourcemaps = require('gulp-sourcemaps')
const concat = require('gulp-concat')
const footer = require('gulp-footer')
const uglify = require('gulp-uglify')
const flatten = require('gulp-flatten')
const rev = require('gulp-rev')
const util = require('gulp-util')
const filenames = require('gulp-filenames')

exports.dep = ['bundle:app']
exports.fn = function (gulp, paths, mode, done) {
  return gulp.src([paths.src + 'jspm_packages/system-polyfills.js',
      paths.src + 'jspm_packages/system.js',
      paths.src + 'app-bundle.conf.js'], { base: '.' })
    .pipe(!mode.production ? sourcemaps.init({loadMaps: true}) : util.noop())
    .pipe(concat('app-bootstrap.js'))
    .pipe(footer('\nSystem.import(\'app/splash\').catch(console.error.bind(console));\nSystem.import(\'aurelia-bootstrapper\').catch(console.error.bind(console));'))
    .pipe(uglify({mangle: mode.production}))
    .pipe(flatten())
    .pipe(mode.production ? rev() : util.noop())
    .pipe(filenames('bootstrapjs'))
    .pipe(!mode.production ? sourcemaps.write('.', {
      mapSources: function (sourcePath) {
        var truncatedSourcePath = sourcePath.substr(sourcePath.indexOf('/') + 1)
        util.log('SourcePath within source map truncated to:', util.colors.cyan(truncatedSourcePath))
        return truncatedSourcePath
      }
    }) : util.noop())
    .pipe(gulp.dest(paths.wwwroot))
}
<|endoftext|>


<commit_before>define([ // jshint ignore:line
    'jquery',
    'underscore',
    'gettext',
    'common/js/components/utils/view_utils',
    'edx-ui-toolkit/js/utils/string-utils',
    'edx-ui-toolkit/js/utils/html-utils'
],
function($, _, gettext, ViewUtils, StringUtils, HtmlUtils) {
    'use strict';
    return function(maintenanceViewURL) {
        var showError;
        // Reset values
        $('#reset-button').click(function(e) {
            e.preventDefault();
            $('#course-id').val('');
            $('#dry-run').prop('checked', true);
            // clear out result container
            $('#result-container').html('');
        });

        showError = function(containerElSelector, error) {
            var errorWrapperElSelector, errorHtml;
            errorWrapperElSelector = containerElSelector + ' .wrapper-error';
            errorHtml = '
' + error + '
';
            HtmlUtils.setHtml($(errorWrapperElSelector), HtmlUtils.HTML(errorHtml));
            $(errorWrapperElSelector).css('display', 'inline-block');
            $(errorWrapperElSelector).fadeOut(5000);
        };

        $('form#force_publish').submit(function(event) {
            var attrs, forcePublishedTemplate, $submitButton, deferred, promise, data;
            event.preventDefault();

            // clear out result container
            $('#result-container').html('');

            $submitButton = $('#submit_force_publish');
            deferred = new $.Deferred();
            promise = deferred.promise();

            data = $('#force_publish').serialize();

            // disable submit button while executing.
            ViewUtils.disableElementWhileRunning($submitButton, function() { return promise; });

            $.ajax({
                type: 'POST',
                url: maintenanceViewURL,
                dataType: 'json',
                data: data
            })
            .done(function(response) {
                if (response.error) {
                    showError('#course-id-container', response.msg);
                } else {
                    if (response.msg) {
                        showError('#result-error', response.msg);
                    } else {
                        attrs = $.extend({}, response, {StringUtils: StringUtils});
                        forcePublishedTemplate = HtmlUtils.template(
                            $('#force-published-course-response-tpl').text()
                        );
                        HtmlUtils.setHtml($('#result-container'), forcePublishedTemplate(attrs));
                    }
                }
            })
            .fail(function() {
                // response.responseText here because it would show some strange output, it may output Traceback
                // sometimes if unexpected issue arises. Better to show just internal error when getting 500 error.
                showError('#result-error', gettext('Internal Server Error.'));
            })
            .always(function() {
                deferred.resolve();
            });
        });
    };
});

<commit_msg>PROD-1256<commit_after>define([ // jshint ignore:line
    'jquery',
    'underscore',
    'gettext',
    'common/js/components/utils/view_utils',
    'edx-ui-toolkit/js/utils/string-utils',
    'edx-ui-toolkit/js/utils/html-utils'
],
function($, _, gettext, ViewUtils, StringUtils, HtmlUtils) {
    'use strict';
    return function(maintenanceViewURL) {
        var showError;
        // Reset values
        $('#reset-button').click(function(e) {
            e.preventDefault();
            $('#course-id').val('');
            $('#dry-run').prop('checked', true);
            // clear out result container
            $('#result-container').html('');
        });

        showError = function(containerElSelector, error) {
            var errorWrapperElSelector, errorHtml;
            errorWrapperElSelector = containerElSelector + ' .wrapper-error';
            errorHtml = HtmlUtils.joinHtml(
                HtmlUtils.HTML('
'),
                error,
                HtmlUtils.HTML('
')
            );
            HtmlUtils.setHtml($(errorWrapperElSelector), HtmlUtils.HTML(errorHtml));
            $(errorWrapperElSelector).css('display', 'inline-block');
            $(errorWrapperElSelector).fadeOut(5000);
        };

        $('form#force_publish').submit(function(event) {
            var attrs, forcePublishedTemplate, $submitButton, deferred, promise, data;
            event.preventDefault();

            // clear out result container
            $('#result-container').html('');

            $submitButton = $('#submit_force_publish');
            deferred = new $.Deferred();
            promise = deferred.promise();

            data = $('#force_publish').serialize();

            // disable submit button while executing.
            ViewUtils.disableElementWhileRunning($submitButton, function() { return promise; });

            $.ajax({
                type: 'POST',
                url: maintenanceViewURL,
                dataType: 'json',
                data: data
            })
            .done(function(response) {
                if (response.error) {
                    showError('#course-id-container', response.msg);
                } else {
                    if (response.msg) {
                        showError('#result-error', response.msg);
                    } else {
                        attrs = $.extend({}, response, {StringUtils: StringUtils});
                        forcePublishedTemplate = HtmlUtils.template(
                            $('#force-published-course-response-tpl').text()
                        );
                        HtmlUtils.setHtml($('#result-container'), forcePublishedTemplate(attrs));
                    }
                }
            })
            .fail(function() {
                // response.responseText here because it would show some strange output, it may output Traceback
                // sometimes if unexpected issue arises. Better to show just internal error when getting 500 error.
                showError('#result-error', gettext('Internal Server Error.'));
            })
            .always(function() {
                deferred.resolve();
            });
        });
    };
});

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ListView,
  Image,
  DrawerLayoutAndroid,
  ToolbarAndroid,
  ToastAndroid,
  BackAndroid,
  TouchableOpacity,
  Dimensions,
  TouchableNativeFeedback,
  RefreshControl,
  InteractionManager,
  Animated,
  Easing,
  PanResponder,
  TouchableHighlight,
} from 'react-native';

import { connect } from 'react-redux';

import NavigatorDrawer from './NavigatorDrawer';
import SegmentedView from './SegmentedView';

import Community from './viewPagers/Community';
import Gene from './viewPagers/Gene';

import { changeSegmentIndex, changeCommunityType, changeGeneType } from '../actions/app';

import { standardColor, accentColor } from '../config/config';

let title = "PSNINE";
let isMounted = false;
let indexWithFloatButton = [0,3,4];
let indexWithoutFloatButton = [1,2];

let communityActions = [
  { title: '搜索', icon: require('image!ic_search_white'), value: '', show: 'always'},
  { title: '全部', value: '', show: 'never' },
  { title: '新闻', value: 'news',show: 'never' },
  { title: '攻略', value: 'guide',show: 'never' },
  { title: '测评', value: 'review',show: 'never' },
  { title: '心得', value: 'plus',show: 'never' },
  { title: 'Plus', value: 'exp',show: 'never' },
  { title: '开箱', value: 'openbox',show: 'never' },
  { title: '游列', value: 'gamelist',show: 'never' },
  { title: '活动', value: 'event',show: 'never' },
  { title: '火星', value: 'mars',show: 'never'},
];

let gameActions = [
  { title: '搜索', icon: require('image!ic_search_white') , show: 'always'},
];

let rankActions = [
  { title: '搜索', icon: require('image!ic_search_white') , show: 'always'},
];

let battleActions = [
  { title: '搜索', icon: require('image!ic_search_white') , show: 'always'},
];

let geneActions = [
  { title: '搜索', icon: require('image!ic_search_white') ,value: '', show: 'always'},
  { title: '全部', value: 'all', show: 'never' },
  { title: '图文类',value: 'photo', show: 'never' },
  { title: '音乐类',value: 'music', show: 'never' },
  { title: '影视类',value: 'movie', show: 'never' },
  { title: '视频类',value: 'video', show: 'never' },
];

let toolbarActions = [communityActions,gameActions,rankActions,battleActions,geneActions]

let titlesArr = ["社区", "问答", "游戏",  "约战", "机因"];

const ds = new ListView.DataSource({
  rowHasChanged: (row1, row2) => row1 !== row2,
});

let clamp = (value,min, max) => {
  return Math.min(Math.max(value, min), max);
};

let toolbarHeight = 56;
let releasedMarginTop = 0;

class Toolbar extends Component {

  constructor(props) {
    super(props);

    this.state = {
      rotation: new Animated.Value(1),
      scale: new Animated.Value(1),
      opacity: new Animated.Value(1),
      marginTop: new Animated.Value(0),
    }
  }

  _renderSegmentedView = () =>{
    return (
      <SegmentedView
        {...{
            communityType: this.props.app.communityType,
            geneType: this.props.app.geneType,
            navigator:this.props.navigator,
            toolbarDispatch: this.props.dispatch,
            segmentedIndex: this.props.app.segmentedIndex,
        }}
        titles={titlesArr}
        index={0}
        style={styles.segmentedView}
        stretch
        switchTo={this.switchTo}
        scrollTo={this.scrollTo}
        duration={200}
        restWidth={10}
        barPosition='bottom'
        underlayColor='#000'
        barColor='#fff'
        titleStyle={{ fontSize:15 }}
        titleWidth={Dimensions.get('window').width/titlesArr.length}
        moveUpResponders = {this.panResponder}
        />
    )
  }

  componentWillReceiveProps(nextProps) {
    this.props.app = nextProps.app;
  }

  onActionSelected = (index) => {
    const { segmentedIndex } = this.props.app;
    const { dispatch } = this.props;
    if(segmentedIndex == 0){
      let type = toolbarActions[segmentedIndex][index].value;
      dispatch(changeCommunityType(type));
    }else if(segmentedIndex == 4){
      let type = toolbarActions[segmentedIndex][index].value;
      dispatch(changeGeneType(type));
    }
  }

  componentDidMount() {
        //this.parallelFadeIn(1);
  }

  componentWillMount() {
        this.panResponder = PanResponder.create({

            onStartShouldSetPanResponderCapture: (e, gesture) =>{
              // console.log('1');
              return false;
            },

            onMoveShouldSetPanResponderCapture:(e, gesture) =>{
              let shouldSet = Math.abs(gesture.dy) >=2;
              // console.log('2');
              return shouldSet;
            },

            onPanResponderGrant:(e, gesture) => {
              // console.log('3');

            },
            onPanResponderMove: (e, gesture) => {
              // console.log(`====>${gesture.vy} ${gesture.vy<=5}`);
              let dy = gesture.dy;
              let vy = gesture.vy;
              if(dy < 0){
                dy = dy + releasedMarginTop;
                if(-dy <= toolbarHeight){
                  if(dy>0)
                    return;
                  this.state.marginTop.setValue(dy);
                }
              }else{
                dy = dy + releasedMarginTop;
                if(-dy <= toolbarHeight){
                  if(dy>0)
                    return;
                  this.state.marginTop.setValue(dy);
                }
              }
            },
            onPanResponderRelease: (e, gesture) => {

            },
            onPanResponderTerminationRequest : (evt, gesture) => {
              // console.log('6');
              return true;
            },
            onPanResponderTerminate: (evt, gesture) => {

            },
            onShouldBlockNativeResponder: (evt, gesture) => {
              // console.log('8');
              return true;
            },
            onPanResponderReject: (evt, gesture) => {
              // console.log('9');
              return false;
            },
            onPanResponderEnd: (evt, gesture) => {
              let dy = gesture.dy;
              let vy = gesture.vy;

              this.state.marginTop.flattenOffset();

              let value = this.state.marginTop._value;
              let duration = 50;

              if(vy<0){

                if(value <= -toolbarHeight/2 || -vy >= 2.0e-7){

                  Animated.timing(this.state.marginTop,{
                    toValue: -toolbarHeight,
                    duration,
                    easing: Easing.linear,
                  }).start();

                  releasedMarginTop = -toolbarHeight;

                }else{

                  Animated.timing(this.state.marginTop,{
                    toValue: 0,
                    duration,
                    easing: Easing.linear,
                  }).start();

                  releasedMarginTop = 0;
                }

              }else{

                if(value >= -toolbarHeight/2 || vy >= 2.0e-7){

                  Animated.timing(this.state.marginTop,{
                    toValue: 0,
                    duration,
                    easing: Easing.linear,
                  }).start();

                  releasedMarginTop = 0;

                }else{

                  Animated.timing(this.state.marginTop,{
                    toValue: -toolbarHeight,
                    duration,
                    easing: Easing.linear,
                  }).start();

                  releasedMarginTop = -toolbarHeight;
                }

              }

            },

        });
  }

  parallelFadeOut = (toValue) => {
    let spring = Animated.spring;
    let timing = Animated.timing;
    Animated.parallel(['opacity','rotation','scale'].map(property => {
        if(property == 'rotation' || property == 'scale'){
          return spring(this.state[property], {
                      toValue: toValue,
                      easing: Easing.elastic(2),
                 });
        }else if(property == 'opacity'){
          return timing(this.state[property], {
                      toValue: toValue,
                      delay: 200,
                      duration: 0,
                 });
        }
    })).start();
  }

  parallelFadeIn = (toValue) => {
    let spring = Animated.spring;
    let timing = Animated.timing;
    Animated.parallel(['opacity','rotation','scale'].map(property => {
        if(property == 'rotation' || property == 'scale'){
          return spring(this.state[property], {
                      toValue: toValue,
                      easing: Easing.elastic(2),
                 });
        }else if(property == 'opacity'){
          return timing(this.state[property], {
                      toValue: toValue,
                      duration: 0,
                 });
        }
    })).start();
  }

  switchTo = (fromIndex,toIndex) => {
    if (indexWithFloatButton.indexOf(fromIndex) != -1 && indexWithoutFloatButton.indexOf(toIndex) !=-1){

      this.parallelFadeOut(0);

    }else if(indexWithoutFloatButton.indexOf(fromIndex) != -1 && indexWithFloatButton.indexOf(toIndex) !=-1){

      this.parallelFadeIn(1);

    }else if(indexWithoutFloatButton.indexOf(fromIndex) != -1 && indexWithoutFloatButton.indexOf(toIndex) !=-1){

    }else if(indexWithFloatButton.indexOf(fromIndex) != -1 && indexWithFloatButton.indexOf(toIndex) !=-1){

      let value = this.state.rotation._value;
      if(fromIndex < toIndex)
        targetValue = value - 1/4;
      else
        targetValue = value + 1/4;
      Animated.timing(this.state.rotation, {
            toValue: targetValue,
            easing: Easing.elastic(2),
      }).start();

    }

  }

  scrollTo = (fromIndex,toIndex, value) => {
    if (isMounted == false){
      isMounted = true;
      return;
    }

    if (indexWithFloatButton.indexOf(fromIndex) != -1 && indexWithoutFloatButton.indexOf(toIndex) !=-1){

      if (fromIndex < toIndex){

        this.state.opacity.setValue(1-value);
        this.state.rotation.setValue(1-value);
        this.state.scale.setValue(1-value);

      }else{

        this.state.opacity.setValue(value);
        this.state.rotation.setValue(1-value);
        this.state.scale.setValue(value);

      }

    }else if(indexWithoutFloatButton.indexOf(fromIndex) != -1 && indexWithFloatButton.indexOf(toIndex) !=-1){

      if (fromIndex < toIndex){

        this.state.opacity.setValue(value);
        this.state.rotation.setValue(1-value);
        this.state.scale.setValue(value);

      }else{

        this.state.opacity.setValue(1-value);
        this.state.rotation.setValue(1-value);
        this.state.scale.setValue(1-value);

      }

    }else if(indexWithoutFloatButton.indexOf(fromIndex) != -1 && indexWithoutFloatButton.indexOf(toIndex) !=-1){

    }else if(indexWithFloatButton.indexOf(fromIndex) != -1 && indexWithFloatButton.indexOf(toIndex) !=-1){
      this.state.rotation.setValue((1-value)/4);
    }

  }

  render() {
    const { app: appReducer } = this.props;
    // console.log('Toolbar.js rendered');
    return (
      <Animated.View
        style={[styles.container,{
          marginTop: this.state.marginTop,
        }]}
      >
        <ToolbarAndroid
          navIcon={require('image!ic_menu_white') }
          title={title}
          style={styles.toolbar}
          titleColor="white"
          overflowIcon={require('image!ic_more_white')}
          actions={toolbarActions[appReducer.segmentedIndex]}
          onActionSelected={this.onActionSelected}
          onIconClicked={this.props._callDrawer() }
          />
          {this._renderSegmentedView() }
          <Animated.View
            ref={float=>this.float=float}
            style={{
              width: 56,
              height: 56,
              borderRadius: 30,
              backgroundColor: accentColor,
              position:'absolute',
              bottom: 16,
              right: 16,
              elevation: 6 ,
              opacity: this.state.opacity,

              transform: [{
                          scale: this.state.scale,
                        },{
                          rotateZ: this.state.rotation.interpolate({
                            inputRange: [0,1],
                            outputRange: ['0deg', '360deg']
                          }),
                        }]
          }}>
          <TouchableHighlight
            onPress={
              ()=>{}
            }
            delayPressIn={0}
            activeOpacity={1}
            underlayColor={accentColor}
            onHideUnderlay={()=>{
              this.float.setNativeProps({
                style :{
                elevation: 6,
              }});
            }}
            onShowUnderlay={()=>{
              this.float.setNativeProps({
                style :{
                elevation: 12,
              }});
            }}
            style={{
              width: 56,
              height: 56,
              borderRadius: 30,
              flex:1,
            }}>
            <View style={{borderRadius: 30,}}>
              <Image source={require('image!ic_add_white')}
                    style={{
                      left:0,
                      top:0,
                  }}
              />

            </View>
          </TouchableHighlight>
          </Animated.View>
      </Animated.View>
    )
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#F5FCFF',
  },
  toolbar: {
    backgroundColor: standardColor,
    height: toolbarHeight,
    elevation: 4,
  },
  segmentedView: {
    backgroundColor: '#F5FCFF',
  },
  selectedTitle: {
    //backgroundColor: '#00ffff'
    //fontSize: 20
  },
  avatar: {
    width: 50,
    height: 50,
  }
});

function mapStateToProps(state) {
    return {
      app: state.app,
    };
}

export default connect(
  mapStateToProps
)(Toolbar);

<commit_msg>增大阈值以解决点击与滑动事件的冲突<commit_after>import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ListView,
  Image,
  DrawerLayoutAndroid,
  ToolbarAndroid,
  ToastAndroid,
  BackAndroid,
  TouchableOpacity,
  Dimensions,
  TouchableNativeFeedback,
  RefreshControl,
  InteractionManager,
  Animated,
  Easing,
  PanResponder,
  TouchableHighlight,
} from 'react-native';

import { connect } from 'react-redux';

import NavigatorDrawer from './NavigatorDrawer';
import SegmentedView from './SegmentedView';

import Community from './viewPagers/Community';
import Gene from './viewPagers/Gene';

import { changeSegmentIndex, changeCommunityType, changeGeneType } from '../actions/app';

import { standardColor, accentColor } from '../config/config';

let title = "PSNINE";
let isMounted = false;
let indexWithFloatButton = [0,3,4];
let indexWithoutFloatButton = [1,2];

let communityActions = [
  { title: '搜索', icon: require('image!ic_search_white'), value: '', show: 'always'},
  { title: '全部', value: '', show: 'never' },
  { title: '新闻', value: 'news',show: 'never' },
  { title: '攻略', value: 'guide',show: 'never' },
  { title: '测评', value: 'review',show: 'never' },
  { title: '心得', value: 'plus',show: 'never' },
  { title: 'Plus', value: 'exp',show: 'never' },
  { title: '开箱', value: 'openbox',show: 'never' },
  { title: '游列', value: 'gamelist',show: 'never' },
  { title: '活动', value: 'event',show: 'never' },
  { title: '火星', value: 'mars',show: 'never'},
];

let gameActions = [
  { title: '搜索', icon: require('image!ic_search_white') , show: 'always'},
];

let rankActions = [
  { title: '搜索', icon: require('image!ic_search_white') , show: 'always'},
];

let battleActions = [
  { title: '搜索', icon: require('image!ic_search_white') , show: 'always'},
];

let geneActions = [
  { title: '搜索', icon: require('image!ic_search_white') ,value: '', show: 'always'},
  { title: '全部', value: 'all', show: 'never' },
  { title: '图文类',value: 'photo', show: 'never' },
  { title: '音乐类',value: 'music', show: 'never' },
  { title: '影视类',value: 'movie', show: 'never' },
  { title: '视频类',value: 'video', show: 'never' },
];

let toolbarActions = [communityActions,gameActions,rankActions,battleActions,geneActions]

let titlesArr = ["社区", "问答", "游戏",  "约战", "机因"];

const ds = new ListView.DataSource({
  rowHasChanged: (row1, row2) => row1 !== row2,
});

let clamp = (value,min, max) => {
  return Math.min(Math.max(value, min), max);
};

let toolbarHeight = 56;
let releasedMarginTop = 0;

class Toolbar extends Component {

  constructor(props) {
    super(props);

    this.state = {
      rotation: new Animated.Value(1),
      scale: new Animated.Value(1),
      opacity: new Animated.Value(1),
      marginTop: new Animated.Value(0),
    }
  }

  _renderSegmentedView = () =>{
    return (
      <SegmentedView
        {...{
            communityType: this.props.app.communityType,
            geneType: this.props.app.geneType,
            navigator:this.props.navigator,
            toolbarDispatch: this.props.dispatch,
            segmentedIndex: this.props.app.segmentedIndex,
        }}
        titles={titlesArr}
        index={0}
        style={styles.segmentedView}
        stretch
        switchTo={this.switchTo}
        scrollTo={this.scrollTo}
        duration={200}
        restWidth={10}
        barPosition='bottom'
        underlayColor='#000'
        barColor='#fff'
        titleStyle={{ fontSize:15 }}
        titleWidth={Dimensions.get('window').width/titlesArr.length}
        moveUpResponders = {this.panResponder}
        />
    )
  }

  componentWillReceiveProps(nextProps) {
    this.props.app = nextProps.app;
  }

  onActionSelected = (index) => {
    const { segmentedIndex } = this.props.app;
    const { dispatch } = this.props;
    if(segmentedIndex == 0){
      let type = toolbarActions[segmentedIndex][index].value;
      dispatch(changeCommunityType(type));
    }else if(segmentedIndex == 4){
      let type = toolbarActions[segmentedIndex][index].value;
      dispatch(changeGeneType(type));
    }
  }

  componentDidMount() {
        //this.parallelFadeIn(1);
  }

  componentWillMount() {
        this.panResponder = PanResponder.create({

            onStartShouldSetPanResponderCapture: (e, gesture) =>{
              // console.log('1');
              return false;
            },

            onMoveShouldSetPanResponderCapture:(e, gesture) =>{
              let shouldSet = Math.abs(gesture.dy) >=4;
              // console.log('2');
              return shouldSet;
            },

            onPanResponderGrant:(e, gesture) => {
              // console.log('3');

            },
            onPanResponderMove: (e, gesture) => {
              // console.log(`====>${gesture.vy} ${gesture.vy<=5}`);
              let dy = gesture.dy;
              let vy = gesture.vy;
              if(dy < 0){
                dy = dy + releasedMarginTop;
                if(-dy <= toolbarHeight){
                  if(dy>0)
                    return;
                  this.state.marginTop.setValue(dy);
                }
              }else{
                dy = dy + releasedMarginTop;
                if(-dy <= toolbarHeight){
                  if(dy>0)
                    return;
                  this.state.marginTop.setValue(dy);
                }
              }
            },
            onPanResponderRelease: (e, gesture) => {

            },
            onPanResponderTerminationRequest : (evt, gesture) => {
              // console.log('6');
              return true;
            },
            onPanResponderTerminate: (evt, gesture) => {

            },
            onShouldBlockNativeResponder: (evt, gesture) => {
              // console.log('8');
              return true;
            },
            onPanResponderReject: (evt, gesture) => {
              // console.log('9');
              return false;
            },
            onPanResponderEnd: (evt, gesture) => {
              let dy = gesture.dy;
              let vy = gesture.vy;

              this.state.marginTop.flattenOffset();

              let value = this.state.marginTop._value;
              let duration = 50;

              if(vy<0){

                if(value <= -toolbarHeight/2 || -vy >= 2.0e-7){

                  Animated.timing(this.state.marginTop,{
                    toValue: -toolbarHeight,
                    duration,
                    easing: Easing.linear,
                  }).start();

                  releasedMarginTop = -toolbarHeight;

                }else{

                  Animated.timing(this.state.marginTop,{
                    toValue: 0,
                    duration,
                    easing: Easing.linear,
                  }).start();

                  releasedMarginTop = 0;
                }

              }else{

                if(value >= -toolbarHeight/2 || vy >= 2.0e-7){

                  Animated.timing(this.state.marginTop,{
                    toValue: 0,
                    duration,
                    easing: Easing.linear,
                  }).start();

                  releasedMarginTop = 0;

                }else{

                  Animated.timing(this.state.marginTop,{
                    toValue: -toolbarHeight,
                    duration,
                    easing: Easing.linear,
                  }).start();

                  releasedMarginTop = -toolbarHeight;
                }

              }

            },

        });
  }

  parallelFadeOut = (toValue) => {
    let spring = Animated.spring;
    let timing = Animated.timing;
    Animated.parallel(['opacity','rotation','scale'].map(property => {
        if(property == 'rotation' || property == 'scale'){
          return spring(this.state[property], {
                      toValue: toValue,
                      easing: Easing.elastic(2),
                 });
        }else if(property == 'opacity'){
          return timing(this.state[property], {
                      toValue: toValue,
                      delay: 200,
                      duration: 0,
                 });
        }
    })).start();
  }

  parallelFadeIn = (toValue) => {
    let spring = Animated.spring;
    let timing = Animated.timing;
    Animated.parallel(['opacity','rotation','scale'].map(property => {
        if(property == 'rotation' || property == 'scale'){
          return spring(this.state[property], {
                      toValue: toValue,
                      easing: Easing.elastic(2),
                 });
        }else if(property == 'opacity'){
          return timing(this.state[property], {
                      toValue: toValue,
                      duration: 0,
                 });
        }
    })).start();
  }

  switchTo = (fromIndex,toIndex) => {
    if (indexWithFloatButton.indexOf(fromIndex) != -1 && indexWithoutFloatButton.indexOf(toIndex) !=-1){

      this.parallelFadeOut(0);

    }else if(indexWithoutFloatButton.indexOf(fromIndex) != -1 && indexWithFloatButton.indexOf(toIndex) !=-1){

      this.parallelFadeIn(1);

    }else if(indexWithoutFloatButton.indexOf(fromIndex) != -1 && indexWithoutFloatButton.indexOf(toIndex) !=-1){

    }else if(indexWithFloatButton.indexOf(fromIndex) != -1 && indexWithFloatButton.indexOf(toIndex) !=-1){

      let value = this.state.rotation._value;
      if(fromIndex < toIndex)
        targetValue = value - 1/4;
      else
        targetValue = value + 1/4;
      Animated.timing(this.state.rotation, {
            toValue: targetValue,
            easing: Easing.elastic(2),
      }).start();

    }

  }

  scrollTo = (fromIndex,toIndex, value) => {
    if (isMounted == false){
      isMounted = true;
      return;
    }

    if (indexWithFloatButton.indexOf(fromIndex) != -1 && indexWithoutFloatButton.indexOf(toIndex) !=-1){

      if (fromIndex < toIndex){

        this.state.opacity.setValue(1-value);
        this.state.rotation.setValue(1-value);
        this.state.scale.setValue(1-value);

      }else{

        this.state.opacity.setValue(value);
        this.state.rotation.setValue(1-value);
        this.state.scale.setValue(value);

      }

    }else if(indexWithoutFloatButton.indexOf(fromIndex) != -1 && indexWithFloatButton.indexOf(toIndex) !=-1){

      if (fromIndex < toIndex){

        this.state.opacity.setValue(value);
        this.state.rotation.setValue(1-value);
        this.state.scale.setValue(value);

      }else{

        this.state.opacity.setValue(1-value);
        this.state.rotation.setValue(1-value);
        this.state.scale.setValue(1-value);

      }

    }else if(indexWithoutFloatButton.indexOf(fromIndex) != -1 && indexWithoutFloatButton.indexOf(toIndex) !=-1){

    }else if(indexWithFloatButton.indexOf(fromIndex) != -1 && indexWithFloatButton.indexOf(toIndex) !=-1){
      this.state.rotation.setValue((1-value)/4);
    }

  }

  render() {
    const { app: appReducer } = this.props;
    // console.log('Toolbar.js rendered');
    return (
      <Animated.View
        style={[styles.container,{
          marginTop: this.state.marginTop,
        }]}
      >
        <ToolbarAndroid
          navIcon={require('image!ic_menu_white') }
          title={title}
          style={styles.toolbar}
          titleColor="white"
          overflowIcon={require('image!ic_more_white')}
          actions={toolbarActions[appReducer.segmentedIndex]}
          onActionSelected={this.onActionSelected}
          onIconClicked={this.props._callDrawer() }
          />
          {this._renderSegmentedView() }
          <Animated.View
            ref={float=>this.float=float}
            style={{
              width: 56,
              height: 56,
              borderRadius: 30,
              backgroundColor: accentColor,
              position:'absolute',
              bottom: 16,
              right: 16,
              elevation: 6 ,
              opacity: this.state.opacity,

              transform: [{
                          scale: this.state.scale,
                        },{
                          rotateZ: this.state.rotation.interpolate({
                            inputRange: [0,1],
                            outputRange: ['0deg', '360deg']
                          }),
                        }]
          }}>
          <TouchableHighlight
            onPress={
              ()=>{}
            }
            delayPressIn={0}
            activeOpacity={1}
            underlayColor={accentColor}
            onHideUnderlay={()=>{
              this.float.setNativeProps({
                style :{
                elevation: 6,
              }});
            }}
            onShowUnderlay={()=>{
              this.float.setNativeProps({
                style :{
                elevation: 12,
              }});
            }}
            style={{
              width: 56,
              height: 56,
              borderRadius: 30,
              flex:1,
            }}>
            <View style={{borderRadius: 30,}}>
              <Image source={require('image!ic_add_white')}
                    style={{
                      left:0,
                      top:0,
                  }}
              />

            </View>
          </TouchableHighlight>
          </Animated.View>
      </Animated.View>
    )
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#F5FCFF',
  },
  toolbar: {
    backgroundColor: standardColor,
    height: toolbarHeight,
    elevation: 4,
  },
  segmentedView: {
    backgroundColor: '#F5FCFF',
  },
  selectedTitle: {
    //backgroundColor: '#00ffff'
    //fontSize: 20
  },
  avatar: {
    width: 50,
    height: 50,
  }
});

function mapStateToProps(state) {
    return {
      app: state.app,
    };
}

export default connect(
  mapStateToProps
)(Toolbar);

<|endoftext|>


<commit_before>/**
 * StopFlash
 *
 * https://github.com/JWhile/StopFlash
 *
 * background.js
 */

// class BackgroundFlashCollection
function BackgroundFlashCollection(background, id, port)
{
    this.background = background; // :StopFlashBackground

    this.id = id; // :int

    this.data = []; // :Array<Object>

    this.port = port; // :chrome.runtime.Port

    var self = this;

    port.onMessage.addListener(function(msg)
    {
        if(msg['stopflashDataUpdate'] && msg['stopflashData'])
        {
            self.data = msg.stopflashData;

            self.background.sendToPopup();
        }
    });

    port.onDisconnect.addListener(function()
    {
        self.port = null;
    });
}

// class StopFlashBackground
function StopFlashBackground(id)
{
    this.id = id; // :int

    this.collectionId = 0; // :int

    this.collections = []; // :Array<BackgroundFlashCollection>
}
// function getCollection(int id):BackgroundFlashCollection
StopFlashBackground.prototype.getCollection = function(id)
{
    for(var i = 0; i < this.collections.length; ++i)
    {
        if(this.collections[i].id === id)
        {
            return this.collections[i];
        }
    }

    return null;
};
// function addContentScript(chrome.runtime.Port contentPort):void
StopFlashBackground.prototype.addContentScript = function(contentPort)
{
    var id = ++this.collectionId;

    this.collections.push(new BackgroundFlashCollection(this, id, contentPort));

    contentPort.postMessage({'stopflashWhitelist': whitelist, 'stopflashCollectionId': id});
};
// function getData():Array<Object>
StopFlashBackground.prototype.getData = function()
{
    var data = [];

    for(var i = 0; i < this.collections.length; ++i)
    {
        Array.prototype.unshift.apply(data, this.collections[i].data);
    }

    return data;
};
// function sendToPopup():void
StopFlashBackground.prototype.sendToPopup = function()
{
    if(popupPort != null)
    {
        popupPort.postMessage({'stopflashData': this.getData()});
    }
};
// function sendToContent(Object msg):void
StopFlashBackground.prototype.sendToContent = function(msg)
{
    for(var i = 0; i < this.collections.length; ++i)
    {
        this.collections[i].port.postMessage(msg);
    }
};
// function clear():void
StopFlashBackground.prototype.clear = function()
{
    if(this.collections.length > 0)
    {
        for(var i = 0; i < this.collections.length; ++i)
        {
            if(this.collections[i].port != null)
            {
                this.collections[i].port.disconnect();
            }
        }
    }

    this.collections = [];
};

var backgrounds = []; // :Array<StopFlashBackground>
var whitelist = []; // :Array<String>
var popupPort = null; // :chrome.runtime.Port

// function getBackground(int id):StopFlashBackground
var getBackground = function(id)
{
    for(var i = 0; i < backgrounds.length; ++i)
    {
        if(backgrounds[i].id === id)
        {
            return backgrounds[i];
        }
    }

    return null;
};

// main
chrome.runtime.onConnect.addListener(function(port)
{
    if(port.name === 'stopflashContentScript' && port.sender.tab != null)
    {
        var data = null;

        port.onMessage.addListener(function(rep)
        {
            if(rep['stopflashInit'])
            {
                data = getBackground(port.sender.tab.id);

                if(data != null)
                {
                    if(rep['stopflashIsMainFrame'])
                    {
                        data.clear();
                    }
                }
                else
                {
                    data = new StopFlashBackground(port.sender.tab.id);

                    backgrounds.push(data);
                }

                data.addContentScript(port);
            }
        });
    }
    else if(port.name === 'stopflashPopup')
    {
        var data = null;

        port.onMessage.addListener(function(rep)
        {
            if(rep['stopflashInit'])
            {
                data = getBackground(rep['stopflashInit']);

                if(data != null)
                {
                    popupPort = port;

                    port.onDisconnect.addListener(function()
                    {
                        popupPort = null;
                    });

                    data.sendToPopup();
                }
            }

            if(rep['stopflashBlock'])
            {
                var collection = data.getCollection(rep['stopflashBlock'].collection);

                if(collection != null)
                {
                    collection.port.postMessage(rep);
                }
            }

            if(rep['stopflashUnblock'])
            {
                var collection = data.getCollection(rep['stopflashUnblock'].collection);

                if(collection != null)
                {
                    collection.port.postMessage(rep);
                }
            }
        });
    }
});
<commit_msg>Show flash objects count on the icon<commit_after>/**
 * StopFlash
 *
 * https://github.com/JWhile/StopFlash
 *
 * background.js
 */

// class BackgroundFlashCollection
function BackgroundFlashCollection(background, id, port)
{
    this.background = background; // :StopFlashBackground

    this.id = id; // :int

    this.data = []; // :Array<Object>

    this.port = port; // :chrome.runtime.Port

    var self = this;

    port.onMessage.addListener(function(msg)
    {
        if(msg['stopflashDataUpdate'] && msg['stopflashData'])
        {
            self.data = msg.stopflashData;

            self.background.sendToPopup();
        }
    });

    port.onDisconnect.addListener(function()
    {
        self.port = null;
    });
}

// class StopFlashBackground
function StopFlashBackground(id)
{
    this.id = id; // :int

    this.collectionId = 0; // :int

    this.collections = []; // :Array<BackgroundFlashCollection>
}
// function getCollection(int id):BackgroundFlashCollection
StopFlashBackground.prototype.getCollection = function(id)
{
    for(var i = 0; i < this.collections.length; ++i)
    {
        if(this.collections[i].id === id)
        {
            return this.collections[i];
        }
    }

    return null;
};
// function addContentScript(chrome.runtime.Port contentPort):void
StopFlashBackground.prototype.addContentScript = function(contentPort)
{
    var id = ++this.collectionId;

    this.collections.push(new BackgroundFlashCollection(this, id, contentPort));

    contentPort.postMessage({'stopflashWhitelist': whitelist, 'stopflashCollectionId': id});
};
// function getData():Array<Object>
StopFlashBackground.prototype.getData = function()
{
    var data = [];

    for(var i = 0; i < this.collections.length; ++i)
    {
        Array.prototype.unshift.apply(data, this.collections[i].data);
    }

    return data;
};
// function sendToPopup():void
StopFlashBackground.prototype.sendToPopup = function()
{
    if(popupPort != null)
    {
        popupPort.postMessage({'stopflashData': this.getData()});
    }
};
// function sendToContent(Object msg):void
StopFlashBackground.prototype.sendToContent = function(msg)
{
    for(var i = 0; i < this.collections.length; ++i)
    {
        this.collections[i].port.postMessage(msg);
    }
};
// function clear():void
StopFlashBackground.prototype.clear = function()
{
    if(this.collections.length > 0)
    {
        for(var i = 0; i < this.collections.length; ++i)
        {
            if(this.collections[i].port != null)
            {
                this.collections[i].port.disconnect();
            }
        }
    }

    this.collections = [];
};

var backgrounds = []; // :Array<StopFlashBackground>
var whitelist = []; // :Array<String>
var popupPort = null; // :chrome.runtime.Port

// function getBackground(int id):StopFlashBackground
var getBackground = function(id)
{
    for(var i = 0; i < backgrounds.length; ++i)
    {
        if(backgrounds[i].id === id)
        {
            return backgrounds[i];
        }
    }

    return null;
};

// main
chrome.tabs.onHighlighted.addListener(function(info)
{
    var data = getBackground(info.tabIds[0]);

    if(data != null)
    {
        chrome.browserAction.setBadgeText({
          'text': data.getData() || ''
        });
    }
    else
    {
        chrome.browserAction.setBadgeText({
          'text': ''
        });
    }
});

chrome.runtime.onConnect.addListener(function(port)
{
    if(port.name === 'stopflashContentScript' && port.sender.tab != null)
    {
        var data = null;

        port.onMessage.addListener(function(rep)
        {
            if(rep['stopflashInit'])
            {
                data = getBackground(port.sender.tab.id);

                if(data != null)
                {
                    if(rep['stopflashIsMainFrame'])
                    {
                        data.clear();
                    }
                }
                else
                {
                    data = new StopFlashBackground(port.sender.tab.id);

                    backgrounds.push(data);
                }

                data.addContentScript(port);
            }
        });
    }
    else if(port.name === 'stopflashPopup')
    {
        var data = null;

        port.onMessage.addListener(function(rep)
        {
            if(rep['stopflashInit'])
            {
                data = getBackground(rep['stopflashInit']);

                if(data != null)
                {
                    popupPort = port;

                    port.onDisconnect.addListener(function()
                    {
                        popupPort = null;
                    });

                    data.sendToPopup();
                }
            }

            if(rep['stopflashBlock'])
            {
                var collection = data.getCollection(rep['stopflashBlock'].collection);

                if(collection != null)
                {
                    collection.port.postMessage(rep);
                }
            }

            if(rep['stopflashUnblock'])
            {
                var collection = data.getCollection(rep['stopflashUnblock'].collection);

                if(collection != null)
                {
                    collection.port.postMessage(rep);
                }
            }
        });
    }
});
<|endoftext|>


<commit_before>var m = require('mithril');

var boardContent = m('div.cg-board-wrap', m('div.cg-board'));

function miniBoard(game) {
  return m('a', {
    key: game.id,
    href: '/' + game.id + (game.color === 'white' ? '' : '/black'),
    class: 'mini_board live_' + game.id + ' parse_fen is2d',
    'data-color': game.color,
    'data-fen': game.fen,
    'data-lastmove': game.lastMove,
    config: function(el, isUpdate) {
      if (!isUpdate) lichess.parseFen($(el));
    }
  }, boardContent);
}

function ratio2percent(r) {
  return Math.round(100 * r) + '%';
}

module.exports = {
  currentPlayer: function(ctrl, pag) {
    if (!ctrl.userId || !pag.currentPageResults) return null;
    return pag.currentPageResults.filter(function(p) {
      return p.name.toLowerCase() === ctrl.userId;
    })[0] || null;
  },
  player: function(p, tag) {
    var ratingDiff, tag = tag || 'a';
    if (p.ratingDiff > 0) ratingDiff = m('span.positive[data-icon=N]', p.ratingDiff);
    else if (p.ratingDiff < 0) ratingDiff = m('span.negative[data-icon=M]', -p.ratingDiff);
    var rating = p.rating + p.ratingDiff + (p.provisional ? '?' : '');
    var fullName = (p.title ? p.title + ' ' : '') + p.name;
    var attrs = {
      class: 'ulpt user_link' + (fullName.length > 15 ? ' long' : ''),
      config: function(el, isUpdate, ctx) {
        if (!isUpdate) ctx.onunload = function() {
          $.powerTip.destroy(el);
        };
      }
    };
    attrs[tag === 'a' ? 'href' : 'data-href'] = '/@/' + p.name;
    return {
      tag: tag,
      attrs: attrs,
      children: [
        m('span.name', fullName),
        m('span.progress', [rating, ratingDiff])
      ]
    };
  },
  miniBoard: miniBoard,
  ratio2percent: ratio2percent,
  numberRow(name, value, typ) {
    return m('tr', [m('th', name), m('td',
      typ === 'percent' ? (
        value[1] > 0 ? ratio2percent(value[0] / value[1]) : 0
      ) : lichess.numberFormat(value)
    )]);
  }
};
<commit_msg>fix JS style<commit_after>var m = require('mithril');

var boardContent = m('div.cg-board-wrap', m('div.cg-board'));

function miniBoard(game) {
  return m('a', {
    key: game.id,
    href: '/' + game.id + (game.color === 'white' ? '' : '/black'),
    class: 'mini_board live_' + game.id + ' parse_fen is2d',
    'data-color': game.color,
    'data-fen': game.fen,
    'data-lastmove': game.lastMove,
    config: function(el, isUpdate) {
      if (!isUpdate) lichess.parseFen($(el));
    }
  }, boardContent);
}

function ratio2percent(r) {
  return Math.round(100 * r) + '%';
}

module.exports = {
  currentPlayer: function(ctrl, pag) {
    if (!ctrl.userId || !pag.currentPageResults) return null;
    return pag.currentPageResults.filter(function(p) {
      return p.name.toLowerCase() === ctrl.userId;
    })[0] || null;
  },
  player: function(p, tag) {
    var ratingDiff, tag = tag || 'a';
    if (p.ratingDiff > 0) ratingDiff = m('span.positive[data-icon=N]', p.ratingDiff);
    else if (p.ratingDiff < 0) ratingDiff = m('span.negative[data-icon=M]', -p.ratingDiff);
    var rating = p.rating + p.ratingDiff + (p.provisional ? '?' : '');
    var fullName = (p.title ? p.title + ' ' : '') + p.name;
    var attrs = {
      class: 'ulpt user_link' + (fullName.length > 15 ? ' long' : ''),
      config: function(el, isUpdate, ctx) {
        if (!isUpdate) ctx.onunload = function() {
          $.powerTip.destroy(el);
        };
      }
    };
    attrs[tag === 'a' ? 'href' : 'data-href'] = '/@/' + p.name;
    return {
      tag: tag,
      attrs: attrs,
      children: [
        m('span.name', fullName),
        m('span.progress', [rating, ratingDiff])
      ]
    };
  },
  miniBoard: miniBoard,
  ratio2percent: ratio2percent,
  numberRow: function(name, value, typ) {
    return m('tr', [m('th', name), m('td',
      typ === 'percent' ? (
        value[1] > 0 ? ratio2percent(value[0] / value[1]) : 0
      ) : lichess.numberFormat(value)
    )]);
  }
};
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var matchFinder = require('./tagFinder.js');

app.use(express.static(__dirname + '/public'));
var engines = require('consolidate');
app.engine('html', engines.hogan);

app.get('/', function(req, res){
  res.render('petownerfinder.html');
});

app.get('/results', function(req, res){
  console.log(req.query.tag);
  console.log(req.query.blogname);
  matchFinder.getBlogs(req.query.tag, req.query.blogname, function(blogData){res.render('results.jade', {data: blogData});
});

app.get('/lala', function(req, res){
  res.render('lala.html');
});
app.get('/hello', function(req, res){
  res.send('Hello World');
});

app.listen(process.env.PORT || 3000, function(){
  console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
<commit_msg>syntax fix<commit_after>var express = require('express');
var app = express();
var matchFinder = require('./tagFinder.js');

app.use(express.static(__dirname + '/public'));
var engines = require('consolidate');
app.engine('html', engines.hogan);

app.get('/', function(req, res){
  res.render('petownerfinder.html');
});

app.get('/results', function(req, res){
  console.log(req.query.tag);
  console.log(req.query.blogname);
  matchFinder.getBlogs(req.query.tag, req.query.blogname, function(blogData){res.render('results.jade', {data: blogData})});
});

app.get('/lala', function(req, res){
  res.render('lala.html');
});
app.get('/hello', function(req, res){
  res.send('Hello World');
});

app.listen(process.env.PORT || 3000, function(){
  console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
<|endoftext|>