<commit_before>module.exports = function(grunt) {

	grunt.initConfig({

		pkg: grunt.file.readJSON('package.json'),

		// sass: Compile Sass to CSS
		sass: require('./grunt_tasks/sass'),

		// svgstore: Merge svgs from a folder
		svgstore: require('./grunt_tasks/svgstore'),

		// concat: Concatenate files.
		concat: require('./grunt_tasks/concat'),

		// autoprefixer: Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website
		autoprefixer: {
			build: {
				options: {
					browsers: ['last 2 versions', '> 1%', 'ie >= 8']
				},
				files: [
					{
						src : ['assets/styles/dist/*.css'],
						dest : 'assets/styles/dist/',
						expand : true,
						flatten : true
					}
				]
			}
		},

		// watch: Run tasks whenever watched files change.
		watch: {
			concat: {
				files: ['assets/scripts/src/**/*.js'],
				tasks: ['concat', 'notify:concat']
			},
			sass: {
				files: ['assets/styles/src/**/*.scss'],
				tasks: ['sass', 'autoprefixer', 'notify:sass'],
				options: {
					spawn: false,
					livereload: true
				}
			},
			svgstore: {
				files: ['assets/images/**/*.svg'],
				tasks: ['svgstore', 'notify:svg']
			},
			tasks: {
				files: ['grunt_tasks/*.js'],
				options: {
			      reload: true
			    }
			}
		},

		// notify: Automatic Notifications when Grunt tasks fail (or succeed)
		notify: {
			watch: {
				options: {
					// title: '<%= pkg.title %>',
					message: 'Keeping an eye out, Chief!'
				}
			},
			sass: {
				options: {
					// title: '<%= pkg.title %>',
					message: 'Sass compiled to CSS.'
				}
			},
			concat: {
				options: {
					// title: '<%= pkg.title %>',
					message: 'JavaScript is now concatenated'
				}
			},
			svg: {
				options: {
					// title: '<%= pkg.title %>',
					message: 'SVG is now concatenated'
				}
			}
		},

		// csscomb: Sort CSS properties in specific order.
		csscomb: {
	        options: {
                config: '.csscomb.json'
            },
	        build: {
	            expand: true,
	            cwd: 'assets/styles/src/',
	            src: ['**/*.scss'],
	            dest: 'assets/styles/src/'
	        }
		},

		// uglify: Minify (javascript)files with UglifyJS
		uglify: {
			target: {
				files: [{
					expand: true,
					cwd: 'assets/scripts/dist/',
					src: '**/*.js',
					dest: 'assets/scripts/dist/'
				}]
			}
		},

		// cssmin: Compress CSS files
		cssmin: {
		  combine: {
			files: [{
				expand: true,
				cwd: 'assets/styles/dist/',
				src: '*.css',
				dest: 'assets/styles/dist/'
			}]

		  }
		},

		// svgmin: Minify SVG
		svgmin: {
	        options: {
	            plugins: [
	                { removeViewBox: false },
	                { cleanupIDs: false },
	                { convertPathData: false },
	                { mergePaths: false },
	                { convertShapeToPath: false },
	                { cleanupNumericValues: false },
	                { convertTransform: false },
				    { removeUselessStrokeAndFill: false }
	            ]
	        },
	        dist: {
	            files: {
	                'assets/images/dist/': 'assets/images/dist/*.svg'
	            }
	        }
	    },

		// imagemin: Minify PNG and JPEG images.
		imagemin: {
			dynamic: {
				files: [{
					expand: true,
					cwd: 'assets/images/',
					src: ['*.{png,jpg,gif}'],
					dest: 'assets/images/'
				}]
			}
		},

		// jsonlint: Validate JSON files
		jsonlint:{
			project:{
				src:[
					'*.json',
					'config/*.json',
					'config/**/*.json',
					'modules/**/config/*.json',
					'modules/**/config/**/*.json'
				]
			},
			charcoal:{
				src:[
					'charcoal/*.json',
					'charcoal/core/config/*.json',
					'charcoal/core/config/**/*.json',
					'charcoal/modules/**/config/*.json',
					'charcoal/modules/**/config/**/*.json'
				]
			}
		},

		// jshint: Validate javascript files with JSHint
		jshint:{
			gruntfile:{
				src:[
					// Self-test
					'Gruntfile.js'
				]
			},
			project:{
				src:[
					'modules/**/assets/scripts/src/*.js',
					'modules/**/assets/scripts/src/**/*.js'
				]
			},
			charcoal:{
				src:[
					'charcoal/core/assets/scripts/src/*.js',
					'charcoal/core/assets/scripts/src/**/*.js',
					'charcoal/modules/**/assets/scripts/src/*.js',
					'charcoal/modules/**/assets/scripts/src/**/*.js'
				]
			}
		},

		// phplint: A simple wrapper around the php -l <filename> command.
		phplint:{
			options: {
				swapPath: '/tmp',
				phpArgs : {
					// add -f for fatal errors
					'-lf': null
				}
			},

			project: [
				'modules/**/code/*.php',
				'modules/**/code/**/*.php',
				'modules/**/assets/templates/*.php',
				'modules/**/assets/templates/**/*.php'
			],
			charcoal: [
				'charcoal/core/code/*.php',
				'charcoal/core/code/**/*.php',
				'charcoal/modules/**/code/*.php',
				'charcoal/modules/**/code/**/*.php'
			]
		}

	});

	// Load tasks
	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-sass');
	grunt.loadNpmTasks('grunt-svgstore');
	grunt.loadNpmTasks('grunt-autoprefixer');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-notify');
	grunt.loadNpmTasks('grunt-csscomb');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-cssmin');
	grunt.loadNpmTasks('grunt-svgmin');
	grunt.loadNpmTasks('grunt-contrib-imagemin');
	grunt.loadNpmTasks('grunt-jsonlint');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks("grunt-phplint");

	// Register tasks
	grunt.registerTask('default', ['watch', 'notify:watch']);
	grunt.registerTask('build', [
		'concat',
		'sass',
		'svgstore',
		'autoprefixer',
		'uglify',
		'cssmin',
		'svgmin',
		'imagemin'
	]);
	grunt.registerTask('c', [
		'csscomb'
	]);
	grunt.registerTask('wlint', [
		// Javasript
		'jshint',
		'jsonlint',
		'concat',

		// PHP
		'phplint',

		// Utilities
		'watch'
	]);

};
<commit_msg>Fixed the svgmin in the gruntfile<commit_after>module.exports = function(grunt) {

	grunt.initConfig({

		pkg: grunt.file.readJSON('package.json'),

		// sass: Compile Sass to CSS
		sass: require('./grunt_tasks/sass'),

		// svgstore: Merge svgs from a folder
		svgstore: require('./grunt_tasks/svgstore'),

		// concat: Concatenate files.
		concat: require('./grunt_tasks/concat'),

		// autoprefixer: Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website
		autoprefixer: {
			build: {
				options: {
					browsers: ['last 2 versions', '> 1%', 'ie >= 8']
				},
				files: [
					{
						src : ['assets/styles/dist/*.css'],
						dest : 'assets/styles/dist/',
						expand : true,
						flatten : true
					}
				]
			}
		},

		// watch: Run tasks whenever watched files change.
		watch: {
			concat: {
				files: ['assets/scripts/src/**/*.js'],
				tasks: ['concat', 'notify:concat']
			},
			sass: {
				files: ['assets/styles/src/**/*.scss'],
				tasks: ['sass', 'autoprefixer', 'notify:sass'],
				options: {
					spawn: false,
					livereload: true
				}
			},
			svgstore: {
				files: ['assets/images/**/*.svg'],
				tasks: ['svgstore', 'notify:svg']
			},
			tasks: {
				files: ['grunt_tasks/*.js'],
				options: {
			      reload: true
			    }
			}
		},

		// notify: Automatic Notifications when Grunt tasks fail (or succeed)
		notify: {
			watch: {
				options: {
					// title: '<%= pkg.title %>',
					message: 'Keeping an eye out, Chief!'
				}
			},
			sass: {
				options: {
					// title: '<%= pkg.title %>',
					message: 'Sass compiled to CSS.'
				}
			},
			concat: {
				options: {
					// title: '<%= pkg.title %>',
					message: 'JavaScript is now concatenated'
				}
			},
			svg: {
				options: {
					// title: '<%= pkg.title %>',
					message: 'SVG is now concatenated'
				}
			}
		},

		// csscomb: Sort CSS properties in specific order.
		csscomb: {
	        options: {
                config: '.csscomb.json'
            },
	        build: {
	            expand: true,
	            cwd: 'assets/styles/src/',
	            src: ['**/*.scss'],
	            dest: 'assets/styles/src/'
	        }
		},

		// uglify: Minify (javascript)files with UglifyJS
		uglify: {
			target: {
				files: [{
					expand: true,
					cwd: 'assets/scripts/dist/',
					src: '**/*.js',
					dest: 'assets/scripts/dist/'
				}]
			}
		},

		// cssmin: Compress CSS files
		cssmin: {
		  combine: {
			files: [{
				expand: true,
				cwd: 'assets/styles/dist/',
				src: '*.css',
				dest: 'assets/styles/dist/'
			}]

		  }
		},

		// svgmin: Minify SVG
		svgmin: {
	        options: {
	            plugins: [
	                { removeViewBox: false },
	                { cleanupIDs: false },
	                { convertPathData: false },
	                { mergePaths: false },
	                { convertShapeToPath: false },
	                { cleanupNumericValues: false },
	                { convertTransform: false },
				    { removeUselessStrokeAndFill: false }
	            ]
	        },
		dist: {
			expand: true,
			cwd: 'assets/images/dist/',
			src: '*.svg',
			dest: 'assets/images/dist/',
			ext: '.svg',
			extDot: 'first'
		}
	    },

		// imagemin: Minify PNG and JPEG images.
		imagemin: {
			dynamic: {
				files: [{
					expand: true,
					cwd: 'assets/images/',
					src: ['*.{png,jpg,gif}'],
					dest: 'assets/images/'
				}]
			}
		},

		// jsonlint: Validate JSON files
		jsonlint:{
			project:{
				src:[
					'*.json',
					'config/*.json',
					'config/**/*.json',
					'modules/**/config/*.json',
					'modules/**/config/**/*.json'
				]
			},
			charcoal:{
				src:[
					'charcoal/*.json',
					'charcoal/core/config/*.json',
					'charcoal/core/config/**/*.json',
					'charcoal/modules/**/config/*.json',
					'charcoal/modules/**/config/**/*.json'
				]
			}
		},

		// jshint: Validate javascript files with JSHint
		jshint:{
			gruntfile:{
				src:[
					// Self-test
					'Gruntfile.js'
				]
			},
			project:{
				src:[
					'modules/**/assets/scripts/src/*.js',
					'modules/**/assets/scripts/src/**/*.js'
				]
			},
			charcoal:{
				src:[
					'charcoal/core/assets/scripts/src/*.js',
					'charcoal/core/assets/scripts/src/**/*.js',
					'charcoal/modules/**/assets/scripts/src/*.js',
					'charcoal/modules/**/assets/scripts/src/**/*.js'
				]
			}
		},

		// phplint: A simple wrapper around the php -l <filename> command.
		phplint:{
			options: {
				swapPath: '/tmp',
				phpArgs : {
					// add -f for fatal errors
					'-lf': null
				}
			},

			project: [
				'modules/**/code/*.php',
				'modules/**/code/**/*.php',
				'modules/**/assets/templates/*.php',
				'modules/**/assets/templates/**/*.php'
			],
			charcoal: [
				'charcoal/core/code/*.php',
				'charcoal/core/code/**/*.php',
				'charcoal/modules/**/code/*.php',
				'charcoal/modules/**/code/**/*.php'
			]
		}

	});

	// Load tasks
	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-sass');
	grunt.loadNpmTasks('grunt-svgstore');
	grunt.loadNpmTasks('grunt-autoprefixer');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-notify');
	grunt.loadNpmTasks('grunt-csscomb');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-cssmin');
	grunt.loadNpmTasks('grunt-svgmin');
	grunt.loadNpmTasks('grunt-contrib-imagemin');
	grunt.loadNpmTasks('grunt-jsonlint');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks("grunt-phplint");

	// Register tasks
	grunt.registerTask('default', ['watch', 'notify:watch']);
	grunt.registerTask('build', [
		'concat',
		'sass',
		'svgstore',
		'autoprefixer',
		'uglify',
		'cssmin',
		'svgmin',
		'imagemin'
	]);
	grunt.registerTask('c', [
		'csscomb'
	]);
	grunt.registerTask('wlint', [
		// Javasript
		'jshint',
		'jsonlint',
		'concat',

		// PHP
		'phplint',

		// Utilities
		'watch'
	]);

};
<|endoftext|>


