<commit_before>(function(app) {
  'use strict';

  var helper = app.helper || require('../helper.js');
  var dom = app.dom || require('../dom.js');
  var Component = app.Component || require('./component.js');
  var Content = app.Content || require('./content.js');
  var Sidebar = app.Sidebar || require('./sidebar.js');

  var ModuleData = function(props) {
    this.packageName = props.packageName || '';
    this.label = props.label || '';
    this.description = props.description || '';
    this.src = props.src || '';
    this.visiblePortNames = props.visiblePortNames || [];
    this.tags = props.tags || [];
  };

  ModuleData.prototype.key = function() {
    return this.packageName + '/' + this.src;
  };

  ModuleData.prototype.keywordScore = function(keyword) {
    if (!keyword) {
      return 0;
    }

    keyword = keyword.toLowerCase();

    var label = this.label.toLowerCase();
    if (label.indexOf(keyword) === 0) {
      return 1;
    }

    var tags = this.tags;
    for (var i = 0, len = tags.length; i < len; i++) {
      var tag = tags[i].toLowerCase();
      if (tag.indexOf(keyword) !== -1) {
        return 0.75;
      }
    }

    if (keyword.length < 2) {
      return 0;
    }

    if (label.indexOf(keyword) !== -1) {
      return 0.5;
    }

    var description = this.description.toLowerCase();
    if (description.indexOf(keyword) !== -1) {
      return 0.25;
    }

    return 0;
  };

  var ModuleDataCollection = function() {
    this.data = {};
  };

  ModuleDataCollection.prototype.load = function() {
    return this.loadPackageNames().then(function(packageNames) {
      return Promise.all(packageNames.map(function(packageName) {
        return this.loadModuleDatas(packageName).then(function(moduleDatas) {
          moduleDatas.forEach(function(moduleData) {
            this.data[moduleData.key()] = moduleData;
          }.bind(this));
        }.bind(this));
      }.bind(this)));
    }.bind(this));
  };

  ModuleDataCollection.prototype.loadPackageNames = function() {
    return dom.ajax({
      type: 'GET',
      url: 'modular_modules/index.json',
    }).then(function(text) {
      return JSON.parse(text);
    });
  };

  ModuleDataCollection.prototype.loadModuleDatas = function(packageName) {
    return dom.ajax({
      type: 'GET',
      url: 'modular_modules/' + packageName + '/index.json',
    }).then(function(text) {
      return JSON.parse(text).map(function(props) {
        return new ModuleData(helper.extend(helper.clone(props), { packageName: packageName }));
      });
    });
  };

  ModuleDataCollection.prototype.get = function(key) {
    return this.data[key] || null;
  };

  ModuleDataCollection.prototype.search = function(keyword) {
    return helper.sortBy(helper.values(this.data).filter(function(moduleData) {
      return (moduleData.keywordScore(keyword) !== 0);
    }), function(moduleData) {
      // sort in descending order
      return -(moduleData.keywordScore(keyword));
    });
  };

  var Body = helper.inherits(function() {
    Body.super_.call(this, { element: dom.body() });

    this.moduleDataCollection = this.prop(new ModuleDataCollection());
    this.dragCount = this.prop(0);

    this.content = new Content({
      element: dom.el('.content'),
      sidebarCollapser: Body.prototype.sidebarCollapser.bind(this),
      sidebarExpander: Body.prototype.sidebarExpander.bind(this),
      moduleDragStarter: Body.prototype.moduleDragStarter.bind(this),
      moduleDragEnder: Body.prototype.moduleDragEnder.bind(this),
    });

    this.sidebar = new Sidebar({
      element: dom.el('.sidebar'),
      moduleDragStarter: Body.prototype.moduleDragStarter.bind(this),
      moduleDragEnder: Body.prototype.moduleDragEnder.bind(this),
      moduleDropper: Body.prototype.moduleDropper.bind(this),
      moduleDataSearcher: Body.prototype.moduleDataSearcher.bind(this),
    });

    dom.ready(Body.prototype.onready.bind(this));
  }, Component);

  Body.prototype.incrementDragCount = function() {
    this.dragCount(this.dragCount() + 1);
  };

  Body.prototype.decrementDragCount = function() {
    this.dragCount(this.dragCount() - 1);
  };

  Body.prototype.redraw = function() {
    this.redrawDragCount();
  };

  Body.prototype.redrawDragCount = function() {
    var dragCount = this.dragCount();
    var cache = this.cache();

    if (dragCount === cache.dragCount) {
      return;
    }

    dom.toggleClass(this.element(), 'module-dragging', dragCount > 0);
    cache.dragCount = dragCount;
  };

  Body.prototype.onready = function() {
    this.content.redraw();
  };

  Body.prototype.sidebarCollapser = function() {
    return new Promise(function(resolve, reject) {
      var element = this.element();

      var ontransitionend = function() {
        dom.off(element, 'transitionend', ontransitionend);
        resolve();
      };

      dom.on(element, 'transitionend', ontransitionend);
      dom.addClass(element, 'no-sidebar');
    }.bind(this));
  };

  Body.prototype.sidebarExpander = function() {
    return new Promise(function(resolve, reject) {
      var element = this.element();

      var ontransitionend = function() {
        dom.off(element, 'transitionend', ontransitionend);
        resolve();
      };

      dom.on(element, 'transitionend', ontransitionend);
      dom.removeClass(element, 'no-sidebar');
    }.bind(this));
  };

  Body.prototype.moduleDragStarter = function() {
    this.incrementDragCount();
  };

  Body.prototype.moduleDragEnder = function() {
    this.decrementDragCount();
  };

  Body.prototype.moduleDropper = function(name, x, y) {
    var moduleData = this.moduleDataCollection().get(name);
    this.content.loadModuleByClientPosition({
      title: moduleData.label,
      name: name,
      x: x,
      y: y,
    }, moduleData.visiblePortNames);
  };

  Body.prototype.moduleDataSearcher = function(searchText) {
    return this.moduleDataCollection().search(searchText);
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = Body;
  } else {
    app.Body = Body;
  }
})(this.app || (this.app = {}));
<commit_msg>Load module-data when the application has been completely loaded<commit_after>(function(app) {
  'use strict';

  var helper = app.helper || require('../helper.js');
  var dom = app.dom || require('../dom.js');
  var Component = app.Component || require('./component.js');
  var Content = app.Content || require('./content.js');
  var Sidebar = app.Sidebar || require('./sidebar.js');

  var ModuleData = function(props) {
    this.packageName = props.packageName || '';
    this.label = props.label || '';
    this.description = props.description || '';
    this.src = props.src || '';
    this.visiblePortNames = props.visiblePortNames || [];
    this.tags = props.tags || [];
  };

  ModuleData.prototype.key = function() {
    return this.packageName + '/' + this.src;
  };

  ModuleData.prototype.keywordScore = function(keyword) {
    if (!keyword) {
      return 0;
    }

    keyword = keyword.toLowerCase();

    var label = this.label.toLowerCase();
    if (label.indexOf(keyword) === 0) {
      return 1;
    }

    var tags = this.tags;
    for (var i = 0, len = tags.length; i < len; i++) {
      var tag = tags[i].toLowerCase();
      if (tag.indexOf(keyword) !== -1) {
        return 0.75;
      }
    }

    if (keyword.length < 2) {
      return 0;
    }

    if (label.indexOf(keyword) !== -1) {
      return 0.5;
    }

    var description = this.description.toLowerCase();
    if (description.indexOf(keyword) !== -1) {
      return 0.25;
    }

    return 0;
  };

  var ModuleDataCollection = function() {
    this.data = {};
  };

  ModuleDataCollection.prototype.load = function() {
    return this.loadPackageNames().then(function(packageNames) {
      return Promise.all(packageNames.map(function(packageName) {
        return this.loadModuleDatas(packageName).then(function(moduleDatas) {
          moduleDatas.forEach(function(moduleData) {
            this.data[moduleData.key()] = moduleData;
          }.bind(this));
        }.bind(this));
      }.bind(this)));
    }.bind(this));
  };

  ModuleDataCollection.prototype.loadPackageNames = function() {
    return dom.ajax({
      type: 'GET',
      url: 'modular_modules/index.json',
    }).then(function(text) {
      return JSON.parse(text);
    });
  };

  ModuleDataCollection.prototype.loadModuleDatas = function(packageName) {
    return dom.ajax({
      type: 'GET',
      url: 'modular_modules/' + packageName + '/index.json',
    }).then(function(text) {
      return JSON.parse(text).map(function(props) {
        return new ModuleData(helper.extend(helper.clone(props), { packageName: packageName }));
      });
    });
  };

  ModuleDataCollection.prototype.get = function(key) {
    return this.data[key] || null;
  };

  ModuleDataCollection.prototype.search = function(keyword) {
    return helper.sortBy(helper.values(this.data).filter(function(moduleData) {
      return (moduleData.keywordScore(keyword) !== 0);
    }), function(moduleData) {
      // sort in descending order
      return -(moduleData.keywordScore(keyword));
    });
  };

  var Body = helper.inherits(function() {
    Body.super_.call(this, { element: dom.body() });

    this.moduleDataCollection = this.prop(new ModuleDataCollection());
    this.dragCount = this.prop(0);

    this.content = new Content({
      element: dom.el('.content'),
      sidebarCollapser: Body.prototype.sidebarCollapser.bind(this),
      sidebarExpander: Body.prototype.sidebarExpander.bind(this),
      moduleDragStarter: Body.prototype.moduleDragStarter.bind(this),
      moduleDragEnder: Body.prototype.moduleDragEnder.bind(this),
    });

    this.sidebar = new Sidebar({
      element: dom.el('.sidebar'),
      moduleDragStarter: Body.prototype.moduleDragStarter.bind(this),
      moduleDragEnder: Body.prototype.moduleDragEnder.bind(this),
      moduleDropper: Body.prototype.moduleDropper.bind(this),
      moduleDataSearcher: Body.prototype.moduleDataSearcher.bind(this),
    });

    dom.ready(Body.prototype.onready.bind(this));
  }, Component);

  Body.prototype.incrementDragCount = function() {
    this.dragCount(this.dragCount() + 1);
  };

  Body.prototype.decrementDragCount = function() {
    this.dragCount(this.dragCount() - 1);
  };

  Body.prototype.redraw = function() {
    this.redrawDragCount();
  };

  Body.prototype.redrawDragCount = function() {
    var dragCount = this.dragCount();
    var cache = this.cache();

    if (dragCount === cache.dragCount) {
      return;
    }

    dom.toggleClass(this.element(), 'module-dragging', dragCount > 0);
    cache.dragCount = dragCount;
  };

  Body.prototype.onready = function() {
    this.content.redraw();
    this.moduleDataCollection().load();
  };

  Body.prototype.sidebarCollapser = function() {
    return new Promise(function(resolve, reject) {
      var element = this.element();

      var ontransitionend = function() {
        dom.off(element, 'transitionend', ontransitionend);
        resolve();
      };

      dom.on(element, 'transitionend', ontransitionend);
      dom.addClass(element, 'no-sidebar');
    }.bind(this));
  };

  Body.prototype.sidebarExpander = function() {
    return new Promise(function(resolve, reject) {
      var element = this.element();

      var ontransitionend = function() {
        dom.off(element, 'transitionend', ontransitionend);
        resolve();
      };

      dom.on(element, 'transitionend', ontransitionend);
      dom.removeClass(element, 'no-sidebar');
    }.bind(this));
  };

  Body.prototype.moduleDragStarter = function() {
    this.incrementDragCount();
  };

  Body.prototype.moduleDragEnder = function() {
    this.decrementDragCount();
  };

  Body.prototype.moduleDropper = function(name, x, y) {
    var moduleData = this.moduleDataCollection().get(name);
    this.content.loadModuleByClientPosition({
      title: moduleData.label,
      name: name,
      x: x,
      y: y,
    }, moduleData.visiblePortNames);
  };

  Body.prototype.moduleDataSearcher = function(searchText) {
    return this.moduleDataCollection().search(searchText);
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = Body;
  } else {
    app.Body = Body;
  }
})(this.app || (this.app = {}));
<|endoftext|>


