<commit_before>var analytics = require('analytics');
var d3 = require('d3');
var convert = require('convert');
var Feedback = require('feedback-modal');
var mouseenter = require('mouseenter');
var mouseleave = require('mouseleave');
var Calculator = require('route-cost-calculator');
var RouteDirections = require('route-directions-table');
var RouteModal = require('route-modal');
var routeSummarySegments = require('route-summary-segments');
var routeResource = require('route-resource');
var session = require('session');
//var transitive = require('transitive');
var view = require('view');
var showMapView = require('map-view');
/**
 * Expose `View`
 */

var View = module.exports = view(require('./template.html'), function(view, model) {
  mouseenter(view.el, function() {
       clearTimeout();
      var itineration = JSON.parse(localStorage.getItem('itineration'));
      for (var i=0; i<itineration.length;i++) {
           var r3 = d3.selectAll(".iteration-"+i);
           if (i!=model.index){
                r3.transition().duration(500).style("stroke", "#E0E0E0");
                r3.attr("data-show","0");

              var rec2 = d3.selectAll(".circle-fade-"+i);
              rec2.attr('class', 'leaflet-marker-icon leaflet-div-icon2 circle-fade-'+i+ ' leaflet-zoom-hide');
           }else {
                r3.attr("data-show","1");
           }
      }

      var orden = 0;
      d3.selectAll(".iteration-200").each(function(e){
            var element = d3.select(this);
            var parent = d3.select(element.node().parentNode);
            parent.attr("class", "g-element");
            parent.attr("data-orden", orden.toString());
            if (Boolean(parseInt(element.attr("data-show")))) {
                parent.attr("data-show", "1");
            }else {
                parent.attr("data-show", "0");
            }

            orden++;
      });

      d3.selectAll(".g-element").each(function(a,b){
            if (Boolean(parseInt(d3.select(this).attr("data-show")))) {
                d3.select(this).node().parentNode.appendChild(this);
            }

      });
  });

  mouseleave(view.el, function() {
       var itineration = JSON.parse(localStorage.getItem('itineration'));
       for (var i=0; i<itineration.length;i++) {
           if (i!=model.index){
              var rec2 = d3.selectAll(".circle-fade-"+i);
              rec2.attr('class', 'leaflet-marker-icon leaflet-div-icon1 circle-fade-'+i+ ' leaflet-zoom-hide');
           }
       }

        var layer_ordenados = [];
        d3.selectAll(".g-element").each(function(a,b){
            var orden = parseInt(d3.select(this).attr("data-orden"));
            layer_ordenados[orden] = this;

        });

        for (i in layer_ordenados) {
            var element = d3.select(layer_ordenados[i]);
            var child = element.select("path");
            element.attr("data-show", "0");

            child.transition().duration(500).style("stroke",function(i,v){
                    return d3.select(this).attr("stroke");

            });
            child.attr("data-show", "0");
            setTimeout(function(){ element.node().parentNode.appendChild(layer_ordenados[i]); }, 500);
        }

  });
});

View.prototype.calculator = function() {
  return new Calculator(this.model);
};

View.prototype.directions = function() {
  return new RouteDirections(this.model);
};

View.prototype.segments = function() {
  return routeSummarySegments(this.model);
};

View.prototype.costSavings = function() {
  return convert.roundNumberToString(this.model.costSavings());
};

View.prototype.timeSavingsAndNoCostSavings = function() {
  return this.model.timeSavings() && !this.model.costSavings();
};

/**
 * Show/hide
 */

View.prototype.showDetails = function(e) {
  e.preventDefault();
  var el = this.el;
  var expanded = document.querySelector('.option.expanded');
  if (expanded) expanded.classList.remove('expanded');

  el.classList.add('expanded');

  analytics.track('Expanded Route Details', {
    plan: session.plan().generateQuery(),
    route: {
      modes: this.model.modes(),
      summary: this.model.summary()
    }
  });

  var scrollable = document.querySelector('.scrollable');
  scrollable.scrollTop = el.offsetTop - 52;
};

View.prototype.hideDetails = function(e) {
  e.preventDefault();
  var list = this.el.classList;
  if (list.contains('expanded')) {
    list.remove('expanded');
  }
};

/**
 * Get the option number for display purposes (1-based)
 */

View.prototype.optionNumber = function() {
  return this.model.index + 1;
};

/**
 * View
 */

View.prototype.feedback = function(e) {
  e.preventDefault();
  Feedback(this.model).show();
};

/**
 * Select this option
 */

View.prototype.selectOption = function() {
  var route = this.model;
  var plan = session.plan();
  var tags = route.tags(plan);

  analytics.send_ga({
    category: 'route-card',
    action: 'select route',
    label: JSON.stringify(tags),
    value: 1
  });
  routeResource.findByTags(tags, function(err, resources) {
    var routeModal = new RouteModal(route, null, {
      context: 'route-card',
      resources: resources
    });
    routeModal.show();
    routeModal.on('next', function() {
      routeModal.hide();
    });
  });
};
<commit_msg>adding a space<commit_after>var analytics = require('analytics');
var d3 = require('d3');
var convert = require('convert');
var Feedback = require('feedback-modal');
var mouseenter = require('mouseenter');
var mouseleave = require('mouseleave');
var Calculator = require('route-cost-calculator');
var RouteDirections = require('route-directions-table');
var RouteModal = require('route-modal');
var routeSummarySegments = require('route-summary-segments');
var routeResource = require('route-resource');
var session = require('session');
//var transitive = require('transitive');
var view = require('view');
var showMapView = require('map-view');
/**
 * Expose `View`
 */

var View = module.exports = view(require('./template.html'), function(view, model) {
  mouseenter(view.el, function() {
       clearTimeout();
      var itineration = JSON.parse(localStorage.getItem('itineration'));
      for (var i=0; i<itineration.length;i++) {
           var r3 = d3.selectAll(".iteration-"+i);
           if (i!=model.index){
                r3.transition().duration(500).style("stroke", "#E0E0E0");
                r3.attr("data-show","0");

              var rec2 = d3.selectAll(".circle-fade-"+i);
              rec2.attr('class', 'leaflet-marker-icon leaflet-div-icon2 circle-fade-'+i+ ' leaflet-zoom-hide');
           }else {
                r3.attr("data-show","1");
           }
      }

      var orden = 0;
      d3.selectAll(".iteration-200").each(function(e){
            var element = d3.select(this);
            var parent = d3.select(element.node().parentNode);
            parent.attr("class", "g-element");
            parent.attr("data-orden", orden.toString());
            if (Boolean(parseInt(element.attr("data-show")))) {
                parent.attr("data-show", "1");
            }else {
                parent.attr("data-show", "0");
            }

            orden++;
      });

      d3.selectAll(".g-element").each(function(a,b){
            if (Boolean(parseInt(d3.select(this).attr("data-show")))) {
                d3.select(this).node().parentNode.appendChild(this);
            }

      });
  });

  mouseleave(view.el, function() {
     if (!view.el.classList.contains('expanded')) {
       var itineration = JSON.parse(localStorage.getItem('itineration'));
       for (var i=0; i<itineration.length;i++) {
           if (i!=model.index){
              var rec2 = d3.selectAll(".circle-fade-"+i);
              rec2.attr('class', 'leaflet-marker-icon leaflet-div-icon1 circle-fade-'+i+ ' leaflet-zoom-hide');
           }
       }

        var layer_ordenados = [];
        d3.selectAll(".g-element").each(function(a,b){
            var orden = parseInt(d3.select(this).attr("data-orden"));
            layer_ordenados[orden] = this;

        });

        for (i in layer_ordenados) {
            var element = d3.select(layer_ordenados[i]);
            var child = element.select("path");
            element.attr("data-show", "0");

            child.transition().duration(500).style("stroke",function(i,v){
                    return d3.select(this).attr("stroke");

            });
            child.attr("data-show", "0");
            setTimeout(function(){ element.node().parentNode.appendChild(layer_ordenados[i]); }, 500);
        }
     }
  });
});

View.prototype.calculator = function() {
  return new Calculator(this.model);
};

View.prototype.directions = function() {
  return new RouteDirections(this.model);
};

View.prototype.segments = function() {
  return routeSummarySegments(this.model);
};

View.prototype.costSavings = function() {
  return convert.roundNumberToString(this.model.costSavings());
};

View.prototype.timeSavingsAndNoCostSavings = function() {
  return this.model.timeSavings() && !this.model.costSavings();
};

/**
 * Show/hide
 */

View.prototype.showDetails = function(e) {
  e.preventDefault();
  var el = this.el;
  var expanded = document.querySelector('.option.expanded');
  if (expanded) expanded.classList.remove('expanded');

  el.classList.add('expanded');

  analytics.track('Expanded Route Details', {
    plan: session.plan().generateQuery(),
    route: {
      modes: this.model.modes(),
      summary: this.model.summary()
    }
  });

  var scrollable = document.querySelector('.scrollable');
  scrollable.scrollTop = el.offsetTop - 52;
};

View.prototype.hideDetails = function(e) {
  e.preventDefault();
  var list = this.el.classList;
  if (list.contains('expanded')) {
    list.remove('expanded');
  }
};

/**
 * Get the option number for display purposes (1-based)
 */

View.prototype.optionNumber = function() {
  return this.model.index + 1;
};

/**
 * View
 */

View.prototype.feedback = function(e) {
  e.preventDefault();
  Feedback(this.model).show();
};

/**
 * Select this option
 */