<commit_before>angular.module('grooveboat', ["LocalStorageModule"])
    .config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {
        $routeProvider
            .when("/", { controller: RoomListCtrl, templateUrl: "static/templates/room_list.html"})
            .when("/room/:room", { controller: RoomCtrl, templateUrl: "static/templates/room.html"})
            .otherwise({redirect_to: "/"});

        $locationProvider.html5Mode(false).hashPrefix("!");
    }])
    .factory("currentUser", ["groove", "localStorageService", function(groove, localStorageService) {
        var user = groove.me;
        var nick = localStorageService.get("user:nickname");
        if (!nick) {
            nick = "Guest " + Math.floor(Math.random()*101);
            localStorageService.set("user:nickname", nick);
        }
        user.nickname = nick;

        return user;
    }])
    .service("groove", Groove);

function RoomListCtrl($scope, $location, currentUser, groove, localStorageService) {
    var selected = -1;
    $scope.currentUser = currentUser;

    $scope.rooms = [
        { name: "Ambient Electronic", selected: false },
        { name: "Indie While You Slack", selected: false }
    ];

    $scope.clickRoom = function(i) {
        if(selected > -1) {
            $scope.rooms[selected].selected = false;
        }

        document.getElementById("join-room").disabled = false;
        $scope.rooms[i].selected = true;
        selected = i;
    }

    $scope.clickJoinRoom = function() {
        var room = $scope.rooms[selected];
        var name = room.name.replace(/\s/g, "-");
        localStorageService.set("user:nickname", currentUser.nickname);
        $location.path("/room/" + name);
    }
}

function RoomCtrl($scope, $routeParams, currentUser, groove, localStorageService) {
    groove.joinRoom($routeParams.room);

    $scope.djs = [
        { name: "stevenleeg", active: true },
        { name: "celehner", active: false },
        { name: "rochacko", active: false },
        { name: "hankcy", active: false }
    ];

    $scope.audience = [
        { name: "manyabot" },
        { name: "omeglebot" }
    ];

    $scope.current_track = {
        title: "True Affection",
        artist: "The Blow"
    }

    $scope.chat_messages = [
        { from: {nickname: "stevenleeg"}, text: "Hello there, world" },
        { from: {nickname: "celehner"}, text: "Hello world" }
    ];

    $scope.currentUser = currentUser;

    $scope.newMessage = function() {
        $scope.chat_messages.push({
            from: currentUser,
            text: $scope.message_text
        });

        groove.sendChat($scope.message_text);
        $scope.message_text = "";

        var messages_div = document.getElementById("messages");
        messages_div.scrollTop = messages_div.scrollHeight + 100;
    };

    groove.on("chat", function(message) {
        $scope.$apply(function($scope) {
            $scope.chat_messages.push(message);
        });
    });
}

RoomListCtrl.$inject = ["$scope", "$location", "currentUser", "groove", "localStorageService"];
RoomCtrl.$inject = ["$scope", "$routeParams", "currentUser", "groove", "localStorageService"];
<commit_msg>Auto-scroll messages only when already scrolled to bottom<commit_after>angular.module('grooveboat', ["LocalStorageModule"])
    .config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {
        $routeProvider
            .when("/", { controller: RoomListCtrl, templateUrl: "static/templates/room_list.html"})
            .when("/room/:room", { controller: RoomCtrl, templateUrl: "static/templates/room.html"})
            .otherwise({redirect_to: "/"});

        $locationProvider.html5Mode(false).hashPrefix("!");
    }])
    .factory("currentUser", ["groove", "localStorageService", function(groove, localStorageService) {
        var user = groove.me;
        var nick = localStorageService.get("user:nickname");
        if (!nick) {
            nick = "Guest " + Math.floor(Math.random()*101);
            localStorageService.set("user:nickname", nick);
        }
        user.nickname = nick;

        return user;
    }])
    .service("groove", Groove);

function RoomListCtrl($scope, $location, currentUser, groove, localStorageService) {
    var selected = -1;
    $scope.currentUser = currentUser;

    $scope.rooms = [
        { name: "Ambient Electronic", selected: false },
        { name: "Indie While You Slack", selected: false }
    ];

    $scope.clickRoom = function(i) {
        if(selected > -1) {
            $scope.rooms[selected].selected = false;
        }

        document.getElementById("join-room").disabled = false;
        $scope.rooms[i].selected = true;
        selected = i;
    }

    $scope.clickJoinRoom = function() {
        var room = $scope.rooms[selected];
        var name = room.name.replace(/\s/g, "-");
        localStorageService.set("user:nickname", currentUser.nickname);
        $location.path("/room/" + name);
    }
}

function RoomCtrl($scope, $routeParams, currentUser, groove, localStorageService) {
    groove.joinRoom($routeParams.room);

    $scope.djs = [
        { name: "stevenleeg", active: true },
        { name: "celehner", active: false },
        { name: "rochacko", active: false },
        { name: "hankcy", active: false }
    ];

    $scope.audience = [
        { name: "manyabot" },
        { name: "omeglebot" }
    ];

    $scope.current_track = {
        title: "True Affection",
        artist: "The Blow"
    }

    $scope.chat_messages = [
        { from: {nickname: "stevenleeg"}, text: "Hello there, world" },
        { from: {nickname: "celehner"}, text: "Hello world" }
    ];

    $scope.currentUser = currentUser;

    $scope.newMessage = function() {
        var messages_div = document.getElementById("messages");
        var isScrolledToBottom = (messages_div.scrollHeight -
            messages_div.scrollTop - messages_div.clientHeight < 10);

        $scope.chat_messages.push({
            from: currentUser,
            text: $scope.message_text
        });

        groove.sendChat($scope.message_text);
        $scope.message_text = "";

        if (isScrolledToBottom) {
            setTimeout(function() {
                messages_div.scrollTop = messages_div.scrollHeight;
            }, 10);
        }
    };

    groove.on("chat", function(message) {
        $scope.$apply(function($scope) {
            $scope.chat_messages.push(message);
        });
    });
}

RoomListCtrl.$inject = ["$scope", "$location", "currentUser", "groove", "localStorageService"];
RoomCtrl.$inject = ["$scope", "$routeParams", "currentUser", "groove", "localStorageService"];
<|endoftext|>


<commit_before>module.exports = rimraf
rimraf.sync = rimrafSync

var path = require("path")
var fs = require("fs")

// for EMFILE handling
var timeout = 0
exports.EMFILE_MAX = 1000
exports.BUSYTRIES_MAX = 3

var isWindows = (process.platform === "win32")

function rimraf (p, cb) {
  if (!cb) throw new Error("No callback passed to rimraf()")

  var busyTries = 0
  rimraf_(p, function CB (er) {
    if (er) {
      if (isWindows && (er.code === "EBUSY" || er.code === "ENOTEMPTY") &&
          busyTries < exports.BUSYTRIES_MAX) {
        busyTries ++
        var time = busyTries * 100
        // try again, with the same exact callback as this one.
        return setTimeout(function () {
          rimraf_(p, CB)
        }, time)
      }

      // this one won't happen if graceful-fs is used.
      if (er.code === "EMFILE" && timeout < exports.EMFILE_MAX) {
        return setTimeout(function () {
          rimraf_(p, CB)
        }, timeout ++)
      }

      // already gone
      if (er.code === "ENOENT") er = null
    }

    timeout = 0
    cb(er)
  })
}

// Two possible strategies.
// 1. Assume it's a file.  unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory.  readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong.  However, there
// are likely far more normal files in the world than directories.  This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow.  But until then, YAGNI.
function rimraf_ (p, cb) {
  fs.unlink(p, function (er) {
    if (er) {
      if (er.code === "ENOENT")
        return cb(null)
      if (er.code === "EPERM")
        return (isWindows) ? fixWinEPERM(p, er, cb) : rmdir(p, er, cb)
      if (er.code === "EISDIR")
        return rmdir(p, er, cb)
    }
    return cb(er)
  })
}

function fixWinEPERM (p, er, cb) {
  fs.chmod(p, 666, function (er2) {
    if (er2)
      cb(er2.code === "ENOENT" ? null : er)
    else
      fs.stat(p, function(er3, stats) {
        if (er3)
          cb(er3.code === "ENOENT" ? null : er)
        else if (stats.isDirectory())
          rmdir(p, er, cb)
        else
          fs.unlink(p, cb)
      })
  })
}

function fixWinEPERMSync (p, er, cb) {
  try {
    fs.chmodSync(p, 666)
  } catch (er2) {
    if (er2.code !== "ENOENT")
      throw er
  }

  try {
    var stats = fs.statSync(p)
  } catch (er3) {
    if (er3 !== "ENOENT")
      throw er
  }

  if (stats.isDirectory())
    rmdirSync(p, er)
  else
    fs.unlinkSync(p)
}