<commit_before>var webpack = require('webpack');
var path = require('path');

// Webpack Config
var webpackConfig = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/app.ts',
  },

  output: {
    path: './dist',
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({name: ['app', 'vendor', 'polyfills'], minChunks: Infinity}),
    new webpack.DefinePlugin({
      'process.env': {
        'POKERTRACKER_URL': JSON.stringify(process.env.POKERTRACKER_URL)
      }
    })
  ],

  module: {
    loaders: [
      // .ts files for TypeScript
      {test: /\.ts$/, loader: 'awesome-typescript-loader'},

    ]
  }

};

// Our Webpack Defaults
var defaultConfig = {
  devtool: 'cheap-module-source-map',
  cache: true,
  debug: true,
  output: {
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
  },

  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          // these packages have problems with their sourcemaps
          path.join(__dirname, 'node_modules', 'rxjs'),
          path.join(__dirname, 'node_modules', '@angular2-material'),
          path.join(__dirname, 'node_modules', '@angular'),
          path.join(__dirname, 'node_modules', 'angular2-highcharts')
        ]
      }
    ],
    noParse: [
      path.join(__dirname, 'node_modules', 'zone.js', 'dist'),
      path.join(__dirname, 'node_modules', 'angular2', 'bundles')
    ]
  },

  resolve: {
    root: [path.join(__dirname, 'src')],
    extensions: ['', '.ts', '.js'],
    alias: {
      'angular2/testing': path.join(__dirname, 'node_modules', '@angular', 'core', 'testing.js'),
      '@angular/testing': path.join(__dirname, 'node_modules', '@angular', 'core', 'testing.js'),
      'angular2/core': path.join(__dirname, 'node_modules', '@angular', 'core', 'index.js'),
      'angular2/platform/browser': path.join(__dirname, 'node_modules', '@angular', 'platform-browser', 'index.js'),
      'angular2/testing': path.join(__dirname, 'node_modules', '@angular', 'testing', 'index.js'),
      'angular2/router': path.join(__dirname, 'node_modules', '@angular', 'router-deprecated', 'index.js'),
      'angular2/http': path.join(__dirname, 'node_modules', '@angular', 'http', 'index.js'),
      'angular2/http/testing': path.join(__dirname, 'node_modules', '@angular', 'http', 'testing.js')
    },
  },

  devServer: {
    historyApiFallback: true,
    watchOptions: {aggregateTimeout: 300, poll: 1000}
  },

  node: {
    global: 1,
    crypto: 'empty',
    module: 0,
    Buffer: 0,
    clearImmediate: 0,
    setImmediate: 0
  },
}

var webpackMerge = require('webpack-merge');
module.exports = webpackMerge(defaultConfig, webpackConfig);
<commit_msg>add new variables to webpack.config.js<commit_after>var webpack = require('webpack');
var path = require('path');

// Webpack Config
var webpackConfig = {
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/app.ts',
  },

  output: {
    path: './dist',
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({name: ['app', 'vendor', 'polyfills'], minChunks: Infinity}),
    new webpack.DefinePlugin({
      'process.env': {
        'POKERTRACKER_COMMAND_URL': JSON.stringify(process.env.POKERTRACKER_COMMAND_URL),
        'POKERTRACKER_QUERY_URL': JSON.stringify(process.env.POKERTRACKER_QUERY_URL)
      }
    })
  ],

  module: {
    loaders: [
      // .ts files for TypeScript
      {test: /\.ts$/, loader: 'awesome-typescript-loader'},

    ]
  }

};

// Our Webpack Defaults
var defaultConfig = {
  devtool: 'cheap-module-source-map',
  cache: true,
  debug: true,
  output: {
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
  },

  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          // these packages have problems with their sourcemaps
          path.join(__dirname, 'node_modules', 'rxjs'),
          path.join(__dirname, 'node_modules', '@angular2-material'),
          path.join(__dirname, 'node_modules', '@angular'),
          path.join(__dirname, 'node_modules', 'angular2-highcharts')
        ]
      }
    ],
    noParse: [
      path.join(__dirname, 'node_modules', 'zone.js', 'dist'),
      path.join(__dirname, 'node_modules', 'angular2', 'bundles')
    ]
  },

  resolve: {
    root: [path.join(__dirname, 'src')],
    extensions: ['', '.ts', '.js'],
    alias: {
      'angular2/testing': path.join(__dirname, 'node_modules', '@angular', 'core', 'testing.js'),
      '@angular/testing': path.join(__dirname, 'node_modules', '@angular', 'core', 'testing.js'),
      'angular2/core': path.join(__dirname, 'node_modules', '@angular', 'core', 'index.js'),
      'angular2/platform/browser': path.join(__dirname, 'node_modules', '@angular', 'platform-browser', 'index.js'),
      'angular2/testing': path.join(__dirname, 'node_modules', '@angular', 'testing', 'index.js'),
      'angular2/router': path.join(__dirname, 'node_modules', '@angular', 'router-deprecated', 'index.js'),
      'angular2/http': path.join(__dirname, 'node_modules', '@angular', 'http', 'index.js'),
      'angular2/http/testing': path.join(__dirname, 'node_modules', '@angular', 'http', 'testing.js')
    },
  },

  devServer: {
    historyApiFallback: true,
    watchOptions: {aggregateTimeout: 300, poll: 1000}
  },

  node: {
    global: 1,
    crypto: 'empty',
    module: 0,
    Buffer: 0,
    clearImmediate: 0,
    setImmediate: 0
  },
}

var webpackMerge = require('webpack-merge');
module.exports = webpackMerge(defaultConfig, webpackConfig);
<|endoftext|>


<commit_before>/**
Models
*/

Lizard.models = {};

Lizard.models.Filter = Backbone.Model.extend({
  initialize: function() {
    // console.log('FilterModel initializing');
  },
  defaults: {
    'selected':  false
  }
});

Lizard.models.Timeserie = Backbone.Model.extend({
  initialize: function(response) {
    this.url = response.url;
    this.fetch({async: false, cache: true});
  },
  defaults: {
    'selected':  false
  },
});

Lizard.models.Location = Backbone.Model.extend({
  initialize: function(response){
    this.url = response.url;
    this.fetch({cache: true})
  },
  defaults: {
    'selected':  false
  },
});

Lizard.models.Parameter = Backbone.Model.extend({
  initialize: function() {
    // console.log('ParameterModel initializing');
  },
  defaults: {
    'selected':  false
  }
});