View.prototype.selectOption = function() {
  var route = this.model;
  var plan = session.plan();
  var tags = route.tags(plan);

  analytics.send_ga({
    category: 'route-card',
    action: 'select route',
    label: JSON.stringify(tags),
    value: 1
  });
  routeResource.findByTags(tags, function(err, resources) {
    var routeModal = new RouteModal(route, null, {
      context: 'route-card',
      resources: resources
    });
    routeModal.show();
    routeModal.on('next', function() {
      routeModal.hide();
    });
  });
};
<|endoftext|>


<commit_before>import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { LEVEL_INFO, LEVEL_WARNING, LEVEL_ERROR, ErrorNotice, InfoNotice, WarningNotice } from '../Notice';

const localMessages = {
  internalError: { id: 'errors.internal', defaultMessage: 'Internal Error' },
  notLoggedIn: { id: 'errors.notLoggedIn', defaultMessage: 'You need to login' },
  details: { id: 'errors.internal.details', defaultMessage: 'details' },
};

class AppNotice extends React.Component {

  state = {
    showDetails: false,
  };

  render() {
    const { message, htmlMessage, level, details } = this.props.info;
    const { formatMessage } = this.props.intl;
    let stringMessage = message;
    if (typeof message === 'object') {
      stringMessage = formatMessage(message);
    }
    const isLowLevelError = (stringMessage.includes('.pm')) || (stringMessage.includes('.py'));  // ie. does it include a stack trace
    let messageContent = stringMessage;
    let detailsContent = details;
    if ((details === undefined) || (details === null)) {
      if (isLowLevelError) {
        if (stringMessage.includes('Invalid API key or authentication cookie')) {
          messageContent = <FormattedMessage {...localMessages.notLoggedIn} />;
        } else {
          messageContent = <FormattedMessage {...localMessages.internalError} />;
        }
        detailsContent = stringMessage;
      }
    } else if (htmlMessage) {
      messageContent = ();
    }
    let content = null;
    switch (level) {
      case LEVEL_INFO:
        content = (
          <InfoNotice details={detailsContent}>
            {messageContent}
          </InfoNotice>
        );
        break;
      case LEVEL_WARNING:
        content = (
          <WarningNotice details={detailsContent}>
            {messageContent}
          </WarningNotice>
        );
        break;
      case LEVEL_ERROR:
      default:
        content = (
          <ErrorNotice details={detailsContent}>
            {messageContent}
          </ErrorNotice>
        );
        break;
    }
    return (content);
  }

}

AppNotice.propTypes = {
  intl: React.PropTypes.object.isRequired,
  info: React.PropTypes.object.isRequired,
};

export default
  injectIntl(
    AppNotice
  );
<commit_msg>more comments to explain logic of notice handling<commit_after>import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { LEVEL_INFO, LEVEL_WARNING, LEVEL_ERROR, ErrorNotice, InfoNotice, WarningNotice } from '../Notice';

const localMessages = {
  internalError: { id: 'errors.internal', defaultMessage: 'Internal Error' },
  notLoggedIn: { id: 'errors.notLoggedIn', defaultMessage: 'You need to login' },
  details: { id: 'errors.internal.details', defaultMessage: 'details' },
};

class AppNotice extends React.Component {

  state = {
    showDetails: false,
  };

  render() {
    const { message, htmlMessage, level, details } = this.props.info;
    const { formatMessage } = this.props.intl;
    let messageContent;
    let detailsContent = details;
    // handle normal string messages, or intl objects
    if (message) {
      // set a string, or parse an intl message object
      let stringMessage;
      if (typeof message === 'object') {
        stringMessage = formatMessage(message);
      } else {
        stringMessage = message;
      }
      messageContent = stringMessage;
      // set the stack trace as the expandable details if it is a low-level message
      const isLowLevelError = (stringMessage.includes('.pm')) || (stringMessage.includes('.py'));  // ie. does it include a stack trace
      if ((details === undefined) || (details === null)) {
        if (isLowLevelError) {
          if (stringMessage.includes('Invalid API key or authentication cookie')) {
            messageContent = <FormattedMessage {...localMessages.notLoggedIn} />;
          } else {
            messageContent = <FormattedMessage {...localMessages.internalError} />;
          }
          detailsContent = stringMessage;
        }
      }
    // handle html messages
    } else if (htmlMessage) {
      messageContent = ();
    }
    // each level will render differently
    let content = null;
    switch (level) {
      case LEVEL_INFO:
        content = (
          <InfoNotice details={detailsContent}>
            {messageContent}
          </InfoNotice>
        );
        break;
      case LEVEL_WARNING:
        content = (
          <WarningNotice details={detailsContent}>
            {messageContent}
          </WarningNotice>
        );
        break;
      case LEVEL_ERROR:
      default:
        content = (
          <ErrorNotice details={detailsContent}>
            {messageContent}
          </ErrorNotice>
        );
        break;
    }
    return (content);
  }

}

AppNotice.propTypes = {
  intl: React.PropTypes.object.isRequired,
  info: React.PropTypes.object.isRequired,
};

export default
  injectIntl(
    AppNotice
  );
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

let TARGET = process.env.npm_lifecycle_event;

// Determinate application environment
let configPath = `${__dirname}/src/config`;
let envPos = process.argv.indexOf('--env');
let env = (envPos !== -1 && fs.existsSync(`${configPath}/config.${process.argv[++envPos]}.json`)) ? process.argv[envPos] : 'dev';

let common = {

  entry: path.join(__dirname, 'src/app/app.js'),

  module: {
    preLoaders: [],
    loaders: [{
      test: /\.js$/,
      loaders: ['ng-annotate', 'babel'],
      exclude: /node_modules/
    },
    {
      test: /\.html$/,
      loader: 'raw'
    },
    {
      test: /\.json$/,
      loader: 'json'
    },
    {
      test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
      loader: 'file'
    }]
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: './src/public/index.html',
      inject: 'body'
    }),

    new CopyWebpackPlugin([
<% if (angularTranslate) { -%>
      { from: 'src/config/i18n' }
<% } -%>
    ])
  ],

  devServer: {
    contentBase: './src/public',
    stats: 'minimal'
  },

  resolve: {
    alias: {
      'app.config': `${configPath}/config.${env}.json`
    }
  }
};

// Development
if (TARGET === 'serve') {
  module.exports = merge.smart(common, {
    module: {
      loaders: [<% if (cssPreprocessor === 'sass') { %>
      {
        test: /\.scss$/,
        loaders: ['style-loader', 'css-loader', 'sass-loader']
      }<% } else if (cssPreprocessor === 'less') { %>,
      {
        test: /\.less$/,
        loaders: ['style-loader', 'css-loader', 'less-loader']
      }<% } else { %>,
      {
        test: /\.css$/,
        loaders: ['style-loader', 'css-loader']
      }<% } %>]
    }
  });
}

// Production
if (TARGET === 'build') {
  module.exports = merge.smart(common, {
    output: {
      path: __dirname + '/dist',
      publicPath: '/',
      filename: '[name].[hash].js',
      chunkFilename: '[name].[hash].js'
    },

    module: {
      loaders: [<% if (cssPreprocessor === 'sass') { %>
        {
          test: /\.scss$/,
          loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader')
        }<% } else if (cssPreprocessor === 'less') { %>
        {
          test: /\.less$/,
          loader: ExtractTextPlugin.extract('style-loader', 'css-loader!less-loader')
        }<% } else { %>
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
        }<% } %>
      ]
    },

    plugins: [
      new webpack.NoErrorsPlugin(),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin(),
      new CopyWebpackPlugin([{
        from: __dirname + '/src/public'
      }]),
      new ExtractTextPlugin('[name].[hash].css')
    ],
  });
}

// Test
if (TARGET === 'test') {
  module.exports = merge.smart(common, {

  });
}
<commit_msg>chore(webpack): add sourcemaps for development<commit_after>'use strict';

const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

let TARGET = process.env.npm_lifecycle_event;

// Determinate application environment
let configPath = `${__dirname}/src/config`;
let envPos = process.argv.indexOf('--env');
let env = (envPos !== -1 && fs.existsSync(`${configPath}/config.${process.argv[++envPos]}.json`)) ? process.argv[envPos] : 'dev';

let common = {

  entry: path.join(__dirname, 'src/app/app.js'),

  module: {
    preLoaders: [],
    loaders: [{
      test: /\.js$/,
      loaders: ['ng-annotate', 'babel'],
      exclude: /node_modules/
    },
    {
      test: /\.html$/,
      loader: 'raw'
    },
    {
      test: /\.json$/,
      loader: 'json'
    },
    {
      test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
      loader: 'file'
    }]
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: './src/public/index.html',
      inject: 'body'
    }),

    new CopyWebpackPlugin([
<% if (angularTranslate) { -%>
      { from: 'src/config/i18n' }
<% } -%>
    ])
  ],

  devServer: {
    contentBase: './src/public',
    stats: 'minimal'
  },

  resolve: {
    alias: {
      'app.config': `${configPath}/config.${env}.json`
    }
  }
};

// Development
if (TARGET === 'serve') {
  module.exports = merge.smart(common, {
    module: {
      loaders: [<% if (cssPreprocessor === 'sass') { %>
      {
        test: /\.scss$/,
        loaders: ['style-loader', 'css-loader', 'sass-loader']
      }<% } else if (cssPreprocessor === 'less') { %>,
      {
        test: /\.less$/,
        loaders: ['style-loader', 'css-loader', 'less-loader']
      }<% } else { %>,
      {
        test: /\.css$/,
        loaders: ['style-loader', 'css-loader']
      }<% } %>]
    },
    devtool: 'cheap-module-eval-source-map'
  });
}