function rmdir (p, originalEr, cb) {
  // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
  // if we guessed wrong, and it's not a directory, then
  // raise the original error.
  fs.rmdir(p, function (er) {
    if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
      rmkids(p, cb)
    else if (er && er.code === "ENOTDIR")
      cb(originalEr)
    else
      cb(er)
  })
}

function rmkids(p, cb) {
  fs.readdir(p, function (er, files) {
    if (er)
      return cb(er)
    var n = files.length
    if (n === 0)
      return fs.rmdir(p, cb)
    var errState
    files.forEach(function (f) {
      rimraf(path.join(p, f), function (er) {
        if (errState)
          return
        if (er)
          return cb(errState = er)
        if (--n === 0)
          fs.rmdir(p, cb)
      })
    })
  })
}

// this looks simpler, and is strictly *faster*, but will
// tie up the JavaScript thread and fail on excessively
// deep directory trees.
function rimrafSync (p) {
  try {
    fs.unlinkSync(p)
  } catch (er) {
    if (er.code === "ENOENT")
      return
    if (er.code === "EPERM")
      return isWindows ? fixWinEPERMSync(p, er) : rmdirSync(p, er)
    if (er.code !== "EISDIR")
      throw er
    rmdirSync(p, er)
  }
}

function rmdirSync (p, originalEr) {
  try {
    fs.rmdirSync(p)
  } catch (er) {
    if (er.code === "ENOENT")
      return
    if (er.code === "ENOTDIR")
      throw originalEr
    if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
      rmkidsSync(p)
  }
}

function rmkidsSync (p) {
  fs.readdirSync(p).forEach(function (f) {
    rimrafSync(path.join(p, f))
  })
  fs.rmdirSync(p)
}
<commit_msg>pass around options object<commit_after>module.exports = rimraf
rimraf.sync = rimrafSync

var path = require("path")
var fs = require("fs")

// for EMFILE handling
var timeout = 0
exports.EMFILE_MAX = 1000
exports.BUSYTRIES_MAX = 3

var isWindows = (process.platform === "win32")

function rimraf (p, options, cb) {
  if (typeof options === 'function') {
    cb = options
    options = {}
  }

  options.path = p

  if (!cb) throw new Error("No callback passed to rimraf()")

  var busyTries = 0
  rimraf_(p, options, function CB (er) {
    if (er) {
      if (isWindows && (er.code === "EBUSY" || er.code === "ENOTEMPTY") &&
          busyTries < exports.BUSYTRIES_MAX) {
        busyTries ++
        var time = busyTries * 100
        // try again, with the same exact callback as this one.
        return setTimeout(function () {
          rimraf_(p, options, CB)
        }, time)
      }

      // this one won't happen if graceful-fs is used.
      if (er.code === "EMFILE" && timeout < exports.EMFILE_MAX) {
        return setTimeout(function () {
          rimraf_(p, options, CB)
        }, timeout ++)
      }

      // already gone
      if (er.code === "ENOENT") er = null
    }

    timeout = 0
    cb(er)
  })
}

// Two possible strategies.
// 1. Assume it's a file.  unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory.  readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong.  However, there
// are likely far more normal files in the world than directories.  This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow.  But until then, YAGNI.
function rimraf_ (p, options, cb) {
  fs.unlink(p, function (er) {
    if (er) {
      if (er.code === "ENOENT")
        return cb(null)
      if (er.code === "EPERM")
        return (isWindows)
          ? fixWinEPERM(p, options, er, cb)
          : rmdir(p, options, er, cb)
      if (er.code === "EISDIR")
        return rmdir(p, options, er, cb)
    }
    return cb(er)
  })
}

function fixWinEPERM (p, options, er, cb) {
  fs.chmod(p, 666, function (er2) {
    if (er2)
      cb(er2.code === "ENOENT" ? null : er)
    else
      fs.stat(p, function(er3, stats) {
        if (er3)
          cb(er3.code === "ENOENT" ? null : er)
        else if (stats.isDirectory())
          rmdir(p, options, er, cb)
        else
          fs.unlink(p, cb)
      })
  })
}

function fixWinEPERMSync (p, er, cb) {
  try {
    fs.chmodSync(p, 666)
  } catch (er2) {
    if (er2.code !== "ENOENT")
      throw er
  }

  try {
    var stats = fs.statSync(p)
  } catch (er3) {
    if (er3 !== "ENOENT")
      throw er
  }

  if (stats.isDirectory())
    rmdirSync(p, er)
  else
    fs.unlinkSync(p)
}

function rmdir (p, options, originalEr, cb) {
  // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
  // if we guessed wrong, and it's not a directory, then
  // raise the original error.
  fs.rmdir(p, function (er) {
    if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
      rmkids(p, options, cb)
    else if (er && er.code === "ENOTDIR")
      cb(originalEr)
    else
      cb(er)
  })
}

function rmkids(p, options, cb) {
  fs.readdir(p, function (er, files) {
    if (er)
      return cb(er)
    var n = files.length
    if (n === 0)
      return fs.rmdir(p, cb)
    var errState
    files.forEach(function (f) {
      rimraf(path.join(p, f), options, function (er) {
        if (errState)
          return
        if (er)
          return cb(errState = er)
        if (--n === 0)
          fs.rmdir(p, cb)
      })
    })
  })
}

// this looks simpler, and is strictly *faster*, but will
// tie up the JavaScript thread and fail on excessively
// deep directory trees.
function rimrafSync (p, options) {
  try {
    fs.unlinkSync(p)
  } catch (er) {
    if (er.code === "ENOENT")
      return
    if (er.code === "EPERM")
      return isWindows ? fixWinEPERMSync(p, er) : rmdirSync(p, er)
    if (er.code !== "EISDIR")
      throw er
    rmdirSync(p, options, er)
  }
}

function rmdirSync (p, options, originalEr) {
  try {
    fs.rmdirSync(p)
  } catch (er) {
    if (er.code === "ENOENT")
      return
    if (er.code === "ENOTDIR")
      throw originalEr
    if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
      rmkidsSync(p, options)
  }
}

function rmkidsSync (p, options) {
  fs.readdirSync(p).forEach(function (f) {
    rimrafSync(path.join(p, f), options)
  })
  fs.rmdirSync(p)
}
<|endoftext|>


<commit_before>import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@material-ui/core/styles';

export default class SSRDocument extends Document {
  static async getInitialProps(ctx) {
    // Render app and page and get the context of the page with collected side effects.
    const sheets = new ServerStyleSheets();

    const initialProps = await Document.getInitialProps({
      ...ctx,
      renderPage: () => ctx.renderPage({
        enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
      }),
    });

    return {
      ...initialProps,
      // Styles fragment is rendered after the app and page rendering finish.
      styles: [
        <React.Fragment key="styles">
          {initialProps.styles}
          {sheets.getStyleElement()}
        </React.Fragment>,
      ],
    };
  }