Lizard.models.Collage = Backbone.Model.extend({
  initialize: function() {
  }
});<commit_msg>semicolon<commit_after>/**
Models
*/

Lizard.models = {};

Lizard.models.Filter = Backbone.Model.extend({
  initialize: function() {
    // console.log('FilterModel initializing');
  },
  defaults: {
    'selected':  false
  }
});

Lizard.models.Timeserie = Backbone.Model.extend({
  initialize: function(response) {
    this.url = response.url;
    this.fetch({async: false, cache: true});
  },
  defaults: {
    'selected':  false
  },
});

Lizard.models.Location = Backbone.Model.extend({
  initialize: function(response){
    this.url = response.url;
    this.fetch({cache: true});
  },
  defaults: {
    'selected':  false
  },
});

Lizard.models.Parameter = Backbone.Model.extend({
  initialize: function() {
    // console.log('ParameterModel initializing');
  },
  defaults: {
    'selected':  false
  }
});

Lizard.models.Collage = Backbone.Model.extend({
  initialize: function() {
  }
});<|endoftext|>


<commit_before>'use strict'

const Hexo = require('hexo');

const fs = require('fs');
const path = require('path');
const util = require('util');
const slugify = require('slugify');

function ContentManager(folderPath, onCreatePost) {
	this.folderPath = folderPath;
	this.createHexo();
	this.onCreatePost = onCreatePost;
}

ContentManager.prototype.createHexo = function () {
	var that = this;
	this.hexo = new Hexo(this.folderPath, {});
	this.hexo.on('new', function(tempPost){
	  console.log('new post');
	  that.load(function (data) {
	  	var fullPost = data.filter(function (post) {
	  		return post.raw === tempPost.content;
	  	})
	  	that.onCreatePost(data, fullPost[0]);
	  });
	});
}

ContentManager.prototype.load = function(callback) {
	// Initialize and Load Hexo Content
	var that = this;
	if (callback != null) {
		that.initCallback = callback;
	}
    that.createHexo();
	that.hexo.init().then(function () {
		that.hexo.load().then(function () {
			console.log('hexo load finished');
			var postQuery = that.hexo.locals.get('posts');
			that.postList = postQuery.data;
			that.postList.sort(function (post1, post2) {
				return post1.canonical_path.localeCompare(post2.canonical_path);
			})
			that.initCallback(that.postList );
		})
	})
};

ContentManager.prototype.filterByID = function(id) {
	return this.hexo.model('Post').findById(id)
};

ContentManager.prototype.createPost = function(createdPost) {
	this.hexo.post.create({
		title: createdPost.title,
		slug: slugify(createdPost.title)
	}, false);
};

ContentManager.prototype.updatePost = function(updatedPost) {
	var currentPost = updatedPost.post;
	var that = this;
	that.isWriting = false;
	if (currentPost != null & !this.isWriting) {
		that.isWriting = true;
		currentPost.title = updatedPost.title;
		currentPost.setTags(updatedPost.tags.split(','));

		currentPost.thumbnail = updatedPost.thumbnail;
		currentPost.save();

		var fullContent =
util.format(`---
title: '%s'
date: %s
tags: [%s]
thumbnail: %s
---
%s`, updatedPost.title, currentPost.date.valueOf(), updatedPost.tags, updatedPost.thumbnail, updatedPost.content);
		fs.writeFile(path.join(this.folderPath, 'source', currentPost.source),
			fullContent, 'utf-8', function (err) {
				that.isWriting = false;
			});
	}

};

ContentManager.prototype.publish = function() {
	var that = this;
	that.hexo.call('generate', {'d':true}).then(function(){
	  alert('Deployed Successful');
	  return that.hexo.exit();
	}).catch(function(err){
	  alert(err);
	  return that.hexo.exit(err);
	});
};

module.exports = ContentManager;<commit_msg>change indent<commit_after>'use strict'

const Hexo = require('hexo');

const fs =  require("fs-extra");
const path = require('path');
const util = require('util');
const slugify = require('slugify');

function ContentManager(folderPath, onCreatePost) {
    this.folderPath = folderPath;
    this.createHexo();
    this.onCreatePost = onCreatePost;
}

ContentManager.prototype.createHexo = function () {
    var that = this;
    this.hexo = new Hexo(this.folderPath, {});
    this.hexo.on('new', function(tempPost){
      console.log('new post');
      that.load(function (data) {
        var fullPost = data.filter(function (post) {
            return post.raw === tempPost.content;
        })

        // Make sure the output directory is there.
        fs.ensureDirSync(path.join(that.hexo.source_dir, 'images', fullPost[0].slug));
        that.onCreatePost(data, fullPost[0]);
      });
    });
}

ContentManager.prototype.load = function(callback) {
    // Initialize and Load Hexo Content
    var that = this;
    if (callback != null) {
        that.initCallback = callback;
    }
    that.createHexo();
    that.hexo.init().then(function () {
        that.hexo.load().then(function () {
            console.log('hexo load finished');
            var postQuery = that.hexo.locals.get('posts');
            that.postList = postQuery.data;
            that.postList.sort(function (post1, post2) {
                return post1.canonical_path.localeCompare(post2.canonical_path);
            })
            that.initCallback(that.postList );
        })
    })
};

ContentManager.prototype.filterByID = function(id) {
    return this.hexo.model('Post').findById(id)
};

ContentManager.prototype.createPost = function(createdPost) {
    var slug = slugify(createdPost.title).toLowerCase();
    this.hexo.post.create({
        title: slug,
        slug: slug
    }, false);
};

ContentManager.prototype.updatePost = function(updatedPost) {
    var currentPost = updatedPost.post;
    var that = this;
    that.isWriting = false;
    if (currentPost != null & !this.isWriting) {
        that.isWriting = true;
        currentPost.title = updatedPost.title;
        currentPost.setTags(updatedPost.tags.split(','));

        currentPost.thumbnail = updatedPost.thumbnail;
        currentPost.save();

        var fullContent =
util.format(`---
title: '%s'
date: %s
tags: [%s]
thumbnail: %s
---
%s`, updatedPost.title, currentPost.date.valueOf(), updatedPost.tags, updatedPost.thumbnail, updatedPost.content);
        fs.writeFile(path.join(this.folderPath, 'source', currentPost.source),
            fullContent, 'utf-8', function (err) {
                that.isWriting = false;
            });
    }

};

ContentManager.prototype.publish = function(callback) {
    var that = this;
    if (that.hexo.config.deploy.repo.includes('http')) {
        return callback('Please change git repo to ssh url, and reload.');
    }
    console.log('Publishing');
    that.hexo.call('generate', {'d':true}).then(function(){
      that.hexo.exit();
      return callback(null);
    }).catch(function(err){
        console.log(err);
      that.hexo.exit(err);
      return callback(err);
    });
};

module.exports = ContentManager;<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash')
var Promise = require('bluebird')
var db = require('./helpers/db')
var React = require('react')
var Fluxxor = require('fluxxor')
var documentReady = require('./helpers/document-ready')

var Gobbldygook = require('./models/gobbldygookApp')
var loadData = require('./helpers/loadData')
var demoStudent = require('../mockups/demo_student')

var actions = require('./actions/StudentActions')
var StudentStore = require('./stores/StudentStore')

module.exports = {
	init: function() {
		// Just for use in the browser console, I swear.
		window._ = _

		// Put the demo student where it can be seen
		window.demoStudent = demoStudent

		// Create the deptnum/crsid cache
		window.deptNumToCrsid = {}

		// Put a promise on document.ready
		document.ready = documentReady

		// Stick React where I (and the Chrome devtools) can see it
		window.React = React

		// Initialize some library options
		Promise.longStackTraces()
		React.initializeTouchEvents(true)
	},
	flux: function() {
		return window.db.students
			.query()
			.filter()
			.execute()
			.then(function(results) {
				var students = []
				if (results.length > 0) {
					console.log('results!', results)
					students = results
				} else {
					console.log('no results!', demoStudent)
					students = [demoStudent]
				}

				var stores = {StudentStore: new StudentStore({students: students})}
				var flux = new Fluxxor.Flux(stores, actions)

				window.flux = flux
			})
	},
	blastoff: function() {
		// Load up some global variables
		this.init()

		// Wait for document.ready and the database.
		Promise.all([db, document.ready]).bind(this).then(function() {
			console.log('3. 2.. 1... Blastoff!')

			// Load data into the database
			loadData()

			// Set up Fluxxor
			return this.flux()
		}).then(function() {
			// Render the app
			var studentComponent = React.renderComponent(
				Gobbldygook({flux: window.flux}),
				document.body)
		}).done()
	},
}

// run it
module.exports.blastoff()
<commit_msg>Add periods to comments<commit_after>'use strict';

var _ = require('lodash')
var Promise = require('bluebird')
var db = require('./helpers/db')
var React = require('react')
var Fluxxor = require('fluxxor')
var documentReady = require('./helpers/document-ready')

var Gobbldygook = require('./models/gobbldygookApp')
var loadData = require('./helpers/loadData')
var demoStudent = require('../mockups/demo_student')

var actions = require('./actions/StudentActions')
var StudentStore = require('./stores/StudentStore')