// Production
if (TARGET === 'build') {
  module.exports = merge.smart(common, {
    output: {
      path: __dirname + '/dist',
      publicPath: '/',
      filename: '[name].[hash].js',
      chunkFilename: '[name].[hash].js'
    },

    module: {
      loaders: [<% if (cssPreprocessor === 'sass') { %>
        {
          test: /\.scss$/,
          loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader')
        }<% } else if (cssPreprocessor === 'less') { %>
        {
          test: /\.less$/,
          loader: ExtractTextPlugin.extract('style-loader', 'css-loader!less-loader')
        }<% } else { %>
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
        }<% } %>
      ]
    },

    plugins: [
      new webpack.NoErrorsPlugin(),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin(),
      new CopyWebpackPlugin([{
        from: __dirname + '/src/public'
      }]),
      new ExtractTextPlugin('[name].[hash].css')
    ],
  });
}

// Test
if (TARGET === 'test') {
  module.exports = merge.smart(common, {

  });
}
<|endoftext|>


<commit_before>let kuro
let _msg
let _table = 'tags'
let _tags = {}

exports.init = function(bot){
	kuro = bot

	// Create the table where we will be storing this module's data
	bot.db.schema.createTableIfNotExists(_table, function (table) {
		table.increments()
		table.string('name')
		table.string('content')
	}).then(function () {

		// Lets load up the existing tags
		bot.db.table(_table).then(function(rows){
			for(let row of rows)
				_tags[row.name] = row.content
		})

	}).catch(function(error) { kuro.error(error) })
}

exports.run = function(msg, args) {

	_msg = msg

	let newargs  = []
	for(let i = 1; i < args.length; i++)
		newargs.push(args[i])

	// Subcommand?
	if(args[0] === 'add') return this.add(newargs)
	if(args[0] === 'del') return this.del(newargs)
	if(args[0] === 'ren') return this.ren(newargs)
	if(args[0] === 'list') return this.list()

	// Not a subcommand, let's see if it's a tag and send it
	if(_tags.hasOwnProperty(args[0])) return _msg.edit(`**__Tag: ${args[0]}__**\n${_tags[args[0]]}`)

	// Not a subcommand, not a tag, let's return the whole list
	return this.list()

}

exports.add = function(args){

	if(args[0] === undefined){
		kuro.edit(_msg, 'No name provided.')
		return
	}

	if(args[1] === undefined){
		kuro.edit(_msg, 'No content provided.')
		return
	}

	let name = args[0]
	let content = args[1]

	// Is the name of the sticker already used?
	if(_tags.hasOwnProperty(name)){
		kuro.edit(_msg, 'Name already in use.')
		return
	}

	kuro.db.table(_table).insert({
		name: name,
		content: content
	}).then(function(){
		_tags[name] = content
		kuro.edit(_msg, 'Tag added', 1000)
	}).catch(function(error) { kuro.error(error) })

}

exports.del = function(args){
	if(args[0] === undefined) return kuro.edit(_msg, 'No name provided.')

	if(args[0] in _tags){
		kuro.db.table(_table).where('name', args[0]).del().then(function(){
			delete(_tags[args[0]])
			return kuro.edit(_msg, 'The tag was removed.', 1000)
		}).catch(function(e){ kuro.edit(_msg, 'Error: \n' + e, 0)})
	}else{
		return kuro.edit(_msg, 'There is no tag by that name.')
	}
}

exports.ren = function(args){
	if(args[0] === undefined) return kuro.edit(_msg, 'No source tag supplied.')
	if(args[1] === undefined) return kuro.edit(_msg, 'No destination tag supplied.')

	if(args[0] in _tags){

		kuro.db.table(_table).where('name', args[0]).update({
			name: args[1]
		}).then(function(){
			_tags[args[1]] = _tags[args[0]]
			delete(_tags[args[0]])
			return kuro.edit(_msg, 'Tag renamed.', 1000)
		}).catch(function(e){ kuro.edit(_msg, 'Error: \n' + e, 0)})

	}else{
		return kuro.edit(_msg, 'There is no tag by that name.')
	}
}

exports.list = function(){
	let list = ''
	for (let tag in _tags)
		if ({}.hasOwnProperty.call(_tags, tag))
			list = list + tag + ', '

	list = list.substr(0, list.length - 2)
	_msg.edit(`**__Tags list__**\n\`\`\`\n${list}\n\`\`\``)
}

exports.tagsCount = function(){
	return Object.keys(_tags).length
}

exports.startServer = function(){}
<commit_msg>Fixed buf on tags module<commit_after>let kuro
let _msg
let _table = 'tags'
let _tags = {}

exports.init = function(bot){
	kuro = bot

	// Create the table where we will be storing this module's data
	bot.db.schema.createTableIfNotExists(_table, function (table) {
		table.increments()
		table.string('name')
		table.string('content')
	}).then(function () {

		// Lets load up the existing tags
		bot.db.table(_table).then(function(rows){
			for(let row of rows)
				_tags[row.name] = row.content
		})

	}).catch(function(error) { kuro.error(error) })
}

exports.run = function(msg, args) {

	_msg = msg

	let newargs  = []
	for(let i = 1; i < args.length; i++)
		newargs.push(args[i])

	// Subcommand?
	if(args[0] === 'add') return this.add(newargs)
	if(args[0] === 'del') return this.del(newargs)
	if(args[0] === 'ren') return this.ren(newargs)
	if(args[0] === 'list') return this.list()

	// Not a subcommand, let's see if it's a tag and send it
	if(_tags.hasOwnProperty(args[0])) return _msg.edit(`**__Tag: ${args[0]}__**\n${_tags[args[0]]}`)

	// Not a subcommand, not a tag, let's return the whole list
	return this.list()

}

exports.add = function(args){

	if(args[0] === undefined){
		kuro.edit(_msg, 'No name provided.')
		return
	}

	if(args[1] === undefined){
		kuro.edit(_msg, 'No content provided.')
		return
	}

	let name = args[0]
	let content = args.slice(1).join(' ')

	// Is the name of the sticker already used?
	if(_tags.hasOwnProperty(name)){
		kuro.edit(_msg, 'Name already in use.')
		return
	}

	kuro.db.table(_table).insert({
		name: name,
		content: content
	}).then(function(){
		_tags[name] = content
		kuro.edit(_msg, 'Tag added', 1000)
	}).catch(function(error) { kuro.error(error) })

}

exports.del = function(args){
	if(args[0] === undefined) return kuro.edit(_msg, 'No name provided.')

	if(args[0] in _tags){
		kuro.db.table(_table).where('name', args[0]).del().then(function(){
			delete(_tags[args[0]])
			return kuro.edit(_msg, 'The tag was removed.', 1000)
		}).catch(function(e){ kuro.edit(_msg, 'Error: \n' + e, 0)})
	}else{
		return kuro.edit(_msg, 'There is no tag by that name.')
	}
}

exports.ren = function(args){
	if(args[0] === undefined) return kuro.edit(_msg, 'No source tag supplied.')
	if(args[1] === undefined) return kuro.edit(_msg, 'No destination tag supplied.')

	if(args[0] in _tags){

		kuro.db.table(_table).where('name', args[0]).update({
			name: args[1]
		}).then(function(){
			_tags[args[1]] = _tags[args[0]]
			delete(_tags[args[0]])
			return kuro.edit(_msg, 'Tag renamed.', 1000)
		}).catch(function(e){ kuro.edit(_msg, 'Error: \n' + e, 0)})

	}else{
		return kuro.edit(_msg, 'There is no tag by that name.')
	}
}

exports.list = function(){
	let list = ''
	for (let tag in _tags)
		if ({}.hasOwnProperty.call(_tags, tag))
			list = list + tag + ', '

	list = list.substr(0, list.length - 2)
	_msg.edit(`**__Tags list__**\n\`\`\`\n${list}\n\`\`\``)
}

exports.tagsCount = function(){
	return Object.keys(_tags).length
}

exports.startServer = function(){}
<|endoftext|>


<commit_before>var analytics = require('analytics');
var d3 = require('d3');
var convert = require('convert');
var Feedback = require('feedback-modal');
var mouseenter = require('mouseenter');
var mouseleave = require('mouseleave');
var Calculator = require('route-cost-calculator');
var RouteDirections = require('route-directions-table');
var RouteModal = require('route-modal');
var routeSummarySegments = require('route-summary-segments');
var routeResource = require('route-resource');
var session = require('session');
//var transitive = require('transitive');
var view = require('view');
var showMapView = require('map-view');
/**
 * Expose `View`
 */