  render() {
    return (
      <Html lang="en">
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
<commit_msg>client: fix lint<commit_after>import React from 'react';
import Document, {
  Html, Head, Main, NextScript,
} from 'next/document';
import { ServerStyleSheets } from '@material-ui/core/styles';

export default class SSRDocument extends Document {
  static async getInitialProps(ctx) {
    // Render app and page and get the context of the page with collected side effects.
    const sheets = new ServerStyleSheets();

    const initialProps = await Document.getInitialProps({
      ...ctx,
      renderPage: () => ctx.renderPage({
        enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
      }),
    });

    return {
      ...initialProps,
      // Styles fragment is rendered after the app and page rendering finish.
      styles: [
        <React.Fragment key="styles">
          {initialProps.styles}
          {sheets.getStyleElement()}
        </React.Fragment>,
      ],
    };
  }

  render() {
    return (
      <Html lang="en">
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
<|endoftext|>


<commit_before>(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (global.vuexI18n = factory());
}(this, (function () { 'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  return typeof obj;
} : function (obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};

var asyncGenerator = function () {
  function AwaitValue(value) {
    this.value = value;
  }

  function AsyncGenerator(gen) {
    var front, back;

    function send(key, arg) {
      return new Promise(function (resolve, reject) {
        var request = {
          key: key,
          arg: arg,
          resolve: resolve,
          reject: reject,
          next: null
        };

        if (back) {
          back = back.next = request;
        } else {
          front = back = request;
          resume(key, arg);
        }
      });
    }

    function resume(key, arg) {
      try {
        var result = gen[key](arg);
        var value = result.value;

        if (value instanceof AwaitValue) {
          Promise.resolve(value.value).then(function (arg) {
            resume("next", arg);
          }, function (arg) {
            resume("throw", arg);
          });
        } else {
          settle(result.done ? "return" : "normal", result.value);
        }
      } catch (err) {
        settle("throw", err);
      }
    }

    function settle(type, value) {
      switch (type) {
        case "return":
          front.resolve({
            value: value,
            done: true
          });
          break;

        case "throw":
          front.reject(value);
          break;

        default:
          front.resolve({
            value: value,
            done: false
          });
          break;
      }

      front = front.next;

      if (front) {
        resume(front.key, front.arg);
      } else {
        back = null;
      }
    }

    this._invoke = send;

    if (typeof gen.return !== "function") {
      this.return = undefined;
    }
  }

  if (typeof Symbol === "function" && Symbol.asyncIterator) {
    AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
      return this;
    };
  }

  AsyncGenerator.prototype.next = function (arg) {
    return this._invoke("next", arg);
  };

  AsyncGenerator.prototype.throw = function (arg) {
    return this._invoke("throw", arg);
  };

  AsyncGenerator.prototype.return = function (arg) {
    return this._invoke("return", arg);
  };

  return {
    wrap: function (fn) {
      return function () {
        return new AsyncGenerator(fn.apply(this, arguments));
      };
    },
    await: function (value) {
      return new AwaitValue(value);
    }
  };
}();

var get = function get(object, property, receiver) {
  if (object === null) object = Function.prototype;
  var desc = Object.getOwnPropertyDescriptor(object, property);

  if (desc === undefined) {
    var parent = Object.getPrototypeOf(object);

    if (parent === null) {
      return undefined;
    } else {
      return get(parent, property, receiver);
    }
  } else if ("value" in desc) {
    return desc.value;
  } else {
    var getter = desc.get;

    if (getter === undefined) {
      return undefined;
    }

    return getter.call(receiver);
  }
};

var set = function set(object, property, value, receiver) {
  var desc = Object.getOwnPropertyDescriptor(object, property);

  if (desc === undefined) {
    var parent = Object.getPrototypeOf(object);

    if (parent !== null) {
      set(parent, property, value, receiver);
    }
  } else if ("value" in desc && desc.writable) {
    desc.value = value;
  } else {
    var setter = desc.set;

    if (setter !== undefined) {
      setter.call(receiver, value);
    }
  }

  return value;
};

/* vuex-i18n-store defines a vuex module to store locale translations. Make sure
** to also include the file vuex-i18n.js to enable easy access to localized
** strings in your vue components.
*/

// define a simple vuex module to handle locale translations
var i18nVuexModule = {
	state: {
		locale: null,
		translations: {}
	},
	mutations: {

		// set the current locale
		SET_LOCALE: function SET_LOCALE(state, payload) {
			state.locale = payload.locale;
		},

		// add a new locale
		ADD_LOCALE: function ADD_LOCALE(state, payload) {
			// reduce the given translations to a single-depth tree
			var translations = flattenTranslations(payload.translations);
			state.translations[payload.locale] = translations;
		},

		// add a new locale
		REMOVE_LOCALE: function REMOVE_LOCALE(state, payload) {

			// check if the given locale is present in the state
			if (state.translations.hasOwnProperty(payload.locale)) {

				// check if the current locale is the given locale to remvoe
				if (state.locale === payload.locale) {
					// reset the current locale
					state.locale = null;
				}

				// create a copy of the translations object
				var translationCopy = Object.assign({}, state.translations);

				// remove the given locale
				delete translationCopy[payload.locale];

				// set the state to the new object
				state.translations = copy;
			}
		}
	},
	actions: {

		// set the current locale
		setLocale: function setLocale(context, payload) {
			context.commit({
				type: 'SET_LOCALE',
				locale: payload.locale
			});
		},

		// add a new locale with translations
		addLocale: function addLocale(context, payload) {
			context.commit({
				type: 'ADD_LOCALE',
				locale: payload.locale,
				translations: payload.translations
			});
		},

		// remove the given locale translations
		removeLocale: function removeLocale(context, payload) {
			context.commit({
				type: 'REMOVE_LOCALE',
				locale: payload.locale,
				translations: payload.translations
			});
		}
	}
};

// flattenTranslations will convert object trees for translations into a
// single-depth object tree
var flattenTranslations = function flattenTranslations(translations) {

	var toReturn = {};

	for (var i in translations) {

		// check if the property is present
		if (!translations.hasOwnProperty(i)) {
			continue;
		}

		// get the type of the property
		var objType = _typeof(translations[i]);

		// allow unflattened array of strings
		if (isArray(translations[i])) {

			var count = translations[i].length;

			for (var index = 0; index < count; index++) {
				var itemType = _typeof(translations[i][index]);

				if (itemType !== 'string') {
					console.warn('vuex-i18n:', 'currently only arrays of strings are fully supported', translations[i]);
					break;
				}
			}

			toReturn[i] = translations[i];
		} else if (objType == 'object' && objType !== null) {

			var flatObject = flattenTranslations(translations[i]);

			for (var x in flatObject) {
				if (!flatObject.hasOwnProperty(x)) continue;

				toReturn[i + '.' + x] = flatObject[x];
			}
		} else {
			toReturn[i] = translations[i];
		}
	}
	return toReturn;
};

// check if the given object is an array
function isArray(obj) {
	return !!obj && Array === obj.constructor;
}

/* vuex-i18n defines the Vuexi18nPlugin to enable localization using a vuex
** module to store the translation information. Make sure to also include the
** file vuex-i18n-store.js to include a respective vuex module.
*/

// initialize the plugin object
var VuexI18nPlugin = {};

// internationalization plugin for vue js using vuex
VuexI18nPlugin.install = function install(Vue, store) {
	var moduleName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'i18n';

	// check if the plugin was correctly initialized
	if (store.state.hasOwnProperty(moduleName) === false) {
		console.error('i18n vuex module is not correctly initialized. Please check the module name:', moduleName);

		// always return the key if module is not initialized correctly
		Vue.prototype.$i18n = function (key) {
			return key;
		};

		Vue.prototype.$getLanguage = function () {
			return null;
		};

		Vue.prototype.$setLanguage = function () {
			console.error('i18n vuex module is not correctly initialized');
		};

		return;
	}

	// get localized string from store
	var translate = function $t(key, options) {

		// get the current language from the store
		var locale = store.state[moduleName].locale;

		// check if the language exists in the store. return the key if not
		if (store.state[moduleName].translations.hasOwnProperty(locale) === false) {
			return render(key, options);
		}

		// check if the key exists in the store. return the key if not
		if (store.state[moduleName].translations[locale].hasOwnProperty(key) === false) {
			return render(key, options);
		}

		// return the value from the store
		return render(store.state[moduleName].translations[locale][key], options);
	};

	var setLocale = function setLocale(locale) {
		store.dispatch({
			type: 'setLocale',
			locale: locale
		});
	};

	var getLocale = function getLocale() {
		return store.state[moduleName].locale;
	};

	// add predefined translations to the store
	var addLocale = function addLocale(locale, translations) {
		return store.dispatch({
			type: 'addLocale',
			locale: locale,
			translations: translations
		});
	};

	// remove the givne locale from the store
	var removeLocale = function removeLocale(locale) {
		if (store.state[moduleName].translations.hasOwnProperty(locale)) {
			store.dispatch({
				type: 'removeLocale',
				locale: locale
			});
		}
	};

	// check if the given locale is already loaded
	var checkLocaleExists = function checkLocaleExists(locale) {
		return store.state[moduleName].translations.hasOwnProperty(locale);
	};

	// register vue prototype methods
	Vue.prototype.$i18n = {
		locale: getLocale,
		set: setLocale,
		add: addLocale,
		remove: removeLocale,
		exists: checkLocaleExists
	};

	// register global methods
	Vue.i18n = {
		locale: getLocale,
		set: setLocale,
		add: addLocale,
		remove: removeLocale,
		exists: checkLocaleExists,
		translate: translate
	};

	// register the translation function on the vue instance
	Vue.prototype.$t = translate;

	// register a filter function for translations
	Vue.filter('translate', translate);
};

// replace will replace the given replacements in the translation string
var replace = function replace(translation, replacements) {
	var warn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

	// check if the object has a replace property
	if (!translation.replace) {
		return translation;
	}

	return translation.replace(/\{\w+\}/g, function (placeholder) {

		var key = placeholder.replace('{', '').replace('}', '');

		if (replacements[key] !== undefined) {
			return replacements[key];
		}

		// warn user that the placeholder has not been found
		if (warn === true) {
			console.group('Not all placeholder founds');
			console.warn('Text:', translation);
			console.warn('Placeholder:', placeholder);
			console.groupEnd();
		}

		// return the original placeholder
		return placeholder;
	});
};

// render will return the given translation object
var render = function render(translation) {
	var replacements = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

	// get the type of the property
	var objType = typeof translation === 'undefined' ? 'undefined' : _typeof(translation);

	if (isArray$1(translation)) {

		// replace the placeholder elements in all sub-items
		return translation.map(function (item) {
			return replace(item, replacements, false);
		});
	} else if (objType === 'string') {
		return replace(translation, replacements);
	}

	// return translation item directly
	return translation;
};

// check if the given object is an array
function isArray$1(obj) {
	return !!obj && Array === obj.constructor;
}

// import the vuex module for localization
// import the corresponding plugin for vue
// export both modules as one file
var index = {
	store: i18nVuexModule,
	plugin: VuexI18nPlugin
};

return index;

})));
<commit_msg>fix #9<commit_after>(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (global.vuexI18n = factory());
}(this, (function () { 'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  return typeof obj;
} : function (obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};

var asyncGenerator = function () {
  function AwaitValue(value) {
    this.value = value;
  }

  function AsyncGenerator(gen) {
    var front, back;

    function send(key, arg) {
      return new Promise(function (resolve, reject) {
        var request = {
          key: key,
          arg: arg,
          resolve: resolve,
          reject: reject,
          next: null
        };

        if (back) {
          back = back.next = request;
        } else {
          front = back = request;
          resume(key, arg);
        }
      });
    }

    function resume(key, arg) {
      try {
        var result = gen[key](arg);
        var value = result.value;

        if (value instanceof AwaitValue) {
          Promise.resolve(value.value).then(function (arg) {
            resume("next", arg);
          }, function (arg) {
            resume("throw", arg);
          });
        } else {
          settle(result.done ? "return" : "normal", result.value);
        }
      } catch (err) {
        settle("throw", err);
      }
    }

    function settle(type, value) {
      switch (type) {
        case "return":
          front.resolve({
            value: value,
            done: true
          });
          break;

        case "throw":
          front.reject(value);
          break;

        default:
          front.resolve({
            value: value,
            done: false
          });
          break;
      }

      front = front.next;

      if (front) {
        resume(front.key, front.arg);
      } else {
        back = null;
      }
    }

    this._invoke = send;

    if (typeof gen.return !== "function") {
      this.return = undefined;
    }
  }

  if (typeof Symbol === "function" && Symbol.asyncIterator) {
    AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
      return this;
    };
  }

  AsyncGenerator.prototype.next = function (arg) {
    return this._invoke("next", arg);
  };

  AsyncGenerator.prototype.throw = function (arg) {
    return this._invoke("throw", arg);
  };

  AsyncGenerator.prototype.return = function (arg) {
    return this._invoke("return", arg);
  };

  return {
    wrap: function (fn) {
      return function () {
        return new AsyncGenerator(fn.apply(this, arguments));
      };
    },
    await: function (value) {
      return new AwaitValue(value);
    }
  };
}();

var get = function get(object, property, receiver) {
  if (object === null) object = Function.prototype;
  var desc = Object.getOwnPropertyDescriptor(object, property);

  if (desc === undefined) {
    var parent = Object.getPrototypeOf(object);

    if (parent === null) {
      return undefined;
    } else {
      return get(parent, property, receiver);
    }
  } else if ("value" in desc) {
    return desc.value;
  } else {
    var getter = desc.get;

    if (getter === undefined) {
      return undefined;
    }

    return getter.call(receiver);
  }
};

var set = function set(object, property, value, receiver) {
  var desc = Object.getOwnPropertyDescriptor(object, property);

  if (desc === undefined) {
    var parent = Object.getPrototypeOf(object);

    if (parent !== null) {
      set(parent, property, value, receiver);
    }
  } else if ("value" in desc && desc.writable) {
    desc.value = value;
  } else {
    var setter = desc.set;

    if (setter !== undefined) {
      setter.call(receiver, value);
    }
  }

  return value;
};

/* vuex-i18n-store defines a vuex module to store locale translations. Make sure
** to also include the file vuex-i18n.js to enable easy access to localized
** strings in your vue components.
*/

// define a simple vuex module to handle locale translations
var i18nVuexModule = {
	state: {
		locale: null,
		translations: {}
	},
	mutations: {

		// set the current locale
		SET_LOCALE: function SET_LOCALE(state, payload) {
			state.locale = payload.locale;
		},

		// add a new locale
		ADD_LOCALE: function ADD_LOCALE(state, payload) {
			// reduce the given translations to a single-depth tree
			var translations = flattenTranslations(payload.translations);
			state.translations[payload.locale] = translations;
		},

		// add a new locale
		REMOVE_LOCALE: function REMOVE_LOCALE(state, payload) {

			// check if the given locale is present in the state
			if (state.translations.hasOwnProperty(payload.locale)) {

				// check if the current locale is the given locale to remvoe
				if (state.locale === payload.locale) {
					// reset the current locale
					state.locale = null;
				}

				// create a copy of the translations object
				var translationCopy = Object.assign({}, state.translations);

				// remove the given locale
				delete translationCopy[payload.locale];

				// set the state to the new object
				state.translations = translationCopy;
			}
		}
	},
	actions: {

		// set the current locale
		setLocale: function setLocale(context, payload) {
			context.commit({
				type: 'SET_LOCALE',
				locale: payload.locale
			});
		},

		// add a new locale with translations
		addLocale: function addLocale(context, payload) {
			context.commit({
				type: 'ADD_LOCALE',
				locale: payload.locale,
				translations: payload.translations
			});
		},

		// remove the given locale translations
		removeLocale: function removeLocale(context, payload) {
			context.commit({
				type: 'REMOVE_LOCALE',
				locale: payload.locale,
				translations: payload.translations
			});
		}
	}
};

// flattenTranslations will convert object trees for translations into a
// single-depth object tree
var flattenTranslations = function flattenTranslations(translations) {

	var toReturn = {};

	for (var i in translations) {

		// check if the property is present
		if (!translations.hasOwnProperty(i)) {
			continue;
		}

		// get the type of the property
		var objType = _typeof(translations[i]);

		// allow unflattened array of strings
		if (isArray(translations[i])) {

			var count = translations[i].length;

			for (var index = 0; index < count; index++) {
				var itemType = _typeof(translations[i][index]);

				if (itemType !== 'string') {
					console.warn('vuex-i18n:', 'currently only arrays of strings are fully supported', translations[i]);
					break;
				}
			}

			toReturn[i] = translations[i];
		} else if (objType == 'object' && objType !== null) {

			var flatObject = flattenTranslations(translations[i]);

			for (var x in flatObject) {
				if (!flatObject.hasOwnProperty(x)) continue;

				toReturn[i + '.' + x] = flatObject[x];
			}
		} else {
			toReturn[i] = translations[i];
		}
	}
	return toReturn;
};

// check if the given object is an array
function isArray(obj) {
	return !!obj && Array === obj.constructor;
}

/* vuex-i18n defines the Vuexi18nPlugin to enable localization using a vuex
** module to store the translation information. Make sure to also include the
** file vuex-i18n-store.js to include a respective vuex module.
*/

// initialize the plugin object
var VuexI18nPlugin = {};

// internationalization plugin for vue js using vuex
VuexI18nPlugin.install = function install(Vue, store) {
	var moduleName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'i18n';

	// check if the plugin was correctly initialized
	if (store.state.hasOwnProperty(moduleName) === false) {
		console.error('i18n vuex module is not correctly initialized. Please check the module name:', moduleName);

		// always return the key if module is not initialized correctly
		Vue.prototype.$i18n = function (key) {
			return key;
		};

		Vue.prototype.$getLanguage = function () {
			return null;
		};

		Vue.prototype.$setLanguage = function () {
			console.error('i18n vuex module is not correctly initialized');
		};

		return;
	}

	// get localized string from store
	var translate = function $t(key, options) {

		// get the current language from the store
		var locale = store.state[moduleName].locale;

		// check if the language exists in the store. return the key if not
		if (store.state[moduleName].translations.hasOwnProperty(locale) === false) {
			return render(key, options);
		}

		// check if the key exists in the store. return the key if not
		if (store.state[moduleName].translations[locale].hasOwnProperty(key) === false) {
			return render(key, options);
		}

		// return the value from the store
		return render(store.state[moduleName].translations[locale][key], options);
	};

	var setLocale = function setLocale(locale) {
		store.dispatch({
			type: 'setLocale',
			locale: locale
		});
	};

	var getLocale = function getLocale() {
		return store.state[moduleName].locale;
	};

	// add predefined translations to the store
	var addLocale = function addLocale(locale, translations) {
		return store.dispatch({
			type: 'addLocale',
			locale: locale,
			translations: translations
		});
	};

	// remove the givne locale from the store
	var removeLocale = function removeLocale(locale) {
		if (store.state[moduleName].translations.hasOwnProperty(locale)) {
			store.dispatch({
				type: 'removeLocale',
				locale: locale
			});
		}
	};

	// check if the given locale is already loaded
	var checkLocaleExists = function checkLocaleExists(locale) {
		return store.state[moduleName].translations.hasOwnProperty(locale);
	};

	// register vue prototype methods
	Vue.prototype.$i18n = {
		locale: getLocale,
		set: setLocale,
		add: addLocale,
		remove: removeLocale,
		exists: checkLocaleExists
	};

	// register global methods
	Vue.i18n = {
		locale: getLocale,
		set: setLocale,
		add: addLocale,
		remove: removeLocale,
		exists: checkLocaleExists,
		translate: translate
	};

	// register the translation function on the vue instance
	Vue.prototype.$t = translate;

	// register a filter function for translations
	Vue.filter('translate', translate);
};

// replace will replace the given replacements in the translation string
var replace = function replace(translation, replacements) {
	var warn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

	// check if the object has a replace property
	if (!translation.replace) {
		return translation;
	}

	return translation.replace(/\{\w+\}/g, function (placeholder) {

		var key = placeholder.replace('{', '').replace('}', '');

		if (replacements[key] !== undefined) {
			return replacements[key];
		}

		// warn user that the placeholder has not been found
		if (warn === true) {
			console.group('Not all placeholder founds');
			console.warn('Text:', translation);
			console.warn('Placeholder:', placeholder);
			console.groupEnd();
		}

		// return the original placeholder
		return placeholder;
	});
};

// render will return the given translation object
var render = function render(translation) {
	var replacements = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

	// get the type of the property
	var objType = typeof translation === 'undefined' ? 'undefined' : _typeof(translation);

	if (isArray$1(translation)) {

		// replace the placeholder elements in all sub-items
		return translation.map(function (item) {
			return replace(item, replacements, false);
		});
	} else if (objType === 'string') {
		return replace(translation, replacements);
	}

	// return translation item directly
	return translation;
};

// check if the given object is an array
function isArray$1(obj) {
	return !!obj && Array === obj.constructor;
}

// import the vuex module for localization
// import the corresponding plugin for vue
// export both modules as one file
var index = {
	store: i18nVuexModule,
	plugin: VuexI18nPlugin
};

return index;

})));
<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Metadata.
    pkg: grunt.file.readJSON('package.json'),
    banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
      '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
      '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
      '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
      ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',

    // Task configuration.
    clean: {
      files: ['dist']
    },
    concat: {
      options: {
        banner: '<%= banner %>',
        stripBanners: true
      },
      dist: {
        src: ['components/requirejs/require.js', '<%= concat.dist.dest %>'],
        dest: 'dist/require.js'
      },
    },
    uglify: {
      options: {
        banner: '<%= banner %>'
      },
      dist: {
        src: '<%= concat.dist.dest %>',
        dest: 'dist/require.min.js'
      },
    },
    qunit: {
      files: ['test/**/*.html']
    },
    jshint: {
      gruntfile: {
        options: {
          jshintrc: '.jshintrc'
        },
      },
      app: {
        options: {
          jshintrc: 'app/.jshintrc'
        },
        src: ['app/**/*.js']
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/**/*.js']
      },
    },
    watch: {
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile']
      },
      src: {
        files: '<%= jshint.app.src %>',
        tasks: ['jshint:src'], 'qunit']
      },
      test: {
        files: '<%= jshint.test.src %>',
        tasks: ['jshint:test'], 'qunit']
      },
    },
    requirejs: {
      compile: {
        options: {
          name: 'config',
          mainConfigFile: 'app/config.js',
          out: '<%= concat.dist.dest %>',
          optimize: 'none'
        }
      }
    },
    connect: {
      development: {
        options: {
          keepalive: true,
        }
      },
      production: {
        options: {
          keepalive: true,
          port: 8000,
          middleware: function(connect, options) {
            return [
              // rewrite requirejs to the compiled version
              function(req, res, next) {
                if (req.url === '/components/requirejs/require.js') {
                  req.url = '/dist/require.min.js';
                }
                next();
              },
              connect.static(options.base),

            ];
          }
        }
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-requirejs');
  grunt.loadNpmTasks('grunt-contrib-connect');

  // Default task.
  grunt.registerTask('default', ['jshint','qunit', 'clean', 'requirejs', 'concat', 'uglify']);
  grunt.registerTask('preview', ['connect:development']);
  grunt.registerTask('preview-live', ['default', 'connect:production']);

};
<commit_msg>Fix error on Gruntfile.js<commit_after>'use strict';

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    // Metadata.
    pkg: grunt.file.readJSON('package.json'),
    banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
      '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
      '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
      '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
      ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',

    // Task configuration.
    clean: {
      files: ['dist']
    },
    concat: {
      options: {
        banner: '<%= banner %>',
        stripBanners: true
      },
      dist: {
        src: ['components/requirejs/require.js', '<%= concat.dist.dest %>'],
        dest: 'dist/require.js'
      },
    },
    uglify: {
      options: {
        banner: '<%= banner %>'
      },
      dist: {
        src: '<%= concat.dist.dest %>',
        dest: 'dist/require.min.js'
      },
    },
    qunit: {
      files: ['test/**/*.html']
    },
    jshint: {
      gruntfile: {
        options: {
          jshintrc: '.jshintrc'
        },
      },
      app: {
        options: {
          jshintrc: 'app/.jshintrc'
        },
        src: ['app/**/*.js']
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/**/*.js']
      },
    },
    watch: {
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile']
      },
      src: {
        files: '<%= jshint.app.src %>',
        tasks: ['jshint:src', 'qunit']
      },
      test: {
        files: '<%= jshint.test.src %>',
        tasks: ['jshint:test', 'qunit']
      },
    },
    requirejs: {
      compile: {
        options: {
          name: 'config',
          mainConfigFile: 'app/config.js',
          out: '<%= concat.dist.dest %>',
          optimize: 'none'
        }
      }
    },
    connect: {
      development: {
        options: {
          keepalive: true,
        }
      },
      production: {
        options: {
          keepalive: true,
          port: 8000,
          middleware: function(connect, options) {
            return [
              // rewrite requirejs to the compiled version
              function(req, res, next) {
                if (req.url === '/components/requirejs/require.js') {
                  req.url = '/dist/require.min.js';
                }
                next();
              },
              connect.static(options.base),

            ];
          }
        }
      }
    }
  });

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-qunit');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-requirejs');
  grunt.loadNpmTasks('grunt-contrib-connect');

  // Default task.
  grunt.registerTask('default', ['jshint','qunit', 'clean', 'requirejs', 'concat', 'uglify']);
  grunt.registerTask('preview', ['connect:development']);
  grunt.registerTask('preview-live', ['default', 'connect:production']);

};
<|endoftext|>