module.exports = {
	init: function() {
		// Just for use in the browser console, I swear.
		window._ = _

		// Put the demo student where it can be seen.
		window.demoStudent = demoStudent

		// Create the deptnum/crsid cache.
		window.deptNumToCrsid = {}

		// Put a promise on document.ready.
		document.ready = documentReady

		// Stick React where I (and the Chrome devtools) can see it.
		window.React = React

		// Initialize some library options.
		Promise.longStackTraces()
		React.initializeTouchEvents(true)
	},
	flux: function() {
		return window.db.students
			.query()
			.filter()
			.execute()
			.then(function(results) {
				var students = []
				if (results.length > 0) {
					console.log('results!', results)
					students = results
				} else {
					console.log('no results!', demoStudent)
					students = [demoStudent]
				}

				var stores = {StudentStore: new StudentStore({students: students})}
				var flux = new Fluxxor.Flux(stores, actions)

				window.flux = flux
			})
	},
	blastoff: function() {
		// Load up some global variables
		this.init()

		// Wait for document.ready and the database.
		Promise.all([db, document.ready]).bind(this).then(function() {
			console.log('3. 2.. 1... Blastoff!')

			// Load data into the database
			loadData()

			// Set up Fluxxor
			return this.flux()
		}).then(function() {
			// Render the app
			var studentComponent = React.renderComponent(
				Gobbldygook({flux: window.flux}),
				document.body)
		}).done()
	},
}

// run it
module.exports.blastoff()
<|endoftext|>


<commit_before>'use strict';
var {updateIn, dissoc, contains, pick, isEqual, get,
	pluck, getIn, assocIn, identity} = require('../underscore_ext');
var {make, mount, compose} = require('./utils');
var {cohortSummary, datasetMetadata, datasetSamplesExamples,
	datasetFieldExamples, fieldCodes, datasetProbeValues,
	sparseDataExamples, segmentDataExamples} = require('../xenaQuery');
var {userServers, datasetQuery} = require('./common');
var Rx = require('../rx');

function setHubs(state, {hubs}) {
	return hubs ?
		hubs.reduce(
			(state, hub) => assocIn(state, ['servers', hub, 'user'], true),
			state) :
		state;
}

var {ajax, of, zip, zipArray} = Rx.Observable;
var ajaxGet = url => ajax({url, crossDomain: true, method: 'GET', responseType: 'text'});

var hubMeta = host => ajaxGet(`${host}/download/meta/info.mdown`).map(r => r.response)
	.catch(() => of(undefined));

var notGenomic = ["sampleMap", "probeMap", "genePred", "genePredExt"];
var genomicCohortSummary = server =>
		zipArray([cohortSummary(server, notGenomic), hubMeta(server)])
		.map(([cohorts, meta]) => ({server, meta, cohorts}))
		.catch(err => {console.log(err); return of({server, cohorts: []});});

function fetchCohortSummary(serverBus, state) {
	var servers = userServers(state.spreadsheet),
		q = Rx.Observable.zipArray(servers.map(genomicCohortSummary));

	serverBus.next(['cohort-summary', q]);
}

function fetchDatasets(serverBus, state) {
	var {cohort} = state.params,
		servers = userServers(state.spreadsheet);
	serverBus.next(['cohort-datasets', datasetQuery(servers, [{name: cohort}]), cohort]);
}

// emit url if HEAD request succeeds
var head = url => ajax({url, crossDomain: true, method: 'HEAD'}).map(() => url);

// Check for dataset download link. If not there, try the link with '.gz'
// suffix. If not there, return undefined.
var checkDownload = (host, dataset) => {
	var link = `${host}/download/${dataset}`,
		gzlink = `${link}.gz`,
		dl = head(link),
		gzdl = head(gzlink),
		nodl = of(undefined);

	return dl.catch(() => gzdl).catch(() => nodl);
};

function fetchMatrixDataSnippets(host, dataset, meta, nProbes = 10, nSamples = 10) {
	var samplesQ = datasetSamplesExamples(host, dataset, nSamples).share(),
		fieldQ = datasetFieldExamples(host, dataset, nProbes).share(),
		codeQ = fieldQ.mergeMap(probes => fieldCodes(host, dataset, probes)),
		dataQ = zipArray(samplesQ, fieldQ)
			.mergeMap(([samples, fields]) => datasetProbeValues(host, dataset, samples, fields).map(data => data[1]));

	return zipArray(samplesQ, fieldQ, codeQ, dataQ)
		.map(([samples, fields, codes, data]) => ({samples, fields, codes, data}));
}

var mutationAttrs = ({rows}) => ({
	chrom: pluck(rows.position, 'chrom'),
	chromstart: pluck(rows.position, 'chromstart'),
	chromend: pluck(rows.position, 'chromend'),
	...pick(rows, 'sampleID', 'ref', 'alt', 'effect', 'amino-acid', 'gene')
});

var fetchMutationDataSnippets = (host, dataset, nProbes = 10) =>
	sparseDataExamples(host, dataset, nProbes).map(mutationAttrs);

var segmentAttrs = ({rows}) => ({
	chrom: pluck(rows.position, 'chrom'),
	chromstart: pluck(rows.position, 'chromstart'),
	chromend: pluck(rows.position, 'chromend'),
	...pick(rows, 'sampleID', 'value')
});

var fetchSegmentedDataSnippets = (host, dataset, nProbes = 10) =>
	segmentDataExamples(host, dataset, nProbes).map(segmentAttrs);

var noSnippets = () => of(undefined);

var snippetMethod = ({type = 'genomicMatrix'} = {}) =>
	type === 'clinicalMatrix' ? fetchMatrixDataSnippets :
	type === 'genomicMatrix' ? fetchMatrixDataSnippets :
	type === 'mutationVector' ? fetchMutationDataSnippets :
	type === 'genomicSegment' ? fetchSegmentedDataSnippets :
	noSnippets;

var datasetMetaAndLinks = (host, dataset) => {
	var metaQ = datasetMetadata(host, dataset).map(m => m[0]).share(),
		downloadQ = checkDownload(host, dataset),
		dataQ = metaQ.mergeMap(meta => snippetMethod(meta)(host, dataset)),
		probemapQ = metaQ.mergeMap(meta =>
			get(meta, 'probeMap') ? checkDownload(host, meta.probeMap) : of(undefined));

	return zip(metaQ, dataQ, downloadQ, probemapQ, (meta, data, downloadLink, probemapLink) =>
			({meta, data, downloadLink, probemapLink}));
};

function fetchDataset(serverBus, state) {
	var {host, dataset} = state.params;
	serverBus.next(['dataset-meta', datasetMetaAndLinks(host, dataset), host, dataset]);
}

var spreadsheetControls = {
	'init': (state, params) => setHubs(state, params),
	'add-host': (state, host) =>
		assocIn(state, ['servers', host], {user: true}),
	'remove-host': (state, host) =>
		updateIn(state, ['servers'], s => dissoc(s, host)),
	'enable-host': (state, host, list) =>
		assocIn(state, ['servers', host, list], true),
	'disable-host': (state, host, list) =>
		assocIn(state, ['servers', host, list], false)
};

var controls = {
	'cohort-summary': (state, cohorts) =>
		assocIn(state, ['datapages', 'cohorts'], cohorts),
	'cohort-datasets': (state, datasets, cohort) =>
		assocIn(state, ['datapages', 'cohort'], {cohort, datasets}),
	'dataset-meta': (state, metaAndLinks, host, dataset) =>
		assocIn(state, ['datapages', 'dataset'], {host, dataset, ...metaAndLinks})
};

var getSection = ({dataset, host, cohort}) =>
	dataset && host ? 'dataset' :
	host ? 'hub' :
	cohort ? 'cohort' :
	'summary';

var needCohorts = state =>
	state.page === 'datapages' &&
	contains(['summary', 'hub'], getSection(state.params));

var hasCohorts = state => getIn(state, ['datapages', 'cohorts']);

var needACohort = state =>
	state.page === 'datapages' &&
	getSection(state.params) === 'cohort' &&
	state.params.cohort;

var hasACohort = (state, cohort) =>
	cohort === getIn(state, ['datapages', 'cohort', 'cohort']);

var needDataset = state =>
	state.page === 'datapages' &&
	getSection(state.params) === 'dataset' &&
	pick(state.params, 'dataset', 'host');

var hasDataset = (state, {dataset, host}) =>
	dataset === getIn(state, ['datapages', 'dataset', 'dataset']) &&
	host === getIn(state, ['datapages', 'dataset', 'host']);

// We don't save datapages over reload. We fetch missing data the first
// time it is required, meaning a) in the previous state we did not
// require it, or b) it is the 'init' action.
function datapagesPostActions(serverBus, state, newState, action) {
	var [type] = action;

	if (needCohorts(newState) && !hasCohorts(newState) &&
			(type === 'init' || !needCohorts(state))) {
		fetchCohortSummary(serverBus, newState);
	}

	var aCohort = needACohort(newState);
	if (aCohort && !hasACohort(newState, aCohort) &&
		   (type === 'init' || needACohort(state) !== aCohort)) {
		fetchDatasets(serverBus, newState);
	}

	var dataset = needDataset(newState);
	if (dataset && !hasDataset(state, dataset) &&
			(type === 'init' || !isEqual(needDataset(state), dataset))) {
		fetchDataset(serverBus, newState);
	}
}