var View = module.exports = view(require('./template.html'), function(view, model) {
  mouseenter(view.el, function() {

      var itineration = JSON.parse(localStorage.getItem('itineration'));

      console.log("obj itineration 1 ->", itineration.length);
      var element = [];
      for (var i=0; i<itineration.length;i++) {
           var r3 = d3.selectAll(".iteration-"+i);
           if (i!=model.index){

                r3.transition().duration(500).style("stroke", "#E0E0E0");
                r3.attr("color", "#ffffff");
                //.transition().duration(400).classed("hide-route", true);
                /*
                rec.setAttribute('data-color', function(d){
                    return this.stroke;
                })
                */
                //.transition().duration(400).style("stroke", "#E0E0E0");
                //.style("opacity", 1)
                //.transition().duration(500).style("opacity", 0);
               //.transition().duration(400).style("stroke", "#E0E0E0");
               //.style("opacity", 1)
           }else {
                r3.attr("color", "#000000");
           }
      }

      var todos = d3.selectAll(".iteration-200");
      todos[0].sort(function(a,b){
            console.log("tiene", a ,this);
      });

  /*
    showMapView.cleanPolyline();
    showMapView.cleanMarkerpoint();
    showMapView.cleanMarkerCollision();
    showMapView.marker_collision_group = [];

    var sesion_plan = JSON.parse(localStorage.getItem('dataplan'));
    sesion_plan = sesion_plan.plan;

     var index_ = model.index;
     var stroke;
     var itineraries = sesion_plan.itineraries;
      for (var i= 0; i < itineraries.length; i++) {
          if (i != index_){
            stroke = {'stroke':true, 'class_name':true}
          }else{
            stroke = {'stroke':false, 'class_name':false}
          }
          for (var j=0; j < itineraries[i].legs.length; j++) {
             showMapView.drawRouteAmigo(itineraries[i].legs[j], itineraries[i].legs[j].mode, stroke);
          }
      }
      showMapView.drawMakerCollision();
    */
  });

  mouseleave(view.el, function() {

  var itineration = JSON.parse(localStorage.getItem('itineration'));
   console.log("obj itineration 2->", itineration.length);
   for (var i=0; i<itineration.length;i++) {

        if (i!=model.index){

            var element = d3.selectAll(".iteration-"+i)
            .transition().duration(500)
            .style('stroke', function(d){
                    return this.stroke;
                });

            console.log(element);
            /*
                d3.selectAll(".iteration-"+i).transition()
                .attr('stroke', function(d){
                    console.log(this);
                    return this["data-color"];
                });
                */
                //.transition().duration(500).style("opacity", 1);
                //.style("opacity", 0)
               //.transition().duration(400).style("stroke", "#E0E0E0");
               //.style("opacity", 0)
        }
   }
  /*
    if (!view.el.classList.contains('expanded')) {
      showMapView.cleanPolyline();
      showMapView.cleanMarkerpoint();
      showMapView.cleanMarkerCollision();
      showMapView.marker_collision_group = [];

      var option_draw = {'stroke':false, 'class_name':false};
      var sesion_plan = JSON.parse(localStorage.getItem('dataplan'));
      sesion_plan = sesion_plan.plan;
      var itineraries = sesion_plan.itineraries;
      for (i = 0; i < itineraries.length; i++) {
          for (ii=0; ii < itineraries[i].legs.length; ii++) {
            showMapView.drawRouteAmigo(itineraries[i].legs[ii], itineraries[i].legs[ii].mode, option_draw);
          }
      }
      showMapView.drawMakerCollision();

    }
    */
  });
});

View.prototype.calculator = function() {
  return new Calculator(this.model);
};

View.prototype.directions = function() {
  return new RouteDirections(this.model);
};

View.prototype.segments = function() {
  return routeSummarySegments(this.model);
};

View.prototype.costSavings = function() {
  return convert.roundNumberToString(this.model.costSavings());
};

View.prototype.timeSavingsAndNoCostSavings = function() {
  return this.model.timeSavings() && !this.model.costSavings();
};

/**
 * Show/hide
 */

View.prototype.showDetails = function(e) {
  e.preventDefault();
  var el = this.el;
  var expanded = document.querySelector('.option.expanded');
  if (expanded) expanded.classList.remove('expanded');

  el.classList.add('expanded');

  analytics.track('Expanded Route Details', {
    plan: session.plan().generateQuery(),
    route: {
      modes: this.model.modes(),
      summary: this.model.summary()
    }
  });

  var scrollable = document.querySelector('.scrollable');
  scrollable.scrollTop = el.offsetTop - 52;
};

View.prototype.hideDetails = function(e) {
  e.preventDefault();
  var list = this.el.classList;
  if (list.contains('expanded')) {
    list.remove('expanded');
  }
};

/**
 * Get the option number for display purposes (1-based)
 */

View.prototype.optionNumber = function() {
  return this.model.index + 1;
};

/**
 * View
 */

View.prototype.feedback = function(e) {
  e.preventDefault();
  Feedback(this.model).show();
};

/**
 * Select this option
 */

View.prototype.selectOption = function() {
  var route = this.model;
  var plan = session.plan();
  var tags = route.tags(plan);

  analytics.send_ga({
    category: 'route-card',
    action: 'select route',
    label: JSON.stringify(tags),
    value: 1
  });
  routeResource.findByTags(tags, function(err, resources) {
    var routeModal = new RouteModal(route, null, {
      context: 'route-card',
      resources: resources
    });
    routeModal.show();
    routeModal.on('next', function() {
      routeModal.hide();
    });
  });
};
<commit_msg>data color<commit_after>var analytics = require('analytics');
var d3 = require('d3');
var convert = require('convert');
var Feedback = require('feedback-modal');
var mouseenter = require('mouseenter');
var mouseleave = require('mouseleave');
var Calculator = require('route-cost-calculator');
var RouteDirections = require('route-directions-table');
var RouteModal = require('route-modal');
var routeSummarySegments = require('route-summary-segments');
var routeResource = require('route-resource');
var session = require('session');
//var transitive = require('transitive');
var view = require('view');
var showMapView = require('map-view');
/**
 * Expose `View`
 */

var View = module.exports = view(require('./template.html'), function(view, model) {
  mouseenter(view.el, function() {

      var itineration = JSON.parse(localStorage.getItem('itineration'));

      console.log("obj itineration 1 ->", itineration.length);
      var element = [];
      for (var i=0; i<itineration.length;i++) {
           var r3 = d3.selectAll(".iteration-"+i);
           if (i!=model.index){

                r3.transition().duration(500).style("stroke", "#E0E0E0");
                r3.attr("color", "#ffffff");
                //.transition().duration(400).classed("hide-route", true);
                /*
                rec.setAttribute('data-color', function(d){
                    return this.stroke;
                })
                */
                //.transition().duration(400).style("stroke", "#E0E0E0");
                //.style("opacity", 1)
                //.transition().duration(500).style("opacity", 0);
               //.transition().duration(400).style("stroke", "#E0E0E0");
               //.style("opacity", 1)
           }else {
                r3.attr("color", "#000000");
           }
      }

      var todos = d3.selectAll(".iteration-200");
      todos[0].sort(function(a,b){
            console.log("tiene", a ,a.attr("color"));
      });

  /*
    showMapView.cleanPolyline();
    showMapView.cleanMarkerpoint();
    showMapView.cleanMarkerCollision();
    showMapView.marker_collision_group = [];

    var sesion_plan = JSON.parse(localStorage.getItem('dataplan'));
    sesion_plan = sesion_plan.plan;

     var index_ = model.index;
     var stroke;
     var itineraries = sesion_plan.itineraries;
      for (var i= 0; i < itineraries.length; i++) {
          if (i != index_){
            stroke = {'stroke':true, 'class_name':true}
          }else{
            stroke = {'stroke':false, 'class_name':false}
          }
          for (var j=0; j < itineraries[i].legs.length; j++) {
             showMapView.drawRouteAmigo(itineraries[i].legs[j], itineraries[i].legs[j].mode, stroke);
          }
      }
      showMapView.drawMakerCollision();
    */
  });

  mouseleave(view.el, function() {

  var itineration = JSON.parse(localStorage.getItem('itineration'));
   console.log("obj itineration 2->", itineration.length);
   for (var i=0; i<itineration.length;i++) {

        if (i!=model.index){

            var element = d3.selectAll(".iteration-"+i)
            .transition().duration(500)
            .style('stroke', function(d){
                    return this.stroke;
                });

            console.log(element);
            /*
                d3.selectAll(".iteration-"+i).transition()
                .attr('stroke', function(d){
                    console.log(this);
                    return this["data-color"];
                });
                */
                //.transition().duration(500).style("opacity", 1);
                //.style("opacity", 0)
               //.transition().duration(400).style("stroke", "#E0E0E0");
               //.style("opacity", 0)
        }
   }
  /*
    if (!view.el.classList.contains('expanded')) {
      showMapView.cleanPolyline();
      showMapView.cleanMarkerpoint();
      showMapView.cleanMarkerCollision();
      showMapView.marker_collision_group = [];

      var option_draw = {'stroke':false, 'class_name':false};
      var sesion_plan = JSON.parse(localStorage.getItem('dataplan'));
      sesion_plan = sesion_plan.plan;
      var itineraries = sesion_plan.itineraries;
      for (i = 0; i < itineraries.length; i++) {
          for (ii=0; ii < itineraries[i].legs.length; ii++) {
            showMapView.drawRouteAmigo(itineraries[i].legs[ii], itineraries[i].legs[ii].mode, option_draw);
          }
      }
      showMapView.drawMakerCollision();

    }
    */
  });
});

View.prototype.calculator = function() {
  return new Calculator(this.model);
};

View.prototype.directions = function() {
  return new RouteDirections(this.model);
};

View.prototype.segments = function() {
  return routeSummarySegments(this.model);
};

View.prototype.costSavings = function() {
  return convert.roundNumberToString(this.model.costSavings());
};

View.prototype.timeSavingsAndNoCostSavings = function() {
  return this.model.timeSavings() && !this.model.costSavings();
};

/**
 * Show/hide
 */

View.prototype.showDetails = function(e) {
  e.preventDefault();
  var el = this.el;
  var expanded = document.querySelector('.option.expanded');
  if (expanded) expanded.classList.remove('expanded');

  el.classList.add('expanded');

  analytics.track('Expanded Route Details', {
    plan: session.plan().generateQuery(),
    route: {
      modes: this.model.modes(),
      summary: this.model.summary()
    }
  });

  var scrollable = document.querySelector('.scrollable');
  scrollable.scrollTop = el.offsetTop - 52;
};

View.prototype.hideDetails = function(e) {
  e.preventDefault();
  var list = this.el.classList;
  if (list.contains('expanded')) {
    list.remove('expanded');
  }
};