<commit_before>Template.profile.helpers({
    user: function () {
        return Meteor.user();
    },
    follow: function () {
        return {
            er: Meteor.user().profile.follower.length,
            ing: Meteor.user().profile.following.length,
            thanks: Meteor.user().profile.thanks.length,
        }
    }
})
Template.editProfile.helpers({
    user: function () {
        return Meteor.user();
    },
})
Template.editProfile.events({
    '#updateProfile': function () {
        console.log($('#name']).val());
    }
})<commit_msg>temp commit<commit_after>Template.profile.helpers({
    user: function () {
        return Meteor.user();
    },
    follow: function () {
        if(Meteor.user()){
            return {
                er: Meteor.user().profile.follower?Meteor.user().profile.follower.length:0,
                ing: Meteor.user().profile.following?Meteor.user().profile.following.length: 0,
                thanks: Meteor.user().profile.thanks?Meteor.user().profile.thanks.length: 0,
            }
        }
    }
})
Template.editProfile.helpers({
    user: function () {
        return Meteor.user();
    },
})
Template.editProfile.events({
    '#updateProfile': function () {
        console.log('a')
    }
})<|endoftext|>


<commit_before>var http     = require('http');
var fs       = require('fs');
var cheerio  = require('cheerio');

var sitemap_file= 'input/sitemap.xml';