var datapagesPostController = {
	action: identity,
	postAction: datapagesPostActions
};

module.exports = compose(
		datapagesPostController,
		mount(make(spreadsheetControls), ['spreadsheet']),
		make(controls));
<commit_msg>Load cohorts from hubs when selected.<commit_after>'use strict';
var {updateIn, dissoc, contains, pick, isEqual, get, difference,
	concat, pluck, getIn, assocIn, identity} = require('../underscore_ext');
var {make, mount, compose} = require('./utils');
var {cohortSummary, datasetMetadata, datasetSamplesExamples,
	datasetFieldExamples, fieldCodes, datasetProbeValues,
	sparseDataExamples, segmentDataExamples} = require('../xenaQuery');
var {userServers, datasetQuery} = require('./common');
var Rx = require('../rx');

function setHubs(state, {hubs}) {
	return hubs ?
		hubs.reduce(
			(state, hub) => assocIn(state, ['servers', hub, 'user'], true),
			state) :
		state;
}

var {ajax, of, zip, zipArray} = Rx.Observable;
var ajaxGet = url => ajax({url, crossDomain: true, method: 'GET', responseType: 'text'});

var hubMeta = host => ajaxGet(`${host}/download/meta/info.mdown`).map(r => r.response)
	.catch(() => of(undefined));

var notGenomic = ["sampleMap", "probeMap", "genePred", "genePredExt"];
var genomicCohortSummary = server =>
		zipArray([cohortSummary(server, notGenomic), hubMeta(server)])
		.map(([cohorts, meta]) => ({server, meta, cohorts}))
		.catch(err => {console.log(err); return of({server, cohorts: []});});

function fetchCohortSummary(serverBus, servers) {
	var q = Rx.Observable.zipArray(servers.map(genomicCohortSummary));

	serverBus.next(['cohort-summary', q]);
}

function fetchDatasets(serverBus, state) {
	var {cohort} = state.params,
		servers = userServers(state.spreadsheet);
	serverBus.next(['cohort-datasets', datasetQuery(servers, [{name: cohort}]), cohort]);
}

// emit url if HEAD request succeeds
var head = url => ajax({url, crossDomain: true, method: 'HEAD'}).map(() => url);

// Check for dataset download link. If not there, try the link with '.gz'
// suffix. If not there, return undefined.
var checkDownload = (host, dataset) => {
	var link = `${host}/download/${dataset}`,
		gzlink = `${link}.gz`,
		dl = head(link),
		gzdl = head(gzlink),
		nodl = of(undefined);

	return dl.catch(() => gzdl).catch(() => nodl);
};

function fetchMatrixDataSnippets(host, dataset, meta, nProbes = 10, nSamples = 10) {
	var samplesQ = datasetSamplesExamples(host, dataset, nSamples).share(),
		fieldQ = datasetFieldExamples(host, dataset, nProbes).share(),
		codeQ = fieldQ.mergeMap(probes => fieldCodes(host, dataset, probes)),
		dataQ = zipArray(samplesQ, fieldQ)
			.mergeMap(([samples, fields]) => datasetProbeValues(host, dataset, samples, fields).map(data => data[1]));

	return zipArray(samplesQ, fieldQ, codeQ, dataQ)
		.map(([samples, fields, codes, data]) => ({samples, fields, codes, data}));
}

var mutationAttrs = ({rows}) => ({
	chrom: pluck(rows.position, 'chrom'),
	chromstart: pluck(rows.position, 'chromstart'),
	chromend: pluck(rows.position, 'chromend'),
	...pick(rows, 'sampleID', 'ref', 'alt', 'effect', 'amino-acid', 'gene')
});

var fetchMutationDataSnippets = (host, dataset, nProbes = 10) =>
	sparseDataExamples(host, dataset, nProbes).map(mutationAttrs);

var segmentAttrs = ({rows}) => ({
	chrom: pluck(rows.position, 'chrom'),
	chromstart: pluck(rows.position, 'chromstart'),
	chromend: pluck(rows.position, 'chromend'),
	...pick(rows, 'sampleID', 'value')
});

var fetchSegmentedDataSnippets = (host, dataset, nProbes = 10) =>
	segmentDataExamples(host, dataset, nProbes).map(segmentAttrs);

var noSnippets = () => of(undefined);

var snippetMethod = ({type = 'genomicMatrix'} = {}) =>
	type === 'clinicalMatrix' ? fetchMatrixDataSnippets :
	type === 'genomicMatrix' ? fetchMatrixDataSnippets :
	type === 'mutationVector' ? fetchMutationDataSnippets :
	type === 'genomicSegment' ? fetchSegmentedDataSnippets :
	noSnippets;

var datasetMetaAndLinks = (host, dataset) => {
	var metaQ = datasetMetadata(host, dataset).map(m => m[0]).share(),
		downloadQ = checkDownload(host, dataset),
		dataQ = metaQ.mergeMap(meta => snippetMethod(meta)(host, dataset)),
		probemapQ = metaQ.mergeMap(meta =>
			get(meta, 'probeMap') ? checkDownload(host, meta.probeMap) : of(undefined));

	return zip(metaQ, dataQ, downloadQ, probemapQ, (meta, data, downloadLink, probemapLink) =>
			({meta, data, downloadLink, probemapLink}));
};

function fetchDataset(serverBus, state) {
	var {host, dataset} = state.params;
	serverBus.next(['dataset-meta', datasetMetaAndLinks(host, dataset), host, dataset]);
}

var spreadsheetControls = {
	'init': (state, params) => setHubs(state, params),
	'add-host': (state, host) =>
		assocIn(state, ['servers', host], {user: true}),
	'remove-host': (state, host) =>
		updateIn(state, ['servers'], s => dissoc(s, host)),
	'enable-host': (state, host, list) =>
		assocIn(state, ['servers', host, list], true),
	'disable-host': (state, host, list) =>
		assocIn(state, ['servers', host, list], false)
};

var controls = {
	'cohort-summary': (state, cohorts) =>
		updateIn(state, ['datapages', 'cohorts'],
				(list = []) => concat(list, cohorts)),
	'cohort-datasets': (state, datasets, cohort) =>
		assocIn(state, ['datapages', 'cohort'], {cohort, datasets}),
	'dataset-meta': (state, metaAndLinks, host, dataset) =>
		assocIn(state, ['datapages', 'dataset'], {host, dataset, ...metaAndLinks})
};

var getSection = ({dataset, host, cohort}) =>
	dataset && host ? 'dataset' :
	host ? 'hub' :
	cohort ? 'cohort' :
	'summary';

var needCohortHubs = state =>
	state.page === 'datapages' &&
	contains(['summary', 'hub'], getSection(state.params)) ?
	userServers(state.spreadsheet) : [];

var hasCohortHubs = state => pluck(getIn(state, ['datapages', 'cohorts'], []), 'server');

var needACohort = state =>
	state.page === 'datapages' &&
	getSection(state.params) === 'cohort' &&
	state.params.cohort;

var hasACohort = (state, cohort) =>
	cohort === getIn(state, ['datapages', 'cohort', 'cohort']);

var needDataset = state =>
	state.page === 'datapages' &&
	getSection(state.params) === 'dataset' &&
	pick(state.params, 'dataset', 'host');

var hasDataset = (state, {dataset, host}) =>
	dataset === getIn(state, ['datapages', 'dataset', 'dataset']) &&
	host === getIn(state, ['datapages', 'dataset', 'host']);

// We don't save datapages over reload. We fetch missing data the first
// time it is required, meaning a) in the previous state we did not
// require it, or b) it is the 'init' action.
function datapagesPostActions(serverBus, state, newState, action) {
	var [type] = action;

	// Fast check for the typical case, where nothing has changed
	if (type === 'init' || newState.spreadsheet.servers !== state.spreadsheet.servers) {
		let needHubs = needCohortHubs(newState),
			hasHubs = hasCohortHubs(newState),
			missing = difference(needHubs, hasHubs);

		if (missing.length) {
			fetchCohortSummary(serverBus, missing);
		}
	}

	var aCohort = needACohort(newState);
	if (aCohort && !hasACohort(newState, aCohort) &&
		   (type === 'init' || needACohort(state) !== aCohort)) {
		fetchDatasets(serverBus, newState);
	}

	var dataset = needDataset(newState);
	if (dataset && !hasDataset(state, dataset) &&
			(type === 'init' || !isEqual(needDataset(state), dataset))) {
		fetchDataset(serverBus, newState);
	}
}

var datapagesPostController = {
	action: identity,
	postAction: datapagesPostActions
};

module.exports = compose(
		datapagesPostController,
		mount(make(spreadsheetControls), ['spreadsheet']),
		make(controls));
<|endoftext|>