/**
 * Get the option number for display purposes (1-based)
 */

View.prototype.optionNumber = function() {
  return this.model.index + 1;
};

/**
 * View
 */

View.prototype.feedback = function(e) {
  e.preventDefault();
  Feedback(this.model).show();
};

/**
 * Select this option
 */

View.prototype.selectOption = function() {
  var route = this.model;
  var plan = session.plan();
  var tags = route.tags(plan);

  analytics.send_ga({
    category: 'route-card',
    action: 'select route',
    label: JSON.stringify(tags),
    value: 1
  });
  routeResource.findByTags(tags, function(err, resources) {
    var routeModal = new RouteModal(route, null, {
      context: 'route-card',
      resources: resources
    });
    routeModal.show();
    routeModal.on('next', function() {
      routeModal.hide();
    });
  });
};
<|endoftext|>


<commit_before>// Building a new feature that uses MutationObserver? You don't need to modify this file
// Instead of adding conditionals to this file try the example from /shared/example.js

(function poll() {
  if (ynabToolKit.pageReady === true && typeof ynabToolKit.shared.feedChanges !== 'undefined') {

    // When this is true, the feature scripts will know they can use the mutationObserver
    ynabToolKit.actOnChangeInit = {};

    // Set 'ynabToolKit.debugNodes = true' to print changes the mutationObserver sees
    // during page interactions and updates to the developer tools console.
    ynabToolKit.debugNodes = false;

    ynabToolKit.actOnChange = function() {

      MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

      var observer = new MutationObserver(function(mutations, observer) {

        if (ynabToolKit.debugNodes) {
          console.log('MODIFIED NODES');
        }

        ynabToolKit.changedNodes = new Set();

        mutations.forEach(function(mutation) {
          var newNodes = mutation.target;
          if (ynabToolKit.debugNodes) {
            console.log(newNodes);
          }

          var $nodes = $(newNodes); // jQuery set
          $nodes.each(function() {
            var nodeClass = $(this).attr('class');
            if (nodeClass) ynabToolKit.changedNodes.add(nodeClass.replace(/^ember-view /,''));
          }); // each node mutation event

        }); // each mutation event

        if (ynabToolKit.debugNodes) {
          console.log(ynabToolKit.changedNodes);
          console.log('###');
        }

        // Now we are ready to feed the change digest to the
        // automatically setup feedChanges file/function
        ynabToolKit.shared.feedChanges(ynabToolKit.changedNodes);

      });

      // This finally says 'Watch for changes' and only needs to be called the one time
      observer.observe($('.ember-view.layout')[0], {
        subtree : true,
        childList : true,
        characterData : true,
        attributes: true,
        attributeFilter : [ 'class' ]
      });

      ynabToolKit.actOnChangeInit = true;
    };
    ynabToolKit.actOnChange(); // Run itself once

  } else {
    setTimeout(poll, 250);
  }
})();
<commit_msg>No need to call act on change functions if the set is empty. Guarding with an if.<commit_after>// Building a new feature that uses MutationObserver? You don't need to modify this file
// Instead of adding conditionals to this file try the example from /shared/example.js

(function poll() {
  if (ynabToolKit.pageReady === true && typeof ynabToolKit.shared.feedChanges !== 'undefined') {

    // When this is true, the feature scripts will know they can use the mutationObserver
    ynabToolKit.actOnChangeInit = {};

    // Set 'ynabToolKit.debugNodes = true' to print changes the mutationObserver sees
    // during page interactions and updates to the developer tools console.
    ynabToolKit.debugNodes = false;

    ynabToolKit.actOnChange = function() {

      MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

      var observer = new MutationObserver(function(mutations, observer) {

        if (ynabToolKit.debugNodes) {
          console.log('MODIFIED NODES');
        }

        ynabToolKit.changedNodes = new Set();

        mutations.forEach(function(mutation) {
          var newNodes = mutation.target;
          if (ynabToolKit.debugNodes) {
            console.log(newNodes);
          }

          var $nodes = $(newNodes); // jQuery set
          $nodes.each(function() {
            var nodeClass = $(this).attr('class');
            if (nodeClass) ynabToolKit.changedNodes.add(nodeClass.replace(/^ember-view /,''));
          }); // each node mutation event

        }); // each mutation event

        if (ynabToolKit.debugNodes) {
          console.log(ynabToolKit.changedNodes);
          console.log('###');
        }

        // Now we are ready to feed the change digest to the
        // automatically setup feedChanges file/function
        if (ynabToolKit.changedNodes.size > 0) {
          ynabToolKit.shared.feedChanges(ynabToolKit.changedNodes);
        }
      });

      // This finally says 'Watch for changes' and only needs to be called the one time
      observer.observe($('.ember-view.layout')[0], {
        subtree : true,
        childList : true,
        characterData : true,
        attributes: true,
        attributeFilter : [ 'class' ]
      });

      ynabToolKit.actOnChangeInit = true;
    };
    ynabToolKit.actOnChange(); // Run itself once

  } else {
    setTimeout(poll, 250);
  }
})();
<|endoftext|>


<commit_before>// ==UserScript==
// @name		Mega Scratch Userscript
// @author		MegaScratchUserscript (collab with some Scratch ATers: https://github.com/MegaScratchUserscript/Mega-Scratch-Userscript#-mega-scratch-userscript)
// @description	A mega userscript with tons of epic uses!
// @include		http://scratch.mit.edu/*
// @version		1.0.0
// @grant		unsafeWindow
// @grant		GM_getResourceText
// @grant		GM_addStyle
// @icon		https://cdn.rawgit.com/MegaScratchUserscript/Mega-Scratch-Userscript/master/resources/icon.png
// @resource	settingshtml resources/settings.htmlpart
// @resource	settingscss resources/settings.css
// @resource	theme resources/theme.csspart
// @require		https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require		https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js
// @require		resources/waitForKeyElements.js
// @require		resources/msuinit.js
// @require		resources/extensions.js
// @require		parts/scratchforum.part.js
// @require		parts/colortheme.part.js
// @require		parts/scratchystuff.part.js
// @require		parts/feed.part.js
// @require		parts/messages.part.js
// @require		parts/titlemessages.part.js
// @require		parts/profileenhancer.part.js
// @require		parts/wikilink.part.js
// @require		parts/scratchtheme.part.js
// ==/UserScript==