if (!fs.existsSync(sitemap_file))
{
    var file = fs.createWriteStream(sitemap_file);
    var request = http.get('http://alser.kz/sitemaps/almaty/sitemap.xml', function(response) {
        response.pipe(sitemap_file);
    });
}<commit_msg>Working MVP<commit_after>var fs       = require('fs');
var request  = require('request');
var cheerio  = require('cheerio');

var sitemap_file = 'input/sitemap.xml';
var sitemap_url  = 'https://alser.kz/sitemaps/almaty/sitemap.xml';

if (!fs.existsSync(sitemap_file))
{
	console.log('no sitemap file');
}

var sitemap_content = fs.readFileSync(sitemap_file, 'utf8');

var sitemap = cheerio.load(sitemap_content, {xmlMode: true});

sitemap('url').map(function(i, url) {

	var page_url     = cheerio(url).find('loc').text();
	var page_id      = 0;
	var match_result = page_url.match(/(?:[a-z0-9_]+)(?:[_]+)([\d]+)/);

	if(page_url.match('^https://'))
	{
		page_url = page_url.replace("https://","http://");
    }

	if (match_result != null)
	{
		page_id = match_result[1];
	}

	if (page_id > 0)
	{
		if (!fs.exists('output/' + page_id + '.json'))
		{
			process_remote_page(page_url);
		}
	}
});

//process_remote_page('http://www.alser.kz/product/parfyumirovannaya_voda_missoni_edp_100_ml_1252074', 1252074);

function process_remote_page(url)
{
	request({ encoding: null, method: "GET", uri: url, proxy : 'http://127.0.0.1:3128', timeout : 30000}, function (error, response, body) {
    	if (!error && response.statusCode == 200)
	    {
	    	console.log('request complete');

			$ = cheerio.load(body);

	    	var page_id = $('.itemMeta.goodMeta').attr('data-code');

	    	var product = {};

	    	product['url']    = url;
	    	product['id']     = page_id;
	    	product['title']  = $('h1.name').text().trim();
	    	product['specs']  = [];
	    	product['photos'] = [];

	    	// Getting specs
	    	$('#fullSpecsInTab > .tableInfo > .row').each(function (i, elem){
	    		product['specs'][i] = {
	    			'name'  : $(this).children('.name').text().trim(),
	    			'value' : $(this).children('.value').text().trim()
	    		};
	    	});

	    	// Getting photos
	    	$('.photoBlock a').each(function (i, elem) {
	    		product['photos'][i] = $(this).attr('href');
	    	});

	    	console.log(JSON.parse(JSON.stringify(product)));

	    	fs.writeFile('output/' + product['id'] + '.json', JSON.stringify(product), function(err) {
			    if (err)
			    {
			        return console.log(err);
			    }
			});
	    }
	    else
	    {
	    	console.log('url: ' + url);
	    	console.log(response.statusCode);
	    	console.log(body)
			console.log('');
		}
	});

	return true;
}<|endoftext|>


<commit_before>'use strict';

/**
 * Upload.js service
 *
 * @description: A set of functions similar to controller's actions to avoid code duplication.
 */

const fs = require('fs');
const crypto = require('crypto');
const _ = require('lodash');
const toArray = require('stream-to-array');
const uuid = require('uuid/v4');

function niceHash(buffer) {
  return crypto
    .createHash('sha256')
    .update(buffer)
    .digest('base64')
    .replace(/=/g, '')
    .replace(/\//g, '-')
    .replace(/\+/, '_');
}

module.exports = {
  bufferize: async files => {
    if (_.isEmpty(files) === 0) {
      throw 'Missing files.';
    }

    // files is always an array to map on
    files = _.isArray(files) ? files : [files];

    // transform all files in buffer
    return Promise.all(
      files.map(async stream => {
        const parts = await toArray(fs.createReadStream(stream.path));
        const buffers = parts.map(
          part => (_.isBuffer(part) ? part : Buffer.from(part)),
        );

        const buffer = Buffer.concat(buffers);

        return {
          tmpPath: stream.path,
          name: stream.name,
          sha256: niceHash(buffer),
          hash: uuid().replace(/-/g, ''),
          ext:
            stream.name.split('.').length > 1
              ? `.${_.last(stream.name.split('.'))}`
              : '',
          buffer,
          mime: stream.type,
          size: (stream.size / 1000).toFixed(2),
        };
      }),
    );
  },

  upload: async (files, config) => {
    // Get upload provider settings to configure the provider to use.
    const provider = _.find(strapi.plugins.upload.config.providers, {
      provider: config.provider,
    });

    if (!provider) {
      throw new Error(
        `The provider package isn't installed. Please run \`npm install strapi-provider-upload-${
          config.provider
        }\``,
      );
    }

    const actions = provider.init(config);

    // Execute upload function of the provider for all files.
    return Promise.all(
      files.map(async file => {
        await actions.upload(file);

        // Remove buffer to don't save it.
        delete file.buffer;

        file.provider = provider.provider;

        const res = await strapi.plugins['upload'].services.upload.add(file);

        // Remove temp file
        fs.unlinkSync(file.tmpPath);
        return res;
      }),
    );
  },

  add: async values => {
    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      return await strapi.plugins['content-manager'].services[
        'contentmanager'
      ].add(
        {
          model: 'file',
        },
        values,
        'upload',
      );
    }

    return strapi.query('file', 'upload').create(values);
  },

  edit: async (params, values) => {
    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      params.model = 'file';
      params.id = params._id || params.id;

      return await strapi.plugins['content-manager'].services[
        'contentmanager'
      ].edit(params, values, 'upload');
    }

    return strapi.query('file', 'upload').update(_.assign(params, values));
  },

  fetch: params => {
    return strapi
      .query('file', 'upload')
      .findOne(_.pick(params, ['_id', 'id']));
  },

  fetchAll: params => {
    return strapi
      .query('file', 'upload')
      .find(strapi.utils.models.convertParams('file', params));
  },

  count: async () => {
    return await strapi.query('file', 'upload').count();
  },

  remove: async (params, config) => {
    params.id = params._id || params.id;

    const file = await strapi.plugins['upload'].services.upload.fetch(params);

    // get upload provider settings to configure the provider to use
    const provider = _.cloneDeep(
      _.find(strapi.plugins.upload.config.providers, {
        provider: config.provider,
      }),
    );
    _.assign(provider, config);
    const actions = provider.init(config);

    // execute delete function of the provider
    if (file.provider === provider.provider) {
      await actions.delete(file);
    }

    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      params.model = 'file';

      await strapi.plugins['content-manager'].services['contentmanager'].delete(
        params,
        { source: 'upload' },
      );
    }

    return strapi.query('file', 'upload').delete(params);
  },

  uploadToEntity: async function(params, files, source) {
    // Retrieve provider settings from database.
    const config = await strapi
      .store({
        environment: strapi.config.environment,
        type: 'plugin',
        name: 'upload',
      })
      .get({ key: 'provider' });

    const model =
      source && source !== 'content-manager'
        ? strapi.plugins[source].models[params.model]
        : strapi.models[params.model];

    // Asynchronous upload.
    await Promise.all(
      Object.keys(files).map(async attribute => {
        // Bufferize files per attribute.
        const buffers = await this.bufferize(files[attribute]);
        const enhancedFiles = buffers.map(file => {
          const details = model.attributes[attribute];

          // Add related information to be able to make
          // the relationships later.
          file[details.via] = [
            {
              refId: params.id,
              ref: params.model,
              source,
              field: attribute,
            },
          ];

          return file;
        });

        // Make upload async.
        return this.upload(enhancedFiles, config);
      }),
    );
  },
};<commit_msg>Fix bookshelf Upload Plugin findOne giving 500 error<commit_after>'use strict';

/**
 * Upload.js service
 *
 * @description: A set of functions similar to controller's actions to avoid code duplication.
 */

const fs = require('fs');
const crypto = require('crypto');
const _ = require('lodash');
const toArray = require('stream-to-array');
const uuid = require('uuid/v4');