<commit_before>(function (angular) {
    'use strict';

    angular.module('squares').factory('gameService', ['$interval', '$timeout', 'colorService', 'squareService',
        function ($interval, $timeout, colorService, squareService) {
            var gameServiceInstance;

            gameServiceInstance = {
                _:{
                    squares: null,
                    retryCount: 0,
                    intervalId: null,
                    streakData: { Count: 0, Text: 'Wins', LastGameWon: false },
                    colorCounts: {},
                    colorProvider: colorService.SimpleColors,
                    initialSeconds: 8,

                    getSquares: function (colorCounts, colorProvider) {
                        var squareRows = [];

                        for (var row = 0; row < 8; row++) {
                            var rowArray = [];
                            for (var col = 0; col < 8; col++) {
                                var color,
                                    colorId,
                                    colorIndex;

                                colorIndex = Math.round(Math.random() * colorProvider.Max);
                                color = colorProvider.GetColor(colorIndex);
                                colorId = color.GetColorId();

                                if (!colorCounts[colorId]) {
                                    colorCounts[colorId] = 0;
                                }
                                colorCounts[colorId]++;

                                rowArray.push(squareService.GetSquare(50, color));
                            }
                            squareRows.push(rowArray)
                        }
                        return squareRows;
                    },

                    getSecondScore:  function (gameMode) {
                        var result = 0;
                        switch (gameMode) {
                            case gameServiceInstance.GameModes.Simple:
                                result = 1000;
                                break;
                            case gameServiceInstance.GameModes.Medium:
                                result = 1500;
                                break;
                            case gameServiceInstance.GameModes.Hard:
                                result = 2500;
                                break;
                            case gameServiceInstance.GameModes.VeryHard:
                                result = 5000;
                                break;
                        }
                        return result;
                    },

                    getCurrentStreak : function (gameWon, streakData) {
                        if (gameWon) {
                            if (streakData.LastGameWon) {
                                streakData.Count++;
                                if (streakData.Count === 1) {
                                    streakData.Text = 'Win';
                                }
                                else {
                                    streakData.Text = 'Wins';
                                }
                            }
                            else {
                                streakData.Count = 1;
                                streakData.Text = 'Win';
                            }

                            streakData.LastGameWon = true;
                        }
                        else {
                            if (!streakData.LastGameWon) {
                                streakData.Count++;
                                if (streakData.Count === 1) {
                                    streakData.Text = 'Loss';
                                }
                                else {
                                    streakData.Text = 'Losses';
                                }
                            }
                            else {
                                streakData.Count = 1;
                                streakData.Text = 'Loss';
                            }
                            streakData.LastGameWon = false;
                        }

                        return streakData.Count + ' ' + streakData.Text;
                    },

                    scoreGame: function (chosenSquare, colorCounts, gameMode, seconds, retryCount) {
                        var result = {
                            gameWon : false,
                            score : 0
                        };

                        if (!(null === chosenSquare || undefined === chosenSquare)) {

                            var gameWon = true,
                                chosenColorId = chosenSquare.Color.GetColorId();

                            for(var colorId in colorCounts){
                               if (colorCounts.hasOwnProperty(colorId)
                                   && colorId !== chosenColorId
                                   && colorCounts[colorId] > colorCounts[chosenColorId]) {

                                    gameWon = false;
                                    break;
                                }
                            }

                            if (gameWon){
                                var scoreMod = gameServiceInstance._.getSecondScore(gameMode);
                                var score = scoreMod * seconds;
                                if (retryCount > 0) {
                                    score = Math.round(score / (retryCount + 1));
                                }
                                result.gameWon = true;
                                result.score =  score;
                            }
                        }

                        return result;
                    },

                    initGame : function(initialSeconds){
                        gameServiceInstance._.colorCounts = {};
                        gameServiceInstance.OutcomeText = '';
                        gameServiceInstance.LastGameWon = false;
                        gameServiceInstance.GameStarted = true;
                        gameServiceInstance.Seconds = initialSeconds;
                        gameServiceInstance.GameOver = false;
                        gameServiceInstance.SelectedColor = null;
                    },

                    cancelCountDown: function (intervalId) {
                        if(null !== intervalId){
                            try {
                                $interval.cancel(intervalId);
                                intervalId = null;
                            }
                            catch (e) {
                                console.log('Failed to cancel intervalId [' + intervalId + '] ' + e);
                            }
                        }
                    },

                    countDown: function () {
                        var intervalId;

                        intervalId = $interval(function () {
                            gameServiceInstance.Seconds--;
                            if (gameServiceInstance.Seconds <= 0) {
                                gameServiceInstance._.cancelCountDown(gameServiceInstance._.intervalId);
                                gameServiceInstance.EndGame(null);
                            }

                        }, 1000);

                        return intervalId;
                    },

                    startCountDown: function(){
                        $timeout(function () {
                            gameServiceInstance._.intervalId = gameServiceInstance._.countDown();
                        });
                    }

                },
                OutcomeText: '',
                Seconds: 0,
                LastGameWon: false,
                GameOver: false,
                CurrentStreak: '0 Wins',
                Score: 0,
                TotalGamesPlayed: 0,
                GameStarted: false,
                GameModes: {
                    Simple: 'simple',
                    Medium: 'medium',
                    Hard: 'hard',
                    VeryHard: 'veryhard'
                },
                GameMode: 'simple',
                SelectedColor: null,
                SetGameMode: function (mode) {
                    switch (mode) {
                        case gameServiceInstance.GameModes.Simple:
                            gameServiceInstance.GameMode = gameServiceInstance.GameModes.Simple;
                            gameServiceInstance._.colorProvider = colorService.SimpleColors;
                            gameServiceInstance._.initialSeconds = 8;
                            break;

                        case gameServiceInstance.GameModes.Medium:
                            gameServiceInstance.GameMode = gameServiceInstance.GameModes.Medium;
                            gameServiceInstance._.colorProvider = colorService.MediumColors;
                            gameServiceInstance._.initialSeconds = 6;
                            break;

                        case gameServiceInstance.GameModes.Hard:
                            gameServiceInstance.GameMode = gameServiceInstance.GameModes.Hard;
                            gameServiceInstance._.colorProvider = colorService.HardColors;
                            gameServiceInstance._.initialSeconds = 4;
                            break;

                        case gameServiceInstance.GameModes.VeryHard:
                            gameServiceInstance.GameMode = gameServiceInstance.GameModes.VeryHard;
                            gameServiceInstance._.colorProvider = colorService.VeryHardColors;
                            gameServiceInstance._.initialSeconds = 4;
                            break;
                    }
                },
                StartGame: function () {
                    var squares;

                    gameServiceInstance._.initGame(gameServiceInstance._.initialSeconds);
                    gameServiceInstance._.retryCount = 0;
                    squares = gameServiceInstance._.getSquares(gameServiceInstance._.colorCounts, gameServiceInstance._.colorProvider);
                    gameServiceInstance._.startCountDown();
                    return squares;
                },

                RestartGame: function () {
                    gameServiceInstance._.retryCount++;
                    gameServiceInstance._.initGame(gameServiceInstance._.initialSeconds);
                    gameServiceInstance._.startCountDown();
                },

                EndGame: function (chosenSquare) {
                    gameServiceInstance._.cancelCountDown(gameServiceInstance._.intervalId);
                    gameServiceInstance.GameStarted = false;
                    gameServiceInstance.GameOver = true;

                    var result = gameServiceInstance._.scoreGame(chosenSquare, gameServiceInstance._.colorCounts,
                        gameServiceInstance.GameMode, gameServiceInstance.Seconds, gameServiceInstance._.retryCount);

                    if(result.gameWon){
                        gameServiceInstance.WinningCount = gameServiceInstance._.colorCounts[chosenSquare.Color.GetColorId()];
                        gameServiceInstance.Score += result.score;
                    }

                    gameServiceInstance.SelectedColor = chosenSquare.Color;
                    gameServiceInstance.CurrentStreak = gameServiceInstance._.getCurrentStreak(result.gameWon, gameServiceInstance._.streakData);

                    gameServiceInstance.LastGameWon = result.gameWon;
                    gameServiceInstance.TotalGamesPlayed++;
                    gameServiceInstance.OutcomeText = (result.gameWon) ? 'WON!!!!' : 'LOST!!!!';

                }
            };

            return gameServiceInstance;
        }]);
}(angular));<commit_msg>fixing scoring again<commit_after>(function (angular) {
    'use strict';

    angular.module('squares').factory('gameService', ['$interval', '$timeout', 'colorService', 'squareService',
        function ($interval, $timeout, colorService, squareService) {
            var gameServiceInstance;

            gameServiceInstance = {
                _:{
                    squares: null,
                    retryCount: 0,
                    intervalId: null,
                    streakData: { Count: 0, Text: 'Wins', LastGameWon: false },
                    colorCounts: {},
                    colorProvider: colorService.SimpleColors,
                    initialSeconds: 8,

                    getSquares: function (colorCounts, colorProvider) {
                        var squareRows = [];

                        for (var row = 0; row < 8; row++) {
                            var rowArray = [];
                            for (var col = 0; col < 8; col++) {
                                var color,
                                    colorId,
                                    colorIndex;

                                colorIndex = Math.round(Math.random() * colorProvider.Max);
                                color = colorProvider.GetColor(colorIndex);
                                colorId = color.GetColorId();

                                if (!colorCounts[colorId]) {
                                    colorCounts[colorId] = 0;
                                }
                                colorCounts[colorId]++;

                                rowArray.push(squareService.GetSquare(50, color));
                            }
                            squareRows.push(rowArray)
                        }
                        return squareRows;
                    },

                    getSecondScore:  function (gameMode) {
                        var result = 0;
                        switch (gameMode) {
                            case gameServiceInstance.GameModes.Simple:
                                result = 1000;
                                break;
                            case gameServiceInstance.GameModes.Medium:
                                result = 1500;
                                break;
                            case gameServiceInstance.GameModes.Hard:
                                result = 2500;
                                break;
                            case gameServiceInstance.GameModes.VeryHard:
                                result = 5000;
                                break;
                        }
                        return result;
                    },

                    getCurrentStreak : function (gameWon, streakData) {
                        if (gameWon) {
                            if (streakData.LastGameWon) {
                                streakData.Count++;
                                if (streakData.Count === 1) {
                                    streakData.Text = 'Win';
                                }
                                else {
                                    streakData.Text = 'Wins';
                                }
                            }
                            else {
                                streakData.Count = 1;
                                streakData.Text = 'Win';
                            }

                            streakData.LastGameWon = true;
                        }
                        else {
                            if (!streakData.LastGameWon) {
                                streakData.Count++;
                                if (streakData.Count === 1) {
                                    streakData.Text = 'Loss';
                                }
                                else {
                                    streakData.Text = 'Losses';
                                }
                            }
                            else {
                                streakData.Count = 1;
                                streakData.Text = 'Loss';
                            }
                            streakData.LastGameWon = false;
                        }

                        return streakData.Count + ' ' + streakData.Text;
                    },

                    scoreGame: function (chosenSquare, colorCounts, gameMode, seconds, retryCount) {
                        var result = {
                            gameWon : false,
                            score : 0
                        };

                        if (!(null === chosenSquare || undefined === chosenSquare)) {

                            var gameWon = true,
                                chosenColorId = chosenSquare.Color.GetColorId();

                            for(var colorId in colorCounts){
                               if (colorCounts.hasOwnProperty(colorId)
                                   && colorId !== chosenColorId
                                   && colorCounts[colorId] > colorCounts[chosenColorId]) {

                                    gameWon = false;
                                    break;
                                }
                            }

                            if (gameWon){
                                var scoreMod = gameServiceInstance._.getSecondScore(gameMode);
                                var score = scoreMod * seconds;
                                if (retryCount > 0) {
                                    score = Math.round(score / (retryCount + 1));
                                }
                                result.gameWon = true;
                                result.score =  score;
                            }
                        }

                        return result;
                    },

                    initGame : function(initialSeconds){
                        gameServiceInstance.OutcomeText = '';
                        gameServiceInstance.LastGameWon = false;
                        gameServiceInstance.GameStarted = true;
                        gameServiceInstance.Seconds = initialSeconds;
                        gameServiceInstance.GameOver = false;
                        gameServiceInstance.SelectedColor = null;
                    },

                    cancelCountDown: function (intervalId) {
                        if(null !== intervalId){
                            try {
                                $interval.cancel(intervalId);
                                intervalId = null;
                            }
                            catch (e) {
                                console.log('Failed to cancel intervalId [' + intervalId + '] ' + e);
                            }
                        }
                    },

                    countDown: function () {
                        var intervalId;

                        intervalId = $interval(function () {
                            gameServiceInstance.Seconds--;
                            if (gameServiceInstance.Seconds <= 0) {
                                gameServiceInstance._.cancelCountDown(gameServiceInstance._.intervalId);
                                gameServiceInstance.EndGame(null);
                            }

                        }, 1000);

                        return intervalId;
                    },

                    startCountDown: function(){
                        $timeout(function () {
                            gameServiceInstance._.intervalId = gameServiceInstance._.countDown();
                        });
                    }

                },
                OutcomeText: '',
                Seconds: 0,
                LastGameWon: false,
                GameOver: false,
                CurrentStreak: '0 Wins',
                Score: 0,
                TotalGamesPlayed: 0,
                GameStarted: false,
                GameModes: {
                    Simple: 'simple',
                    Medium: 'medium',
                    Hard: 'hard',
                    VeryHard: 'veryhard'
                },
                GameMode: 'simple',
                SelectedColor: null,
                SetGameMode: function (mode) {
                    switch (mode) {
                        case gameServiceInstance.GameModes.Simple:
                            gameServiceInstance.GameMode = gameServiceInstance.GameModes.Simple;
                            gameServiceInstance._.colorProvider = colorService.SimpleColors;
                            gameServiceInstance._.initialSeconds = 8;
                            break;

                        case gameServiceInstance.GameModes.Medium:
                            gameServiceInstance.GameMode = gameServiceInstance.GameModes.Medium;
                            gameServiceInstance._.colorProvider = colorService.MediumColors;
                            gameServiceInstance._.initialSeconds = 6;
                            break;

                        case gameServiceInstance.GameModes.Hard:
                            gameServiceInstance.GameMode = gameServiceInstance.GameModes.Hard;
                            gameServiceInstance._.colorProvider = colorService.HardColors;
                            gameServiceInstance._.initialSeconds = 4;
                            break;

                        case gameServiceInstance.GameModes.VeryHard:
                            gameServiceInstance.GameMode = gameServiceInstance.GameModes.VeryHard;
                            gameServiceInstance._.colorProvider = colorService.VeryHardColors;
                            gameServiceInstance._.initialSeconds = 4;
                            break;
                    }
                },
                StartGame: function () {
                    var squares;
                    gameServiceInstance._.colorCounts = {};
                    gameServiceInstance._.initGame(gameServiceInstance._.initialSeconds);
                    gameServiceInstance._.retryCount = 0;
                    squares = gameServiceInstance._.getSquares(gameServiceInstance._.colorCounts, gameServiceInstance._.colorProvider);
                    gameServiceInstance._.startCountDown();
                    return squares;
                },

                RestartGame: function () {
                    gameServiceInstance._.retryCount++;
                    gameServiceInstance._.initGame(gameServiceInstance._.initialSeconds);
                    gameServiceInstance._.startCountDown();
                },

                EndGame: function (chosenSquare) {
                    gameServiceInstance._.cancelCountDown(gameServiceInstance._.intervalId);
                    gameServiceInstance.GameStarted = false;
                    gameServiceInstance.GameOver = true;

                    var result = gameServiceInstance._.scoreGame(chosenSquare, gameServiceInstance._.colorCounts,
                        gameServiceInstance.GameMode, gameServiceInstance.Seconds, gameServiceInstance._.retryCount);

                    if(result.gameWon){
                        gameServiceInstance.WinningCount = gameServiceInstance._.colorCounts[chosenSquare.Color.GetColorId()];
                        gameServiceInstance.Score += result.score;
                    }

                    gameServiceInstance.SelectedColor = chosenSquare.Color;
                    gameServiceInstance.CurrentStreak = gameServiceInstance._.getCurrentStreak(result.gameWon, gameServiceInstance._.streakData);

                    gameServiceInstance.LastGameWon = result.gameWon;
                    gameServiceInstance.TotalGamesPlayed++;
                    gameServiceInstance.OutcomeText = (result.gameWon) ? 'WON!!!!' : 'LOST!!!!';

                }
            };

            return gameServiceInstance;
        }]);
}(angular));<|endoftext|>