// I called this base.user.js in case this is the main script
var ScratchUserscript = {
    MODE_DEV: true, // change to false in the release; use this flag to print data to console for debug, etc
	_settingsHTML: $("

"),
	_partsEnabled: {},
	_init: function(){
		if(typeof localStorage != 'undefined'){
			if(typeof localStorage.msuPartsEnabled == 'undefined'){
				localStorage.msuPartsEnabled = "{themeeffects:false}";
			}
			ScratchUserscript._partsEnabled = JSON.parse(localStorage.msuPartsEnabled);
		}
		ScratchUserscript._settingsHTML.css("display","none").appendTo(document.body).dialog({dialogClass:"jqui-modal", autoOpen: false, width: 800, height: 550});
		$("#msu-settings-dialog").parent().append('<html><head></head><body></body></html>');
		ScratchUserscript._settingsHTML.html(GM_getResourceText("settingshtml"));
		GM_addStyle(GM_getResourceText("settingscss"));
		var openSettings = $("<acronym title='Mega Scratch Userscript'>MSU</acronym> Settings");
		openSettings.click(function(){
			ScratchUserscript._settingsHTML.dialog("open");
		});
		$("

").append(openSettings).insertBefore($(".user-nav .logout"));

		for(x in msuParts){
			if(typeof msuParts[x] !== "undefined"){
				(msuParts[x])(ScratchUserscript);
			}
		}
		if(ScratchUserscript.MODE_DEV){
			console.log("Scratchuserscript started!");
		}
	},
	readSetting: function(partName, settingName, defaultValue){
		if(typeof localStorage != 'undefined'){
			var settings = {};
			if(typeof localStorage.msuSettingsStorage != 'undefined'){
				settings = JSON.parse(localStorage.msuSettingsStorage);
			}
			if(settings.hasOwnProperty(partName+"-"+settingName)){
				return settings[partName+"-"+settingName];
			} else return defaultValue;
		}
	},
	writeSetting: function(partName, settingName, settingValue){
		if(typeof localStorage != 'undefined'){
			var settings = {};
			if(typeof localStorage.msuSettingsStorage != 'undefined'){
				settings = JSON.parse(localStorage.msuSettingsStorage);
			}
			settings[partName+"-"+settingName] = settingValue;
			localStorage.msuSettingsStorage = JSON.stringify(settings);
		}
	},
	/**
	 * Returns if a part is enabled (as per the settings GUI)
	 * It's up to parts to call this and check
	 * @return true if enabled, false otherwise
	 */
	isPartEnabled: function(name){
		if(!ScratchUserscript._partsEnabled.hasOwnProperty(name.replace(/[^a-zA-Z\d]/g, "").toLowerCase())){
			return true; // not in the object = enabled
		}
		if(ScratchUserscript._partsEnabled[name.replace(/[^a-zA-Z\d]/g, "").toLowerCase()]){
			return true;
		}
		return false;
	},
	/**
	 * Registers a part of the userscript onto the settings dialog
	 * @param name The name of the part
	 * @param description A description
	 * @param settings HTML for the part's settings page, if any
	 */
	registerPart: function(name, description, settings){
		// almost verbatim copied from my test JSFiddle: http://jsfiddle.net/a8cewv3u/
		// very messy, should be cleaned up

		var qualifiedName = name.replace(/[^a-zA-Z\d]/g, "").toLowerCase();
		if(ScratchUserscript.MODE_DEV)
			console.log("Part registered name="+name+" qualifiedName="+qualifiedName);
		var li = $("

");
		var isEnabled = ScratchUserscript.isPartEnabled(name);
		li.append($("<input data-ischeck='yup' type='checkbox' title='Enable this' id='enable-" + qualifiedName + "' data-for='" + qualifiedName + "' />")
				.bind('change', function () {
			ck = $(this).is(":checked");
			$("#isenabled-" + $(this).attr("data-for")).text(ck ? "yes":"no");
			ScratchUserscript._partsEnabled[$(this).attr("data-for")] = ck;
			if(typeof localStorage != 'undefined'){
				localStorage.msuPartsEnabled = JSON.stringify(ScratchUserscript._partsEnabled);
			}
		}).attr("checked", isEnabled));
		li.append($("" + name + "").attr("data-for", qualifiedName));
		li.click(function (e) {
			if ($(e.target).attr("data-ischeck") == 'yup') return;
			ScratchUserscript._settingsHTML.find(".msu-settings-content-div").slideUp();
			ScratchUserscript._settingsHTML.find("#msu-settings-content-" + $(this).find("label").attr("data-for")).slideDown();
			ScratchUserscript._settingsHTML.find(".msu-settings-side-tabs li").removeClass("sel");
			$(this).addClass("sel");
		});
		ScratchUserscript._settingsHTML.find(".msu-settings-side-tabs").append(li);
		var content = $("

");
		content.append("
" + name + "
").append("Enabled: no
");
		if(isEnabled) content.find("#isenabled-"+qualifiedName).text("yes");
		content.append("Description: "+description + "

")
			.append(settings == null ? "No additional settings" : settings);
		content.attr("id", "msu-settings-content-" + qualifiedName)
			.css("display", "none").addClass("msu-settings-content-div")
			.appendTo(ScratchUserscript._settingsHTML.find(".msu-settings-content"));
		if(ScratchUserscript._settingsHTML.find('.msu-settings-side-tabs li.sel').length==0){
			li.addClass("sel");
			content.show();
		}
	},
	/**
	 * Gets the page type
	 * @return The type, in the form of a JSON object:
	 *		type: either project, studio, messages, mystuff, settings, forum, profile, or unknown
	 *		subtype: in forums, either section, topic, or null
	 *  	id: the forum topic id, project id, studio id, etc
	 */
	getPageType: function(){
		var obj = {type: "unknown", subtype: null, id: null};
		if (/^\/projects\/\d+\/$/.test(location.pathname)){
			obj.type = "project";
			obj.id = parseInt(/^\/projects\/(\d+)\/$/.exec(location.pathname)[1]);
		}
		if (/^\/studios\/\d+\/$/.test(location.pathname)){
			obj.type = "studio";
			obj.id = parseInt(/^\/studios\/(\d+)\/$/.exec(location.pathname)[1]);
		}
		if (/^\/users\/[a-zA-Z0-9\-_]+\/$/.test(location.pathname)){
			obj.type = "profile";
			obj.id = /^\/users\/([a-zA-Z0-9\-_]+)\/$/.exec(location.pathname)[1];
		}
		if(/^\/discuss\//.test(location.pathname)){
			obj.type = "forum";
			if(/^\/discuss\/\d+\/$/.test(location.pathname)){
				obj.subtype = "section";
				obj.id = parseInt(/^\/discuss\/(\d+)\/$/.exec(location.pathname)[1]);
			}
			if(/^\/discuss\/topic\/\d+\//.test(location.pathname)){
				obj.subtype = "topic";
				obj.id = parseInt(/^\/discuss\/topic\/(\d+)\//.exec(location.pathname)[1]);
			}
		}
		if (/^\/accounts\/(password_change|email_change|change_country)\/$/.test(location.pathname)){
			obj.type = "settings";
		}
		if (location.pathname == '/messages/'){
			obj.type = "messages";
		}
		if (location.pathname == '/mystuff/'){
			obj.type = "mystuff";
		}
		return obj;
	},
	/**
	 * @return The username of the currently logged in user, or null if not logged in
	 */
	getUsername: function(){
		return unsafeWindow.Scratch.INIT_DATA.LOGGED_IN_USER.model ? unsafeWindow.Scratch.INIT_DATA.LOGGED_IN_USER.model.username : null;
	}
};

$(document).ready(ScratchUserscript._init);
<commit_msg>stupid json parser<commit_after>// ==UserScript==
// @name		Mega Scratch Userscript
// @author		MegaScratchUserscript (collab with some Scratch ATers: https://github.com/MegaScratchUserscript/Mega-Scratch-Userscript#-mega-scratch-userscript)
// @description	A mega userscript with tons of epic uses!
// @include		http://scratch.mit.edu/*
// @version		1.0.0
// @grant		unsafeWindow
// @grant		GM_getResourceText
// @grant		GM_addStyle
// @icon		https://cdn.rawgit.com/MegaScratchUserscript/Mega-Scratch-Userscript/master/resources/icon.png
// @resource	settingshtml resources/settings.htmlpart
// @resource	settingscss resources/settings.css
// @resource	theme resources/theme.csspart
// @require		https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require		https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js
// @require		resources/waitForKeyElements.js
// @require		resources/msuinit.js
// @require		resources/extensions.js
// @require		parts/scratchforum.part.js
// @require		parts/colortheme.part.js
// @require		parts/scratchystuff.part.js
// @require		parts/feed.part.js
// @require		parts/messages.part.js
// @require		parts/titlemessages.part.js
// @require		parts/profileenhancer.part.js
// @require		parts/wikilink.part.js
// @require		parts/scratchtheme.part.js
// ==/UserScript==

// I called this base.user.js in case this is the main script
var ScratchUserscript = {
    MODE_DEV: true, // change to false in the release; use this flag to print data to console for debug, etc
	_settingsHTML: $("

"),
	_partsEnabled: {},
	_init: function(){
		if(typeof localStorage != 'undefined'){
			if(typeof localStorage.msuPartsEnabled == 'undefined'){
				localStorage.msuPartsEnabled = "{\"themeeffects\":false}";
			}
			ScratchUserscript._partsEnabled = JSON.parse(localStorage.msuPartsEnabled);
		}
		ScratchUserscript._settingsHTML.css("display","none").appendTo(document.body).dialog({dialogClass:"jqui-modal", autoOpen: false, width: 800, height: 550});
		$("#msu-settings-dialog").parent().append('<html><head></head><body></body></html>');
		ScratchUserscript._settingsHTML.html(GM_getResourceText("settingshtml"));
		GM_addStyle(GM_getResourceText("settingscss"));
		var openSettings = $("<acronym title='Mega Scratch Userscript'>MSU</acronym> Settings");
		openSettings.click(function(){
			ScratchUserscript._settingsHTML.dialog("open");
		});
		$("

").append(openSettings).insertBefore($(".user-nav .logout"));

		for(x in msuParts){
			if(typeof msuParts[x] !== "undefined"){
				(msuParts[x])(ScratchUserscript);
			}
		}
		if(ScratchUserscript.MODE_DEV){
			console.log("Scratchuserscript started!");
		}
	},
	readSetting: function(partName, settingName, defaultValue){
		if(typeof localStorage != 'undefined'){
			var settings = {};
			if(typeof localStorage.msuSettingsStorage != 'undefined'){
				settings = JSON.parse(localStorage.msuSettingsStorage);
			}
			if(settings.hasOwnProperty(partName+"-"+settingName)){
				return settings[partName+"-"+settingName];
			} else return defaultValue;
		}
	},
	writeSetting: function(partName, settingName, settingValue){
		if(typeof localStorage != 'undefined'){
			var settings = {};
			if(typeof localStorage.msuSettingsStorage != 'undefined'){
				settings = JSON.parse(localStorage.msuSettingsStorage);
			}
			settings[partName+"-"+settingName] = settingValue;
			localStorage.msuSettingsStorage = JSON.stringify(settings);
		}
	},
	/**
	 * Returns if a part is enabled (as per the settings GUI)
	 * It's up to parts to call this and check
	 * @return true if enabled, false otherwise
	 */
	isPartEnabled: function(name){
		if(!ScratchUserscript._partsEnabled.hasOwnProperty(name.replace(/[^a-zA-Z\d]/g, "").toLowerCase())){
			return true; // not in the object = enabled
		}
		if(ScratchUserscript._partsEnabled[name.replace(/[^a-zA-Z\d]/g, "").toLowerCase()]){
			return true;
		}
		return false;
	},
	/**
	 * Registers a part of the userscript onto the settings dialog
	 * @param name The name of the part
	 * @param description A description
	 * @param settings HTML for the part's settings page, if any
	 */
	registerPart: function(name, description, settings){
		// almost verbatim copied from my test JSFiddle: http://jsfiddle.net/a8cewv3u/
		// very messy, should be cleaned up

		var qualifiedName = name.replace(/[^a-zA-Z\d]/g, "").toLowerCase();
		if(ScratchUserscript.MODE_DEV)
			console.log("Part registered name="+name+" qualifiedName="+qualifiedName);
		var li = $("

");
		var isEnabled = ScratchUserscript.isPartEnabled(name);
		li.append($("<input data-ischeck='yup' type='checkbox' title='Enable this' id='enable-" + qualifiedName + "' data-for='" + qualifiedName + "' />")
				.bind('change', function () {
			ck = $(this).is(":checked");
			$("#isenabled-" + $(this).attr("data-for")).text(ck ? "yes":"no");
			ScratchUserscript._partsEnabled[$(this).attr("data-for")] = ck;
			if(typeof localStorage != 'undefined'){
				localStorage.msuPartsEnabled = JSON.stringify(ScratchUserscript._partsEnabled);
			}
		}).attr("checked", isEnabled));
		li.append($("" + name + "").attr("data-for", qualifiedName));
		li.click(function (e) {
			if ($(e.target).attr("data-ischeck") == 'yup') return;
			ScratchUserscript._settingsHTML.find(".msu-settings-content-div").slideUp();
			ScratchUserscript._settingsHTML.find("#msu-settings-content-" + $(this).find("label").attr("data-for")).slideDown();
			ScratchUserscript._settingsHTML.find(".msu-settings-side-tabs li").removeClass("sel");
			$(this).addClass("sel");
		});
		ScratchUserscript._settingsHTML.find(".msu-settings-side-tabs").append(li);
		var content = $("

");
		content.append("
" + name + "
").append("Enabled: no
");
		if(isEnabled) content.find("#isenabled-"+qualifiedName).text("yes");
		content.append("Description: "+description + "

")
			.append(settings == null ? "No additional settings" : settings);
		content.attr("id", "msu-settings-content-" + qualifiedName)
			.css("display", "none").addClass("msu-settings-content-div")
			.appendTo(ScratchUserscript._settingsHTML.find(".msu-settings-content"));
		if(ScratchUserscript._settingsHTML.find('.msu-settings-side-tabs li.sel').length==0){
			li.addClass("sel");
			content.show();
		}
	},
	/**
	 * Gets the page type
	 * @return The type, in the form of a JSON object:
	 *		type: either project, studio, messages, mystuff, settings, forum, profile, or unknown
	 *		subtype: in forums, either section, topic, or null
	 *  	id: the forum topic id, project id, studio id, etc
	 */
	getPageType: function(){
		var obj = {type: "unknown", subtype: null, id: null};
		if (/^\/projects\/\d+\/$/.test(location.pathname)){
			obj.type = "project";
			obj.id = parseInt(/^\/projects\/(\d+)\/$/.exec(location.pathname)[1]);
		}
		if (/^\/studios\/\d+\/$/.test(location.pathname)){
			obj.type = "studio";
			obj.id = parseInt(/^\/studios\/(\d+)\/$/.exec(location.pathname)[1]);
		}
		if (/^\/users\/[a-zA-Z0-9\-_]+\/$/.test(location.pathname)){
			obj.type = "profile";
			obj.id = /^\/users\/([a-zA-Z0-9\-_]+)\/$/.exec(location.pathname)[1];
		}
		if(/^\/discuss\//.test(location.pathname)){
			obj.type = "forum";
			if(/^\/discuss\/\d+\/$/.test(location.pathname)){
				obj.subtype = "section";
				obj.id = parseInt(/^\/discuss\/(\d+)\/$/.exec(location.pathname)[1]);
			}
			if(/^\/discuss\/topic\/\d+\//.test(location.pathname)){
				obj.subtype = "topic";
				obj.id = parseInt(/^\/discuss\/topic\/(\d+)\//.exec(location.pathname)[1]);
			}
		}
		if (/^\/accounts\/(password_change|email_change|change_country)\/$/.test(location.pathname)){
			obj.type = "settings";
		}
		if (location.pathname == '/messages/'){
			obj.type = "messages";
		}
		if (location.pathname == '/mystuff/'){
			obj.type = "mystuff";
		}
		return obj;
	},
	/**
	 * @return The username of the currently logged in user, or null if not logged in
	 */
	getUsername: function(){
		return unsafeWindow.Scratch.INIT_DATA.LOGGED_IN_USER.model ? unsafeWindow.Scratch.INIT_DATA.LOGGED_IN_USER.model.username : null;
	}
};

$(document).ready(ScratchUserscript._init);
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import {Link} from 'react-router'
import utils from 'utils'

import * as Models from 'models'

const MODEL_NAMES = Object.keys(Models).map(key => {
	let camel = utils.camelCase(key)
	Models[camel] = Models[key]
	return camel
})

export default class LinkTo extends Component {
	static propTypes = {
		componentClass: PropTypes.oneOfType([
			PropTypes.string,
			PropTypes.func,
		]),
	}

	render() {
		let {componentClass, children, ...componentProps} = this.props

		let modelName = Object.keys(componentProps).find(key => MODEL_NAMES.indexOf(key) !== -1)
		if (!modelName) {
			console.error('You called LinkTo without passing a Model as a prop')
			return null
		}

		let modelInstance = this.props[modelName]
		if (!modelInstance)
			return null

		let modelClass = Models[modelName]
		let to = modelClass.pathFor(modelInstance)
		componentProps = Object.without(componentProps, modelName)

		let Component = componentClass || Link
		return <Component to={to} {...componentProps}>
			{children || modelClass.prototype.toString.call(modelInstance)}
		</Component>
	}
}

MODEL_NAMES.forEach(key => LinkTo.propTypes[key] = PropTypes.oneOfType([
	PropTypes.instanceOf(Models[key]),
	PropTypes.object,
]))
<commit_msg>Add edit and button props to LinkTo<commit_after>import React, {Component, PropTypes} from 'react'
import {Link} from 'react-router'
import utils from 'utils'

import * as Models from 'models'

const MODEL_NAMES = Object.keys(Models).map(key => {
	let camel = utils.camelCase(key)
	Models[camel] = Models[key]
	return camel
})

export default class LinkTo extends Component {
	static propTypes = {
		componentClass: PropTypes.oneOfType([
			PropTypes.string,
			PropTypes.func,
		]),

		edit: PropTypes.bool,

		// Configures this link to look like a button. Set it to true to make it a button,
		// or pass a string to set a button type
		button: PropTypes.oneOfType([
			PropTypes.bool,
			PropTypes.string,
		])
	}

	render() {
		let {componentClass, children, edit, button, className, ...componentProps} = this.props

		if (button) {
			componentProps.className = [className, 'btn', `btn-${button === true ? 'default' : button}`].join(' ')
		}

		let modelName = Object.keys(componentProps).find(key => MODEL_NAMES.indexOf(key) !== -1)
		if (!modelName) {
			console.error('You called LinkTo without passing a Model as a prop')
			return null
		}

		let modelInstance = this.props[modelName]
		if (!modelInstance)
			return null

		let modelClass = Models[modelName]
		let to = modelInstance
		if (typeof to !== 'string') {
			to = edit ? modelClass.pathForEdit(modelInstance) : modelClass.pathFor(modelInstance)
		}

		componentProps = Object.without(componentProps, modelName)

		let Component = componentClass || Link
		return <Component to={to} {...componentProps}>
			{children || modelClass.prototype.toString.call(modelInstance)}
		</Component>
	}
}

MODEL_NAMES.forEach(key => LinkTo.propTypes[key] = PropTypes.oneOfType([
	PropTypes.instanceOf(Models[key]),
	PropTypes.object,
	PropTypes.string,
]))
<|endoftext|>


<commit_before>(function poll() {
  if (typeof ynabToolKit !== "undefined" && ynabToolKit.pageReady === true) {

    // When this is true, the feature scripts will know they can use the mutationObserver
    ynabToolKit.actOnChangeInit = {};

    // Set 'ynabToolKit.debugNodes = true' to print changes the mutationObserver sees
    // during page interactions and updates to the developer tools console.
    ynabToolKit.debugNodes = false;

    ynabToolKit.actOnChange = function() {

      MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

      var observer = new MutationObserver(function(mutations, observer) {

        if (ynabToolKit.debugNodes) {
          console.log('MODIFIED NODES');
        }

        // Reset the digest of changed nodes on each unique mutation event
        ynabToolKit.digest = new Array();

        mutations.forEach(function(mutation) {
          var newNodes = mutation.target;
          if (ynabToolKit.debugNodes) {
            console.log(newNodes);
          }

          var $nodes = $(newNodes); // jQuery set
          $nodes.each(function() {
            var $node = $(this);

            ynabToolKit.digest.push($node);

          }); // each node mutation event

        }); // each mutation event

        if (ynabToolKit.debugNodes) {
          console.log('###')
        }

        // Loop through the array and act if we find a relevant changed node in the digest
        for ( var i = 0; i < ynabToolKit.digest.length; i++ ) {

        	// Changes are detected in the category balances
        	if ($(ynabToolKit.digest[i]).hasClass("budget-table-cell-available-div")) {

        	  if ( ynabToolKit.featureOptions.updateInspectorColours ) {
        	      ynabToolKit.updateInspectorColours();
        	  }

        	  break;

        	}
        }

        for ( var i = 0; i < ynabToolKit.digest.length; i++ ) {

        	// The user has switched screens
        	if ($(ynabToolKit.digest[i]).hasClass('layout')) {
        		if ( ynabToolKit.featureOptions.resizeInspector ){
        		  ynabToolKit.resizeInspector();
        		}
        		break;
        	}

        }

        for ( var i = 0; i < ynabToolKit.digest.length; i++ ) {

        	// The user has returned back to the budget screen
        	if ($(ynabToolKit.digest[i]).hasClass('budget-inspector')) {

        		if ( ynabToolKit.featureOptions.checkCreditBalances ){
        		  ynabToolKit.checkCreditBalances();
        		}
        		if ( ynabToolKit.featureOptions.highlightNegativesNegative ){
        		  ynabToolKit.highlightNegativesNegative();
        		}
        		if ( ynabToolKit.featureOptions.insertPacingColumns ){
        		  ynabToolKit.insertPacingColumns();
        		}
            if ( ynabToolKit.featureOptions.budgetProgressBars ){
              ynabToolKit.budgetProgressBars();
            }

            // Reset the digest of changed nodes on each unique mutation event
            ynabToolKit.digest = new Array();

            mutations.forEach(function(mutation) {
              var newNodes = mutation.target;
              if (ynabToolKit.debugNodes) {
                console.log(newNodes);
              }

              var $nodes = $(newNodes); // jQuery set
              $nodes.each(function() {
                var $node = $(this);

                ynabToolKit.digest.push($node);

              }); // each node mutation event

            }); // each mutation event

            if (ynabToolKit.debugNodes) {
              console.log('###')
            }

            // Loop through the array and act if we find a relevant changed node in the digest
            for (var i = 0; i < ynabToolKit.digest.length; i++) {

              // Changes are detected in the category balances
              if ($(ynabToolKit.digest[i]).hasClass(
                  "budget-table-cell-available-div")) {

                if (ynabToolKit.featureOptions.updateInspectorColours) {
                  ynabToolKit.updateInspectorColours();
                }

                break;

              }
            }

            for (var i = 0; i < ynabToolKit.digest.length; i++) {

              // The user has returned back to the budget screen
              if ($(ynabToolKit.digest[i]).hasClass(
                  'budget-inspector')) {

                if (ynabToolKit.featureOptions.checkCreditBalances) {
                  ynabToolKit.checkCreditBalances();
                }
                if (ynabToolKit.featureOptions.highlightNegativesNegative) {
                  ynabToolKit.highlightNegativesNegative();
                }
                if (ynabToolKit.featureOptions.insertPacingColumns) {
                  ynabToolKit.insertPacingColumns();
                }
                if (ynabToolKit.featureOptions.budgetProgressBars) {
                  ynabToolKit.budgetProgressBars();
                }
                if ( ynabToolKit.featureOptions.goalIndicator ){
                  ynabToolKit.goalIndicator();
                }

                break;
              }

            }

            for (var i = 0; i < ynabToolKit.digest.length; i++) {

              // We found a modal pop-up
              if ($(ynabToolKit.digest[i]).hasClass(
                  "options-shown")) {

                if (ynabToolKit.featureOptions.removeZeroCategories) {
                  ynabToolKit.removeZeroCategories();
                }
                if (ynabToolKit.featureOptions.moveMoneyAutoComplete) {
                  ynabToolKit.moveMoneyAutoComplete();
                }

                break;

              }
            }

            for (var i = 0; i < ynabToolKit.digest.length; i++) {

              // User has selected a specific sub-category
              if ($(ynabToolKit.digest[i]).hasClass(
                  'is-sub-category')
                  && $(ynabToolKit.digest[i]).hasClass(
                      'is-checked')) {

                if (ynabToolKit.featureOptions.updateInspectorColours) {
                  ynabToolKit.updateInspectorColours();
                }

                break;

              }
            }

            for (var i = 0; i < ynabToolKit.digest.length; i++) {

              // We found Account transactions rows
              if ($(ynabToolKit.digest[i]).hasClass(
                  'ynab-grid-body')) {

                if (ynabToolKit.featureOptions.swapClearedFlagged) {
                  ynabToolKit.swapClearedFlagged();
                }

                break;

              }
            }

          });

      // This finally says 'Watch for changes' and only needs to be called the one time
      observer.observe($('.ember-view.layout')[0], {
        subtree : true,
        childList : true,
        characterData : true,
        attributeFilter : [ 'class' ]
      });

      ynabToolKit.actOnChangeInit = true;
    };
    ynabToolKit.actOnChange(); // Run itself once

  } else {
    setTimeout(poll, 250);
  }
})();
<commit_msg>Repair errors due to challenging merge conflict introduced by to many line changes<commit_after>(function poll() {
  if (typeof ynabToolKit !== "undefined" && ynabToolKit.pageReady === true) {

    // When this is true, the feature scripts will know they can use the mutationObserver
    ynabToolKit.actOnChangeInit = {};

    // Set 'ynabToolKit.debugNodes = true' to print changes the mutationObserver sees
    // during page interactions and updates to the developer tools console.
    ynabToolKit.debugNodes = false;

    ynabToolKit.actOnChange = function() {

      MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

      var observer = new MutationObserver(function(mutations, observer) {

        if (ynabToolKit.debugNodes) {
          console.log('MODIFIED NODES');
        }

        // Reset the digest of changed nodes on each unique mutation event
        ynabToolKit.digest = new Array();

        mutations.forEach(function(mutation) {
          var newNodes = mutation.target;
          if (ynabToolKit.debugNodes) {
            console.log(newNodes);
          }

          var $nodes = $(newNodes); // jQuery set
          $nodes.each(function() {
            var $node = $(this);

            ynabToolKit.digest.push($node);

          }); // each node mutation event

        }); // each mutation event

        if (ynabToolKit.debugNodes) {
          console.log('###')
        }

        // Loop through the array and act if we find a relevant changed node in the digest
        for ( var i = 0; i < ynabToolKit.digest.length; i++ ) {

          // Changes are detected in the category balances
          if ($(ynabToolKit.digest[i]).hasClass("budget-table-cell-available-div")) {

            if ( ynabToolKit.featureOptions.updateInspectorColours ) {
                ynabToolKit.updateInspectorColours();
            }

            break;

          }
        }

        for ( var i = 0; i < ynabToolKit.digest.length; i++ ) {

          // The user has switched screens
          if ($(ynabToolKit.digest[i]).hasClass('layout')) {
            if ( ynabToolKit.featureOptions.resizeInspector ){
              ynabToolKit.resizeInspector();
            }
            break;
          }

        }

        for ( var i = 0; i < ynabToolKit.digest.length; i++ ) {

          // The user has returned back to the budget screen
          if ($(ynabToolKit.digest[i]).hasClass('budget-inspector')) {

            if ( ynabToolKit.featureOptions.checkCreditBalances ){
              ynabToolKit.checkCreditBalances();
            }
            if ( ynabToolKit.featureOptions.highlightNegativesNegative ){
              ynabToolKit.highlightNegativesNegative();
            }
            if ( ynabToolKit.featureOptions.insertPacingColumns ){
              ynabToolKit.insertPacingColumns();
            }
            if ( ynabToolKit.featureOptions.budgetProgressBars ){
              ynabToolKit.budgetProgressBars();
            }

                break;
              }

            }

            for (var i = 0; i < ynabToolKit.digest.length; i++) {

              // We found a modal pop-up
              if ($(ynabToolKit.digest[i]).hasClass("options-shown")) {

                if (ynabToolKit.featureOptions.removeZeroCategories) {
                  ynabToolKit.removeZeroCategories();
                }
                if (ynabToolKit.featureOptions.moveMoneyAutoComplete) {
                  ynabToolKit.moveMoneyAutoComplete();
                }

                break;

              }
            }

            for (var i = 0; i < ynabToolKit.digest.length; i++) {

              // User has selected a specific sub-category
              if ($(ynabToolKit.digest[i]).hasClass('is-sub-category') && $(ynabToolKit.digest[i]).hasClass('is-checked')) {

                if (ynabToolKit.featureOptions.updateInspectorColours) {
                  ynabToolKit.updateInspectorColours();
                }

                break;

              }
            }

            for (var i = 0; i < ynabToolKit.digest.length; i++) {

              // We found Account transactions rows
              if ($(ynabToolKit.digest[i]).hasClass('ynab-grid-body')) {

                if (ynabToolKit.featureOptions.swapClearedFlagged) {
                  ynabToolKit.swapClearedFlagged();
                }

                break;

              }
            }

          });

      // This finally says 'Watch for changes' and only needs to be called the one time
      observer.observe($('.ember-view.layout')[0], {
        subtree : true,
        childList : true,
        characterData : true,
        attributeFilter : [ 'class' ]
      });

      ynabToolKit.actOnChangeInit = true;
    };
    ynabToolKit.actOnChange(); // Run itself once

  } else {
    setTimeout(poll, 250);
  }
})();
<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';

import { logoutUser } from '../../redux/actions';

const NavBar = ({ isAuthenticated, logoutUser }) => (

<Link to="/">Home</Link>

        { isAuthenticated &&
            [

<Link to="/history">History</Link>
,

<Link to="/history/april">April</Link>
,

<Link to="/stopwatch">Stopwatch</Link>

            ]
        }
        { !isAuthenticated &&
            [

<Link to="/signup">Signup</Link>
,

                    <Link to="/login">Login</Link>

            ]
        }
        { isAuthenticated &&

                <button onClick={ logoutUser }>Logout</button>

        }

);

export default connect(
    ({ root }) => ({ isAuthenticated: root.isAuthenticated }),
    { logoutUser }
)(NavBar);
<commit_msg>Update NavBar to dynamically set current month link<commit_after>import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { format } from 'date-fns';

import { logoutUser } from '../../redux/actions';

const NavBar = ({ isAuthenticated, logoutUser }) => {
    const currentMonth = format(new Date(), 'MMMM');

    return (

<Link to="/">Home</Link>

            { isAuthenticated &&
                [

<Link to="/history">History</Link>
,

                        <Link to={`/history/${currentMonth}`}>{ currentMonth }</Link>

,

<Link to="/stopwatch">Stopwatch</Link>

                ]
            }
            { !isAuthenticated &&
                [

<Link to="/signup">Signup</Link>
,

                        <Link to="/login">Login</Link>

                ]
            }
            { isAuthenticated &&

                    <button onClick={ logoutUser }>Logout</button>

            }

    );
};

export default connect(
    ({ root }) => ({ isAuthenticated: root.isAuthenticated }),
    { logoutUser }
)(NavBar);
<|endoftext|>