function niceHash(buffer) {
  return crypto
    .createHash('sha256')
    .update(buffer)
    .digest('base64')
    .replace(/=/g, '')
    .replace(/\//g, '-')
    .replace(/\+/, '_');
}

module.exports = {
  bufferize: async files => {
    if (_.isEmpty(files) === 0) {
      throw 'Missing files.';
    }

    // files is always an array to map on
    files = _.isArray(files) ? files : [files];

    // transform all files in buffer
    return Promise.all(
      files.map(async stream => {
        const parts = await toArray(fs.createReadStream(stream.path));
        const buffers = parts.map(
          part => (_.isBuffer(part) ? part : Buffer.from(part)),
        );

        const buffer = Buffer.concat(buffers);

        return {
          tmpPath: stream.path,
          name: stream.name,
          sha256: niceHash(buffer),
          hash: uuid().replace(/-/g, ''),
          ext:
            stream.name.split('.').length > 1
              ? `.${_.last(stream.name.split('.'))}`
              : '',
          buffer,
          mime: stream.type,
          size: (stream.size / 1000).toFixed(2),
        };
      }),
    );
  },

  upload: async (files, config) => {
    // Get upload provider settings to configure the provider to use.
    const provider = _.find(strapi.plugins.upload.config.providers, {
      provider: config.provider,
    });

    if (!provider) {
      throw new Error(
        `The provider package isn't installed. Please run \`npm install strapi-provider-upload-${
          config.provider
        }\``,
      );
    }

    const actions = provider.init(config);

    // Execute upload function of the provider for all files.
    return Promise.all(
      files.map(async file => {
        await actions.upload(file);

        // Remove buffer to don't save it.
        delete file.buffer;

        file.provider = provider.provider;

        const res = await strapi.plugins['upload'].services.upload.add(file);

        // Remove temp file
        fs.unlinkSync(file.tmpPath);
        return res;
      }),
    );
  },

  add: async values => {
    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      return await strapi.plugins['content-manager'].services[
        'contentmanager'
      ].add(
        {
          model: 'file',
        },
        values,
        'upload',
      );
    }

    return strapi.query('file', 'upload').create(values);
  },

  edit: async (params, values) => {
    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      params.model = 'file';
      params.id = params._id || params.id;

      return await strapi.plugins['content-manager'].services[
        'contentmanager'
      ].edit(params, values, 'upload');
    }

    return strapi.query('file', 'upload').update(_.assign(params, values));
  },

  fetch: params => {
    params.id = params._id || params.id;
    return strapi
      .query('file', 'upload')
      .findOne(_.pick(params, ['id']));
  },

  fetchAll: params => {
    return strapi
      .query('file', 'upload')
      .find(strapi.utils.models.convertParams('file', params));
  },

  count: async () => {
    return await strapi.query('file', 'upload').count();
  },

  remove: async (params, config) => {
    params.id = params._id || params.id;

    const file = await strapi.plugins['upload'].services.upload.fetch(params);

    // get upload provider settings to configure the provider to use
    const provider = _.cloneDeep(
      _.find(strapi.plugins.upload.config.providers, {
        provider: config.provider,
      }),
    );
    _.assign(provider, config);
    const actions = provider.init(config);

    // execute delete function of the provider
    if (file.provider === provider.provider) {
      await actions.delete(file);
    }

    // Use Content Manager business logic to handle relation.
    if (strapi.plugins['content-manager']) {
      params.model = 'file';

      await strapi.plugins['content-manager'].services['contentmanager'].delete(
        params,
        { source: 'upload' },
      );
    }

    return strapi.query('file', 'upload').delete(params);
  },

  uploadToEntity: async function(params, files, source) {
    // Retrieve provider settings from database.
    const config = await strapi
      .store({
        environment: strapi.config.environment,
        type: 'plugin',
        name: 'upload',
      })
      .get({ key: 'provider' });

    const model =
      source && source !== 'content-manager'
        ? strapi.plugins[source].models[params.model]
        : strapi.models[params.model];

    // Asynchronous upload.
    await Promise.all(
      Object.keys(files).map(async attribute => {
        // Bufferize files per attribute.
        const buffers = await this.bufferize(files[attribute]);
        const enhancedFiles = buffers.map(file => {
          const details = model.attributes[attribute];

          // Add related information to be able to make
          // the relationships later.
          file[details.via] = [
            {
              refId: params.id,
              ref: params.model,
              source,
              field: attribute,
            },
          ];

          return file;
        });

        // Make upload async.
        return this.upload(enhancedFiles, config);
      }),
    );
  },
};<|endoftext|>


<commit_before>vegalab = {};

function compile(){
    // Capture the Vega and Javascript code.
    var spec = d3.select("#vega").node().value;
    var js = d3.select("#js").node().value;

    // Create a JavaScript object out of the spec.
    //
    // TODO(choudhury): error checking for the eval call.
    spec = eval("(" + spec + ")");

    // Compile the Vega code into the template, and display it on the page.
    var source = vg.compile(spec, vegalab.template);
    d3.select("#code")
        .text(source);

    // Eval the generated source, and capture the resulting function with a
    // name.
    eval("vegalab.make_chart = " + source + ";");

    // Create a visualization by calling the function.
    vegalab.chart = vegalab.make_chart();
    vegalab.chart.el("#chart");

    // Eval the user Javascript, which should be just an object with properties
    // named "data" and "extra".
    vegalab.js = eval("(" + js + ")");

    // The "data" property should contain a function that returns the data to be
    // used with the visualization.
    if(vegalab.js.data !== undefined){
        vegalab.chart.data(vegalab.js.data());
    }
    else{
        console.log("warning: no 'data' function in javascript code");
    }

    // Now that the data is ready, create the chart.
    vegalab.chart.init().update();

    // The "extra" property should contain a function that takes a Vega
    // visualization as an input and performs some extra work on it (to
    // implement interactin behavior, etc.).
    if(vegalab.js.extra !== undefined){
        vegalab.js.extra(vegalab.chart);
    }
    else{
        console.log("warning: no 'extra' function in javascript code");
    }
}

// A callback function for reading a selected file and pasting its contents into
// a textarea element.
function textplop(textarea_id){
    return function(e){
        // Grab the filename from the element.
        var file = d3.event.target.files[0];

        // Instantiate a file reader object, whose callback will simply plop
        // the text into the element.
        var reader = new FileReader();
        reader.onload = function(e){
            // Grab the text.
            var text = e.target.result;

            // Place it into the textarea element.
            d3.select("#" + textarea_id)
                .text(text);
        };
        reader.readAsText(file);
    }
}

window.onload = function(){
    // Load the Vega template text.
    d3.text("/lib/vgd3-template.js.txt", function(text){
        // Save the text.
        vegalab.template = text;

        // Now that the necessary data is loaded, install the actions on the
        // buttons.
        //
        // Install file upload handlers on the textarea buttons.
        d3.select("#vega_file")
            .on("change", textplop("vega"));

        d3.select("#js_file")
            .on("change", textplop("js"));

        d3.select("#data_file")
            .on("change", textplop("data"));

        // Install click handler for compile button, and enable the button.
        d3.select("#compile")
            .on("click", compile)
            .attr("disabled", null);
    });
};
<commit_msg>Implemented data window; repurposed JS window.<commit_after>vegalab = {};

function compile(){
    // Capture the Vega and Javascript code.
    var spec = d3.select("#vega").node().value;
    var js = d3.select("#js").node().value;
    var data = d3.select("#data").node().value;

    // Create a JavaScript object out of the spec.
    //
    // TODO(choudhury): error checking for the eval call.
    try{
        spec = eval("(" + spec + ")");
    }
    catch(e){
        console.log("error parsing Vega spec: " + e);
        return;
    }

    // Compile the Vega code into the template, and display it on the page.
    var source = vg.compile(spec, vegalab.template);
    d3.select("#code")
        .text(source);

    // Eval the generated source, and capture the resulting function with a
    // name.
    eval("vegalab.make_chart = " + source + ";");

    // Create a visualization by calling the function.
    vegalab.chart = vegalab.make_chart();
    vegalab.chart.el("#chart");

    // Eval the user Javascript, which should be just a function.  Default to
    // the function that does nothing.
    if(js.length > 0){
        try{
            eval("vegalab.js = " + js);
        }
        catch(e){
            console.log("error parsing user JavaScript: " + e);
            return;
        }
    }
    else{
        vegalab.js = function() {};
    }

    // The data window should contain either a function that returns the data to
    // be used, or a JSON object describing the data directly.
    if(data.length > 0){
        try{
            // Try to parse a JSON object from the data window.
            var d = $.parseJSON(data);

            // If we succeed, send the data object to the vega object.
            vegalab.chart.data(d);
        }
        catch(e){
            // Reaching here means the data window could not be parsed as JSON.
            // Try to parse it as JavaScript now.  The window should contain a
            // single function that returns a data value.
            try{
                eval("d = " + data);

                // Call d as a function, and send its output to the vega object.
                vegalab.chart.data(d());
            }
            catch(e){
                console.log("error parsing user data: " + e);
                return;
            }
        }
    }

    // Now that the data is ready, create the chart.
    vegalab.chart.init().update();

    // Call the user JavaScript code on the vega object.
    vegalab.js(vegalab.chart);
}

// A callback function for reading a selected file and pasting its contents into
// a textarea element.
function textplop(textarea_id){
    return function(e){
        // Grab the filename from the element.
        var file = d3.event.target.files[0];

        // Instantiate a file reader object, whose callback will simply plop
        // the text into the element.
        var reader = new FileReader();
        reader.onload = function(e){
            // Grab the text.
            var text = e.target.result;

            // Place it into the textarea element.
            d3.select("#" + textarea_id)
                .text(text);
        };
        reader.readAsText(file);
    }
}

window.onload = function(){
    // Load the Vega template text.
    d3.text("/lib/vgd3-template.js.txt", function(text){
        // Save the text.
        vegalab.template = text;

        // Now that the necessary data is loaded, install the actions on the
        // buttons.
        //
        // Install file upload handlers on the textarea buttons.
        d3.select("#vega_file")
            .on("change", textplop("vega"));

        d3.select("#js_file")
            .on("change", textplop("js"));

        d3.select("#data_file")
            .on("change", textplop("data"));

        // Install click handler for compile button, and enable the button.
        d3.select("#compile")
            .on("click", compile)
            .attr("disabled", null);
    });
};
<|endoftext|>