<commit_before>var app = angular.module('portal', ['ngRoute']);

app.config(function($routeProvider) {
    $routeProvider.when('/login', {
        templateUrl: 'login/login.html',
        controller: 'LoginCtrl'
    });
    $routeProvider.when('/Dashboard', {
        templateUrl: 'Dashboard/main.html',
        controller: 'MainCtrl'
    });
    $routeProvider.when('/resetPwd', {
        templateUrl: 'resetpassword/resetpassword.html',
       // controller: 'ResetController'
    });
    $routeProvider.otherwise({ redirectTo: '/login' });
});
app.run(function(authentication, $rootScope, $location) {
    $rootScope.$on('$routeChangeStart', function(evt) {
        if(!authentication.isAuthenticated){
            $location.url("/login");
        }
        event.preventDefault();
    });
})

app.controller('LoginCtrl', function($scope, $http, $location, authentication) {
    $scope.login = function() {

        if ($scope.username === 'test' && $scope.password === '1234') {
            console.log('successful')
            authentication.isAuthenticated = true;
            authentication.user = { name: $scope.username };
            $location.url("/Dashboard");
        } else {
            $scope.loginError = "Invalid username/password combination";
            console.log('Login failed..');
        };
    };
});

app.controller('AppCtrl', function($scope, $httpBackend, $http, authentication) {
    $scope.templates =
        [
            { url: 'login.html' },
            { url: 'home.html' }
        ];
    $scope.template = $scope.templates[0];
    $scope.login = function (username, password) {
        if ( username === 'admin' && password === '1234') {

            authentication.isAuthenticated = true;
            $scope.template = $scope.templates[1];
            $scope.user = username;
        } else {
            $scope.loginError = "Invalid username/password combination";
        };
    };

});

app.controller('MainCtrl', function($scope, authentication) {
    $scope.user = authentication.user.name;

});

app.factory('authentication', function() {
    return {
        isAuthenticated: false,
        user: null
    }
});<commit_msg>Forgot password redirect issue<commit_after>var app = angular.module('portal', ['ngRoute']);

