commit
stringlengths
40
40
subject
stringlengths
1
1.49k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
new_contents
stringlengths
1
29.8k
old_contents
stringlengths
0
9.9k
lang
stringclasses
3 values
proba
float64
0
1
b926723724dfdd4563ca31b7abfaa16943a2e507
read api key from environment
server/routes/spotsHW.js
server/routes/spotsHW.js
var express = require('express'); var uuid = require('uuid'); var router = express.Router(); var SPOTS_API_KEY = process.env.SPOTS_API_KEY; console.log("Using SPOTS_API_KEY = %s", SPOTS_API_KEY) router.post('/update/:key/:lotID/:spotID/:vacancy/:cardID?', (req, res, next) => { console.log(req.params); key = req.params.key; if(key != SPOTS_API_KEY) { res.status(401).send({error:"invalid key"}); return; } if(req.params.cardID == '123456789') { res.send({authorized: true}); } else { res.send({authorized: false}); } }); module.exports = router;
var express = require('express'); var uuid = require('uuid'); var router = express.Router(); var SPOTS_API_KEY; if(process.env.BUILD == 'development') { SPOTS_API_KEY = '1234'; } else { SPOTS_API_KEY = uuid(); } console.log("Using SPOTS_API_KEY = %s", SPOTS_API_KEY) router.post('/update/:key/:lotID/:spotID/:vacancy/:cardID?', (req, res, next) => { console.log(req.params); key = req.params.key; if(key != SPOTS_API_KEY) { res.status(401).send({error:"invalid key"}); return; } if(req.params.cardID == '123456789') { res.send({authorized: true}); } else { res.send({authorized: false}); } }); module.exports = router;
JavaScript
0
370e4f4b2d9c7c7449389f3d47c5d985af8ee4b9
add event for left arrow
Animals/js/main.js
Animals/js/main.js
//create a new Game instance //set the game dimensions and set the Phaser.AUTO (OpenGL or Canvas) var game = new Phaser.Game(640, 360, Phaser.AUTO); //create a game state (this contains the logic of the game) var GameState = { //assets are loaded in this function preload: function(){ //load the images from the assets folder this.load.image('backgroundImageKey', 'assets/images/background.png'); this.load.image('chickenImageKey', 'assets/images/chicken.png'); this.load.image('horseImageKey', 'assets/images/horse.png'); this.load.image('pigImageKey', 'assets/images/pig.png'); this.load.image('sheepImageKey', 'assets/images/sheep.png'); this.load.image('arrowImageKey', 'assets/images/arrow.png'); }, //after preloading create function is called create: function(){ //to make the game responsive i.e. make it viewable on different types of devices //SHOW_ALL mode makes the game fit the screen this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; //to align the game in the center this.scale.pageAlignHorizontally = true; this.scale.pageAlignVertically = true; //this will create a sprite for the background this.background = this.game.add.sprite(0,0, 'backgroundImageKey'); //this will create a sprite for the chicken this.chicken = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'chickenImageKey'); //by default the anchor point is top left corner of the image //inorder to change it we do it so with the following code this.chicken.anchor.setTo(0.5, 0.5);//takes two arguments for X and Y, if both X and Y values are same then one argument will do the job //left arrow (previous) this.leftArrow = this.game.add.sprite(this.game.world.centerX - 210, this.game.world.centerY - 50, 'arrowImageKey'); this.leftArrow.anchor.setTo = (0.5, 0.5); this.leftArrow.scale.x = -1;//flip the right arrow to make the left arrow this.leftArrow.customParams = {direction: 1}; this.leftArrow.inputEnabled = true;//enable input this.leftArrow.input.pixelPerfectClick = true;//this will the clickable area to shape of the sprite and not a regular rectangle this.leftArrow.events.onInputDown.add(this.changeAnimal, this);//add event when user clicks //right arrow (next) this.rightArrow = this.game.add.sprite(this.game.world.centerX + 210, this.game.world.centerY - 50, 'arrowImageKey'); this.rightArrow.anchor.setTo = (0.5, 0.5); this.rightArrow.customParams = {direction: 1}; }, //this function is called multiple times to handle the requests when game is live update: function(){ }, //changeAnimal function changeAnimal: function(sprite, event){ console.log(sprite, event); } }; //add state to the main game game.state.add('GameState', GameState); //to launch the game game.state.start('GameState');
//create a new Game instance //set the game dimensions and set the Phaser.AUTO (OpenGL or Canvas) var game = new Phaser.Game(640, 360, Phaser.AUTO); //create a game state (this contains the logic of the game) var GameState = { //assets are loaded in this function preload: function(){ //load the images from the assets folder this.load.image('backgroundImageKey', 'assets/images/background.png'); this.load.image('chickenImageKey', 'assets/images/chicken.png'); this.load.image('horseImageKey', 'assets/images/horse.png'); this.load.image('pigImageKey', 'assets/images/pig.png'); this.load.image('sheepImageKey', 'assets/images/sheep.png'); this.load.image('arrowImageKey', 'assets/images/arrow.png'); }, //after preloading create function is called create: function(){ //to make the game responsive i.e. make it viewable on different types of devices //SHOW_ALL mode makes the game fit the screen this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; //to align the game in the center this.scale.pageAlignHorizontally = true; this.scale.pageAlignVertically = true; //this will create a sprite for the background this.background = this.game.add.sprite(0,0, 'backgroundImageKey'); //this will create a sprite for the chicken this.chicken = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'chickenImageKey'); //by default the anchor point is top left corner of the image //inorder to change it we do it so with the following code this.chicken.anchor.setTo(0.5, 0.5);//takes two arguments for X and Y, if both X and Y values are same then one argument will do the job //left arrow (previous) this.leftArrow = this.game.add.sprite(this.game.world.centerX - 210, this.game.world.centerY - 50, 'arrowImageKey'); this.leftArrow.anchor.setTo = (0.5, 0.5); this.leftArrow.scale.x = -1;//flip the right arrow to make the left arrow this.leftArrow.customParams = {direction: 1}; //right arrow (next) this.rightArrow = this.game.add.sprite(this.game.world.centerX + 210, this.game.world.centerY - 50, 'arrowImageKey'); this.rightArrow.anchor.setTo = (0.5, 0.5); this.rightArrow.customParams = {direction: 1}; }, //this function is called multiple times to handle the requests when game is live update: function(){ } }; //add state to the main game game.state.add('GameState', GameState); //to launch the game game.state.start('GameState');
JavaScript
0.000001
4ef671e04c87c671bc6c9950cd5e5334553c906d
Fix syntax error according to eslint
modules/core/client/app/init.js
modules/core/client/app/init.js
'use strict'; //Start by defining the main module and adding the module dependencies angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies); // Setting HTML5 Location Mode angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', '$httpProvider', function ($locationProvider, $httpProvider) { $locationProvider.html5Mode(true).hashPrefix('!'); $httpProvider.interceptors.push('authInterceptor'); } ]); angular.module(ApplicationConfiguration.applicationModuleName).run(function ($rootScope, $state, Authentication) { // Check authentication before changing state $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { if (toState.data && toState.data.roles && toState.data.roles.length > 0) { var allowed = false; toState.data.roles.forEach(function (role) { if (Authentication.user.roles !== undefined && Authentication.user.roles.indexOf(role) !== -1) { allowed = true; return true; } }); if (!allowed) { event.preventDefault(); if (Authentication.user !== undefined && typeof Authentication.user === 'object') { $state.go('forbidden'); } else { $state.go('authentication.signin').then(function () { storePreviousState(toState, toParams); }); } } } }); // Record previous state $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) { if((fromState.name !== 'authentication.signin' || toState.name !== 'authentication.signup') && (fromState.name !== 'authentication.signup' || toState.name !== 'authentication.signin')) { // The user may switch between sign-in and sign-up before been successfully authenticated // Then we want to redirect him to the page he tried to access, not sign-in or sign-up again storePreviousState(fromState, fromParams); } }); // Store previous state function storePreviousState(state, params) { // only store this state if it shouldn't be ignored if (!state.data || !state.data.ignoreState) { $state.previous = { state: state, params: params, href: $state.href(state, params) }; } } }); //Then define the init function for starting up the application angular.element(document).ready(function () { //Fixing facebook bug with redirect if (window.location.hash && window.location.hash === '#_=_') { if (window.history && history.pushState) { window.history.pushState('', document.title, window.location.pathname); } else { // Prevent scrolling by storing the page's current scroll offset var scroll = { top: document.body.scrollTop, left: document.body.scrollLeft }; window.location.hash = ''; // Restore the scroll offset, should be flicker free document.body.scrollTop = scroll.top; document.body.scrollLeft = scroll.left; } } //Then init the app angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]); });
'use strict'; //Start by defining the main module and adding the module dependencies angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies); // Setting HTML5 Location Mode angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', '$httpProvider', function ($locationProvider, $httpProvider) { $locationProvider.html5Mode(true).hashPrefix('!'); $httpProvider.interceptors.push('authInterceptor'); } ]); angular.module(ApplicationConfiguration.applicationModuleName).run(function ($rootScope, $state, Authentication) { // Check authentication before changing state $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { if (toState.data && toState.data.roles && toState.data.roles.length > 0) { var allowed = false; toState.data.roles.forEach(function (role) { if (Authentication.user.roles !== undefined && Authentication.user.roles.indexOf(role) !== -1) { allowed = true; return true; } }); if (!allowed) { event.preventDefault(); if (Authentication.user !== undefined && typeof Authentication.user === 'object') { $state.go('forbidden'); } else { $state.go('authentication.signin').then(function () { storePreviousState(toState, toParams); }); } } } }); // Record previous state $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) { if( (fromState.name !== 'authentication.signin' || toState.name !== 'authentication.signup') && (fromState.name !== 'authentication.signup' || toState.name !== 'authentication.signin') ) { // The user may switch between sign-in and sign-up before been successfully authenticated // Then we want to redirect him to the page he tried to access, not sign-in or sign-up again storePreviousState(fromState, fromParams); } }); // Store previous state function storePreviousState(state, params) { // only store this state if it shouldn't be ignored if (!state.data || !state.data.ignoreState) { $state.previous = { state: state, params: params, href: $state.href(state, params) }; } } }); //Then define the init function for starting up the application angular.element(document).ready(function () { //Fixing facebook bug with redirect if (window.location.hash && window.location.hash === '#_=_') { if (window.history && history.pushState) { window.history.pushState('', document.title, window.location.pathname); } else { // Prevent scrolling by storing the page's current scroll offset var scroll = { top: document.body.scrollTop, left: document.body.scrollLeft }; window.location.hash = ''; // Restore the scroll offset, should be flicker free document.body.scrollTop = scroll.top; document.body.scrollLeft = scroll.left; } } //Then init the app angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]); });
JavaScript
0.000675
31e4bddbca6b5e50a4958a956a48bdbf61045086
Fix lint errors
lib/index.js
lib/index.js
// TODO: ES2015 maybe, baby? var rollup = require('rollup'); var babel = require('rollup-plugin-babel'); var camelCase = require('camel-case'); var formats = ['es6', 'cjs', 'umd']; module.exports = function rollupLib(options) { var rollupOptions = Object.assign({}, options); var baseConfig = {}; var builds = []; rollupOptions.name = rollupOptions.name || 'mylibrary'; // TODO: If we go about using Object.assign instead of modifying `options`, // we should have some way of taking `name` from `moduleName` without it // being too hack-y rollupOptions.moduleName = rollupOptions.moduleName || camelCase(options.name); rollupOptions.dest = rollupOptions.dest || 'dist'; rollupOptions.entry = rollupOptions.entry || 'index.js'; rollupOptions.format = rollupOptions.format || ['es6', 'cjs', 'umd']; rollupOptions.plugins = rollupOptions.plugins || [babel()]; baseConfig = { entry: rollupOptions.entry, plugins: rollupOptions.plugins, }; builds = formats.map(function buildFormat(format) { var config = Object.assign({}, baseConfig); config.format = format; config.dest = options.dest + '/' + name; if (format === 'es6') { config.dest += '.es2015'; } if (format === 'umd') { config.dest += '.umd'; config.moduleName = options.moduleName; } config.dest += '.js'; return rollup.rollup(config).then(function rollupBundle(bundle) { bundle.write(config); }); }); return Promise.all(builds).then(function buildThen() { console.log('All done!'); }).catch(function buildCatch(err) { console.log('Error while generating a build:'); console.log(err); }); };
// TODO: ES2015 maybe, baby? var rollup = require('rollup'); var babel = require('rollup-plugin-babel'); var camelCase = require('camel-case'); var pkg = require('./package.json'); var name = pkg.name; var moduleName = 'ReactLibStarterkit'; var formats = ['es6', 'cjs', 'umd']; module.exports = function(options) { // TODO: Hmm, a voice in my head says we shouldn't modify arguments options = options || {}; options.name = options.name || 'mylibrary'; // TODO: If we go about using Object.assign instead of modifying `options`, // we should have some way of taking `name` from `moduleName` without it // being too hack-y options.moduleName = options.moduleName || camelCase(options.name); options.dest = options.dest || 'dist'; options.entry = options.entry || 'index.js'; options.format = options.format || ['es6', 'cjs', 'umd']; options.plugins = options.plugins || [babel()]; var baseConfig = { entry: options.entry, plugins: options.plugins, }; var builds = formats.map(function(format) { var config = Object.assign({}, baseConfig); config.format = format; config.dest = options.dest + '/' + name; if (format === 'es6') { config.dest += '.es2015'; } if (format === 'umd') { config.dest += '.umd'; config.moduleName = options.moduleName; } config.dest += '.js'; return rollup.rollup(config).then(function(bundle) { bundle.write(config); }); }); return Promise.all(builds).then(function() { console.log('All done!'); }).catch(function(err) { console.log('Error while generating a build:'); console.log(err); }); };
JavaScript
0
6fb41f60c91166c9f72e3f32ac78dafa617bf5a8
allow remote connections for socket
server/static/js/main.js
server/static/js/main.js
$(document).ready(function(){ var ws = new WebSocket('ws://' + window.location.hostname + ':9010'); ws.onopen = function(){ enableKeys(); $('#socket-status').removeClass('label-default label-success label-danger') .addClass('label-success') .text('online'); }; ws.onerror = function(){ clearScreen(); disableKeys(); $('#socket-status').removeClass('label-default label-success label-danger') .addClass('label-danger') .text('error'); }; ws.onclose = function(){ clearScreen(); disableKeys(); $('#socket-status').removeClass('label-default label-success label-danger') .addClass('label-default') .text('offline'); }; ws.addEventListener("message", function(event) { var data = JSON.parse(event.data); updateScreen(data.pixel); }); var updateScreen = function(pixel){ for (var x=0; x<pixel.length; x++){ // rows for (var y=0; y<pixel[x].length; y++){ // col var id = '#pixel-'+y+'-'+x, p = pixel[x][y]; $(id).css('background-color', rgbToHex(p[0], p[1], p[2])); } } }; var clearScreen = function(){ $('.pixel').css('background-color', '#000000'); }; var disableKeys = function(){ $('.send-key').attr('disabled', true); }; var enableKeys = function(){ $('.send-key').removeAttr('disabled'); }; $('body').on('click', '.send-key', function(e){ var $this = $(this), key = $this.data('key'), json = JSON.stringify({'key': key}); e.preventDefault(); ws.send(json); }); function componentToHex(c) { var hex = c.toString(16); return hex.length === 1 ? "0" + hex : hex; } function rgbToHex(r, g, b) { return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); } $('body').on('click', '.fullscreen', toggleFullscreen); function toggleFullscreen() { if ((document.fullScreenElement && document.fullScreenElement !== null) || (!document.mozFullScreen && !document.webkitIsFullScreen)) { if (document.documentElement.requestFullScreen) { document.documentElement.requestFullScreen(); } else if (document.documentElement.mozRequestFullScreen) { document.documentElement.mozRequestFullScreen(); } else if (document.documentElement.webkitRequestFullScreen) { document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } } else { if (document.cancelFullScreen) { document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } } } });
$(document).ready(function(){ var ws = new WebSocket('ws://127.0.0.1:9010'); ws.onopen = function(){ enableKeys(); $('#socket-status').removeClass('label-default label-success label-danger') .addClass('label-success') .text('online'); }; ws.onerror = function(){ clearScreen(); disableKeys(); $('#socket-status').removeClass('label-default label-success label-danger') .addClass('label-danger') .text('error'); }; ws.onclose = function(){ clearScreen(); disableKeys(); $('#socket-status').removeClass('label-default label-success label-danger') .addClass('label-default') .text('offline'); }; ws.addEventListener("message", function(event) { var data = JSON.parse(event.data); updateScreen(data.pixel); }); var updateScreen = function(pixel){ for (var x=0; x<pixel.length; x++){ // rows for (var y=0; y<pixel[x].length; y++){ // col var id = '#pixel-'+y+'-'+x, p = pixel[x][y]; $(id).css('background-color', rgbToHex(p[0], p[1], p[2])); } } }; var clearScreen = function(){ $('.pixel').css('background-color', '#000000'); }; var disableKeys = function(){ $('.send-key').attr('disabled', true); }; var enableKeys = function(){ $('.send-key').removeAttr('disabled'); }; $('body').on('click', '.send-key', function(e){ var $this = $(this), key = $this.data('key'), json = JSON.stringify({'key': key}); e.preventDefault(); ws.send(json); }); function componentToHex(c) { var hex = c.toString(16); return hex.length === 1 ? "0" + hex : hex; } function rgbToHex(r, g, b) { return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); } $('body').on('click', '.fullscreen', toggleFullscreen); function toggleFullscreen() { if ((document.fullScreenElement && document.fullScreenElement !== null) || (!document.mozFullScreen && !document.webkitIsFullScreen)) { if (document.documentElement.requestFullScreen) { document.documentElement.requestFullScreen(); } else if (document.documentElement.mozRequestFullScreen) { document.documentElement.mozRequestFullScreen(); } else if (document.documentElement.webkitRequestFullScreen) { document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } } else { if (document.cancelFullScreen) { document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } } } });
JavaScript
0
035b23de64769966fc68e28f752311b40f0f11a0
Flairs should be lowercase
modules/flair/DestinyTheGame.js
modules/flair/DestinyTheGame.js
const base = require( './base.js' ); module.exports = Object.assign( {}, base, { isDev: function isDev ( user ) { if ( !user[ this.type ] ) { return false; } for ( const flairString of this.list ) { if ( user[ this.type ].includes( flairString ) ) { return true; } } return false; }, list: [ 'verified-bungie-employee', ], type: 'author_flair_css_class', } );
const base = require( './base.js' ); module.exports = Object.assign( {}, base, { isDev: function isDev ( user ) { if ( !user[ this.type ] ) { return false; } for ( const flairString of this.list ) { if ( user[ this.type ].includes( flairString ) ) { return true; } } return false; }, list: [ 'Verified-Bungie-Employee', ], type: 'author_flair_css_class', } );
JavaScript
0.999999
94abbde4e9a58168089cb802c84f621420e5a2fa
Fix emit name
lib/index.js
lib/index.js
'use strict'; var rump = module.exports = require('rump'); var configs = require('./configs'); var originalAddGulpTasks = rump.addGulpTasks; // TODO remove on next major core update rump.addGulpTasks = function(options) { originalAddGulpTasks(options); require('./gulp'); return rump; }; rump.on('update:main', function() { configs.rebuild(); rump.emit('update:server'); }); rump.on('gulp:main', function(options) { require('./gulp'); rump.emit('gulp:server', options); }); Object.defineProperty(rump.configs, 'browserSync', { get: function() { return configs.browserSync; } });
'use strict'; var rump = module.exports = require('rump'); var configs = require('./configs'); var originalAddGulpTasks = rump.addGulpTasks; // TODO remove on next major core update rump.addGulpTasks = function(options) { originalAddGulpTasks(options); require('./gulp'); return rump; }; rump.on('update:main', function() { configs.rebuild(); rump.emit('update:server:dev'); }); rump.on('gulp:main', function(options) { require('./gulp'); rump.emit('gulp:server:dev', options); }); Object.defineProperty(rump.configs, 'browserSync', { get: function() { return configs.browserSync; } });
JavaScript
0.000007
69c04f13abf149f929c9c248e123cadb3e5b35c2
Update elite flairs
modules/flair/EliteDangerous.js
modules/flair/EliteDangerous.js
module.exports = { getFlairs: function getFlairs () { return this.list; }, list: [ 'bot img', 'cmdr img aduval', 'cmdr img alduval', 'cmdr img alliance', 'cmdr img antal', 'cmdr img cobra', 'cmdr img combat', 'cmdr img coredyn', 'cmdr img delaine', 'cmdr img empire', 'cmdr img explore', 'cmdr img fdelacy', 'cmdr img federation', 'cmdr img galnet', 'cmdr img grom', 'cmdr img hudson', 'cmdr img mahon', 'cmdr img patreus', 'cmdr img rescue', 'cmdr img sidey', 'cmdr img skull', 'cmdr img snoo', 'cmdr img thargint', 'cmdr img thargsen', 'cmdr img trade', 'cmdr img viper', 'cmdr img winters', 'cmdr img yongrui', 'cmdr img zorgpet', 'cmdr star', 'cmdr', 'competent cmdr', 'dangerous cmdr', 'empire cmdr img', 'empire', 'harmless cmdr', 'img sidey cmdr', 'img viper cmdr', 'mostlyharmless cmdr', 'novice cmdr', 'star', ], type: 'author_flair_css_class', };
module.exports = { getFlairs: function getFlairs () { return this.list; }, list: [ 'bot img', 'cmdr img alliance', 'cmdr img cobra', 'cmdr img empire', 'cmdr img federation', 'cmdr img sidey', 'cmdr img skull', 'cmdr img viper', 'cmdr star', 'cmdr', 'competent cmdr', 'dangerous cmdr', 'empire cmdr img', 'empire', 'harmless cmdr', 'img sidey cmdr', 'img viper cmdr', 'mostlyharmless cmdr', 'novice cmdr', 'star', ], type: 'author_flair_css_class', };
JavaScript
0
941049a2cabb292f189a4496589eac834a5cf68f
Improve documentation
panopticon.js
panopticon.js
/* Example schema: var personSchema = mongoose.Schema({ name: String, email: String, pets: [{ name: String }] }); var pn = require('panopticon'); var rules = { 'name': function(newValue) { this // the document at the point of post-save }, 'email': { 'surname': function() { create new audit item when person changes their email.surname; } }, 'pets': { 'name': function() {} } }; pn.watch(personSchema, rules); */ var jsondiffpatch = require('jsondiffpatch'), _ = require('underscore'); /* * watch() * <schema> - a Mongoose schema * <rules> - an object containing watch rules * */ exports.watch = function(schema, rules) { // SET UP ORIGINAL OBJECT schema.pre('init', function (next, doc) { // stringify prunes methods from the document doc._original = JSON.parse(JSON.stringify(doc)); next(); }); // SET UP POST SAVE WITH DIFFING /* Example diff: diff: { pets: { name: ['berty', 'fred'] }, email: [oldEmail, newEmail].surname } */ schema.post('save', function () { var doc = this; var original = doc.get('_original'); if (original) { var updated = JSON.parse(JSON.stringify(doc)); var differ = jsondiffpatch.create({ // this is so the differ can tell what has changed for arrays of objects objectHash: function(obj) { return obj.name || obj.id || obj._id || obj._id || JSON.stringify(obj); } }); var diff = differ.diff(original, updated); // FIRE RULES BEHAVIOURS // iterate over keys of rules // if value is function, call with document (as this) and newValue // if value is object, iterate over value /* * getNewValue() * * Returns the new value of a document property * * @param {Array} diffItem representing change to property (see jsondiffpatch) */ function getNewValue(diffItem){ if (!_.isArray(diffItem)) { throw new TypeError('diffItem must be an array'); } if (diffItem.length === 3) { return null; } return _.last(diffItem); } /* * applyRules() * * Calls rules functions * * @param {Object} rules the functions to call when paths in diff * @param {Object} diff the diff between the old and new document * * @throws TypeError if diff is array (rule does not reflect model structure) * @throws TypeError if rules contains an array (invalid) */ function applyRules(rules, diff) { if (_.isArray(diff)) { throw new TypeError('diff cannot be an array') } _(rules).each(function(rule, key){ if(_.isArray(rule)) { throw new TypeError('panopticon rule cannot be an array'); } var diffItem = diff[key]; if (diffItem) { if (typeof rule === 'function') { newValue = getNewValue(diffItem); rule.call(doc, newValue); } else if (_.isObject(rule)) { applyRules(rule, diffItem); } } }); } applyRules(rules, diff); } }); };
/* Example schema: var personSchema = mongoose.Schema({ name: String, email: String, pets: [{ name: String }] }); var pn = require('panopticon'); var rules = { 'name': function(newValue) { this // the document at the point of post-save }, 'email': { 'surname': function() { create new audit item when person changes their email.surname; } }, 'pets': { 'name': function() {} } }; pn.watch(personSchema, rules); */ var jsondiffpatch = require('jsondiffpatch'), _ = require('underscore'); /* * watch() * <schema> - a Mongoose schema * <rules> - an object containing watch rules * */ exports.watch = function(schema, rules) { // SET UP ORIGINAL OBJECT schema.pre('init', function (next, doc) { // stringify prunes methods from the document doc._original = JSON.parse(JSON.stringify(doc)); next(); }); // SET UP POST SAVE WITH DIFFING /* Example diff: diff: { pets: { name: ['berty', 'fred'] }, email: [oldEmail, newEmail].surname } */ schema.post('save', function () { var doc = this; var original = doc.get('_original'); if (original) { var updated = JSON.parse(JSON.stringify(doc)); var differ = jsondiffpatch.create({ // this is so the differ can tell what has changed for arrays of objects objectHash: function(obj) { return obj.name || obj.id || obj._id || obj._id || JSON.stringify(obj); } }); var diff = differ.diff(original, updated); // FIRE RULES BEHAVIOURS // iterate over keys of rules // if value is function, call with document (as this) and newValue // if value is object, iterate over value /* * getNewValue() * <diffItem> - array representing diff of item. * - Length 1 is addition [new] * - Length 2 is update [old, new] * - Length 3 is deletion [old, 0, 0] */ function getNewValue(diffItem){ if (!_.isArray(diffItem)) { throw new TypeError('diffItem must be an array'); } if (diffItem.length === 3) { return null; } return _.last(diffItem); } /* * applyRules() * <rules> * <diff> * * <throws> TypeError if <diff> is array (rule does not reflect model structure) * <throws> TypeError if <rules> contains an array (invalid) */ function applyRules(rules, diff) { if (_.isArray(diff)) { throw new TypeError('diff cannot be an array') } _(rules).each(function(rule, key){ if(_.isArray(rule)) { throw new TypeError('panopticon rule cannot be an array'); } var diffItem = diff[key]; if (diffItem) { if (typeof rule === 'function') { newValue = getNewValue(diffItem); rule.call(doc, newValue); } else if (_.isObject(rule)) { applyRules(rule, diffItem); } } }); } applyRules(rules, diff); } }); };
JavaScript
0.000004
12643745c29f46b214074383b2bd8c3a22b9b8ae
fix bug in usaa scrape/example
service/examples/usaa.js
service/examples/usaa.js
var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: false, frame: false }); var path = require('path'); var getPrivateInfo = require('./getPrivateInfo').usaa; nightmare .goto('https://mobile.usaa.com/inet/ent_logon/Logon?acf=1') .click('#logOnButton a') .type('input#input_onlineid', getPrivateInfo().username()) .type('input#input_password', getPrivateInfo().password()) .click('input[type="submit"]') .wait('input#pinTextField') .type('input#pinTextField', getPrivateInfo().pin()) .click('button[type="submit"]') .wait('label[for="securityQuestionTextField"]') .evaluate(() => document.querySelector('label[for="securityQuestionTextField"]').innerHTML) .then(result => { return nightmare .type('#securityQuestionTextField', getPrivateInfo().answer(result.toLowerCase())) .click('button[type="submit"]') .wait('#menu') .click('#menu li:first-child a') .wait('.acct-group-list') //TODO: get info from here then move on to the next step (for each account) .screenshot(path.join(__dirname, 'usaa.png')) .end() }) .then(function (result) { console.log(result) }) .catch(function (error) { console.error('Error:', error); }); // nightmare // .goto('https://mobile.usaa.com/inet/ent_logon/Logon?acf=1') // .click('input#input_onlineid') // .click('div#main-ctr > div.section-ctr:nth-child(4)') // .click('input#input_password') // .click('div#main-ctr > div.section-ctr:nth-child(4)') // .click('div#main-ctr > div.section-ctr:nth-child(4) > div.button-ctr:nth-child(1) > div.yui3-g.padded:nth-child(1) > div.yui3-u-1:nth-child(1) > input.main-button:nth-child(1)') // .click('input#pinTextField') // .click('button#id4') // .click('input#securityQuestionTextField') // .click('div#flowWrapper') // .click('button#id6') // .click('div#id3 > ul.acct-group-list:nth-child(1) > li.acct-group-row:nth-child(1) > a.usaa-link.acct-info.clearfix:nth-child(1) > span.link-liner:nth-child(1) > span.acct-name:nth-child(1)') // .end() // .then(function (result) { // console.log(result) // }) // .catch(function (error) { // console.error('Error:', error); // });
var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: false, frame: false }); var path = require('path'); var getPrivateInfo = require('./getPrivateInfo').usaa; nightmare .goto('https://mobile.usaa.com/inet/ent_logon/Logon?acf=1') .click('#logOnButton a') .type('input#input_onlineid', getPrivateInfo().username()) .type('input#input_password', getPrivateInfo().password()) .click('input[type="submit"]') .wait('input#pinTextField') .type('input#pinTextField', getPrivateInfo().pin()) .click('button[type="submit"]') .wait('label[for="securityQuestionTextField"]') .evaluate(() => document.querySelector('label[for="securityQuestionTextField"]').innerHTML) .then(result => { return nightmare .type('#securityQuestionTextField', getPrivateInfo().answer(result)) .click('button[type="submit"]') .wait('#menu') .click('#menu li:first-child a') .wait('.acct-group-list') //TODO: get info from here then move on to the next step (for each account) .screenshot(path.join(__dirname, 'usaa.png')) .end() }) .then(function (result) { console.log(result) }) .catch(function (error) { console.error('Error:', error); }); // nightmare // .goto('https://mobile.usaa.com/inet/ent_logon/Logon?acf=1') // .click('input#input_onlineid') // .click('div#main-ctr > div.section-ctr:nth-child(4)') // .click('input#input_password') // .click('div#main-ctr > div.section-ctr:nth-child(4)') // .click('div#main-ctr > div.section-ctr:nth-child(4) > div.button-ctr:nth-child(1) > div.yui3-g.padded:nth-child(1) > div.yui3-u-1:nth-child(1) > input.main-button:nth-child(1)') // .click('input#pinTextField') // .click('button#id4') // .click('input#securityQuestionTextField') // .click('div#flowWrapper') // .click('button#id6') // .click('div#id3 > ul.acct-group-list:nth-child(1) > li.acct-group-row:nth-child(1) > a.usaa-link.acct-info.clearfix:nth-child(1) > span.link-liner:nth-child(1) > span.acct-name:nth-child(1)') // .end() // .then(function (result) { // console.log(result) // }) // .catch(function (error) { // console.error('Error:', error); // });
JavaScript
0
183654150e87967e8d94a93fb39157061b5a970d
remove alert
PlatformProject.AdminConsole/app/Controllers/TenantController.js
PlatformProject.AdminConsole/app/Controllers/TenantController.js
angular.module('admin').controller('tenantController', ['$scope', '$window', 'TenantService', 'SharedServices', function ($scope, $window, TenantService, SharedServices) { $scope.isFormMode = false; $scope.isEdit = false; loadRecords(); //Function to load all Tenant records function loadRecords() { var promiseGet = TenantService.getTenants(); //The Method Call from service promiseGet.then(function (pl) { $scope.Tenants = pl.data; SharedServices.locateToWindow("http://localhost:40838/index.html#/TenantManagement"); }, function (errorPl) { $log.error('failure loading Tenants', errorPl); }); }; $scope.save = function () { var tenant = { tId: $scope.tId, Name: $scope.tName, tString: $scope.tString, tLogo: $scope.tLogo, tEnable: $scope.tEnable }; if ($scope.isNew) { var promisePost = TenantService.createTenant(tenant); //promisePost.then(function (pl) { // $scope.Id = pl.data.Id; $scope.Message = "Created Successfuly"; // console.log($scope.Message); $scope.clear(); loadRecords(); // }, function (err) { // console.log("Err" + err); // }); } else { //Else Edit the record var promisePut = TenantService.updateTenant($scope.tId, tenant); promisePut.then(function (pl) { $scope.Message = "Updated Successfuly"; $scope.clear(); loadRecords(); }, function (err) { console.log("Err" + err); }); } }; //Method to Delete $scope.delete = function (tId) { var promiseDelete = TenantService.removeTenant(tId); promiseDelete.then(function (pl) { $scope.Message = "Deleted Successfuly"; $scope.tId = 0; $scope.tName = ""; $scope.tString = ""; $scope.tLogo = ""; $scope.tEnable = ""; loadRecords(); }, function (err) { console.log("Err" + err); }); } //Method to Get Single tenant based on Id $scope.get = function (tId) { var promiseGetSingle = TenantService.getTenantData(tId); promiseGetSingle.then(function (pl) { var res = pl.data; $scope.tId = res.id; $scope.tName = res.name; $scope.tString = res.tenantString; $scope.tLogo = res.logoUrl; $scope.tEnable = res.enable; $scope.isNew = false; }, function (errorPl) { console.log('failure loading Tenant', errorPl); }); }; $scope.clear = function () { $scope.tId = ""; $scope.tName = ""; $scope.tString = ""; $scope.tLogo = ""; $scope.tEnable = ""; }; $scope.edit = function (Id) { $scope.isNew = false; $scope.isFormMode = true; $scope.isEdit = true; $scope.Message = ""; $scope.get(Id); }; $scope.createNew = function () { $scope.clear(); $scope.isFormMode = true; $scope.isNew = true; $scope.Message = ""; } $scope.cancel = function () { $scope.clear(); $scope.isFormMode = false; $scope.isEdit = false; $scope.isNew = false; }; }]);
angular.module('admin').controller('tenantController', ['$scope', '$window', 'TenantService', 'SharedServices', function ($scope, $window, TenantService, SharedServices) { $scope.isFormMode = false; $scope.isEdit = false; loadRecords(); //Function to load all Tenant records function loadRecords() { var promiseGet = TenantService.getTenants(); //The Method Call from service promiseGet.then(function (pl) { $scope.Tenants = pl.data; alert(pl.data); SharedServices.locateToWindow("http://localhost:40838/index.html#/TenantManagement"); }, function (errorPl) { $log.error('failure loading Tenants', errorPl); }); }; $scope.save = function () { var tenant = { tId: $scope.tId, Name: $scope.tName, tString: $scope.tString, tLogo: $scope.tLogo, tEnable: $scope.tEnable }; if ($scope.isNew) { var promisePost = TenantService.createTenant(tenant); //promisePost.then(function (pl) { // $scope.Id = pl.data.Id; $scope.Message = "Created Successfuly"; // console.log($scope.Message); $scope.clear(); loadRecords(); // }, function (err) { // console.log("Err" + err); // }); } else { //Else Edit the record var promisePut = TenantService.updateTenant($scope.tId, tenant); promisePut.then(function (pl) { $scope.Message = "Updated Successfuly"; $scope.clear(); loadRecords(); }, function (err) { console.log("Err" + err); }); } }; //Method to Delete $scope.delete = function (tId) { var promiseDelete = TenantService.removeTenant(tId); promiseDelete.then(function (pl) { $scope.Message = "Deleted Successfuly"; $scope.tId = 0; $scope.tName = ""; $scope.tString = ""; $scope.tLogo = ""; $scope.tEnable = ""; loadRecords(); }, function (err) { console.log("Err" + err); }); } //Method to Get Single tenant based on Id $scope.get = function (tId) { var promiseGetSingle = TenantService.getTenantData(tId); promiseGetSingle.then(function (pl) { var res = pl.data; $scope.tId = res.id; $scope.tName = res.name; $scope.tString = res.tenantString; $scope.tLogo = res.logoUrl; $scope.tEnable = res.enable; $scope.isNew = false; }, function (errorPl) { console.log('failure loading Tenant', errorPl); }); }; $scope.clear = function () { $scope.tId = ""; $scope.tName = ""; $scope.tString = ""; $scope.tLogo = ""; $scope.tEnable = ""; }; $scope.edit = function (Id) { $scope.isNew = false; $scope.isFormMode = true; $scope.isEdit = true; $scope.Message = ""; $scope.get(Id); }; $scope.createNew = function () { $scope.clear(); $scope.isFormMode = true; $scope.isNew = true; $scope.Message = ""; } $scope.cancel = function () { $scope.clear(); $scope.isFormMode = false; $scope.isEdit = false; $scope.isNew = false; }; }]);
JavaScript
0.000001