<commit_before>var RitualGame = (function () {
  var levels = [
        {
          numShapes: 10,
          shapeDescriptions: [
            { kind: 'polygon', numSides: 3 },
            { kind: 'polygon', numSides: 4 },
            { kind: 'polygon', numSides: 5 },
            { kind: 'polygon', numSides: 6 },
            { kind: 'polygon', numSides: 7 },
            { kind: 'polygon', numSides: 8 }
            // { kind: 'star', numVertices: 5 },
            // { kind: 'star', numVertices: 7 }
          ]
        }
      ],
      minSpeed = 0.5,
      maxSpeed = 10,
      size = {
        play: {}
      },
      color = {
        background: '#f1f0cf'
      },
      currentLevel,
      pi = Math.PI,
      sin = Math.sin,
      cos = Math.cos,
      containers = {},
      canvases = {},
      contexts = {},
      shapes;

  function makePolygon(description) {
    var i, a,
        numSides = description.numSides,
        shape = {},
        origin = shape.origin = { x: 0, y: 0 },
        exteriorAngle = 2 * pi / numSides,
        angle = shape.angle = 0,
        scale = shape.scale = 1,
        points = shape.points = new Array(numSides);
    a = (pi - exteriorAngle) / 2;
    for (i = 0; i < numSides; ++i) {
      a += exteriorAngle;
      points[i] = { x: cos(a), y: sin(a) };
    }
    shape.paint = function (context) {
      var x0 = origin.x,
          y0 = origin.y,
          i;
      context.save();
      context.translate(x0, y0);
      context.rotate(angle);
      context.scale(shape.scale, shape.scale);
      context.beginPath();
      context.moveTo(points[numSides - 1].x, points[numSides - 1].y);
      for (i = 0; i < numSides; ++i) {
        context.lineTo(points[i].x, points[i].y);
      }
      context.closePath();
      context.fill();
      context.restore();
    };
    return shape;
  }

  function makeStar(description) {
  }

  function makeShape(description) {
    var kind = description.kind,
        angle,
        shape;
    if (kind == 'polygon') {
      shape = makePolygon(description);
    }
    if (kind == 'star') {
      shape = makeStar(description);
    }
    angle = Math.random() * 2 * pi;
    speed = minSpeed + Math.random() * (maxSpeed - minSpeed);
    shape.velocity = { x: cos(angle) * speed, y: sin(angle) * speed };
    return shape;
  }

  function paintFrame() {
    var canvas = canvases.shapes,
        context = contexts.shapes,
        shape,
        i;
    context.clearRect(0, 0, size.play, size.play);
    for (i = 0; i < shapes.length; ++i) {
      shape = shapes[i];
      shape.paint(context);
    }
  }

  function paintBackground() {
    var context = contexts.background;
    context.fillStyle = color.background;
    context.fillRect(0, 0, size.play, size.play);
  }

  function loadLevel() {
    var level = currentLevel,
        numShapes = level.numShapes,
        shapeDescriptions = level.shapeDescriptions,
        shape,
        i;
    shapes = new Array(numShapes);
    for (i = 0; i < numShapes; ++i) {
      shape = shapes[i] = makeShape(shapeDescriptions[
          Math.floor(shapeDescriptions.length * Math.random())]);
      shape.scale = size.play / 10;
      shape.origin.x = shape.origin.y = size.play / 2;
    }
  }

  function updateGame() {
    shapes.forEach(function (shape) {
      shape.origin.x = (shape.origin.x + shape.velocity.x +
          size.play) % size.play;
      shape.origin.y = (shape.origin.y + shape.velocity.y +
          size.play) % size.play;
    });
    paintFrame();
    window.requestAnimationFrame(updateGame);
  }

  function layout() {
    size.play = Math.min(window.innerWidth, window.innerHeight);
    Object.keys(canvases).forEach(function (name) {
      var canvas = canvases[name];
      canvas.width = canvas.height = size.play;
    });
    paintBackground();
  }

  function load() {
    containers.canvas = document.getElementById('gameContainer');
    [ 'background', 'shapes' ].forEach(function (name) {
      var canvas = canvases[name] = document.createElement('canvas');
      containers.canvas.appendChild(canvas);
      contexts[name] = canvas.getContext('2d');
    });
    currentLevel = levels[0];
    window.onresize = layout;
    layout();
    loadLevel();
    updateGame();
  }

  return {
    load: load
  };
})();

window.onload = RitualGame.load;
<commit_msg>Add colors and fix some bugs<commit_after>var RitualGame = (function () {
  var pi = Math.PI,
      levels = [
        {
          numShapes: 10,
          shapeDescriptions: [
            { kind: 'polygon', numSides: { min: 3, max: 8 } }
          ]
        }
      ],
      minSpeed = 0.5,
      maxSpeed = 5,
      minRotate = pi / 600,
      maxRotate = pi / 120,
      size = {
        play: {}
      },
      color = {
        background: '#000',
        shape: {
          fill: [ '#aebf94', '#99bfa6', '#95b5bf', '#969bbf', '#a68dbf',
                  '#bf8a97', '#bf9d8e', '#bfba95' ],
          stroke: '#444'
        }
      },
      currentLevel,
      sin = Math.sin,
      cos = Math.cos,
      containers = {},
      canvases = {},
      contexts = {},
      shapes;

  function makePolygon(description) {
    var i, a,
        minSides = description.numSides.min,
        maxSides = description.numSides.max,
        numSides = minSides +
            Math.floor(Math.random() * (maxSides - minSides)),
        shape = {},
        origin = shape.origin = { x: 0, y: 0 },
        exteriorAngle = 2 * pi / numSides,
        rotate = shape.rotate = 0,
        scale = shape.scale = 0.1,
        fillColor = color.shape.fill[Math.floor(Math.random() *
            color.shape.fill.length)],
        strokeColor = color.shape.stroke,
        points = shape.points = new Array(numSides);
    a = (pi - exteriorAngle) / 2;
    for (i = 0; i < numSides; ++i) {
      a += exteriorAngle;
      points[i] = { x: cos(a), y: sin(a) };
    }
    shape.paint = function (context) {
      var x0 = origin.x,
          y0 = origin.y,
          i;
      context.save();
      context.translate(x0, y0);
      context.rotate(shape.rotate);
      context.scale(shape.scale * size.play, shape.scale * size.play);
      context.beginPath();
      context.moveTo(points[numSides - 1].x, points[numSides - 1].y);
      for (i = 0; i < numSides; ++i) {
        context.lineTo(points[i].x, points[i].y);
      }
      context.closePath();
      context.fillStyle = fillColor;
      context.fill();
      context.lineWidth = 4 / (shape.scale * size.play);
      context.strokeStyle = strokeColor;
      context.stroke();
      context.restore();
    };
    return shape;
  }

  function makeShape(description) {
    var kind = description.kind,
        rotate,
        shape;
    if (kind == 'polygon') {
      shape = makePolygon(description);
    }
    rotate = Math.random() * 2 * pi;
    speed = minSpeed + Math.random() * (maxSpeed - minSpeed);
    shape.move = { x: cos(rotate) * speed, y: sin(rotate) * speed,
      rotate: minRotate + Math.random() * (maxRotate - minRotate)
    };
    if (Math.random() < 0.5) {
      shape.move.rotate *= -1;
    }
    return shape;
  }

  function paintFrame() {
    var canvas = canvases.shapes,
        context = contexts.shapes,
        shape,
        i;
    context.clearRect(0, 0, size.play, size.play);
    for (i = 0; i < shapes.length; ++i) {
      shape = shapes[i];
      shape.paint(context);
    }
  }

  function paintBackground() {
    var context = contexts.background;
    context.fillStyle = color.background;
    context.fillRect(0, 0, size.play, size.play);
  }

  function loadLevel() {
    var level = currentLevel,
        numShapes = level.numShapes,
        shapeDescriptions = level.shapeDescriptions,
        shape,
        i;
    shapes = new Array(numShapes);
    for (i = 0; i < numShapes; ++i) {
      shape = shapes[i] = makeShape(shapeDescriptions[
          Math.floor(shapeDescriptions.length * Math.random())]);
      shape.origin.x = shape.origin.y = size.play / 2;
    }
  }

  function updateGame() {
    shapes.forEach(function (shape) {
      shape.origin.x = (shape.origin.x + shape.move.x +
          size.play) % size.play;
      shape.origin.y = (shape.origin.y + shape.move.y +
          size.play) % size.play;
      shape.rotate = (shape.rotate + shape.move.rotate);
      while (shape.rotate > 2 * pi) {
        shape.rotate -= 2 * pi;
      }
      while (shape.rotate < -2 * pi) {
        shape.rotate += 2 * pi;
      }
    });
    paintFrame();
    window.requestAnimationFrame(updateGame);
  }

  function layout() {
    size.play = Math.min(window.innerWidth, window.innerHeight);
    Object.keys(canvases).forEach(function (name) {
      var canvas = canvases[name];
      canvas.width = canvas.height = size.play;
    });
    paintBackground();
  }

  function load() {
    containers.canvas = document.getElementById('gameContainer');
    [ 'background', 'shapes' ].forEach(function (name) {
      var canvas = canvases[name] = document.createElement('canvas');
      containers.canvas.appendChild(canvas);
      contexts[name] = canvas.getContext('2d');
    });
    currentLevel = levels[0];
    window.onresize = layout;
    layout();
    loadLevel();
    updateGame();
  }

  return {
    load: load
  };
})();

window.onload = RitualGame.load;
<|endoftext|>


<commit_before>import { observe } from 'mobx';
import Asset from 'hippo/models/asset';
import {
    BaseModel, identifiedBy, identifier, belongsTo, field, computed,
} from './base';

@identifiedBy('sm/venue')
export default class Venue extends BaseModel {
    @identifier id;

    @field code = '';
    @field name = '';
    @field address = '';
    @field phone_number;
    @field capacity;
    @field timezone;

    @belongsTo({ model: Asset, inverseOf: 'owner' }) logo;

    constructor(attrs) {
        super(attrs);
        observe(this, 'syncInProgress', ({ newValue, oldValue }) => {
            if (!oldValue && newValue && newValue.isCreate) {
                if (this.constructor.$cachedCollection) {
                    this.constructor.$cachedCollection.push(this);
                }
            }
        });
    }

    @computed static get sharedCollection() {
        this.$cachedCollection = (
            this.$cachedCollection || this.Collection.create([], { fetch: true })
        );
        return this.$cachedCollection;
    }
}
<commit_msg>set default timezone to browser detected default<commit_after>import { observe } from 'mobx';
import Asset from 'hippo/models/asset';
import {
    BaseModel, identifiedBy, identifier, belongsTo, field, computed,
} from './base';
import moment from 'moment-timezone';

@identifiedBy('sm/venue')
export default class Venue extends BaseModel {
    @identifier id;

    @field code = '';
    @field name = '';
    @field address = '';
    @field phone_number;
    @field capacity;
    @field timezone = moment.tz.guess();

    @belongsTo({ model: Asset, inverseOf: 'owner' }) logo;

    constructor(attrs) {
        super(attrs);
        observe(this, 'syncInProgress', ({ newValue, oldValue }) => {
            if (!oldValue && newValue && newValue.isCreate) {
                if (this.constructor.$cachedCollection) {
                    this.constructor.$cachedCollection.push(this);
                }
            }
        });
    }

    @computed static get sharedCollection() {
        this.$cachedCollection = (
            this.$cachedCollection || this.Collection.create([], { fetch: true })
        );
        return this.$cachedCollection;
    }
}
<|endoftext|>