app.config(function($routeProvider) {
    $routeProvider.when('/login', {
        templateUrl: 'login/login.html',
        controller: 'LoginCtrl'
    });
    $routeProvider.when('/Dashboard', {
        templateUrl: 'Dashboard/main.html',
        controller: 'MainCtrl'
    });
    $routeProvider.when('/resetPwd', {
        templateUrl: 'resetpassword/resetpassword.html',
       // controller: 'ResetController'
    });
    $routeProvider.otherwise({ redirectTo: '/login' });
});
app.run(function(authentication, $rootScope, $location) {
    $rootScope.$on('$routeChangeStart', function(evt) {
       // if(!authentication.isAuthenticated){
          //  $location.url("/login");
       // }
       // event.preventDefault();
    });
})

app.controller('LoginCtrl', function($scope, $http, $location, authentication) {
    $scope.login = function() {

        if ($scope.username === 'test' && $scope.password === '1234') {
            console.log('successful')
            authentication.isAuthenticated = true;
            authentication.user = { name: $scope.username };
            $location.url("/Dashboard");
        } else {
            $scope.loginError = "Invalid username/password combination";
            console.log('Login failed..');
        };
    };
});

app.controller('AppCtrl', function($scope, $httpBackend, $http, authentication) {
    $scope.templates =
        [
            { url: 'login.html' },
            { url: 'home.html' }
        ];
    $scope.template = $scope.templates[0];
    $scope.login = function (username, password) {
        if ( username === 'admin' && password === '1234') {

            authentication.isAuthenticated = true;
            $scope.template = $scope.templates[1];
            $scope.user = username;
        } else {
            $scope.loginError = "Invalid username/password combination";
        };
    };

});

app.controller('MainCtrl', function($scope, authentication) {
    $scope.user = authentication.user.name;

});

app.factory('authentication', function() {
    return {
        isAuthenticated: false,
        user: null
    }
});<|endoftext|>


<commit_before>'use strict';

var path = require('path')
  , webpack = require('webpack');

const
    // Module folders
      VENDORS = ['node_modules', 'bower_components']
    , VENDOR_RE = new RegExp(VENDORS.join('|'))

    // Input and output folders
    , SRC_PATH = path.join(__dirname, 'src')
    , BUILD_PATH = path.join(__dirname, 'static')

    // If you change these, you must change the script tags in index.html
    , PUBLIC_PATH = '/static/'
    , SRC_BUNDLE = 'main'
    , VENDOR_BUNDLE = 'vendor';

// Check if module is vendor, for chunking
const isVendor = (module) => {
  var r = module.userRequest;
  return typeof r === 'string' && r.match(VENDOR_RE);
}

var config = {
  // What file to start at
  entry: [path.join(SRC_PATH, `${SRC_BUNDLE}.coffee`)],

  // Where to output
  output: {
    path: BUILD_PATH,
    publicPath: PUBLIC_PATH,
    filename: '[name].js',
  },

  // Where to load modules from
  resolve: {
    modulesDirectories: VENDORS,
    extensions: ['', '.coffee', '.styl', '.js', '.css']
  },

  // Where to load loaders from
  resolveLoader: {
    modulesDirectories: VENDORS,
  },

  // Coffeelint options
  coffeelint: {
    configFile: 'coffeelint.json',
  },

  // Stylus options
  stylus: {
    use: [require('nib')()],
    import: ['~nib/lib/nib/index.styl'],
    preferPathResolver: 'webpack',
  },

  // Stylint options
  stylint: {
    config: '.stylintrc',
  },

  // Module loading options
  module: {
    // Linters, etc
    preLoaders: [
      { // Coffeelint
        test: /\.coffee$/,
        loader: 'coffee-lint',
        exclude: VENDOR_RE,
      },
      { // Stylint
        test: /\.styl/,
        loader: 'stylint',
        exclude: VENDOR_RE,
      },
    ],

    // Files to load
    loaders: [
      { // Coffeescript (DO NOT MOVE)
        test: /\.coffee$/,
        loaders: ['coffee'],
      },
      { // Stylus
        test: /\.styl$/,
        exclude: /\.u\.styl/,
        loaders: ['style', 'css', 'stylus'],
      },
      { // Reference-counted stylus
        test: /\.u\.styl/,
        loaders: ['style/useable', 'css', 'stylus'],
      },
      { // Plain CSS
        test: /\.css$/,
        loaders: ['style', 'css'],
      },
      { // Media
        test: /\.(png|jpe?g|gif|svg|woff|woff2|eot|ttf)$/,
        loaders: ['url'],
      },
    ],
  },

  plugins: [
    // Separate vendor bundle
    new webpack.optimize.CommonsChunkPlugin({
      name: VENDOR_BUNDLE,
      minChunks: isVendor,
    }),
  ],
};

// Production
if (process.env.NODE_ENV === 'production') {
  config.plugins.unshift(
    // Production environment variable
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production'),
      },
    }),

    // Deduplicate
    new webpack.optimize.DedupePlugin()
  );
  config.plugins.push(
    // Minify
    new webpack.optimize.UglifyJsPlugin({
      compress: {warnings: false},
    })
  );

// Development
} else {
  // Source maps
  config.devtool = 'cheap-module-eval-source-map';

  // -- Hot loading --

  config.entry.unshift('react-hot-loader/patch');
  config.plugins.unshift(new webpack.HotModuleReplacementPlugin());
  config.devServer = {
    // Adjust entry point
    inline: true,

    // Hot reloading
    hot: true,

    // Allow routing
    historyApiFallback: true,

    // Display options
    stats: {
      // Do not show list of hundreds of files included in a bundle
      chunkModules: false,
      colors: true,
    },
  };
}

module.exports = config;
<commit_msg>OMG HOT LOADING WORKS :fire: :fire: :fire:<commit_after>'use strict';

var path = require('path')
  , webpack = require('webpack');

const
    // Module folders
      VENDORS = ['node_modules', 'bower_components']
    , VENDOR_RE = new RegExp(VENDORS.join('|'))

    // Input and output folders
    , SRC_PATH = path.join(__dirname, 'src')
    , BUILD_PATH = path.join(__dirname, 'static')

    // If you change these, you must change the script tags in index.html
    , PUBLIC_PATH = '/static/'
    , SRC_BUNDLE = 'main'
    , VENDOR_BUNDLE = 'vendor';

// Check if module is vendor, for chunking
const isVendor = (module) => {
  var r = module.userRequest;
  return typeof r === 'string' && r.match(VENDOR_RE);
}

var config = {
  // What file to start at
  entry: [path.join(SRC_PATH, `${SRC_BUNDLE}.coffee`)],

  // Where to output
  output: {
    path: BUILD_PATH,
    publicPath: PUBLIC_PATH,
    filename: '[name].js',
  },

  // Where to load modules from
  resolve: {
    modulesDirectories: VENDORS,
    extensions: ['', '.coffee', '.styl', '.js', '.css']
  },

  // Where to load loaders from
  resolveLoader: {
    modulesDirectories: VENDORS,
  },

  // Coffeelint options
  coffeelint: {
    configFile: 'coffeelint.json',
  },

  // Stylus options
  stylus: {
    use: [require('nib')()],
    import: ['~nib/lib/nib/index.styl'],
    preferPathResolver: 'webpack',
  },

  // Stylint options
  stylint: {
    config: '.stylintrc',
  },

  // Module loading options
  module: {
    // Linters, etc
    preLoaders: [
      { // Coffeelint
        test: /\.coffee$/,
        loader: 'coffee-lint',
        exclude: VENDOR_RE,
      },
      { // Stylint
        test: /\.styl/,
        loader: 'stylint',
        exclude: VENDOR_RE,
      },
    ],

    // Files to load
    loaders: [
      { // Coffeescript (DO NOT MOVE)
        test: /\.coffee$/,
        loaders: ['coffee'],
      },
      { // Stylus
        test: /\.styl$/,
        exclude: /\.u\.styl/,
        loaders: ['style', 'css', 'stylus'],
      },
      { // Reference-counted stylus
        test: /\.u\.styl/,
        loaders: ['style/useable', 'css', 'stylus'],
      },
      { // Plain CSS
        test: /\.css$/,
        loaders: ['style', 'css'],
      },
      { // Media
        test: /\.(png|jpe?g|gif|svg|woff|woff2|eot|ttf)$/,
        loaders: ['url'],
      },
    ],
  },

  plugins: [
    // Separate vendor bundle
    new webpack.optimize.CommonsChunkPlugin({
      name: VENDOR_BUNDLE,
      minChunks: isVendor,
    }),
  ],
};

// Production
if (process.env.NODE_ENV === 'production') {
  config.plugins.unshift(
    // Production environment variable
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production'),
      },
    }),

    // Deduplicate
    new webpack.optimize.DedupePlugin()
  );
  config.plugins.push(
    // Minify
    new webpack.optimize.UglifyJsPlugin({
      compress: {warnings: false},
    })
  );

// Development
} else {
  // Source maps
  config.devtool = 'cheap-module-eval-source-map';

  // -- Hot loading --

  config.entry.unshift('react-hot-loader/patch');

  // loaders[0] is coffee
  config.module.loaders[0].loaders.unshift('react-hot-loader/webpack');
  config.plugins.unshift(new webpack.HotModuleReplacementPlugin());

  config.devServer = {
    // Adjust entry point
    inline: true,

    // Hot reloading
    hot: true,

    // Allow routing
    historyApiFallback: true,

    // Display options
    stats: {
      // Do not show list of hundreds of files included in a bundle
      chunkModules: false,
      colors: true,
    },
  };
}

module.exports = config;
<|endoftext|>