commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
3bcd8129a40887f3976a3336cba44d5e4d9d84c6
move connectionClosed handler to a separate function
lib/ws-server.js
lib/ws-server.js
var WebSocketServer = require('ws').Server, EventEmitter = require('events').EventEmitter, util = require('./util'), crypt = require('./crypt'), config = util.getConfig(), isAuthorized = false, _ws = null, events = null, wss = null, port = null; function WSServer(params) { port = params.port; setupServer(); setupEventEmitter(); return { on: events.on.bind(events) }; } function setupEventEmitter() { events = new EventEmitter(); } function setupServer() { wss = new WebSocketServer({ port: port }); wss.on('connection', handleConnect); console.log('[' + config.hostname + '] Server is up and waiting for changes'); } function handleConnect(ws) { _ws = ws; ws.on('message', handleMessage); ws.on('close', function() { events.emit('connection-closed'); }); } function send(obj) { _ws.send(crypt.stringifyAndEncrypt(obj)); } function handshake(message) { if (message.token === config.secret) { isAuthorized = true; send({ subject: 'handshake', isAllowed: isAuthorized }); } else { _ws.close(); } } function handleFileChange(message) { events.emit('file-change', message); } function handleMessage(message) { var parsedMessage = crypt.decryptAndParse(message); if (parsedMessage.subject === 'handshake') { return handshake(parsedMessage); } if (isAuthorized && parsedMessage.subject === 'file') { return handleFileChange(parsedMessage); } // If we've received a message that isn't recognized, bail console.log('Server is closing'); process.exit(); } module.exports = WSServer;
JavaScript
0.000001
@@ -812,42 +812,8 @@ e', -function() %7B%0A events.emit(' conn @@ -822,24 +822,14 @@ tion --c +C losed -');%0A %7D );%0A%7D @@ -1652,16 +1652,87 @@ t();%0A%7D%0A%0A +function connectionClosed() %7B%0A events.emit('connection-closed');%0A%7D%0A%0A module.e
1cde6271d8b7a3c38dfb6e75f0229b670921238a
Add retry mechanism for iOS screenshots
src/targets/native/ios-simulator.js
src/targets/native/ios-simulator.js
const createWebsocketTarget = require('./create-websocket-target'); const osnap = require('osnap/src/ios'); const saveScreenshotToFile = filename => osnap.saveToFile({ filename }); const createIOSSimulatorTarget = socketUri => createWebsocketTarget(socketUri, 'ios', saveScreenshotToFile); module.exports = createIOSSimulatorTarget;
JavaScript
0
@@ -3,59 +3,154 @@ nst -createWebsocketTarget = require('./ +fs = require('fs-extra');%0Aconst osnap = require('osnap/src/ios');%0Aconst %7B withRetries %7D = require('../../failure-handling');%0Aconst create --w +W ebsocket -tar @@ -149,55 +149,51 @@ cket --t +T arget -');%0Aconst osnap = require('osnap/src/ios + = require('./create-websocket-target ');%0A @@ -221,16 +221,37 @@ ToFile = + withRetries(3)(async filenam @@ -254,16 +254,26 @@ ename =%3E + %7B%0A await osnap.s @@ -296,16 +296,131 @@ name %7D); +%0A const %7B size %7D = await fs.stat(filename);%0A if (size === 0) %7B%0A throw new Error('Screenshot failed ');%0A %7D%0A%7D); %0A%0Aconst
f6c17d0546e77d5b2e6a5eeb00ba78a8d3091016
Make sure denns works on wednesdays
crawlers/denns.js
crawlers/denns.js
const pdf2text = require('../lib/pdf-parser.js'); const download = require('download-file'); const DateFns = require('date-fns'); function downloadFile(url, options) { return new Promise((resolve, reject) => { download(url, options, function (err) { if (err) reject(err); resolve(); }) }) } module.exports.getMenu = async function getMenu(date = new Date()) { const url = 'http://www.denns-biomarkt.at/file/23308_Mittagsmen%C3%BC%20Wien%20Singerstr.pdf'; const options = { directory: "./tmp/", filename: "denns.pdf" }; const todayString = getDayFormatted(date); const tomorrowString = getDayFormatted(DateFns.addDays(date, 1)); try { await downloadFile(url, options); let text = await pdf2text.pdf2txt(options.directory + options.filename); return camelCaseToWords(text.substring(text.indexOf(todayString), text.lastIndexOf(tomorrowString))).concat('\n',url); } catch (err) { throw err; } }; function camelCaseToWords(str){ return str.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1").replace(/- /g, "-").replace(/ /g, ' '); } function getDayFormatted(date) { if (DateFns.isMonday(date)) return "Mo"; if (DateFns.isTuesday(date)) return "Di"; if (DateFns.isWednesday(date)) return "Mi"; if (DateFns.isThursday(date)) return "Do"; if (DateFns.isFriday(date)) return "Fr"; if (DateFns.isSaturday(date)) return "Sa"; if (DateFns.isSunday(date)) return "GutenAppetitwünschtIhnenIhrdenn"; }
JavaScript
0
@@ -801,22 +801,22 @@ );%0A%0A -return +text = camelCa @@ -825,16 +825,34 @@ ToWords( +text);%0A text = text.sub @@ -863,17 +863,21 @@ ng(text. -i +lastI ndexOf(t @@ -922,17 +922,34 @@ String)) -) +;%0A%0A return text .concat( @@ -1225,16 +1225,17 @@ turn %22Mo + %22;%0A if @@ -1270,16 +1270,17 @@ turn %22Di + %22;%0A if @@ -1317,16 +1317,17 @@ turn %22Mi + %22;%0A if @@ -1363,16 +1363,17 @@ turn %22Do + %22;%0A if @@ -1407,16 +1407,17 @@ turn %22Fr + %22;%0A if @@ -1453,16 +1453,17 @@ turn %22Sa + %22;%0A if
0496bf6677a117179cce73c2a81107710bb84289
Fix widget selector
core/core.js
core/core.js
define(['core/widget/widget'], function(widget) { var widgets = document.querySelectorAll('.widget'); widgets.forEach(function(w) { widget.add({element: w, type: 'button'}); }); require(['widget/button/button']); });
JavaScript
0.000001
@@ -58,16 +58,27 @@ dgets = +Array.from( document @@ -105,16 +105,17 @@ widget') +) ;%0A%0A%09widg @@ -189,17 +189,16 @@ );%0A%09%7D);%0A -%09 %0A%09requir
a7e6d0e8cfbf4d8d2697d81f9d2376128d853a0b
Fix aspect ratio
core/game.js
core/game.js
/*global performance:true*/ define(function(require) { require('util/math'); var Factory = require('core/factory'); var Field = require('core/field'); var Player = require('core/player'); var requestAnimationFrame = require('lib/requestAnimationFrame'); var InputManager = require('core/inputManager'); var Display = require('core/display'); function Game(options) { this.playing = true; this.entities = []; this.width = 800; this.height = 600; this.display = new Display(this.width, this.height); this.camera = Factory.create('camera', { 'Camera': { 'width': this.width, 'heigth': this.height }}); this.addEntity(this.camera); this.field = new Field(this, 100); this.addEntity(this.field); this.players = [ new Player(this, 'blue', this.field, { human: true }), new Player(this, 'red', this.field) ]; this.entities.push(this.players[0]); this.entities.push(this.players[1]); this.debugList(); } Game.prototype.addEntity = function(entity) { this.entities.push(entity); var appearance = entity.getComponent('Appearance'); if (appearance) this.display.add(appearance.mesh); var camera = entity.getComponent('Camera'); if (camera) this.display.add(camera.camera); }; Game.prototype.removeEntity = function(entity) { var index = this.entities.indexOf(entity); if (index != -1) { this.entities.splice(index); var appearance = entity.getComponent('Appearance'); if (appearance) this.display.remove(appearance.mesh); var camera = entity.getComponent('Camera'); if (camera) this.display.remove(camera.camera); } }; Game.prototype.debugList = function() { var html = '<ul>'; this.entities.forEach(function(entity, i) { if (entity.tag === 'Resource' || entity.tag === null || entity.tag === 'Camera') return; html += '<li><a class="entity-details" href="#" data-id="' + i + '">' + entity.tag + '</a></li>'; }); html += '</ul>'; document.getElementById('debug').innerHTML = html; var centerOnEntity = function(e) { var id = e.target.dataset.id; var entity = this.entities[id]; this.camera.getComponent('Camera').follow(entity); }.bind(this); var links = document.querySelectorAll('.entity-details'); for (var i = 0; i < links.length; i++) { links[i].addEventListener('click', centerOnEntity); } }; Game.prototype.fixedUpdate = function(dt) { var i = this.entities.length; var entity; while (i) { i--; entity = this.entities[i]; entity.fixedUpdate(dt); } }; Game.prototype.update = function(dt, elapsed) { var i = this.entities.length; while (i) { i--; this.entities[i].update(dt, elapsed); } InputManager.update(); }; Game.prototype.run = function() { this.playing = true; var t0 = performance.now() - 16; var game = this; var logicRate = 200; // 5fps var lastLogicTick; InputManager.observe(document.body); this.entities.forEach(function(entity) { entity.broadcast('Start', game); }); var render = function(t) { try { var dt = t - t0; var elapsed = (t - lastLogicTick) / logicRate; t0 = t; if (game.playing) requestAnimationFrame(render); game.update(dt, elapsed); game.display.render(); } catch(e) { game.stop(); throw e; } }; render(performance.now()); var logic = function() { var dt; lastLogicTick = performance.now(); dt = lastLogicTick - t0; if (game.playing) setTimeout(logic, logicRate); game.fixedUpdate(dt); }; logic(); }; Game.prototype.stop = function() { InputManager.detach(); this.playing = false; }; return Game; });
JavaScript
0.000004
@@ -654,18 +654,18 @@ h, 'heig -t h +t ': this.
ca4fadac1723ca0f288ba2c2161b16c6fc2bdaf4
Document the function
module/index.js
module/index.js
JavaScript
0.999999
@@ -0,0 +1,887 @@ + /**%0A * The %60element%60 will be updated in place with bindings from the %60ast%60 using%0A * the %60variables%60 you give us. The %60ast%60 will generally come from the module%0A * %5Bparametric-svg-parse%5D%5B%5D. You can also generate it yourself using%0A * %5Bparametric-svg-ast%5D%5B%5D.%0A *%0A * If a parametric attribute depends on a variable you don%E2%80%99t give us, we won%E2%80%99t%0A * update the attribute. For example, if you have%0A * a %60%3Crect parametric:x=%22a + 1%22%60 y=%225%22 parametric:y=%22b + 1%22 /%3E%60 and only%0A * give us %60%7Ba: 10%7D%60 as %60variables%60, the result will be%0A * %60%3Crect x=%2211%22 parametric:x=%22a + 1%22%60 y=%225%22 parametric:y=%22b + 1%22 /%3E%60.%0A *%0A * %5Bparametric-svg-parse%5D: https://npmjs.com/package/parametric-svg-parse%0A * %5Bparametric-svg-ast%5D: https://npmjs.com/package/parametric-svg-ast%0A *%0A * @jsig%0A * patch(%0A * element: DOMElement,%0A * ast: ParametricSvgAst,%0A * variables: Object%0A * ) =%3E void%0A */%0A
d7ec9e56fc0f1761215045ae15abae7017c3a05a
Update to airbnb style
module/index.js
module/index.js
import { ifElse, isFunction, filter, compose } from '1-liners'; const castBool = val => val === true; const throwError = msg => () => { throw new Error(msg); }; const filterCurried = filterFn => ifElse( Array.isArray, arr => filter( compose(castBool, filterFn), arr), throwError('Filter expected an array')); export default ifElse( isFunction, filterCurried, throwError('Filter expected a function'));
JavaScript
0
@@ -45,17 +45,17 @@ compose - +%0A %7D from ' @@ -83,19 +83,21 @@ tBool = +( val +) =%3E val @@ -125,19 +125,21 @@ Error = +( msg +) =%3E () = @@ -190,24 +190,25 @@ rried = +( filterFn =%3E%0A if @@ -203,13 +203,12 @@ erFn +) =%3E -%0A ifE @@ -212,18 +212,16 @@ ifElse(%0A - Array. @@ -235,13 +235,13 @@ ,%0A - +( arr +) =%3E @@ -247,17 +247,16 @@ filter( - compose( @@ -282,18 +282,16 @@ , arr),%0A - throwE @@ -322,16 +322,17 @@ array') +%0A );%0A%0Aexpo @@ -341,18 +341,16 @@ default -%0A ifElse( @@ -350,18 +350,16 @@ ifElse(%0A - isFunc @@ -366,18 +366,16 @@ tion,%0A - - filterCu @@ -381,18 +381,16 @@ urried,%0A - throwE @@ -423,11 +423,12 @@ nction') +%0A );%0A
f5b51df54cc3ab21c8d9cf7930ab180f9a80e5b0
Fix regex so .+(r+)rand doesn't match
modules/rand.js
modules/rand.js
module.exports.command = /(r+)and/; module.exports.run = function(r, parts, reply, command) { var res = command.match(module.exports.command); var levels = res[1].length - 1; if(levels > 3 || parts.length > 10 + levels) { reply("dicks a million times"); return; } if(levels == 0) { reply(parts[Math.floor(Math.random() * parts.length)]); return; } var results = {}; for(var level = 0; level < levels; level++) { if(parseInt(parts[level],10) > 9e5) { reply("no"); return; } for(var i = 0; i < parseInt(parts[level],10); i++) { var choice = parts[Math.floor(Math.random() * (parts.length - levels)) + levels]; if(typeof results[choice] == "undefined") { results[choice] = 1; } else { results[choice] = results[choice] + 1; } } } reply( Object.keys(results) .sort(function(k1,k2){return results[k2]-results[k1];}) .map(function(k) { return k + " " + results[k] + " times"; }) .join(", ") ); };
JavaScript
0.999859
@@ -19,16 +19,17 @@ mand = / +%5E (r+)and/
48f70e23c3e45b73f89b07c15885930127dcfa60
Fix bad loop on element
contribs/gmf/src/controllers/AbstractMobileController.js
contribs/gmf/src/controllers/AbstractMobileController.js
goog.provide('gmf.controllers.AbstractMobileController'); goog.require('gmf.controllers.AbstractAppController'); goog.require('gmf.mobile.measure.module'); goog.require('gmf.mobile.navigation.module'); goog.require('gmf.query.windowComponent'); goog.require('ngeo.geolocation.mobile'); goog.require('ol'); goog.require('ol.obj'); goog.require('ol.proj'); goog.require('ol.Map'); goog.require('ol.View'); goog.require('ol.control.ScaleLine'); goog.require('ol.control.Zoom'); goog.require('ol.control.Rotate'); goog.require('ol.interaction'); goog.require('ol.style.Circle'); goog.require('ol.style.Fill'); goog.require('ol.style.Stroke'); goog.require('ol.style.Style'); /** * Mobile application abstract controller. * * This file includes `goog.require`'s mobile components/directives used * by the HTML page and the controller to provide the configuration. * * @param {gmfx.Config} config A part of the application config. * @param {angular.Scope} $scope Scope. * @param {angular.$injector} $injector Main injector. * @constructor * @extends {gmf.controllers.AbstractAppController} * @ngdoc controller * @ngInject * @export */ gmf.controllers.AbstractMobileController = function(config, $scope, $injector) { /** * @type {boolean} * @export */ this.leftNavVisible = false; /** * @type {boolean} * @export */ this.rightNavVisible = false; /** * @type {boolean} * @export */ this.searchOverlayVisible = false; /** * @type {ngeox.SearchDirectiveListeners} * @export */ this.searchListeners = /** @type {ngeox.SearchDirectiveListeners} */ ({ open: function() { this.searchOverlayVisible = true; }.bind(this), close: function() { this.searchOverlayVisible = false; }.bind(this) }); const positionFeatureStyle = config.positionFeatureStyle || new ol.style.Style({ image: new ol.style.Circle({ radius: 6, fill: new ol.style.Fill({color: 'rgba(230, 100, 100, 1)'}), stroke: new ol.style.Stroke({color: 'rgba(230, 40, 40, 1)', width: 2}) }) }); const accuracyFeatureStyle = config.accuracyFeatureStyle || new ol.style.Style({ fill: new ol.style.Fill({color: 'rgba(100, 100, 230, 0.3)'}), stroke: new ol.style.Stroke({color: 'rgba(40, 40, 230, 1)', width: 2}) }); /** * @type {ngeox.MobileGeolocationDirectiveOptions} * @export */ this.mobileGeolocationOptions = { positionFeatureStyle: positionFeatureStyle, accuracyFeatureStyle: accuracyFeatureStyle, zoom: config.geolocationZoom, autorotate: config.autorotate }; const viewConfig = { projection: ol.proj.get(`EPSG:${config.srid || 21781}`) }; ol.obj.assign(viewConfig, config.mapViewConfig || {}); const arrow = gmf.controllers.AbstractAppController.prototype.getLocationIcon(); /** * @type {ol.Map} * @export */ this.map = new ol.Map({ pixelRatio: config.mapPixelRatio, layers: [], view: new ol.View(viewConfig), controls: config.mapControls || [ new ol.control.ScaleLine(), new ol.control.Zoom({ zoomInTipLabel: '', zoomOutTipLabel: '' }), new ol.control.Rotate({ label: arrow, tipLabel: '' }) ], interactions: config.mapInteractions || ol.interaction.defaults({pinchRotate: true}) }); gmf.controllers.AbstractAppController.call(this, config, $scope, $injector); this.manageResize = true; this.resizeTransition = 500; // Close right nave on successful login. $scope.$watch(() => this.gmfUser.username, (newVal) => { if (newVal !== null && this.navIsVisible()) { this.rightNavVisible = false; } }); }; ol.inherits(gmf.controllers.AbstractMobileController, gmf.controllers.AbstractAppController); /** * @export */ gmf.controllers.AbstractMobileController.prototype.toggleLeftNavVisibility = function() { this.leftNavVisible = !this.leftNavVisible; }; /** * @export */ gmf.controllers.AbstractMobileController.prototype.toggleRightNavVisibility = function() { this.rightNavVisible = !this.rightNavVisible; }; /** * Hide both navigation menus. * @export */ gmf.controllers.AbstractMobileController.prototype.hideNav = function() { this.leftNavVisible = this.rightNavVisible = false; }; /** * @return {boolean} Return true if one of the navigation menus is visible, * otherwise false. * @export */ gmf.controllers.AbstractMobileController.prototype.navIsVisible = function() { return this.leftNavVisible || this.rightNavVisible; }; /** * Hide search overlay. * @export */ gmf.controllers.AbstractMobileController.prototype.hideSearchOverlay = function() { this.searchOverlayVisible = false; }; /** * @return {boolean} Return true if the left navigation menus is visible, * otherwise false. * @export */ gmf.controllers.AbstractMobileController.prototype.leftNavIsVisible = function() { return this.leftNavVisible; }; /** * @return {boolean} Return true if the right navigation menus is visible, * otherwise false. * @export */ gmf.controllers.AbstractMobileController.prototype.rightNavIsVisible = function() { return this.rightNavVisible; }; /** * Open the menu with corresponding to the data-target attribute value. * @param {string} target the data-target value. * @export */ gmf.controllers.AbstractMobileController.prototype.openNavMenu = function(target) { const navElements = document.getElementsByClassName('gmf-mobile-nav-button'); for (const key in navElements) { const element = navElements[key]; if (element.dataset && element.dataset.target === target) { element.click(); } } }; gmf.controllers.AbstractMobileController.module = angular.module('GmfAbstractMobileControllerModule', [ gmf.controllers.AbstractAppController.module.name, gmf.mobile.measure.module.name, gmf.mobile.navigation.module.name, gmf.query.windowComponent.name, ngeo.geolocation.mobile.name, ]); gmf.controllers.AbstractMobileController.module.controller('AbstractMobileController', gmf.controllers.AbstractMobileController); gmf.controllers.AbstractMobileController.module.value('isMobile', true); gmf.controllers.AbstractMobileController.module.value('ngeoQueryOptions', { 'tolerance': 10 });
JavaScript
0.000006
@@ -5484,32 +5484,46 @@ or ( -const key in navElements +let i = 0; i %3C navElements.length; i++ ) %7B%0A @@ -5558,11 +5558,9 @@ nts%5B -key +i %5D;%0A
b2d87b790a02baaa82f7b8e7317ce854a97a72bd
Update validation.js
app/utils/validation.js
app/utils/validation.js
'use strict'; const filerObject = require('filter-object'); module.exports = { /** * */ hasValidationErrors: error => { if (!error.errors) { return false; } return !!filerObject(error.errors, err => { return err.name === 'ValidatorError'; }); }, /** * */ extractErrors: (error, i18nAlias) => { const errors = []; if (!error.errors) { return []; } const validationErrors = filerObject(error.errors, err => { return err.name === 'ValidatorError'; }); for (let err in validationErrors) { if ((err = validationErrors[err]).message) { errors.push({ messageCode: err.message, property: i18nAlias ? `${i18nAlias}.${err.path}` : err.path, value: err.value }); } } return errors; } };
JavaScript
0.000001
@@ -13,24 +13,25 @@ ;%0A%0Aconst fil +t erObject = r @@ -222,16 +222,17 @@ rn !!fil +t erObject @@ -985,8 +985,9 @@ %7D%0A%7D; +%0A
b0417ac87a8373a5c682850468eed87872ea40d9
Add changelog for v1.0.3
lostorage.min.js
lostorage.min.js
// Copyright (c) 2012 Florian H., https://github.com/js-coder https://github.com/js-coder/lostorage.js !function(a,b){var c={isArray:Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},isPlainObj:function(a){return a===Object(a)},toArray:function(a){return Array.prototype.slice.call(a)},prepareArgs:function(a,b){return a=c.toArray(a),a.unshift(b),a},getObjKeyByValue:function(a,b){for(var c in a)if(a.hasOwnProperty(c)&&a[c]===b)return c},prepareReturn:function(b){return a[c.getObjKeyByValue(f,b)]},retrieve:function(a,c){return a==b?c:a},serialize:function(a){return JSON.stringify(a)},unserialize:function(a){return a==b?b:JSON.parse(a)}},d=function(){return d.get.apply(this,arguments)};a.storage=function(){return storage.get.apply(storage,arguments)},a.session=function(){return session.get.apply(session,arguments)},d.set=function(a,b,d){if(c.isPlainObj(b))for(var e in b)b.hasOwnProperty(e)&&a.setItem(e,c.serialize(b[e]));else a.setItem(b,c.serialize(d));return c.prepareReturn(a)},d.invert=function(a,b){return this.set(a,b,!this.get(a,b))},d.add=function(a,b,c){return this.set(a,b,this.get(a,b)+parseInt(c,10))},d.increase=function(a,b){return this.add(a,b,1)},d.decrease=function(a,b){return this.add(a,b,-1)},d.concat=function(a,b,c){return this.set(a,b,this.get(a,b)+c)},d.push=function(a,b){var e=c.toArray(arguments),f=this.get(a,b);return e.splice(0,2),f.push.apply(f,e),this.set(a,b,f)},d.extend=function(a,b,d,e){var f=this.get(a,b,{});if(c.isPlainObj(d))for(var g in d)d.hasOwnProperty(g)&&(f[g]=d[g]);else f[d]=e;return this.set(a,b,f)},d.remove=function(a,b){b=c.isArray(b)?b:c.toArray(arguments);for(var d=0,e=b.length;e>d;d++)delete a[b[d]];return c.prepareReturn(a)},d.empty=function(a){return a.clear(),c.prepareReturn(a)},d.get=function(a,d,e){if(e=e||b,c.isArray(d)){for(var f={},g=0,h=d.length;h>g;g++){var i=d[g];f[i]=this.get(a,i,e)}return f}return c.retrieve(c.unserialize(a.getItem(d)),e)},d.all=function(a){var b=JSON.parse(JSON.stringify(a));for(var d in b)b.hasOwnProperty(d)&&(b[d]=c.unserialize(b[d]));return b};for(var e="set invert add increase decrease concat push extend remove empty get all".split(" "),f={storage:localStorage,session:sessionStorage},g=0,h=e.length;h>g;g++){var i=e[g];for(var j in f)if(f.hasOwnProperty(j)){var k=f[j];a[j][i]=function(a,b){return function(){var e=c.prepareArgs(arguments,b);return d[a].apply(d,e)}}(i,k)}}}(window);
JavaScript
0.000001
@@ -1976,84 +1976,63 @@ (a)%7B +for( var b= -JSON.parse(JSON.stringify(a));for(var d in b)b.hasOwnPropert +%7B%7D,d=0,e=a.length;e%3Ed;d++)%7Bvar f=a.ke y(d) -&&(b%5Bd +;b%5Bf %5D=c. @@ -2047,15 +2047,22 @@ ize( -b%5Bd%5D)); +a.getItem(f))%7D retu
7bc3956862cad3f25e0d72f19e8266754927d257
improve uuid.js performance
javascript/uuid.js
javascript/uuid.js
// keywords: js, javascript, uuid generator /** * An Universal Unique ID generator * * @return {String} The new UUID. */ function uuid() { var s = (Math.random().toString(16) + "00000000").slice(2, 10); s += "-"; s += (Math.random().toString(16) + "0000").slice(2, 6); s += "-"; s += (Math.random().toString(16) + "0000").slice(2, 6); s += "-"; s += (Math.random().toString(16) + "0000").slice(2, 6); s += "-"; s += (Math.random().toString(16) + "000000").slice(2, 8); s += (Math.random().toString(16) + "000000").slice(2, 8); return s; }
JavaScript
0.000003
@@ -144,314 +144,419 @@ %7B%0A -var s = (Math.random().toString(16) + %2200000000%22).slice(2, 10);%0A s +return (%2200000000%22 + Math.floor(%0A Math.random() * 0x100000000%0A ).toString(16)).slice(-8) + -= %22-%22 -;%0A s += (Math.random().toString(16) + %220000%22).slice(2, 6);%0A s + + (%220000%22 + Math.floor(%0A Math.random() * 0x10000%0A ).toString(16)).slice(-4) + -= %22-%22 -;%0A s += (Math.random().toString(16) + %220000%22).slice(2, 6);%0A s += %22-%22;%0A s += (Math.random().toString(16) + %220000%22).slice(2, 6);%0A s += %22-%22;%0A s += (Math.random( + + (%220000%22 + Math.floor(%0A Math.random() * 0x10000%0A ).toString(16)).slice(-4) + %22-%22 + (%220000%22 + Math.floor(%0A Math.random() * 0x10000%0A ).toString(16)).slice(-4) + %22-%22 + (%220000%22 + Math.floor(%0A Math.random() * 0x10000%0A ).to @@ -569,104 +569,107 @@ (16) +).slice(-4) + +( %22000000 -%22).slice(2, 8);%0A s += (Math.random().toString(16) + %22000000%22).slice(2, 8);%0A return s +00%22 + Math.floor(%0A Math.random() * 0x100000000%0A ).toString(16)).slice(-8) ;%0A%7D%0A
5de51bb34afa77d54af3f31386e53faa7c06c4cd
add test for query util
src/utils/__tests__/query.test.js
src/utils/__tests__/query.test.js
JavaScript
0.000002
@@ -0,0 +1,1985 @@ +'use strict';%0A%0Aimport %7BReact, TestUtils%7D from 'react';%0Aimport %7Bexpect%7D from 'chai';%0A%0Aimport * as Query from '../query.util.js';%0A%0Adescribe('Test Query Util Class', () =%3E %7B%0A it('should convert a query string object to an internal query object', () =%3E %7B%0A let result = Query.stringToObject(%7B%7D);%0A expect(result).to.deep.equal(%5B%5D);%0A%0A let query = %7B text: 'kanin%7Cfisk', 'term.type': '%C3%A6ble%7Cbanan' %7D;%0A let expectedResult = %5B%0A %7Bvalue: 'kanin', type: 'text', index: 'textkanin0'%7D,%0A %7Bvalue: 'fisk', type: 'text', index: 'textfisk1'%7D,%0A %7Bvalue: '%C3%A6ble', type: 'term.type', index: 'term.type%C3%A6ble0'%7D,%0A %7Bvalue: 'banan', type: 'term.type', index: 'term.typebanan1'%7D%0A %5D;%0A result = Query.stringToObject(query);%0A expect(result).to.deep.equal(expectedResult);%0A %7D);%0A%0A it('should convert internal query object to a query string', () =%3E %7B%0A let result = Query.objectToString(%5B%5D);%0A expect(result).to.deep.equal('');%0A%0A let objects = %5B%0A %7Bvalue: 'kanin', type: 'text', index: 'textkanin0'%7D,%0A %7Bvalue: 'fisk', type: 'text', index: 'textfisk1'%7D,%0A %7Bvalue: '%C3%A6ble', type: 'term.type', index: 'term.type%C3%A6ble0'%7D,%0A %7Bvalue: 'banan', type: 'term.type', index: 'term.typebanan1'%7D%0A %5D;%0A let expectedResult = 'text=kanin%7Cfisk&term.type=%C3%A6ble%7Cbanan';%0A result = Query.objectToString(objects);%0A expect(result).to.deep.equal(expectedResult);%0A %7D);%0A%0A it('should convert internal query object to a CQL string', () =%3E %7B%0A let result = Query.objectToCql(%5B%5D);%0A expect(result).to.deep.equal('');%0A%0A let objects = %5B%0A %7Bvalue: 'kanin', type: 'text', index: 'textkanin0'%7D,%0A %7Bvalue: 'fisk', type: 'text', index: 'textfisk1'%7D,%0A %7Bvalue: '%C3%A6ble', type: 'term.type', index: 'term.type%C3%A6ble0'%7D,%0A %7Bvalue: 'banan', type: 'term.type', index: 'term.typebanan1'%7D%0A %5D;%0A let expectedResult = '(kanin and fisk) and term.type=(%C3%A6ble and banan)';%0A result = Query.objectToCql(objects);%0A expect(result).to.deep.equal(expectedResult);%0A %7D);%0A%7D);%0A
d4da80abaedac22d5749dd53d9c5f139cc8a77d8
set read only
widget.js
widget.js
// set editor basepath CKEDITOR_BASEPATH = '/widgets-custom/CKEditor/libs/ckeditor/'; WAF.define('CKEditor', ['waf-core/widget'], function(widget) { var CKEditor = widget.create('CKEditor', { init: function() { try { var _this = this; // create editor with CKEditor plugin _this.editor = CKEDITOR.appendTo(_this.node, { customConfig: _this.customConfigPath(), language: _this.language() }); // add content to datasource _this.editor.on('change', function(e) { // clear timer if (_this.throttleGet) { clearTimeout(_this.throttleGet); } // throttle function calls to every 250 milliseconds _this.throttleGet = setTimeout(function() { subscriber.pause(); // set datasource value _this.content(_this.editor.getData()); subscriber.resume(); }, 250); }); // set editor content on datasource current element change var subscriber = _this.content.onChange(function() { _this.setValue(_this.content()); }); // set initial editor content _this.editor.on('instanceReady', function() { _this.editor.resize(_this.width(), _this.height()); _this.editor.setData(_this.content()); _this.fire('instanceReady'); }); } catch (e) { console.log(e.message); } }, content: widget.property({ type: 'string', defaultValue: '' }), customConfigPath: widget.property({ type: 'string', defaultValue: '' }), language: widget.property({ type: 'string', bindable: false, defaultValue: 'en' }), getValue: function() { // get editor value return this.editor.getData(); }, setValue: function(value) { var _this = this; // throttle function to set editor content if (_this.throttleSet) { clearTimeout(_this.throttleSet); } _this.throttleSet = setTimeout(function() { // set editor data if (value == 'null' || value == null) { _this.editor.setData(''); } else { _this.editor.setData(value); } }, 50); } }); return CKEditor; }); /* For more information, refer to http://doc.wakanda.org/Wakanda0.DevBranch/help/Title/en/page3871.html */
JavaScript
0
@@ -2687,24 +2687,138 @@ %09%7D, 50);%0A + %09%7D,%0A %09setReadOnly: function(value) %7B%0A %09 // set read only%0A this.editor.setReadOnly(value);%0A %09%7D%0A %7D
e6257fec0397ac4386a7485bc10cf7ef9fc03b9f
Allow Zendesk to load a tab image since it insists
src/scripts/config.js
src/scripts/config.js
(function () { 'use strict'; require.config({ // # Paths paths: { // ## Requirejs plugins text: '../../bower_components/requirejs-text/text', hbs: '../../bower_components/require-handlebars-plugin/hbs', // ## Core Libraries jquery: '../../bower_components/jquery/dist/jquery', underscore: '../../bower_components/lodash/dist/lodash', backbone: '../../bower_components/backbone/backbone', 'hbs/handlebars': '../../bower_components/require-handlebars-plugin/hbs/handlebars', // ## Backbone plugins 'backbone-associations': '../../bower_components/backbone-associations/backbone-associations', // ## MathJax mathjax: '//cdn.mathjax.org/mathjax/2.3-latest/MathJax.js?config=MML_HTMLorMML', // ## Zendesk zendesk: '//assets.zendesk.com/external/zenbox/v2.6/zenbox', // Use Minified Aloha because loading files in a different requirejs context is a royal pain aloha: '../../bower_components/aloha-editor/target/build-profile-with-oer/rjs-output/lib/aloha', // ## UI Libraries and Helpers tooltip: 'helpers/backbone/views/attached/tooltip/tooltip', popover: 'helpers/backbone/views/attached/popover/popover', // Boostrap Plugins bootstrapAffix: '../../bower_components/bootstrap/js/affix', bootstrapAlert: '../../bower_components/bootstrap/js/alert', bootstrapButton: '../../bower_components/bootstrap/js/button', bootstrapCarousel: '../../bower_components/bootstrap/js/carousel', bootstrapCollapse: '../../bower_components/bootstrap/js/collapse', bootstrapDropdown: '../../bower_components/bootstrap/js/dropdown', bootstrapModal: '../../bower_components/bootstrap/js/modal', bootstrapPopover: '../../bower_components/bootstrap/js/popover', bootstrapScrollspy: '../../bower_components/bootstrap/js/scrollspy', bootstrapTab: '../../bower_components/bootstrap/js/tab', bootstrapTooltip: '../../bower_components/bootstrap/js/tooltip', bootstrapTransition: '../../bower_components/bootstrap/js/transition', // # Select2 multiselect widget select2: '../../bower_components/select2/select2' }, // # Packages packages: [{ name: 'cs', location: '../../bower_components/require-cs', main: 'cs' }, { name: 'coffee-script', location: '../../bower_components/coffeescript/extras', main: 'coffee-script' }, { name: 'css', location: '../../bower_components/require-css', main: 'css' }, { name: 'less', location: '../../bower_components/require-less', main: 'less' }], // # Shims shim: { // ## Aloha aloha: { // To disable MathJax comment out the `mathjax` entry in `deps` below. deps: ['jquery', 'mathjax', 'cs!configs/aloha', 'bootstrapModal', 'bootstrapPopover'], exports: 'Aloha', init: function () { return window.Aloha; } }, // ## MathJax mathjax: { exports: 'MathJax', init: function () { // This config is copied from // `../../bower_components/aloha-editor/cnx/mathjax-config.coffee` // // It configures the TeX and AsciiMath inputs and the MML output // mostly for the Math editor. // // MathMenu and Zoom may not be needed but the `noErrors` is useful // for previewing as you type. window.MathJax.Hub.Config({ jax: [ 'input/MathML', 'input/TeX', 'input/AsciiMath', 'output/NativeMML', 'output/HTML-CSS' ], extensions: [ 'asciimath2jax.js', 'tex2jax.js', 'mml2jax.js', 'MathMenu.js', 'MathZoom.js' ], tex2jax: { inlineMath: [ ['[TEX_START]', '[TEX_END]'], ['\\(', '\\)'] ] }, TeX: { extensions: [ 'AMSmath.js', 'AMSsymbols.js', 'noErrors.js', 'noUndefined.js' ], noErrors: { disabled: true } }, AsciiMath: { noErrors: { disabled: true } } }); return window.MathJax; } }, zendesk: { deps: ['css!//assets.zendesk.com/external/zenbox/v2.6/zenbox'], exports: 'Zendesk', init: function () { if (typeof Zenbox !== 'undefined') { window.Zenbox.init({ dropboxID: '20186520', url: 'https://openstaxcnx.zendesk.com', tabTooltip: 'Ask Us', //tabImageURL: 'https://p2.zdassets.com/external/zenbox/images/tab_ask_us_right.png', tabColor: '#78b04a', tabPosition: 'Right' }); } return window.Zenbox; } }, // ## UI Libraries // # Bootstrap Plugins bootstrapAffix: ['jquery'], bootstrapAlert: ['jquery'], bootstrapButton: ['jquery'], bootstrapCarousel: ['jquery'], bootstrapCollapse: ['jquery', 'bootstrapTransition'], bootstrapDropdown: ['jquery'], bootstrapModal: ['jquery', 'bootstrapTransition'], bootstrapPopover: ['jquery', 'bootstrapTooltip'], bootstrapScrollspy: ['jquery'], bootstrapTab: ['jquery'], bootstrapTooltip: ['jquery'], bootstrapTransition: ['jquery'], // Select2 select2: { deps: ['jquery', 'css!../../bower_components/select2/select2'], exports: 'Select2' } }, // Handlebars Requirejs Plugin Configuration // Used when loading templates `'hbs!...'`. hbs: { templateExtension: 'html', helperPathCallback: function (name) { return 'cs!helpers/handlebars/' + name; } } }); })();
JavaScript
0
@@ -4876,18 +4876,16 @@ -// tabImage
72b9345f47df766daa896391589849bcd44b65f6
Update config for require-cs 0.5
src/scripts/config.js
src/scripts/config.js
(function () { 'use strict'; require.config({ // # Paths paths: { // ## Requirejs plugins text: '../../bower_components/requirejs-text/text', hbs: '../../bower_components/require-handlebars-plugin/hbs', cs: '../../bower_components/require-cs/cs', // ## Core Libraries jquery: '../../bower_components/jquery/dist/jquery', underscore: '../../bower_components/lodash/dist/lodash', backbone: '../../bower_components/backbone/backbone', 'hbs/handlebars': '../../bower_components/require-handlebars-plugin/hbs/handlebars', // ## Backbone plugins 'backbone-associations': '../../bower_components/backbone-associations/backbone-associations', // ## MathJax mathjax: 'http://cdn.mathjax.org/mathjax/2.3-latest/MathJax.js?config=MML_HTMLorMML', // Use Minified Aloha because loading files in a different requirejs context is a royal pain aloha: '../../bower_components/aloha-editor/target/build-profile-with-oer/rjs-output/lib/aloha', // ## UI Libraries and Helpers tooltip: 'helpers/backbone/views/attached/tooltip/tooltip', popover: 'helpers/backbone/views/attached/popover/popover', // Boostrap Plugins bootstrapAffix: '../../bower_components/bootstrap/js/affix', bootstrapAlert: '../../bower_components/bootstrap/js/alert', bootstrapButton: '../../bower_components/bootstrap/js/button', bootstrapCarousel: '../../bower_components/bootstrap/js/carousel', bootstrapCollapse: '../../bower_components/bootstrap/js/collapse', bootstrapDropdown: '../../bower_components/bootstrap/js/dropdown', bootstrapModal: '../../bower_components/bootstrap/js/modal', bootstrapPopover: '../../bower_components/bootstrap/js/popover', bootstrapScrollspy: '../../bower_components/bootstrap/js/scrollspy', bootstrapTab: '../../bower_components/bootstrap/js/tab', bootstrapTooltip: '../../bower_components/bootstrap/js/tooltip', bootstrapTransition: '../../bower_components/bootstrap/js/transition', // # Select2 multiselect widget select2: '../../bower_components/select2/select2', // ## CoffeeScript Compiler 'coffee-script': '../../bower_components/coffee-script/index' }, // # Packages packages: [{ name: 'css', location: '../../bower_components/require-css', main: 'css' }, { name: 'less', location: '../../bower_components/require-less', main: 'less' }], // # Shims shim: { // ## Aloha aloha: { // To disable MathJax comment out the `mathjax` entry in `deps` below. deps: ['jquery', 'mathjax', 'cs!configs/aloha', 'bootstrapModal', 'bootstrapPopover'], exports: 'Aloha', init: function () { return window.Aloha; } }, // ## MathJax mathjax: { exports: 'MathJax', init: function () { // This config is copied from // `../../bower_components/aloha-editor/cnx/mathjax-config.coffee` // // It configures the TeX and AsciiMath inputs and the MML output // mostly for the Math editor. // // MathMenu and Zoom may not be needed but the `noErrors` is useful // for previewing as you type. window.MathJax.Hub.Config({ jax: [ 'input/MathML', 'input/TeX', 'input/AsciiMath', 'output/NativeMML', 'output/HTML-CSS' ], extensions: [ 'asciimath2jax.js', 'tex2jax.js', 'mml2jax.js', 'MathMenu.js', 'MathZoom.js' ], tex2jax: { inlineMath: [ ['[TEX_START]', '[TEX_END]'], ['\\(', '\\)'] ] }, TeX: { extensions: [ 'AMSmath.js', 'AMSsymbols.js', 'noErrors.js', 'noUndefined.js' ], noErrors: { disabled: true } }, AsciiMath: { noErrors: { disabled: true } } }); return window.MathJax; } }, // ## UI Libraries // # Bootstrap Plugins bootstrapAffix: ['jquery'], bootstrapAlert: ['jquery'], bootstrapButton: ['jquery'], bootstrapCarousel: ['jquery'], bootstrapCollapse: ['jquery', 'bootstrapTransition'], bootstrapDropdown: ['jquery'], bootstrapModal: ['jquery', 'bootstrapTransition'], bootstrapPopover: ['jquery', 'bootstrapTooltip'], bootstrapScrollspy: ['jquery'], bootstrapTab: ['jquery'], bootstrapTooltip: ['jquery'], bootstrapTransition: ['jquery'], // Select2 select2: { deps: ['jquery', 'css!../../bower_components/select2/select2'], exports: 'Select2' } }, // Handlebars Requirejs Plugin Configuration // Used when loading templates `'hbs!...'`. hbs: { templateExtension: 'html', helperPathCallback: function (name) { return 'cs!helpers/handlebars/' + name; } } }); })();
JavaScript
0
@@ -230,58 +230,8 @@ bs', -%0A cs: '../../bower_components/require-cs/cs', %0A%0A @@ -2115,50 +2115,160 @@ ct2' +%0A %7D ,%0A%0A - - // # -# CoffeeScript Compiler + Packages%0A packages: %5B%7B%0A name: 'cs',%0A location: '../../bower_components/require-cs',%0A main: 'cs'%0A %7D, %7B %0A + name: 'co @@ -2279,16 +2279,32 @@ -script' +,%0A location : '../.. @@ -2331,64 +2331,59 @@ ffee -- script/ -index'%0A %7D,%0A%0A // # Packages%0A packages: %5B +extras',%0A main: 'coffee-script'%0A %7D, %7B%0A
da386dcb1feea443dc425ab45ffc047cbd0fbcc2
Allow injection of mock github client.
lib/github.js
lib/github.js
var Github = require('github'), _ = require('underscore'); module.exports = (function() { var Client, authenticate; Client = function(token) { this.token = token; this.ghClient = new Github({ version: '3.0.0', protocol: 'https' }); }; Client.prototype.getPullRequests = function(repo, state, callback) { authenticate(this); repoInfo = repo.split('/'); this.ghClient.pullRequests.getAll({ user: repoInfo[0], repo: repoInfo[1], state: state }, function(err, res) { if (err) { return callback(err); } callback(null, res); }); } authenticate = function(client) { client.ghClient.authenticate({ type: 'oauth', token: client.token }); }; return Client; }());
JavaScript
0
@@ -571,16 +571,97 @@ %09%09%7D);%0A%09%7D +;%0A%0A%09Client.prototype.setClient = function(client) %7B%0A%09%09this.ghClient = client;%0A%09%7D; %0A%0A%09authe
685a0518eb514d71a9eae96312b843a0dd7228a9
fix null body handling
lib/google.js
lib/google.js
var request = require('request') , cheerio = require('cheerio') , fs = require('fs') , querystring = require('querystring') , util = require('util'); var linkSel = 'h3.r a' , descSel = 'div.s' , itemSel = 'li.g' , nextSel = 'td.b a span' , noneFoundSel = ".med:contains(No results)"; var URL = 'http://www.google.com/search?hl=en&q=%s&start=%s&sa=N&num=%s&ie=UTF-8&oe=UTF-8'; function google(query, callback) { igoogle(query, 0, callback); } google.resultsPerPage = 10; var igoogle = function(query, start, callback) { var opt; if (typeof query === 'object') { opt = { query: querystring.escape(query.query), proxy: query.proxy }; } else { opt = { query: querystring.escape(query) }; } //console.log("google:options") //console.log(opt); if (google.resultsPerPage > 100) google.resultsPerPage = 100; //Google won't allow greater than 100 anyway var newUrl = util.format(URL, opt.query, start, google.resultsPerPage); var rOpt = { url: newUrl, proxy: opt.proxy }; request(rOpt, function(err, resp, body) { if ((err === null) && resp.statusCode === 200) { if (body.indexOf("No results found for ") !== -1){ return callback(null, null, []); } var $ = cheerio.load(body) , links = [] , text = []; $(itemSel).each(function(i, elem) { var linkElem = $(elem).find(linkSel) , descElem = $(elem).find(descSel) , item = {title: $(linkElem).text(), link: null, description: null, href: null} , qsObj = querystring.parse($(linkElem).attr('href')); if (qsObj['/url?q']) { item.link = qsObj['/url?q']; item.href = item.link; } else if (!!(Object.keys(qsObj))[0]) { item.href = (Object.keys(qsObj))[0]; } $(descElem).find('div').remove(); item.description = $(descElem).text(); if (!!item.href){ if (item.href.substring(0,4) === "http"){ links.push(item); } } }); var nextFunc = null; if ($(nextSel).last().text() === 'Next'){ nextFunc = function() { igoogle(opt.query, start + google.resultsPerPage, callback); }; } callback(null, nextFunc, links); } else { e = new Error(); if (!!resp) { e.status = resp.statusCode; } else if (!!err) { e = err; } callback(e, null, null); //callback(new Error('Error on response (' + resp.statusCode + '):' + err +" : " + body), null, null); } }); }; module.exports = google;
JavaScript
0.000003
@@ -1153,16 +1153,25 @@ if ( +!body %7C%7C body.ind
c29eb1e9d74438621585ac56c239a92ba2eb503b
Fix for Nav items duplicating
vendor/assets/javascripts/koi/form-for.js
vendor/assets/javascripts/koi/form-for.js
(function($) { $(function(){ // https://stackoverflow.com/questions/20658402/internet-explorer-issue-with-html5-form-attribute-for-button-element // detect if browser supports this var sampleElement = $('[form]').get(0); var isIE11 = !(window.ActiveXObject) && "ActiveXObject" in window; if (sampleElement && window.HTMLFormElement && sampleElement.form instanceof HTMLFormElement && !isIE11) { // browser supports it, no need to fix return; } $("body").on("click", "button[form]", function(e){ var $element = $(this); var $form = $("#" + $element.attr("form")); $form.submit(); }); }); })(jQuery);
JavaScript
0
@@ -24,17 +24,16 @@ tion()%7B%0A -%0A // h @@ -192,56 +192,99 @@ -var sampleElement = $('%5Bform%5D').get(0 +$(%22body%22).on(%22click%22, %22button%5Bform%5D%22, function(e)%7B%0A var $element = $(this );%0A + var isIE @@ -283,71 +283,32 @@ var -isIE11 = !(window.ActiveXObject) && %22ActiveXObject%22 in window;%0A +sampleElement = this;%0A @@ -403,23 +403,14 @@ ment - && !isIE11 ) %7B%0A + @@ -456,16 +456,18 @@ x%0A + return;%0A @@ -474,95 +474,11 @@ -%7D%0A%0A $(%22body%22).on(%22click%22, %22button%5Bform%5D%22, function(e)%7B%0A var $element = $(this); + %7D %0A @@ -571,8 +571,9 @@ jQuery); +%0A
66201befa7a218a6a29fd838d163c78ede04f2f5
Fix bug
src/web/resources/scripts/home.js
src/web/resources/scripts/home.js
$(function() { try { Notification.requestPermission(); } catch (e) { } // オートセーブがあるなら復元 if ($.cookie('post-autosave')) { $('#post-form textarea').val($.cookie('post-autosave')); } socket = io.connect('https://api.misskey.xyz:1207/streaming/web/home', { port: 1207 }); socket.on('connected', function() { console.log('Connected'); }); socket.on('disconnect', function(client) { }); socket.on('post', function(post) { console.log('post', post); var currentPath = location.pathname; currentPath = currentPath.indexOf('/') == 0 ? currentPath : '/' + currentPath; if (currentPath != "/i/mention") { new Audio('/resources/sounds/pop.mp3').play(); var $post = TIMELINE.generatePostElement(post, conf).hide(); TIMELINE.setEventPost($post); $post.prependTo($('#timeline .timeline > .statuses')).show(200); } }); socket.on('repost', function(post) { console.log('repost', post); new Audio('/resources/sounds/pop.mp3').play(); var $post = TIMELINE.generatePostElement(post, conf).hide(); TIMELINE.setEventPost($post); $post.prependTo($('#timeline .timeline > .statuses')).show(200); }); socket.on('reply', function(post) { console.log('reply', post); var currentPath = location.pathname; currentPath = currentPath.indexOf('/') == 0 ? currentPath : '/' + currentPath; if (currentPath == "/i/mention") { new Audio('/resources/sounds/pop.mp3').play(); var $post = TIMELINE.generatePostElement(post, conf).hide(); TIMELINE.setEventPost($post); $post.prependTo($('#timeline .timeline > .statuses')).show(200); var n = new Notification(post.user.name, { body: post.text, icon: conf.url + '/img/icon/' + post.user.screenName }); n.onshow = function() { setTimeout(function() { n.close(); }, 10000); }; n.onclick = function() { window.open(conf.url + '/' + post.user.screenName + '/post/' + post.id); }; } }); socket.on('talkMessage', function(message) { console.log('talkMessage', message); var windowId = 'misskey-window-talk-' + message.user.id; if ($('#' + windowId)[0]) { return; } var n = new Notification(message.user.name, { body: message.text, icon: conf.url + '/img/icon/' + message.user.screenName }); n.onshow = function() { setTimeout(function() { n.close(); }, 10000); }; n.onclick = function() { var url = 'https://misskey.xyz/' + message.user.screenName + '/talk?noheader=true'; var $content = $("<iframe>").attr({ src: url, seamless: true }); openWindow(windowId, $content, '<i class="fa fa-comments"></i>' + escapeHTML(message.user.name), 300, 450, true, url); }; }); $('#postForm').find('.imageAttacher input[name=image]').change(function() { var $input = $(this); var file = $(this).prop('files')[0]; if (!file.type.match('image.*')) return; var reader = new FileReader(); reader.onload = function() { var $img = $('<img>').attr('src', reader.result); $input.parent('.imageAttacher').find('p, img').remove(); $input.parent('.imageAttacher').append($img); }; reader.readAsDataURL(file); }); $(window).keypress(function(e) { if (e.charCode == 13 && e.ctrlKey) { post($('#postForm textarea')); } }); $('#post-form').submit(function(event) { event.preventDefault(); post($(this)); }); function post($form) { var $submitButton = $form.find('[type=submit]'); $submitButton.attr('disabled', true); $submitButton.text('Updating...'); $.ajax('https://api.misskey.xyz/status/update', { type: 'post', processData: false, contentType: false, data: new FormData($form[0]), dataType: 'json', xhrFields: { withCredentials: true } }).done(function(data) { $form[0].reset(); $form.find('textarea').focus(); $form.find('.image-attacher').find('p, img').remove(); $form.find('.image-attacher').append($('<p><i class="fa fa-picture-o"></i></p>')); $submitButton.attr('disabled', false); $submitButton.text('Update'); $.removeCookie('post-autosave'); }).fail(function(data) { $form[0].reset(); $form.find('textarea').focus(); /*alert('error');*/ $submitButton.attr('disabled', false); $submitButton.text('Update'); }); } $('#post-form textarea').bind('input', function() { var text = $('#post-form textarea').val(); // オートセーブ $.cookie('post-autosave', text, { path: '/', expires: 365 }); }); $('#timeline .load-more').click(function() { $button = $(this); $button.attr('disabled', true); $button.text('Loading...'); $.ajax('https://api.misskey.xyz/post/timeline', { type: 'get', data: { max_id: $('#timeline .timeline .statuses > .status:last-child').attr('data-id') }, dataType: 'json', xhrFields: { withCredentials: true } }).done(function(data) { $button.attr('disabled', false); $button.text('Read more!'); data.forEach(function(post) { var $post = TIMELINE.generatePostElement(post, conf).hide(); TIMELINE.setEventPost($post); $post.appendTo($('#timeline .timeline > .statuses')).show(200); }); }).fail(function(data) { $button.attr('disabled', false); $button.text('Failed...'); }); }); });
JavaScript
0.000001
@@ -409,20 +409,22 @@ ket.on(' -po st +atus ', funct @@ -450,20 +450,22 @@ le.log(' -po st +atus ', post)
62abd8d1822cd4dc0da7050d40b56d61be90bb49
load files relative to module installation directory
core/queries.js
core/queries.js
var u = require('util'); var fs = require('fs'); var YAML = require('yamljs'); var hashOf = require('../utils/hashOf'); var template = require('../utils/template'); var hashSourceTarget = function(input) { if(!input.id && (!input.source || !input.target || !input.type)) throw new Error(u.format("Type '%s' requires id or source, target", input.type)); return input.id || hashOf([input.source,input.type,input.target]); }; var requireId = function(input) { if(!input.id) throw new Error(u.format("Type '%s' requires an id", input.type)); return input.id; }; // we define how identifiers are created for each structure here var identifiers = { node: requireId, arc: hashSourceTarget, equivalence: hashSourceTarget }; // load queries from file "structure.operation.{ cypher, description }" var qs = YAML.parse(fs.readFileSync('./core/queries.yaml', {encoding: 'utf8'})); // make cypher queries out of structure manipulation request exports.mkQuery = function(request) { var operation = request.operation; var structure = request.structure; if(!qs[structure]) throw new Error(u.format('No such structure "%s"', structure)); if(!qs[structure][operation]) throw new Error(u.format('No such operation "%s" on "%s"', operation, structure)); // lookup query string and... var cypher_string = qs[structure][operation].cypher; // ...string replace all occurances of «type» var s = template(cypher_string, {type: request.type}); // note ^ this is not a security breach, we assume input has been sanitized // at this point. TODO actually we assume, but don't sanitise // compute id if missing request.id = identifiers[structure](request); // return promise return { parameters: request, statement: s }; }; exports.structures = qs;
JavaScript
0
@@ -799,16 +799,63 @@ tion %7D%22%0A +var fn = path.join(__dirname, 'queries.yaml');%0A var qs = @@ -886,29 +886,10 @@ ync( -'./core/queries.yaml' +fn , %7Be
d1a48657feb203591ff08e52578af81559d14c9c
Update ispc-mode.js (#2108)
static/modes/ispc-mode.js
static/modes/ispc-mode.js
// Copyright (c) 2017, Matt Godbolt // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. 'use strict'; var jquery = require('jquery'); var monaco = require('monaco-editor'); var cpp = require('monaco-editor/esm/vs/basic-languages/cpp/cpp'); function definition() { var ispc = jquery.extend(true, {}, cpp.language); // deep copy ispc.tokenPostfix = '.ispc'; ispc.keywords.push( 'cbreak', 'ccontinue', 'cdo', 'cfor', 'cif', 'creturn', 'cwhile', 'delete', 'export', 'foreach', 'foreach_active', 'foreach_tiled', 'foreach_unique', 'int16', 'int32', 'int64', 'int8', 'launch', 'new', 'operator', 'programCount', 'programIndex', 'reference', 'soa', 'sync', 'task', 'taskCount', 'taskCount0', 'taskCount1', 'taskCount2', 'taskIndex', 'taskIndex0', 'taskIndex1', 'taskIndex2', 'threadCount', 'threadIndex', 'uniform', 'unmasked', 'varying' ); return ispc; } monaco.languages.register({id: 'ispc'}); monaco.languages.setLanguageConfiguration('ispc', cpp.conf); monaco.languages.setMonarchTokensProvider('ispc', definition());
JavaScript
0
@@ -2117,24 +2117,42 @@ reference',%0A + 'size_t',%0A 'soa @@ -2398,32 +2398,103 @@ 'threadIndex',%0A + 'uint16',%0A 'uint32',%0A 'uint64',%0A 'uint8',%0A 'uniform
ce3710a27ee009afeb00d9f4b4314caddb946f3d
Remove duplicate line and use _.defaults in Interlock constructor
lib/index.es6
lib/index.es6
import * as path from "path"; import * as fs from "fs"; import { watch } from "chokidar"; import {sync as mkdirp} from "mkdirp"; import most from "most"; import compile from "./compile"; import { entries } from "./util"; import loadAst from "./compile/modules/load-ast"; import compileModules from "./compile/modules/compile"; export default function Interlock (options) { const cwd = process.cwd(); options = options || {}; if (!options.emit || !options.emit.length) { throw new Error("Must define at least one bundle."); } // TODO: validate options, or only persist specific values options.context = options.context || cwd; options.outputPath = options.outputPath || path.join(cwd, "dist"); options.extensions = options.extensions || [".js", ".jsx", ".es6"]; options.ns = options.ns || require(path.join(options.root, "./package.json")).name; options.context = options.context || cwd; this.options = options; } Interlock.prototype.build = function () { compile(this.options).then(this._saveBundles); }; Interlock.prototype._saveBundles = function (compilation) { for (let [bundleDest, bundle] of entries(compilation.bundles)) { const bundleOutput = bundle.raw; const outputPath = path.join(compilation.opts.outputPath, bundleDest); mkdirp(path.dirname(outputPath)); fs.writeFileSync(outputPath, bundleOutput); } }; function getRefreshedAsset (compilation, changedFilePath) { const origAsset = compilation.cache.modulesByAbsPath[changedFilePath]; let newAsset = Object.assign({}, origAsset, { rawSource: null, ast: null, requireNodes: null, dependencies: null, hash: null }); return loadAst.call(compilation, newAsset); } Interlock.prototype.watch = function (save=false) { const self = this; let lastCompilation = null; const absPathToModuleHash = Object.create(null); const watcher = watch([], {}); return most.create(add => { function onCompileComplete (compilation) { lastCompilation = compilation; for (let [, bundleObj] of entries(compilation.bundles)) { for (let module of bundleObj.modules || []) { watcher.add(module.path); absPathToModuleHash[module.path] = module.hash; } } if (save) { self._saveBundles(compilation); } // Emit compilation. add({ compilation }); } watcher.on("change", changedFilePath => { for (let modulePath of Object.keys(absPathToModuleHash)) { watcher.unwatch(modulePath); } const refreshedAsset = getRefreshedAsset(lastCompilation, changedFilePath); delete lastCompilation.cache.modulesByAbsPath[changedFilePath]; compileModules.call(lastCompilation, most.from([refreshedAsset])) .reduce((updatedModules, module) => { updatedModules.push(module); return updatedModules; }, []) .then(patchModules => { // Emit patch modules (changed module plus any new dependencies). add({ patchModules, changedFilePath }); compile(lastCompilation.opts).then(onCompileComplete); }); }); compile(this.options).then(onCompileComplete); }); };
JavaScript
0.000001
@@ -147,16 +147,40 @@ %22most%22; +%0Aimport _ from %22lodash%22; %0A%0Aimport @@ -425,35 +425,8 @@ d(); -%0A options = options %7C%7C %7B%7D; %0A%0A @@ -599,52 +599,71 @@ s%0A +this. options -.context = options. + = _.defaults(options %7C%7C %7B%7D, %7B%0A context - %7C%7C +: cwd;%0A opti @@ -662,37 +662,10 @@ ;%0A -options.outputPath = options. + outp @@ -670,19 +670,17 @@ tputPath - %7C%7C +: path.jo @@ -702,37 +702,10 @@ ;%0A -options.extensions = options. + exte @@ -710,19 +710,17 @@ tensions - %7C%7C +: %5B%22.js%22, @@ -743,34 +743,13 @@ ;%0A -options.ns = options.ns %7C%7C + ns: req @@ -808,74 +808,10 @@ ;%0A -options.context = options.context %7C%7C cwd;%0A this.options = options +%7D) ;%0A%7D%0A
d8914285c2a396f0e58331a33e1dfb5a387b5e6e
Update container.js
static/views/container.js
static/views/container.js
define([ 'jquery', 'underscore', 'views/base', 'globals/eventbus', 'bootbox', 'modules/cloudstore', 'ace', 'codemirror' 'add2home', 'css!libs/add2home/add2home.css', 'sha256', 'aes'], function($, _, BaseView, EventBus, bootbox, CloudStore, ace, codemirror) { "use strict"; console.log("ContainerView."); var ContainerView = BaseView.extend({ el: $('#container'), message: undefined, events: { "keyup #password": "passwordsMatch", "keyup #password2": "passwordsMatch", "click #encrypt": "encryptMessage", "click #decrypt": "decryptMessage", "click #message": "refreshMessage", "keyup #message": "refreshMessage", "click #clearMessage": "clearMessage", "click #dbChooseFile": "readFile", "click #dbSaveFile": "saveFile", "click #backToTop": "backToTop", "click #logout": "logout" }, logout: function () { CloudStore.logout(); }, readFile: function () { console.group("readFile"); var promise = CloudStore.readFile(); var message = this.message; promise.done( function( text ) { console.log("read."); $('#message').val( text ) //message.setValue( text ); EventBus.trigger('message:updated'); console.groupEnd(); }); promise.fail( function( ) { console.log("read failed."); console.groupEnd(); }); }, saveFile: function () { console.group("saveFile"); //var promise = CloudStore.saveFile( this.message.getValue() ); var promise = CloudStore.saveFile( $('#message').val() ); promise.done( function( ) { console.log("saved."); console.groupEnd(); }); promise.fail( function( ) { console.log("save failed."); console.groupEnd(); }); }, encrypt: function (text, pass) { //console.log('pass:' + pass + ' encrypt IN:' + text); var key = Sha256.hash(pass); var encrypted = Aes.Ctr.encrypt(text, key, 256); //console.log('encrypt OUT:' + encrypted); return encrypted; }, decrypt: function (text, pass) { //console.log('pass:' + pass + ' decrypt IN:' + text); var key = Sha256.hash(pass); var decrypted = Aes.Ctr.decrypt(text, key, 256); //console.log('decrypt OUT:' + decrypted); return decrypted; }, encryptMessage: function() { console.group("encryptMessage()"); if ( this.passwordsMatch() ) { $('#message').val( this.encrypt( $('#message').val(), $('#password').val() ) ); //this.message.setValue( this.encrypt( this.message.getValue(), $('#password').val() ) ); EventBus.trigger('message:updated'); } console.groupEnd(); }, decryptMessage: function () { console.group("decryptMessage()"); if( this.passwordsMatch() ) { $('#message').val( this.decrypt( $('#message').val(), $('#password').val() ) ); //this.message.setValue( this.decrypt( this.message.getValue(), $('#password').val() ) ); EventBus.trigger('message:updated'); } console.groupEnd(); }, refreshMessage: function () { console.log("refreshMessage()"); var m = $('#message'); $("#count").text( m.val().length ); m.autosize({ append: '\n'}); //$("#count").text( this.message.getValue().length ); //this.message.renderer.adjustWrapLimit() //this.message.resize(); }, clearMessage: function () { var message = this.message; bootbox.confirm("Clear message?", function(result) { if(result == true) { $('#message').val(''); $('#message').trigger('change'); //message.setValue(''); EventBus.trigger('message:updated'); } }); }, passwordsMatch: function () { console.log("passwordsMatch()"); if( $('#password').val() == $('#password2').val() ) { $('#passGroup').removeClass("has-error"); $('#passwordError').addClass("hidden"); return true; } $('#passGroup').addClass("has-error"); $('#passwordError').removeClass("hidden"); this.backToTop(); return false; }, backToTop: function () { $("html, body").animate({ scrollTop: 0 }, "slow"); }, initialize: function(options) { console.log("ContainerView()"); BaseView.prototype.initialize.call(this, options); //this.message = window.ace.edit("message"); //this.message.setOptions({ // minLines: 10, // maxLines: 1000 //}); var editor = CodeMirror.fromTextArea(document.getElementById("message"), { lineNumbers: true, styleActiveLine: true, matchBrackets: true }); this.refreshMessage(); EventBus.on('message:updated', function(){ console.log('message:updated'); //$('#message').select(); this.refreshMessage(); }, this); }, destroy: function() { EventBus.off('message:updated'); BaseView.prototype.destroy.call(this); } }); return ContainerView; });
JavaScript
0.000001
@@ -114,16 +114,18 @@ emirror' +, %0A 'add2
a6bdbd8884b31d74404e46ac687059fe10ed5f41
fix typo
static/flow/util/message-executor.js
static/flow/util/message-executor.js
// // Send a websocket message to a controller // and handle a response. // // @param config - A json object containing configuration info. // // The config can contain the folowing keys: // // message_type - the message type to send. // message_params - the params to send with the // outgoing message. // target_folder - the destination controller to send // the message to. // response_type - (optional) for messages which // do not respond with <message_type>_response, specify // the name of the response message type. // src_folder - (optional) only handle responses from // the src_folder controller. // response_func - function to call when response is received. // This function will be passed a timestamp and // a params json object. This has the form // function(timestamp, params) // remove_handler - (optional) If true, remove the handler // after handling the response. If false, do not remove // the handler after handling the response. The default is // true. // var MessageExecutor = function(config) { this.message_type = config.message_type; this.message_params = config.message_params; this.target_folder = config.target_folder; this.response_type = this.message_type + "_response"; this.src_folder = null; this.response_func = config.response_func; this.remove_handler = true; var _this = this; // // Add optional config parameters. // if(config.response_type) { this.response_type = config.response_type; } if(config.src_folder) { this.src_folder = config.src_folder; } if('remove_handler' in config) { this.remove_handler = config.remove_handler; } else { this.remove_handler = true; } // // Send the message and set the response handler. // this.execute = function() { console.log("[DEBUG] MessageExecutor execute()"); console.log("[DEBUG] MessageExecutor call addMessageHandler", this.response_type ); // // Some kind of bug here does not allow multiple message types // to be handled simultaneously. // removeMessageHandlers(); addMessageHandler( this.response_type, function(timestamp, params) { console.log("[DEBUG] MessageExecutor handleResponse()", _this.response_type, _this.response_func, params); if( _this.src_folder != null && _this.src_folder != params.src_folder) { console.log("[DEBUG] MessageExecutor ignoring message from " + params.src_folder); return; } if(_this.remove_handler) { removeMessageHandler(_this.response_type); } _this.response_func(timestamp, params); }); console.log("[DEBUG] MessageExecutor setting subscription and " + "target folder: " + this.target_folder); subscribeToFolder(this.target_folder); setTargetFolder(this.target_folder); if(g_webSocketInited) { console.log("[INFO] MessageExecutor sending message on connected websocket. " + this.message_type + " " + this.message_params); sendSubscriptions(); sendMessage(this.message_type, this.message_params); return; } connectWebSocket(function() { console.log("[INFO] MessageExecutor connecting websocket."); sendMessage(_this.message_type, _this.message_params); }); } return this; }
JavaScript
0.999991
@@ -2979,32 +2979,34 @@ +// console.log(%22%5BDE @@ -3049,32 +3049,34 @@ +// mes
99fe696986d58636d5826a5d3b88f4d6caf6151f
update to closure compiler 20180506
make/Settings.js
make/Settings.js
"use strict"; /* Configuration settings. * * These settings can be overridden from the command line, and will * affect various aspects of the build process. */ var fs = require("fs"); var Q = require("q"); var prevSettingsFile = "build/prev-settings.json"; module.exports = function Settings() { var configSettings = { build: "debug", closure_urlbase: "http://dl.google.com/closure-compiler", closure_language: "ECMASCRIPT5_STRICT", closure_level: "SIMPLE", closure_version: "20160822", verbose: "true", logprefix: "true", c3d_closure_level: "ADVANCED", c3d_closure_warnings: "VERBOSE", cc_closure_level: "ADVANCED", cc_closure_warnings: "DEFAULT", cgl_closure_level: "ADVANCED", cgl_closure_warnings: "VERBOSE", qh3d_closure_warnings: "DEFAULT", qh3d_closure_level: "SIMPLE", gwt_version: "2.7.0", gwt_urlbase: "http://storage.googleapis.com/gwt-releases", gwt_args: "", }; var perTaskSettings = {}; this.get = function(key) { return configSettings[key]; }; this.set = function(key, val) { configSettings[key] = val; }; this.prevSetting = function(taskName, key) { var task = perTaskSettings[taskName]; return task ? task[key] : undefined; }; this.store = function() { var json = JSON.stringify(perTaskSettings); // Can't use qfs: https://github.com/kriskowal/q-io/issues/149 //return qfs.write(prevSettingsFile, json); return Q.nfcall(fs.writeFile, prevSettingsFile, json); }; this.load = function() { var json = fs.readFileSync(prevSettingsFile, "utf-8"); perTaskSettings = JSON.parse(json) || {}; }; this.remember = function(taskName, values) { if (Object.keys(values).length !== 0) perTaskSettings[taskName] = values; }; this.forget = function(taskName) { delete perTaskSettings[taskName]; }; };
JavaScript
0
@@ -529,13 +529,13 @@ %22201 -60822 +80506 %22,%0A
96cdb0862839bfa3c4d3942a37eab7e35537551a
exclude *.Tests.* from standard cover-dotnet
cover-dotnet.js
cover-dotnet.js
var gulp = requireModule('gulp-with-help'), dotNetCover = requireModule('gulp-dotnetcover'); gulp.task('cover-dotnet', 'Runs tests from projects matching *.Tests with DotCover coverage', function() { return gulp.src('**/*.Tests.dll') .pipe(dotNetCover({ debug: false, architecture: 'x86', exclude: ['FluentMigrator.*', 'PeanutButter.*', 'AutoMapper', 'AutoMapper.*', 'WindsorTestHelpers.*', 'MvcTestHelpers', 'TestUtils'] })); });
JavaScript
0
@@ -653,16 +653,57 @@ stUtils' +,%0A '*.Tests.*' %5D%0A @@ -718,9 +718,8 @@ ));%0A%7D);%0A -%0A
9f44c0fd49dc993b59a3dc3274f2d658eeecd865
add system tests
test/backend/client_instantiator.js
test/backend/client_instantiator.js
'use strict'; /** * This sets up the testClient and lodash. * * The testClient's endpoint is configured to point to cloudify.localhost.com. * The manager is expected to have at least one blueprint called 'HelloWorld' installed. * * Usage: * require('../client_instantiator'); */ if (typeof(window) !== 'undefined') { window.testClient = new TestClient({endpoint: 'http://cloudify.localhost.com'}); window._ = require('lodash'); window.depName = 'HelloWorld-' + Date.now(); } else if (!!global) { global.testClient = new TestClient({endpoint: 'http://cloudify.localhost.com'}); global._ = require('lodash'); global.depName = 'HelloWorld-' + Date.now(); }
JavaScript
0
@@ -8,16 +8,306 @@ rict';%0A%0A +var conf = require('../../conf/dev/meConf.json');%0A%0A/**%0A * conf/dev/meConf.json holds the connection configuration:%0A *%0A * %7B%0A %22endpoint%22: %22http://cloudify.localhost.com%22,%0A %22cloudifyAuth%22: %7B%0A %22user%22: %22__user__%22,%0A %22pass%22: %22__pass__%22%0A %7D%0A %7D%0A *%0A */%0A%0A%0A /**%0A * T @@ -657,51 +657,12 @@ ent( -%7Bendpoint: 'http://cloudify.localhost.com'%7D +conf );%0A @@ -809,51 +809,12 @@ ent( -%7Bendpoint: 'http://cloudify.localhost.com'%7D +conf );%0A
eb366a8668330a3603134e45ff023c184280e084
Update abilities.js
mods/usermons/abilities.js
mods/usermons/abilities.js
exports.BattleAbilities = { "drunkenfist": { desc: "If a contact move knocks out this Pokemon, the opponent receives damage equal to one-fourth of its max HP.", shortDesc: "If this Pokemon is KOed with a contact move, that move's user loses 1/4 its max HP.", id: "drunkenfist", name: "Drunken Fist", onStart: function (pokemon) { this.add('-message', pokemon.name + " is drunk!"); pokemon.addVolatile('confusion'); self: { boosts: { spa: 2, atk: 2 }, } }, rating: 3, num: 800 }, "objection": { desc: "This Pokémon avoids all Rock-type attacks and hazards when switching in.", shortDesc: "On switch-in, this Pokemon avoids all Rock-type attacks and Stealth Rock.", onImmunity: function(type, target) { if (type === 'Normal' && !target.activeTurns) { return false; this.add('-message', pokemon.name + " objectified the normal type move!"); } }, id: "objection", name: "OBJECTION", rating: 3.5, num: 801 }, } };
JavaScript
0.000001
@@ -314,12 +314,15 @@ %09onS -tart +witchIn : fu
5a501ae68cdbb7aaf882e51873439fa2dc7c6251
add test to PageContent
test/components/test_pagecontent.js
test/components/test_pagecontent.js
import React from 'react'; import { shallow, mount } from 'enzyme'; import sinon from 'sinon'; import assert from 'power-assert'; import PageContent from '../../components/pagecontent.cjsx'; describe('<PageContent>', () => { it('should render one <div>', () => { const wrapper = shallow(<PageContent />); assert.equal(wrapper.find('div').length, 1); assert.equal(wrapper.text(), ""); }); it('renders the content', () => { const wrapper = shallow(<PageContent content="content text" />); assert.equal(wrapper.text(), "content text"); }); it('should call onContentChange callback on input', () => { const onContentChange = sinon.spy(); const wrapper = mount(<PageContent content="content text" onContentChange={onContentChange} />); wrapper.find('div').simulate('input'); assert.equal(onContentChange.calledOnce, true); assert.equal(onContentChange.args[0], "content text"); }); });
JavaScript
0
@@ -662,16 +662,37 @@ non.spy( +text =%3E %7Breturn text%7D );%0A c @@ -937,22 +937,89 @@ ent text%22);%0A + assert.equal(onContentChange.returnValues%5B0%5D, %22content text%22);%0A %7D);%0A%7D);%0A
b23d7d1c349f988379000f5d180e9ece02b821a9
remove logs
src/routes/Post/reducers/Comments.js
src/routes/Post/reducers/Comments.js
import { combineReducers } from 'redux'; import * as actionTypes from '../constants/index'; // const BY_ID_HANDLER = { // [actionTypes.RECEIVED_COMMENTS]: (state, action) => { // return Object.assign({}, // state, // action.payload.comments.reduce((obj, comment) => { // obj[comment.id] = comment // return obj // }, {}) // ) // }, // } // // export function byId (state = {}, action) { // const handler = BY_ID_HANDLER[action.type]; // // return handler ? handler(state, action) : state; // } const ALL_COMMENTS_HANDLER = { [actionTypes.RECEIVED_COMMENTS]: (state, action) => { const obj = {}; obj[action.payload.postId] = action.payload.comments; return Object.assign( {}, state, obj ) } } export function allComments( state = {}, action) { const handler = ALL_COMMENTS_HANDLER[action.type]; console.log('handles', handler) console.log('state', state) return handler ? handler(state, action) : state; } export default combineReducers({ all: allComments, })
JavaScript
0.000001
@@ -885,67 +885,8 @@ e%5D;%0A -console.log('handles', handler)%0Aconsole.log('state', state) %0A r
9846c5f46fc0ca7ffba0d1c10d978a23bd2264ba
Make sure plugin-list is loaded
web/war/src/main/webapp/js/admin/admin.js
web/war/src/main/webapp/js/admin/admin.js
define([ 'flight/lib/component', 'configuration/admin/plugin', 'hbs!./template', 'tpl!util/alert', 'd3' ], function( defineComponent, lumifyAdminPlugins, template, alertTemplate, d3) { 'use strict'; return defineComponent(AdminList); function AdminList() { this.defaultAttrs({ listSelector: '.admin-list', pluginItemSelector: '.admin-list > li a', formSelector: '.admin-form' }); this.after('initialize', function() { this.on(document, 'showAdminPlugin', this.onShowAdminPlugin); this.on('click', { pluginItemSelector: this.onClickPluginItem }); this.$node.html(template({})); this.update(); }); this.onClickPluginItem = function(event) { event.preventDefault(); this.trigger('showAdminPlugin', $(event.target).closest('li').data('component')); }; this.onShowAdminPlugin = function(event, data) { var self = this; // TODO: toggleMenubar display if not visible this.$node.find('li').filter(function() { return _.isEqual($(this).data('component'), data); }).addClass('active').siblings('.active').removeClass('active'); var container = this.select('formSelector'), form = container.resizable({ handles: 'e', minWidth: 120, maxWidth: 500, resize: function() { self.trigger(document, 'paneResized'); } }).show().find('.content'); component = _.findWhere(lumifyAdminPlugins.ALL_COMPONENTS, data); form.teardownAllComponents(); component.Component.attachTo(form); this.trigger(document, 'paneResized'); }; this.update = function() { var self = this, items = [], lastSection; _.sortBy(lumifyAdminPlugins.ALL_COMPONENTS, function(component) { return component.section.toLowerCase() + component.name.toLowerCase(); }).forEach(function(component) { if (lastSection !== component.section) { items.push(component.section); lastSection = component.section; } items.push(component); }); d3.select(this.select('listSelector').get(0)) .selectAll('li') .data(items) .call(function() { this.enter().append('li') .attr('class', function(component) { if (_.isString(component)) { return 'nav-header'; } }).each(function(component) { if (!_.isString(component)) { d3.select(this).append('a').attr('href', '#'); } }); this.each(function(component) { if (_.isString(component)) { this.textContent = component; return; } d3.select(this) .attr('data-component', JSON.stringify(_.pick(component, 'section', 'name'))) .select('a') .call(function() { this.append('div') .attr('class', 'nav-list-title') .text(component.name) this.append('div') .attr('class', 'nav-list-subtitle') .attr('title', component.subtitle) .text(component.subtitle) }); }); }) .exit().remove(); if (items.length === 0) { this.$node.prepend(alertTemplate({ warning: i18n('admin.plugins.none_available') })); } else { this.$node.children('.alert').remove(); } } } });
JavaScript
0.000001
@@ -116,16 +116,37 @@ 'd3' +,%0A './plugin-list' %0A%5D, func
8f27ad2b4ca7a6e90f59f19ab369517424f6f879
Fix typo margin padding
src/scripts/directives/fa-surface.js
src/scripts/directives/fa-surface.js
/** * @ngdoc directive * @name faSurface * @module famous.angular * @restrict EA * @description * This directive is used to create general Famo.us surfaces, which are the * leaf nodes of the scene graph. The content inside * surfaces is what gets rendered to the screen. * This is where you can create form elements, attach * images, or output raw text content with one-way databinding {{}}. * You can include entire complex HTML snippets inside a faSurface, including * ngIncludes or custom (vanilla Angular) directives. * * @usage * ```html * <fa-surface> * Here's some data-bound content {{myScopeVariable}} * </fa-surface> * ``` */ angular.module('famous.angular') .config(['$provide', '$animateProvider', function($provide, $animateProvider) { // Hook into the animation system to emit ng-class syncers to surfaces $provide.decorator('$animate', ['$delegate', '$$asyncCallback', '$famous', function($delegate, $$asyncCallback, $famous) { var Surface = $famous['famous/core/Surface']; /** * Check if the element selected has an isolate renderNode that accepts classes. * @param {Array} element - derived element * @return {boolean} */ function isClassable(element) { return $famous.getIsolate(element.scope()).renderNode instanceof Surface; } // Fork $animateProvider methods that update class lists with ng-class // in the most efficient way we can. Delegate directly to irrelevant methods // (enter, leave, move). These method forks only get invoked when: // 1. The element has a directive like ng-class that is updating classes // 2. The element is an fa-element with an in-scope isolate // 3. The isolate's renderNode is some kind of Surface return { enabled: $delegate.enabled, enter: $delegate.enter, leave: $delegate.leave, move: $delegate.move, addClass: function(element, className, done) { $delegate.addClass(element, className, done); if (isClassable(element)) { $famous.getIsolate(element.scope()).renderNode.addClass(className); } }, removeClass: function(element, className, done) { $delegate.removeClass(element, className, done); if (isClassable(element)) { $famous.getIsolate(element.scope()).renderNode.removeClass(className); } }, setClass: function(element, add, remove, done) { $delegate.setClass(element, add, remove, done); if (isClassable(element)) { var surface = $famous.getIsolate(element.scope()).renderNode; // There isn't a good way to delegate down to Surface.setClasses // because Angular has already negotiated the list of items to add // and items to remove. Manually loop through both lists. angular.forEach(add.split(' '), function(className) { surface.addClass(className); }); angular.forEach(remove.split(' '), function(className) { surface.removeClass(className); }); } } } }]); }]) .directive('faSurface', ['$famous', '$famousDecorator', '$interpolate', '$controller', '$compile', function ($famous, $famousDecorator, $interpolate, $controller, $compile) { return { scope: true, transclude: true, template: '<div class="fa-surface"></div>', restrict: 'EA', compile: function(tElem, tAttrs, transclude){ return { pre: function(scope, element, attrs){ var isolate = $famousDecorator.ensureIsolate(scope); var Surface = $famous['famous/core/Surface']; var Transform = $famous['famous/core/Transform'] var EventHandler = $famous['famous/core/EventHandler']; //update properties //TODO: is this going to be a bottleneck? scope.$watch( function(){ return isolate.getProperties() }, function(){ if(isolate.renderNode) isolate.renderNode.setProperties(isolate.getProperties()); }, true ) isolate.getProperties = function(){ return { backgroundColor: scope.$eval(attrs.faBackgroundColor), color: scope.$eval(attrs.faColor), margin: scope.$eval(attrs.faPadding), padding: scope.$eval(attrs.faMargin) }; }; isolate.renderNode = new Surface({ size: scope.$eval(attrs.faSize), class: scope.$eval(attrs.class), properties: isolate.getProperties() }); if (attrs.class) { isolate.renderNode.setClasses(attrs['class'].split(' ')); } }, post: function(scope, element, attrs){ var isolate = $famousDecorator.ensureIsolate(scope); var updateContent = function() { isolate.renderNode.setContent(element[0].querySelector('div.fa-surface')); }; updateContent(); //boilerplate transclude(scope, function(clone) { angular.element(element[0].querySelectorAll('div.fa-surface')).append(clone); }); scope.$emit('registerChild', isolate); } } } }; }]);
JavaScript
0.000298
@@ -4517,15 +4517,14 @@ s.fa -Padd +Marg in -g ),%0A @@ -4567,22 +4567,23 @@ attrs.fa -Marg +Padd in +g )%0A
8fa4ec3b7d2ba0145b16e6e2a1c8f9e7366e96de
Fix date issue on edit
webapp/client/app/transforms/timestamp.js
webapp/client/app/transforms/timestamp.js
import DS from 'ember-data'; import Firebase from 'firebase'; export default DS.DateTransform.extend({ serialize: function(date) { if (date === Firebase.ServerValue.TIMESTAMP){ return date; } return this._super(date); } });
JavaScript
0.000001
@@ -231,31 +231,62 @@ -return this._super(date +// to timestamp%0A return new Date(date).getTime( );%0A
b37014f5dc73c0e1a2c10447aa37eceb56f60e69
Remove the third param when new Loader
lib/loader.js
lib/loader.js
const getConfigFn = require('think-config').getConfigFn; const Logger = require('think-logger3'); const Loader = require('think-loader'); const path = require('path'); const helper = require('think-helper'); const Crontab = require('think-crontab'); require('./think.js'); // ThinkJS root path const thinkPath = path.join(__dirname, '..'); /** * think loader * @param {Object} options */ const thinkLoader = class { constructor(options = {}){ this.options = options; } /** * init path */ initPath(){ think.ROOT_PATH = this.options.ROOT_PATH; think.APP_PATH = this.options.APP_PATH; //set env if(this.options.env){ think.app.env = this.options.env; } //set proxy if(this.options.proxy){ think.app.proxy = this.options.proxy; } } /** * load app data */ loadData(){ //add data to koa application think.app.modules = think.loader.modules; think.app.controllers = think.loader.loadController(); think.app.logics = think.loader.loadLogic(); think.app.models = think.loader.loadModel(); think.app.services = think.loader.loadService(); think.app.routers = think.loader.loadRouter(); think.app.validators = think.loader.loadValidator(); } /** * load middleware */ loadMiddleware(){ const middlewares = think.loader.loadMiddleware(think.app); middlewares.forEach(middleware => { think.app.use(middleware); }); } /** * load extend */ loadExtend(){ let exts = think.loader.loadExtend(); const list = [ ['think', think], ['application', think.app], ['context', think.app.context], ['request', think.app.request], ['response', think.app.response], ['controller', think.Controller.prototype], ['logic', think.Logic.prototype] ]; list.forEach(item => { if(!exts[item[0]]) return; Loader.extend(item[1], exts[item[0]]); }); } /** * load crontab */ loadCrontab(){ const crontab = think.loader.loadCrontab(); const instance = new Crontab(crontab, think.app); instance.runTask(); } /** * load all data */ loadAll(type){ this.initPath(); think.loader = new Loader(think.APP_PATH, thinkPath, think.app); think.config = getConfigFn(think.loader.loadConfig(think.app.env), think.loader.modules.length > 0); think.logger = new Logger(helper.parseAdapterConfig(think.config('logger')), true); if(type !== 'master'){ this.loadExtend(); this.loadData(); this.loadMiddleware(); if(!think.isCli){ this.loadCrontab(); } } think.loader.loadBootstrap(type); } } module.exports = thinkLoader;
JavaScript
0.000014
@@ -2234,27 +2234,16 @@ hinkPath -, think.app );%0A t @@ -2675,8 +2675,9 @@ kLoader; +%0A
8fdca71a37574935971c96e00b16817423c579b6
Add 'timestamp' configuration to logger.
lib/logger.js
lib/logger.js
module.exports = function(sails) { /** * Module dependencies. */ var _ = require('lodash'), util = require('./util'); /** * Expose Logger */ return Logger; /** * Logger encapsulates winston, a logging library, * to manage logging to different adapters */ function Logger(config) { var self = this; // Save config in instance and extend w/ defaults this.config = config = _.defaults(config || {}, { maxSize: 10000000, maxFiles: 10, json: false, colorize: true, level: 'info' }); var winston = require('winston'); // Available transports var transports = [ new(winston.transports.Console)({ level: 'debug', colorize: config.colorize }) ]; // If filePath option is set, ALSO write log output to a flat file if (!_.isUndefined(config.filePath)) { transports.push( new(winston.transports.File)({ filename: config.filePath, maxsize: config.maxSize, maxFiles: config.maxFiles, level: 'verbose', json: config.json, colorize: config.colorize })); } var logLevels = { verbose: 5, info: 4, debug: 3, warn: 2, error: 1, silent: 0 }; // if adapter option is set, ALSO write log output to an adapter if (!_.isUndefined(config.adapters)) { _.each(config.adapters, function(val, transport) { if (typeof val.module !== 'undefined') { // The winston module MUST be exported to a variable of same name var module = require(val.module)[transport]; // Make sure it was exported correctly if (module) { transports.push( new(module)(val) ); } } }); } // Instantiate winston var logger = new(winston.Logger)({ transports: transports }); // Basic log usage var CaptainsLog = log('debug'); CaptainsLog.log = log('debug'); CaptainsLog.debug = log('debug'); CaptainsLog.verbose = log('verbose'); CaptainsLog.info = log('info'); CaptainsLog.warn = log('warn'); CaptainsLog.error = log('error'); // ASCII art and easter eggs CaptainsLog.ship = drawShip(CaptainsLog); // Export logger object return CaptainsLog; // Level-aware log function function log(level) { return function() { // Compose string of all the arguments var str = []; _.each(arguments, function(arg) { if (typeof arg === 'object') { if (arg instanceof Error) { str.push(arg.stack); return; } str.push(util.inspect(arg)); return; } if (typeof arg === 'function') { str.push(arg.valueOf()); return; } str.push(arg); }); if (logLevels[level] <= logLevels[self.config.level]) { logger[level](str.join(' ')); } }; } } /** Draw an ASCII image of a ship I~ |\ /|.\ / || \ ,' |' \ .-'.-==|/_--' `--'-------' */ function drawShip(log) { log = log || console.log; return function() { log.info(''); log.info(''); log.info(' Sails.js <|'); log.info(' v'+sails.version+' |\\'); log.info(' /|.\\'); log.info(' / || \\'); log.info(' ,\' |\' \\'); log.info(' .-\'.-==|/_--\''); log.info(' `--\'-------\' '); log.info(' __---___--___---___--___---___--___'); log.info(' ____---___--___---___--___---___--___-__'); log.info(''); }; // <{ // / |\ // / | \ // / ( | \ // { ___|___\ // _____|____ // \__\__ /__/ // return function() { // log(''); // log(''); // log(''); // log(' Sails.js <|'); // log(' v'+sails.version+' |\\'); // log(' /|.\\'); // log(' / || \\'); // log(' ,\' |\' \\'); // log(' .-\'.-==|/_--\''); // log(' `--\'-------\' '); // log(' __---___--___---___--___---___--___'); // log(' ____---___--___---___--___---___--___-__'); // log(''); // }; // return function() { // log(''); // log(''); // log(''); // log(' Sails.js <|'); // log(' v' + sails.version + ' |'); // log(' \\\\____//'); // log(' __---___--___---___--___---___--___'); // log(' ____---___--___---___--___---___--___-__'); // }; } };
JavaScript
0
@@ -637,16 +637,46 @@ : 'info' +,%0A timestamp: false %0A @@ -894,32 +894,77 @@ config.colorize +,%0A timestamp: config.timestamp %0A %7D)%0A @@ -1410,16 +1410,61 @@ colorize +,%0A timestamp: config.timestamp %0A
c56f1f8a5288cacecc4f7c8ce05738eca1681307
Add some helper methods for realtime testing
test/functional/realtime-session.js
test/functional/realtime-session.js
import SocketIO from 'socket.io-client'; const eventTimeout = 2000; const silenceTimeout = 500; /** * Session is a helper class * for the realtime testing */ export default class Session { socket = null; name = ''; static create(port, name = '') { const options = { transports: ['websocket'], 'force new connection': true, }; return new Promise((resolve, reject) => { const socket = SocketIO.connect(`http://localhost:${port}/`, options); socket.on('error', reject); socket.on('connect_error', reject); socket.on('connect', () => resolve(new Session(socket, name))); }); } constructor(socket, name = '') { this.socket = socket; this.name = name; } send(event, data) { this.socket.emit(event, data); } disconnect() { this.socket.disconnect(); } receive(event) { return new Promise((resolve, reject) => { const success = (data) => { this.socket.off(event, success); clearTimeout(timer); resolve(data); }; this.socket.on(event, success); const timer = setTimeout(() => reject(new Error(`${this.name ? `${this.name}: ` : ''}Expecting '${event}' event, got timeout`)), eventTimeout); }); } notReceive(event) { return new Promise((resolve, reject) => { const fail = () => { this.socket.off(event, fail); clearTimeout(timer); reject(new Error(`${this.name ? `${this.name}: ` : ''}Expecting silence, got '${event}' event`)); }; this.socket.on(event, fail); const timer = setTimeout(() => resolve(null), silenceTimeout); }); } }
JavaScript
0.000001
@@ -1595,11 +1595,260 @@ %7D);%0A %7D +%0A%0A async receiveWhile(event, ...promises) %7B%0A const %5Bresult%5D = await Promise.all(%5Bthis.receive(event), ...promises%5D);%0A return result;%0A %7D%0A%0A async notReceiveWhile(event, ...promises) %7B%0A await Promise.all(%5Bthis.notReceive(event), ...promises%5D);%0A %7D %0A%7D%0A
6ae7c7d15f0aef738b57da693d63e8da483a975a
Add function to handle AJAX error
assets/js/src/market.js
assets/js/src/market.js
/* global $ pluginsTable */ 'use strict' let pluginsTable $(document).ready(() => { $('.box-body').css( 'min-height', $('.content-wrapper').height() - $('.content-header').outerHeight() - 120 ) pluginsTable = $('#plugin-table').DataTable({ language: trans('vendor.datatables'), scrollX: true, autoWidth: false, processing: true, ordering: false, serverSide: false, //未知原因,开了这个会有问题 ajax: { url: '/admin/plugins-market/data', dataSrc: '' }, columnDefs: [ { targets: 0, title: trans('market.market.title'), data: 'title' }, { targets: 1, title: trans('market.market.description'), data: 'description', width: '40%' }, { targets: 2, title: trans('market.market.author'), data: 'author', width: '10%' }, { targets: 3, title: trans('market.market.version'), data: 'version', width: '9%', render (data, type, row, meta) { let options = '' for (let i = data.length - 1; i >= 0; i--) { options += `<option>${data[i]}</option>` } return ( `<select id="plugin-${ row.name }-vers" class="form-control">${ options }</select>` ) } }, { targets: 4, title: trans('market.market.size'), data: 'size', width: '8%' }, { targets: 5, title: trans('market.market.operations'), data: 'brief', width: '20%', render (data, type, row, meta) { let downloadButtonClass = 'btn-primary' let downloadButtonHint = '' switch (row.versionStatus) { case 'preview': downloadButtonClass = 'btn-warning' downloadButtonHint = trans('market.market.versionPre') break case 'new': downloadButtonClass = 'btn-success' downloadButtonHint = trans('market.market.versionNew') break default: break } const downloadButton = `<input type="button" id="plugin-${ row.name }" class="btn ${ downloadButtonClass } btn-sm" title="${ downloadButtonHint }"` + ` onclick="readyToDownload('${ row.name }','${ row.title }','${ row.versionStatus }');" value="${ trans('market.market.download') }">` const briefButton = `<a class="btn btn-default btn-sm" href="${ data }" target="_blank" title="${ trans('market.market.briefHint') }">${ trans('market.market.viewBrief') }</a>` return downloadButton + briefButton } } ] }) }) function readyToDownload (pluginName, pluginTitle, versionStatus) { if (versionStatus === 'preview') { swal({ title: trans('market.preview.title'), text: trans('market.preview.text'), type: 'warning', showCancelButton: true, confirmButtonText: trans('market.preview.confirmButton'), cancelButtonText: trans('market.preview.cancelButton') }).then(() => download(pluginName, pluginTitle)) } else { const version = $(`select#plugin-${pluginName}-vers`).val() return download(pluginName, pluginTitle, version) } } function download (pluginName, pluginTitle, version) { $(`input#plugin-${pluginName}`).attr({ disabled: true }) $(`input#plugin-${pluginName}`).val(trans('market.downloading')) toastr.info( trans('market.readyToDownload', { 'plugin-name': pluginTitle }) ) $.post( '/admin/plugins-market/download', { name: pluginName, version }, data => { if (data.code === undefined) { toastr.error(trans('market.error.unknown')) } else { switch (data.code) { case -1: toastr.error( trans('market.failedDownload', { message: trans('market.error.requestPermission') }) ) break case 0: toastr.success( trans('market.completeDownload', { 'plugin-name': pluginTitle }) ) if ($(`input#plugin-${pluginName}`).hasClass('btn-success')) { $(`input#plugin-${pluginName}`) .removeClass('btn-success') .addClass('btn-primary') } if ($(`input#plugin-${pluginName}`).hasClass('btn-warning')) { $(`input#plugin-${pluginName}`) .removeClass('btn-warning') .addClass('btn-primary') } break case 1: toastr.error( trans('market.failedDownload', { message: trans('market.error.writePermission') }) ) break case 2: toastr.error( trans('market.failedDownload', { message: trans('market.error.connection') }) ) break case 3: toastr.error( trans('market.failedDownload', { message: trans('market.error.download') }) ) break case 4: toastr.error( trans('market.failedDownload', { message: trans('market.error.unzip') }) ) break default: toastr.error(trans('market.error.unknown')) break } } $(`input#plugin-${pluginName}`).attr({ disabled: false }) $(`input#plugin-${pluginName}`).val(trans('market.download')) } ) } window.readyToDownload = readyToDownload
JavaScript
0.000001
@@ -3902,17 +3902,41 @@ $. -post(%0A +ajax(%7B%0A type: 'POST',%0A url: '/a @@ -3969,16 +3969,22 @@ ad',%0A + data: %7B%0A @@ -4031,15 +4031,22 @@ +success ( data - =%3E +) %7B%0A @@ -6062,19 +6062,154 @@ ))%0A %7D +, %0A + error () %7B%0A toastr.error(trans('market.error.unknown'))%0A $(%60input#plugin-$%7BpluginName%7D%60).attr('disabled', false)%0A %7D%0A %7D )%0A%7D%0A%0Awin
a881a11c00ba7e30901dd4fe020535a800fd763e
fix openActive #2
jquery.treemenu.js
jquery.treemenu.js
/* treeMenu - jQuery plugin version: 0.4 Copyright 2014 Stepan Krapivin */ (function($){ $.fn.openActive = function(activeSel) { activeSel = activeSel || ".active"; var c = this.attr("class"); this.find(activeSel).each(function(){ var el = $(this).parent(); while (el.attr("class") !== c) { if(el.prop("tagName") === 'UL') { el.show(); } else if (el.prop("tagName") === 'LI') { el.removeClass('tree-closed'); el.addClass("tree-opened"); } el = el.parent(); } }); return this; } $.fn.treemenu = function(options) { options = options || {}; options.delay = options.delay || 0; options.openActive = options.openActive || false; options.closeOther = options.closeOther || false; options.activeSelector = options.activeSelector || ""; this.addClass("treemenu"); this.find("> li").each(function() { e = $(this); var subtree = e.find('> ul'); var button = e.find('span').eq(0).addClass('toggler'); if( button.length == 0) { var button = $('<span>'); button.addClass('toggler'); e.prepend(button); } else { button.addClass('toggler'); } if(subtree.length > 0) { subtree.hide(); e.addClass('tree-closed'); e.find(button).click(function() { var li = $(this).parent('li'); if (options.closeOther && li.hasClass('tree-closed')) { var siblings = li.parent('ul').find("li"); siblings.removeClass("tree-opened"); siblings.addClass("tree-closed"); siblings.removeClass(options.activeSelector); siblings.find('> ul').slideUp(options.delay); } li.find('> ul').slideToggle(options.delay); li.toggleClass('tree-opened'); li.toggleClass('tree-closed'); li.toggleClass(options.activeSelector); }); $(this).find('> ul').treemenu(options); } else { $(this).addClass('tree-empty'); } }); if (options.openActive) { this.openActive(options.activeSelector); } return this; } })(jQuery);
JavaScript
0.000004
@@ -340,24 +340,64 @@ %22) !== c) %7B%0A + el.find('%3E ul').show();%0A @@ -614,32 +614,63 @@ %22tree-opened%22);%0A + el.show();%0A
5237fa5d45837be981fe1acab969516ed668cd98
remove deprecated cloneWithProps in favor of React.cloneElement
modules/components/Menu.js
modules/components/Menu.js
var React = require('react/addons'); var Immutable = require('immutable'); var cx = require("classnames"); var cloneWithProps = React.addons.cloneWithProps; var { object, func, instanceOf } = React.PropTypes; var Menu = React.createClass({ propTypes: { content: instanceOf(Immutable.Map), selection: object.isRequired, onChange: func }, getDefaultProps() { return { onChange: Function.prototype }; }, getInitialState() { return { inputMode: false }; }, componentDidUpdate() { if (!this.state.inputMode) { return; } setTimeout( () => { React.findDOMNode(this.refs.linkInput).focus(); }, 1); }, // switch to allow input if button needs a value // create a snapshot of the selection so we can restore it if they close handleSetValue(obj, ref) { this.selSnapshot = this.props.selection; this.valueButton = this.refs[ref]; this.setState({inputMode: true}); }, // handle typing in input handleOnKeyUp(e) { e.stopPropagation(); }, // handle enter key for input handleOnKeyDown(e) { var escapeKey = 27; if (e.keyCode === escapeKey) { this.handleCancelInput(); } var returnKey = 13; if (e.keyCode !== returnKey) { return; } e.stopPropagation(); e.preventDefault(); var value = e.target.value; this.valueButton.setValue(value); React.findDOMNode(this.refs.linkInput).value = ""; this.setState({inputMode: false}); }, // pass the selection snapshot upstream to restore it handleCancelInput() { this.setState({inputMode: false}); this.props.onChange(this.selSnapshot); }, menuClasses() { return cx('arc-Editor-Menu', { 'arc-Editor-Menu--active': this.props.selection.showMenuButtons(), 'arc-Editor-Menu--link': this.state.inputMode }); }, itemsClasses() { return cx('arc-Editor-Menu__items', { 'arc-Editor-Menu__items--active': !this.state.inputMode }); }, linkClasses() { return cx('arc-Editor-Menu__linkinput', { 'arc-Editor-Menu__linkinput--active': this.state.inputMode }); }, // move menu to selected text menuStyles() { if (!this.props.selection.bounds) { return {}; } var selection = this.props.selection; var bounds = selection.bounds; if (!bounds.top && !bounds.left) { return {}; } var buttonHeight = 50; var menuWidth = Object.keys(this.renderButtons()).length * 43; return { top: window.pageYOffset + bounds.top - buttonHeight, left: bounds.left + (bounds.width / 2) - (menuWidth / 2) }; }, // build buttons from children renderButtons() { var buttons = []; React.Children.forEach(this.props.children, (child, i) => { var refName = `button_${child.props.type}`; var cloned = cloneWithProps(child, { content: this.props.content, selection: this.props.selection, onSetValue: this.handleSetValue.bind(this, child, refName), ref: refName }); // some buttons may not be visible based on the selection if (cloned.type.isVisible(this.props.content, this.props.selection)) { buttons.push( <li className="arc-Editor-Menu__item" key={`button_${i}`}> {cloned} </li> ); } }); return buttons; }, render() { return ( <div ref="menu" className={this.menuClasses()} style={this.menuStyles()}> <div className="arc-Editor-Menu__inner"> <ul className={this.itemsClasses()}> {this.renderButtons()} </ul> <div className={this.linkClasses()}> <input type="text" ref="linkInput" className="arc-Editor-Menu__linkinput-field" placeholder="Paste or type a link" onKeyUp={this.handleOnKeyUp} onKeyDown={this.handleOnKeyDown} /> <button className="arc-Editor-Menu__linkinput_button arc-Editor-MenuButton" onClick={this.handleCancelInput} > <i className="arc-Editor-MenuButton__icon fa fa-times"></i> <span className="arc-Editor-MenuButton__icon-text arc-Editor-MenuButton__icon-text--sr"> Close </span> </button> </div> </div> <div className="arc-Editor-Menu__arrow-clip"> <span className="arc-Editor-Menu__arrow"></span> </div> </div> ); } }); module.exports = Menu;
JavaScript
0.000001
@@ -105,58 +105,8 @@ );%0A%0A -var cloneWithProps = React.addons.cloneWithProps;%0A var @@ -2716,16 +2716,17 @@ type%7D%60;%0A +%0A va @@ -2740,22 +2740,26 @@ d = -cloneWithProps +React.cloneElement (chi
0e2f869976dc01798fb9e9a031e477f92684af20
handle empty remote addresses
lib/master.js
lib/master.js
'use strict'; var log = require('./log'); module.exports = function (workers, options) { var DEBUG = options.debug; var CONCURRENCY = options.concurrency; var PORT = options.port; var serverInstance; function serverCreate () { var hash = require('string-hash'); return require('net') .createServer({ pauseOnConnect: true }, function (connection) { var index = hash(connection.remoteAddress) % CONCURRENCY; workers.entrust(index, connection); }); } function serverStart (callback) { serverInstance = serverCreate(); serverInstance.listen(PORT, callback); } function serverStop (callback) { serverInstance.close(function (err) { if (err) console.log(err); else return callback(); }); } function stop () { // stop proxy server if (DEBUG) log('MASTER stop..'); serverStop(function () { if (DEBUG) log('MASTER ..stopped'); // stop nodes if (DEBUG) log('WORKERS stop..'); workers.stop(); }); } function start () { // start proxy server if (DEBUG) log('MASTER start..'); serverStart(function () { if (DEBUG) log('MASTER ..started at port %d', PORT); // start nodes if (DEBUG) log('WORKERS start..'); workers.start(); // stop everything when requested process.once('SIGINT', stop); }); } return { start: start, stop: stop }; };
JavaScript
0.000001
@@ -415,16 +415,22 @@ eAddress + %7C%7C '' ) %25 CONC
ad736959264f0cdc2bae5fa0391569f432fb3c65
Add and require custom-methods file
029-distinct-powers/javascript-solution.js
029-distinct-powers/javascript-solution.js
exponentiateStrings = function(string1, string2) { // must have a powers function for strings because 100 ** 100 is too high for JS... } // var powers = []; // for (var a = 2; a <= 100; a++) { // for (var b = 2; b <= 100; b++) { // powers.push(exponentiateStrings(a.toString(), b.toString())); // } // } // var distinctPowers = []; // var usedPowers = {}; // powers.forEach(function(power) { // if (!usedPowers[power]) { // distinctPowers.push(power); // } // usedPowers[power] = true; // }) // console.log(distinctPowers.length);
JavaScript
0
@@ -1,24 +1,58 @@ +require(%22../custom-methods%22)%0A%0A%0A// exponentiateStrings = fu @@ -78,16 +78,19 @@ ing2) %7B%0A +// // mus @@ -167,16 +167,19 @@ r JS...%0A +// %7D%0A%0A// va
c2764adb0ebe14f78351995cfaca3849e19885d9
add JSON load
js/dual-listbox.js
js/dual-listbox.js
(function($) { 'use strict'; $.fn.dualListBox = function(options) { var defaults = function ($listBox) { return { delay: $listBox.data('delay') || 200, sort: $listBox.data('sort') || true } }; var filter = function(list, search) { var regex = new RegExp(search, 'gi'); var $items = $('option', list); $.each($items, function() { var $item = $(this); if($item.text().match(regex) === null) { $item.hide(); } else { $item.show(); } }); }; var sortOptions = function (items) { return items.sort(function(a, b){ var aText = $(a).text(), bText = $(b).text(); if (aText == bText) { return 0; } return aText > bText ? 1 : -1; }); }; var update = function($listBox) { // update lists' counters $listBox.find('[data-list-count]').each(function() { var $results = $(this), $list = $listBox.find('select[data-list="' + $results.data('list-count') + '"]'); $results.text($('option:visible', $list).length) }); // update button disabled status $listBox.find('button[data-move]').each(function() { var $options, $button = $(this), $list = $listBox.find('select[data-list!="' + $button.data('move-to') + '"]'); if ($button.data('move') == 'all') { $button.prop('disabled', !$('option:visible', $list).length); } else if ($button.data('move') == 'selected') { $button.prop('disabled', !$('option:visible:selected', $list).length); } }); }; return this.each(function() { var $listBox = $(this); var settings = $.extend(true, {}, defaults($listBox), $listBox, options); $listBox.find('button[data-move]').click(function(e) { var selected, items, $button = $(this), from = 'select[data-list!="' + $button.data('move-to') + '"]', to = 'select[data-list="' + $button.data('move-to') + '"]'; if ($button.data('move') == 'selected') { items = $('option:selected:visible', $listBox.find(from)); } else if ($button.data('move') == 'all') { items = $('option:visible', $listBox.find(from)); } items = items.add($('option', $listBox.find(to))); items.prop('selected', false); $listBox.find(to).html(settings.sort ? sortOptions(items) : items); update($listBox); }); var thread = null; $('input[data-filter]').keydown(function(event) { var keycode = (event.keyCode ? event.keyCode : event.which); if(keycode != '13'){ clearTimeout(thread); var $filterBox = $(this); thread = setTimeout(function() { filter('select[data-list="' + $filterBox.data('filter') + '"]', $filterBox.val()); update($listBox); }, settings.delay); } }); $listBox.find('select[data-list]').change( function() { update($listBox) } ); update($listBox); }); }; $('div[data-role="dual-listbox"]').dualListBox(); })(jQuery);
JavaScript
0.000001
@@ -1994,19 +1994,92 @@ -return this +var loadItems = function ($listBox) %7B%0A $listBox.find('select%5Bdata-list%5D') .eac @@ -2101,24 +2101,28 @@ + + var $listBox @@ -2118,19 +2118,16 @@ ar $list -Box = $(thi @@ -2120,33 +2120,33 @@ $list = $(this) -; +, %0A var @@ -2146,82 +2146,611 @@ -var settings = $.extend(true, %7B%7D, defaults($listBox), $listBox, options);%0A + itemsUrl = $list.data('items-url');%0A if (itemsUrl) %7B%0A $.getJSON(itemsUrl).done(function(data) %7B%0A var items = $('option', $list);%0A $.each(data, function(index, value) %7B%0A items = items.add($('%3Coption%3E').prop('value', index).text(value));%0A %7D);%0A $list.html( sortOptions(items));%0A update($listBox);%0A %7D);%0A %7D%0A %7D);%0A %7D;%0A%0A var attachButtons = function ($listBox, sort) %7B %0A @@ -3495,25 +3495,16 @@ o).html( -settings. sort ? s @@ -3573,32 +3573,99 @@ %7D);%0A + %7D;%0A%0A var attachFilter = function ($listBox, delay) %7B %0A var @@ -3680,16 +3680,17 @@ = null;%0A +%0A @@ -3735,20 +3735,16 @@ nction(e -vent ) %7B%0A @@ -3771,20 +3771,16 @@ ode = (e -vent .keyCode @@ -3783,20 +3783,16 @@ Code ? e -vent .keyCode @@ -3799,12 +3799,8 @@ : e -vent .whi @@ -4159,17 +4159,8 @@ %7D, -settings. dela @@ -4189,32 +4189,308 @@ %7D);%0A + %7D;%0A%0A return this.each(function() %7B%0A var $listBox = $(this),%0A settings = $.extend(true, %7B%7D, defaults($listBox), $listBox, options);%0A%0A attachButtons($listBox, settings.sort);%0A attachFilter($listBox, settings.delay); %0A $li @@ -4563,16 +4563,49 @@ ox) %7D ); +%0A loadItems($listBox); %0A%0A @@ -4647,20 +4647,16 @@ %0A %7D;%0A - %0A $('
3639b2c452cb671dab8df860d5d58773a1b61248
Add updateImports to matter module
lib/matter.js
lib/matter.js
// matter.js // 'use strict'; var utils = require('./utils'); var fs = require('fs'); var cp = require('child_process'); var url = require('url'); var rimraf = require('rimraf'); var Queue = require('queue'); var which = require('which'); module.exports = { clean: function (lib, cb) { var locale = getLocale(lib); utils.exists(`./${locale}/matter/_matter.scss`, function (err) { // Callback silently if 'locale' is not a Matter lib. if (err) cb(null); rimraf(`./${locale}`, { disableGlob: true }, cb); }); }, clone: function (lib, done) { var cloneUrl = url.parse(getCloneUrl(lib)); var locale = getLocale(lib); var q = new Queue({ concurrency: 1 }); // 1. Check if cloneUrl protocol is 'https:'. q.push(function (cb) { if (cloneUrl.protocol !== 'https:') { var err = utils.createError( `"${protocol}" is an unsupported protocol. URLs should start with "https:".` ); cb(err); } cb(null); }); // 2. Check Git is installed. q.push(function (cb) { which('git', cb); }); // 3. Check 'cloneUrl.href' is a valid Git-remote. q.push(function (cb) { isValidGitRemote(cloneUrl.href, cb); }); // 4. Verify lib. locale has the correct suffix. q.push(function (cb) { if (!locale.endsWith('-matter')) { var err = utils.createError( `Unsupported locale. "${locale}" should have a "-matter" suffix.` ); cb(err); } cb(null); }); // 5. Git clone the Matter lib. q.push(function (cb) { cp.spawn('git', ['clone', cloneUrl.href, locale], { stdio: 'inherit' }) .on('close', function (code) { if (code !== 0) { var err = utils.createError( `There was a problem cloning the Matter lib. from "${cloneUrl.href}".` ); cb(err); } cb(null); }); }); // Go. q.start(function (err) { done(err); }); }, getLocale: getLocale, }; /** * Retrieves a Matter lib's clone URL from a formulated string. * @param {string} matterLib collider.json matterLib item. * @return {string} A Matter lib's clone URL. */ function getCloneUrl(lib) { var cloneUrl = lib.split(',')[0]; return cloneUrl; } /** * Retrieves a Matter lib's locale from a formulated string. * @param {string} matterLib collider.json matterLib item. * @return {string} A Matter lib's locale. */ function getLocale(lib) { var locale = lib.split(',')[1]; return locale; } /** * Uses `git ls-remote` to check if the given URL is an accessible Git repo. * @param {String} url A URL to a remote git repository. */ function isValidGitRemote(url, cb) { cp.exec(`git ls-remote ${url}`, function (err) { cb(err); }); }
JavaScript
0
@@ -261,16 +261,349 @@ ts = %7B%0A%0A + updateImports: function (libs, cb) %7B%0A var imports = %5B%5D;%0A var data = '';%0A%0A libs.forEach(function (lib) %7B%0A var locale = getLocale(lib);%0A imports.push(%60@import %22../$%7Blocale%7D/matter/index%22;%60);%0A %7D);%0A%0A data = imports.join('%5Cn');%0A data += '%5Cn';%0A%0A fs.writeFile('./collider/_matter.scss', data, cb);%0A %7D,%0A%0A clean:
e0dc20ff5839548cd33776d0a0a2f7730cb9af6f
Revert and inspector buttons should not focus the form. Fixes #1139
js/id/ui/preset.js
js/id/ui/preset.js
iD.ui.preset = function(context, entity, preset) { var original = context.graph().base().entities[entity.id], event = d3.dispatch('change', 'close'), fields = [], tags = {}, formwrap, formbuttonwrap; function UIField(field, show) { field = _.clone(field); field.input = iD.ui.preset[field.type](field, context) .on('close', event.close) .on('change', event.change); if (field.type === 'address') { field.input.entity(entity); } field.keys = field.keys || [field.key]; field.show = show; field.shown = function() { return field.id === 'name' || field.show || _.any(field.keys, function(key) { return !!tags[key]; }); }; field.modified = function() { return _.any(field.keys, function(key) { return original ? tags[key] !== original.tags[key] : tags[key]; }); }; return field; } fields.push(UIField(context.presets().field('name'))); var geometry = entity.geometry(context.graph()); preset.fields.forEach(function(field) { if (field.matchGeometry(geometry)) { fields.push(UIField(field, true)); } }); context.presets().universal().forEach(function(field) { if (fields.indexOf(field) < 0) { fields.push(UIField(field)); } }); function fieldKey(field) { return field.id; } function shown() { return fields.filter(function(field) { return field.shown(); }); } function notShown() { return fields.filter(function(field) { return !field.shown(); }); } function show(field) { field.show = true; render(); field.input.focus(); } function revert(field) { var t = {}; field.keys.forEach(function(key) { t[key] = original ? original.tags[key] : undefined; }); event.change(t); } function toggleReference(field) { _.forEach(fields, function(other) { if (other.id === field.id) { other.showingReference = !other.showingReference; } else { other.showingReference = false; } }); render(); } function render() { var selection = formwrap.selectAll('.form-field') .data(shown(), fieldKey); var enter = selection.enter() .insert('div', '.more-buttons') .style('opacity', 0) .attr('class', function(field) { return 'form-field form-field-' + field.id + ' fillL col12'; }); enter.transition() .style('max-height', '0px') .style('padding-top', '0px') .style('opacity', '0') .transition() .duration(200) .style('padding-top', '20px') .style('max-height', '200px') .style('opacity', '1'); var label = enter.append('label') .attr('class', 'form-label') .attr('for', function(field) { return 'preset-input-' + field.id; }) .text(function(field) { return field.label(); }); label.append('button') .attr('class', 'tag-reference-button fr') .attr('tabindex', -1) .on('click', toggleReference) .append('span') .attr('class', 'icon inspect'); label.append('button') .attr('class', 'fr modified-icon') .attr('tabindex', -1) .on('click', revert) .append('div') .attr('class','icon undo'); enter.each(function(field) { d3.select(this).call(field.input); }); enter.append('div') .attr('class', 'tag-help'); selection .classed('modified', function(field) { return field.modified(); }); selection.selectAll('.tag-help') .style('display', function(field) { return field.showingReference ? 'block' : 'block'; }) .each(function(field) { if (field.showingReference) { d3.select(this) .call(iD.ui.TagReference(entity, {key: field.key})) .style('max-height', '0px') .style('padding-top', '0px') .style('opacity', '0') .transition() .duration(200) .style('padding-top', '20px') .style('max-height', '200px') .style('opacity', '1'); } else { d3.select(this) .call(iD.ui.TagReference(entity, {key: field.key})) .transition() .duration(200) .style('max-height', '0px') .style('padding-top', '0px') .style('opacity', '0'); } }); selection.exit() .remove(); var addFields = formbuttonwrap.selectAll('.preset-add-field') .data(notShown(), fieldKey); addFields.enter() .append('button') .attr('class', 'preset-add-field') .on('click', show) .call(bootstrap.tooltip() .placement('top') .title(function(d) { return d.label(); })) .append('span') .attr('class', function(d) { return 'icon ' + d.icon; }); addFields.exit() .transition() .style('opacity', 0) .remove(); return selection; } function presets(selection) { selection.html(''); formwrap = selection; formbuttonwrap = selection.append('div') .attr('class', 'col12 more-buttons inspector-inner'); render(); } presets.rendered = function() { return _.flatten(shown().map(function(field) { return field.keys; })); }; presets.preset = function(_) { if (!arguments.length) return preset; preset = _; return presets; }; presets.change = function(_) { tags = _; fields.forEach(function(field) { if (field.shown()) { field.input.tags(_); } }); render(); return presets; }; return d3.rebind(presets, event, 'on'); };
JavaScript
0
@@ -1838,32 +1838,103 @@ revert(field) %7B%0A + d3.event.stopPropagation();%0A d3.event.preventDefault();%0A var t = @@ -1937,16 +1937,16 @@ t = %7B%7D;%0A - @@ -2118,32 +2118,103 @@ erence(field) %7B%0A + d3.event.stopPropagation();%0A d3.event.preventDefault();%0A _.forEac @@ -3388,18 +3388,16 @@ ); %7D);%0A%0A -%0A%0A @@ -4865,17 +4865,16 @@ %7D else %7B - %0A @@ -5129,32 +5129,32 @@ ng-top', '0px')%0A + @@ -5184,31 +5184,8 @@ 0'); - %0A
591dcfc08531d79473e7c4e6ae1fb6d964f7497d
Remove Pointers for Devlopement
src/tap/controller.js
src/tap/controller.js
import status from './status'; import abduction from './abduction'; import imgvalid from './IMGvalidation'; import xmlvalid from './XMLvalidation'; import ingest from './ingestion'; /** * [someFunction description] * @return {[type]} [description] */ let fileList = []; abduction(fileList); //imgvalid(); //xmlvalid(); if(status==='sucess'){ ingest(); function cleanup(){ // Remove Files from original folder }; }; function controller(input) { console.log('controller '+input); }; export default controller;
JavaScript
0
@@ -1,12 +1,15 @@ +// import statu @@ -27,16 +27,19 @@ tatus';%0A +// import a @@ -63,24 +63,27 @@ abduction';%0A +// import imgva @@ -106,24 +106,27 @@ alidation';%0A +// import xmlva @@ -153,16 +153,19 @@ ation';%0A +// import i @@ -283,16 +283,19 @@ t = %5B%5D;%0A +// abductio @@ -307,16 +307,16 @@ eList);%0A - %0A//imgva @@ -337,16 +337,19 @@ lid();%0A%0A +// if(statu @@ -363,16 +363,19 @@ cess')%7B%0A +// ingest @@ -378,17 +378,22 @@ gest();%0A -%0A +//%0A// functi @@ -406,16 +406,19 @@ anup()%7B%0A +// // @@ -455,17 +455,25 @@ der%0A +// %7D;%0A +// %7D;%0A +// %0A%0A%0Af
30e48646c7a2881376748568fae34f28fc0969e6
fix params parsing
lib/module.js
lib/module.js
'use strict'; angular.module('coq', [ 'ngResource', 'ngSanitize' ]); angular.module('coq').config(function($provide) { // Add $$routeVariables to every $resource instance // > Because resourceFactory keep route object, make it // unreachable outside the $resource instance // // Route class is also unreachable outside the $resource service, // that's why this snippet is used here $provide.decorator('$resource', function($delegate) { var $wrapper = function resourceWrapper() { var url = arguments[0], variables = [], inst = $delegate.apply(arguments); angular.forEach(url.split(/\W/), function(param){ if (param && (new RegExp('(^|[^\\\\]):' + param + '\\W').test(url))) { variables.push(param); } }); inst.$$routeVariables = variables; return inst; }; return $wrapper; }); });
JavaScript
0.000001
@@ -572,16 +572,54 @@ s = %5B%5D,%0A + parts = url.split('/'),%0A @@ -648,16 +648,27 @@ e.apply( +$delegate, argument @@ -698,23 +698,13 @@ ach( -url.split(/%5CW/) +parts , fu @@ -739,66 +739,19 @@ aram - && (new RegExp('(%5E%7C%5B%5E%5C%5C%5C%5C%5D):' + param + '%5C%5CW').test(url)) +%5B0%5D === ':' ) %7B%0A @@ -780,16 +780,26 @@ sh(param +.substr(1) );%0A
6a20700fec26e9d9382f94e7d5548223988355b3
fix range bug
lib/number.js
lib/number.js
/* * Generate random number * options: * 'min': minimun value of random number * 'max': maximun value of random number */ "use strict"; var _ = require('underscore'); var defaultOptions = { min: 0, max: 100 }, userOptions = null, result = null; function _getOptionByKey(key) { return userOptions[key] ? userOptions[key] : defaultOptions[key]; } function _isInteger(number) { return number % 1 === 0; } function match(input, userOptions) { return _.isNumber(input); } function generate(input, options) { userOptions = options; var min, max; if (_isInteger(input)) { // generate a integer result = _.random(Math.floor(_getOptionByKey('min')), Math.floor(_getOptionByKey('max'))); } else { // generator a float number min = Math.floor(_getOptionByKey('min') * 100); max = Math.floor(_getOptionByKey('max') * 100); result = _.random(min, max) / 100; } userOptions = null; return result; } module.exports = { match: match, generate: generate };
JavaScript
0
@@ -228,16 +228,17 @@ max: 100 +0 %0A%7D, %0A
a94348fcd51e78a610aba4a7909cb6184bab155a
remove extra code
lib/params.js
lib/params.js
var fs = require('fs') var path = require('path') if (!process) { process = require('process') // > v0.4.0 } var cosmiconfig = require('cosmiconfig'); var repeatString = require('repeat-string') var editorconfig = require('editorconfig') var isEmptyObject = require('./util').isEmptyObject var defaultIndentWidth = repeatString(' ', 2) function hasScssInWorkingDir(wd) { var dirs = fs.readdirSync(wd) return dirs.some(function (dir) { return dir.match(/.*\.scss/) }) } function getIndentationFromEditorConfig(from, hasScss) { var config if (hasScss) { config = editorconfig.parseSync(path.resolve(process.cwd(), '*.scss')) } else { config = editorconfig.parseSync(path.resolve(process.cwd(), '*.css')) } if (config == undefined) { return defaultIndentWidth } switch (config.indent_style) { case 'tab': return '\t' case 'space': return repeatString(' ', config.indent_size) default: return defaultIndentWidth } } function getIndentationFromStylelintConfig(rules) { var indentaiton = rules['indentation'] switch (typeof indentaiton) { case 'string': return '\t' break case 'number': return repeatString(' ', indentaiton) default: return defaultIndentWidth } } function parmas(from) { var wd = path.dirname(from) || process.cwd() var params = {} var hasScss = hasScssInWorkingDir(wd) params.hasScss = hasScss return cosmiconfig('stylelint', { // same as the options in stylelint argv: false, rcExtensions: true, }).then(function (stylelint) { if (isEmptyObject(stylelint)) { params.indentWidth = getIndentationFromEditorConfig(wd, hasScss) params.stylelint = {} } else { params.indentWidth = getIndentationFromStylelintConfig(stylelint.config.rules) params.stylelint = stylelint.config.rules } return params }) } module.exports = parmas
JavaScript
0.000192
@@ -46,69 +46,8 @@ th') -%0Aif (!process) %7B%0A process = require('process') // %3E v0.4.0%0A%7D %0A%0Ava
65038c6b9e6b695030badddef7aefcf8d3d01b08
load map once
js/screens/main.js
js/screens/main.js
game.MainScreen = me.ScreenObject.extend({ init: function () { this.font = new me.Font("Verdana", 12, "#fff", "center"); }, onDestroyEvent: function () { me.game.world.removeChild(this.HUD); me.game.world.removeChild(this.player); var socket = global.network.socket; if (!socket) return; socket.removeAllListeners("returnToLobby"); socket.removeAllListeners("refreshPlayer"); socket.removeAllListeners("scoreUpdate"); socket.removeAllListeners("scoreUpdate"); socket.removeAllListeners("removePlayer"); socket.removeAllListeners("victory"); socket.removeAllListeners("defeat"); socket.removeAllListeners("killed"); }, onResetEvent: function () { // Connect to server and set global reference to the socket that's connected if (me.game.HASH.debug === true) { console.log("gameStarted") } me.levelDirector.loadLevel("area01"); setTimeout(function () { if (me.game.HASH.debug === true) { console.log("player init."); } Object.keys(game.data.lobbyPlayers).forEach(function (id) { var playerInfo = game.data.lobbyPlayers[id]; if (me.game.HASH.debug === true) { console.log("player added " + playerInfo.id) } var player = me.pool.pull("mainPlayer", playerInfo.x, playerInfo.y, playerInfo.id, playerInfo.spriteIndex); me.game.world.addChild(player); game.data.players[playerInfo.id] = player; if (game.data.clientId === playerInfo.id.substring(2)) { if (me.game.HASH.debug === true) { console.log("localPlayer added for " + game.data.clientId); } game.data.localPlayer = player; } }); game.data.lobbyPlayers = {}; }, 500); //global.network.socket.on("returnToLobby", function () { // me.state.change(me.state.MENU); //}); global.network.socket.on("killed", function () { me.game.viewport.shake(15, 300, me.game.viewport.AXIS.BOTH); }); global.network.socket.on("refreshPlayer", function (infos) { var player = game.functions.playerById(infos.id); if (player && me.game.HASH.debug === true) { console.log("refreshPlayer " + player.playerId + "@" + infos.x + "," + infos.y); } if (player) { player.refresh(infos); } }); global.network.socket.on("scoreUpdate", function (score) { game.data.score = score.gauge; game.data.time = score.time; }); global.network.socket.on("removePlayer", function (playerId) { var player = game.functions.playerById(playerId); me.game.world.removeChild(player); game.data.players[playerId] = null; }); global.network.socket.on("victory", function (playerId) { game.data.victory = true; game.data.ended = true; me.state.change(me.state.GAME_END); }); global.network.socket.on("defeat", function (playerId) { game.data.defeat = true; game.data.ended = true; me.state.change(me.state.GAME_END); }); me.levelDirector.loadLevel("area01"); me.input.bindKey(me.input.KEY.LEFT, "left"); me.input.bindKey(me.input.KEY.RIGHT, "right"); me.input.bindKey(me.input.KEY.UP, "up"); me.input.bindKey(me.input.KEY.DOWN, "down"); me.input.bindKey(me.input.KEY.X, "dance"); me.input.bindKey(me.input.KEY.W, "mark"); this.player = me.pool.pull("networkPlayer"); me.game.world.addChild(this.player); this.HUD = new game.HUD.Container(); me.game.world.addChild(this.HUD); } });
JavaScript
0.000002
@@ -944,32 +944,35 @@ %7D%0A%0A +//s me.levelDirect
60e3e24ae0f4ce5da7034531663c416102db2c5e
Fix bugs
js/sensor-setup.js
js/sensor-setup.js
(function(exports){ $(document).ready(function(){ $('.modal-trigger').leanModal(); }); const GEOCODE_URL = 'https://maps.googleapis.com/maps/api/geocode/json?address='; const API_KEY = '&key=AIzaSyAWlJoUn2DS8XUYilLXZE8dxYEXbo6dnaE'; const TOAST_DUR = 4000; var userId = $.url().param('userId'); var sensorName = $('#sensor-name'); var sensorLocation = $('#sensor-location'); var sensorDescription = $('#sensor-description'); var sensorProject = $('#sensor-project'); var sensorCoords; var gMap; $('select').material_select(); $(window).load(function handleClientLoad() { var auth = gapi.auth2.getAuthInstance(); if (!auth) { return; } var loginBtn = $('#login-btn'); var accountBtn = $('#account-btn'); function btnState(isSignedIn) { if (isSignedIn) { var email = auth.currentUser.get().getBasicProfile().getEmail(); $.ajax({ url: API_URL + 'users?email=' + email, dataType: 'jsonp' }) .done(function(result) { loginBtn.addClass('hide'); accountBtn.removeClass('hide'); accountBtn.attr('href', 'user-detail.html?userId=' + result.id); }) .fail(function(err) { console.error(err) }); } else { accountBtn.addClass('hide'); loginBtn.removeClass('hide'); } } btnState(auth.isSignedIn.get() || auth.currentUser.get().isSignedIn()); auth.isSignedIn.listen(btnState); }); function onSignIn(googleUser) { var userId = $('#user-id').val(); if (!userId) { return; } var auth = googleUser.getAuthResponse(); var profile = googleUser.getBasicProfile(); var userData = { // token: auth.access_token, Do we really need this? id: userId, name: profile.getName(), email: profile.getEmail(), picture: profile.getImageUrl() }; //TODO: create user in DB and get user profile $('#user-id').text(); $('#google-sign-in-modal').closeModal(); $.ajax({ type: 'POST', url: API_URL + 'users', data: userData, dataType: 'jsonp' }) .done(function() { window.location = 'user-detail.html?userId=' + userId; }) .fail(function(err) { console.error(err) }); } $('#setup-sensor').click(function() { if (!sensorCoords) { Materialize.toast('Please check your address on the map', TOAST_DUR); return; } var name = sensorName.val(); var projectKey = sensorProject.val(); $.ajax({ type: 'POST', url: API_URL + 'projects/' + projectKey + '/sensors', data: { userId: userId, name: name, description: sensorDescription.val(), address: sensorLocation.val(), // XXX: Need String type here. coords: JSON.stringify(sensorCoords), // TOOD: Please add the google token here. token: 'Google token' }, dataType: 'jsonp' }) .done(function(result) { if (result.result === 'success') { window.location = './user-detail.html?userId=' + userId; } else { alert(result.message); } }) .fail(function(err) { console.error(err) }); }); $('#check-addr-btn').click(function() { var address = sensorLocation.val(); if (!address) { return; } var formattedAddr = address.split(' ').join('+'); $.ajax({ url: GEOCODE_URL + formattedAddr + API_KEY, }) .done(function(data) { if (!data.results[0]) { return; } sensorCoords = data.results[0].geometry.location; gMap = new google.maps.Map(document.getElementById('location-map'), { zoom: 16, center: sensorCoords }); var gMapMarker = new google.maps.Marker({ position: sensorCoords, map: gMap, draggable:true, animation: google.maps.Animation.DROP }); google.maps.event.addListener(gMapMarker, 'dragend', function() { sensorCoords = gMapMarker.getPosition().toJSON(); }); }) .fail(function(error) { console.error(error); }); }); function initMap() { gMap = new google.maps.Map(document.getElementById('location-map'), { zoom: 1, center: {lat: 0, lng: 0} }); } exports.initMap = initMap; exports.onSignIn = onSignIn; })(window);
JavaScript
0.000004
@@ -1146,31 +1146,24 @@ href', 'user --detail .html?userId @@ -2187,31 +2187,24 @@ tion = 'user --detail .html?userId @@ -3073,15 +3073,8 @@ user --detail .htm
f575fa5b0bdd3dcaf09ac9416a8344cc74e86df0
Update unauthorized.js
js/unauthorized.js
js/unauthorized.js
// This script will modify the "Unauthorized" message that users may see if they click through // to the course home page, but the course hasn't been published yet. The message has been // modified to be a little more user friendly. require(['jquery'], function($) { /** * This function checks to see if the page is the course home page. * * Only the course home page unauthorized message needs to be changed, * others should be left as-is. * * @returns {Boolean} True if it is the course home, otherwise false. */ function is_course_home_page() { return /^\/courses\/\d+/.test(window.location.pathname); }; /** * This function modifies the unauthorized message on the page by tweaking * the HTML. Here's an example of what the HTML looks like prior to modification: * * <div id="unauthorized_holder"> * <div id="unauthorized_message" class=""> * <h2 class="ui-state-error"> * Unauthorized * </h2> * <p> * It appears that you don&#x27;t have permission to access this page. Please make sure you&#x27;re authorized to view this content. * If you think you should be able to view this page, please use the &quot;Help&quot; link to notify support of the problem. * </p> * </div> * </div> * * @returns undefined */ function modify_unauthorized_message(msg) { var $holder = $('#unauthorized_holder'); if($holder.length > 0) { $holder.find('h2').html(msg.title); $holder.find('p').replaceWith(msg.content); $holder.find('p:first').css({paddingBottom: 0}); } }; // Checks if this is the home page and modifies the unauthorized message (if present). if(is_course_home_page()) { modify_unauthorized_message({ title: 'Not Available', content: '<p>You do not currently have access to view this page. It may be that the site has not yet been published by the teaching staff, or that access to the site is restricted.</p><p>If you think you should have access, please use the "Help" link to contact support.</p>' }); } });
JavaScript
0.000001
@@ -317,139 +317,37 @@ is -the course home page.%0A%09 *%0A%09 * Only the course home page unauthorized message needs to be changed,%0A%09 * others should be left as-is. +in the context of the course. %0A%09 *
6a3e7ca19e8e691bf82ab8320c73df3dbdb402cf
update type=text and password
js/zsi.bswriter.js
js/zsi.bswriter.js
/** * zsiBSWriter.js * @author German M. Fuentes <[email protected]> * @copyright 2015 ZettaSolutions, Inc. <zetta-solutions.net> * @license under MIT <https://github.com/smager/zsiBSwriter/blob/master/LICENSE> * @createddate Feb-22-2015 **/ /* dictionary: */ var _ud = 'undefined'; if(typeof zsi===_ud) zsi={}; zsi.bsWriter = function(config){ //get new instance; var bsw =this; if(typeof config.hasNoConfigFile === _ud) config.hasNoConfigFile=false; if(config.hasNoConfigFile==true && typeof config.url===_ud ) throw new Error("hasNoConfigFile is set to false, url is required "); //get default config url config.url = (typeof config.url === _ud && config.hasNoConfigFile==false) ? config.url="templates/config.txt":config.url; //private variables this.__activeDiv="_activeDiv_"; //private functions this.__closeDiv=function(){ $("." + bsw.__activeDiv).removeClass(bsw.__activeDiv); } this.__getTemplate=function(p_tmp,info){ var ts = bsw.__templates; for(var i=0;i<ts.length;i++){ if(ts[i].name.toLowerCase()== p_tmp.toLowerCase()){ if(!info.id) if(info.name) info.id=info.name; if(!info.name) if(info.id) info.name=info.id; if(info.labelsize) info.labelsize = "col-" + config.SizeType + "-" + info.labelsize if(info.inputsize) info.inputsize = "col-" + config.SizeType + "-" + info.inputsize return bsw.__compile(unescape(ts[i].html),info); } } } this.__compile=function(tmp,data){ var template = Handlebars.compile(tmp); return template( data); } //create prototype functions for node. this.__setFunction=function(fnName){ bsw.node.prototype[fnName] = function(jsonData){ var h = bsw.__getTemplate(fnName,jsonData); $("." + bsw.__activeDiv).append(h); return this; }; } this.__loadTemplates=function(templates,node){ var loadedItems=0; for(var i=0;i<templates.length;i++){ loadTemplate( templates[i].name, templates[i].url); } function loadTemplate(templateName,url){ var _tmpl=templateName; $.get(url ,function (info){ bsw.__templates.push({name:templateName,html:info}); bsw.__setFunction(templateName); loadedItems++; loadCompleted(); } ); } function loadCompleted(){ if(templates.length ==loadedItems) { if(typeof node.__loadComplete!==_ud) { node.__loadComplete(); } } } } this.__templates=[]; //public functions this.write= function(callBackFunc){ var node = new bsw.node(); node.__loadComplete=callBackFunc; $.getJSON(config.url,function onLoadComplete(data){ if(config.hasNoConfigFile){ //if not using config file //or using only single file //or single data from the database for templates bsw.__templates = data; for(var i=0;i<data.length;i++){ bsw.__setFunction(data[i].name) } if(typeof node.__loadComplete!==_ud) node.__loadComplete(); } else{ bsw.__loadTemplates(data,node); } }); } this.node = function(){ this.lastObj = $("." + config.targetClass).addClass(bsw.__activeDiv); } // node prototypes this.node.prototype.div = function(jsonData){ var _id=""; var _guid = this.guid(); bsw.__closeDiv();//close current div if(jsonData.id) _id ='id="' + jsonData.id + '"'; var h ='<div ' + _id + ' class="' + jsonData.class + ' ' + bsw.__activeDiv + ' ' + _guid + '"></div>'; if (jsonData.parentClass) $("." + jsonData.parentClass).append(h); else this.lastObj.append(h); this.lastObj = $("." + _guid); return this; } this.node.prototype.html = function(value){ this.lastObj.html(value); return this; } this.node.prototype.prepend = function(value){ this.lastObj.prepend(value); return this; } this.node.prototype.append = function(value){ this.lastObj.append(value); return this; } this.node.prototype.end = function(callBackFunc){ bsw.__closeDiv(); //remove generated temporay class $('[class*="p___"]').each(function() { var _class = $(this).attr("class"); $(this).attr("class",_class.substr(0,_class.indexOf("p___"))); }); //delete unused objects. delete this.__loadComplete; delete this.lastObj; if(callBackFunc) callBackFunc(); } this.node.prototype.guid = function(){ function S4() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); } return "p___" + (S4()+S4()).toLowerCase(); } }
JavaScript
0.000004
@@ -1747,16 +1747,186 @@ Data)%7B%0D%0A + if( fnName.toLowerCase().indexOf(%22input%22) %3E -1) %7B%0D%0A if(!jsonData.type) jsonData.type=%22text%22; %0D%0A %7D%0D%0A console.log(jsonData);%0D%0A %09%09%09var h
0eab425a7cdb357d9a33588fc38ded2a95323a00
Remove trailing whitespace
lib/person.js
lib/person.js
var Helpers = require('./helpers'); // Generates valid brazillian CPF numbers // See http://en.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas exports.brCPF = function () { var baseNumber = Helpers.randomize('###.###.###'), number = Helpers.replaceSymbolWithNumber(baseNumber), firstDigit, secondDigit, parts; parts = number.split(''); // Computing first verification digit firstDigit = 10 * parts[0] + 9 * parts[1] + 8 * parts[2] + 7 * parts[4] + 6 * parts[5] + 5 * parts[6] + 4 * parts[8] + 3 * parts[9] + 2 * parts[10]; firstDigit = 11 - (firstDigit % 11); if (firstDigit >= 10) { firstDigit = 0; } // Computing second verification digit secondDigit = 11 * parts[0] + 10 * parts[1] + 9 * parts[2] + 8 * parts[4] + 7 * parts[5] + 6 * parts[6] + 5 * parts[8] + 4 * parts[9] + 3 * parts[10] + 2 * firstDigit; secondDigit = 11 - (secondDigit % 11); if (secondDigit >= 10) { secondDigit = 0; } return number + '-' + firstDigit + secondDigit; }
JavaScript
0.999999
@@ -313,17 +313,16 @@ parts;%0A -%09 %0A%09parts
2b828f0f4ba9e1dcad07af344a058d8cb3f2b49b
fix for game reporting wrong size of the local map
lib/pipmap.js
lib/pipmap.js
exports.decodeMap = function(buffer) { var cursor = 0; var width = buffer.readUInt32LE(cursor); cursor += 4; var height = buffer.readUInt32LE(cursor); cursor += 4; function decodeExtents() { var x = buffer.readFloatLE(cursor); cursor += 4; var y = buffer.readFloatLE(cursor); cursor += 4; return {x: x, y: y}; } var nw = decodeExtents(); var ne = decodeExtents(); var sw = decodeExtents(); var pixels = buffer.slice(cursor, cursor + width * height); return { width: width, height: height, pixels: pixels, extents: { nw: nw, ne: ne, sw: sw } }; }
JavaScript
0
@@ -427,16 +427,432 @@ nts();%0A%0A + // fix for invalid map size from https://github.com/nkatsaros/pipboygo/blob/master/protocol/map.go#L55%0A // originally from https://github.com/CyberShadow/csfo4/blob/master/mapfix/mapfix.d%0A // thanks to nkatsaros and CyberShadow!%0A if (width * height %3C buffer.length - 32) %7B%0A width = (buffer.length - 32) / height;%0A if (buffer.length != 32 + width * height) %7B%0A throw 'invalid map stride';%0A %7D%0A %7D%0A%0A var pi
e56eaaac65bd2a3877abd403f1358ed1ba7150b5
rename variables so as to minimize collisions
lib/script.js
lib/script.js
module.exports=function(opt){ opt=opt||{}; var error=opt.error||console.error; var pattern=/<\?js[\s\S]*?js\?>/g, idPattern=/\{js\d+?\}/g; return function(req,res,next){ if(res.body && pattern.test(res.body)){ // common variables var JS={}, results={}, total=0, count, done=function(){ --count === 0 && res.api.finish(); }; res.api=res.api||{}; res.api.finish=function(){ res.body=res.body.replace(idPattern,function(id){ return results[id]; }); next(); }; res.api.wait=function(n){ count+=(typeof n==='number'?Math.floor(n):1); return done; }; res.body=res.body.replace(pattern,function(block){ var id='{js'+(total++)+'}'; JS[id]=block.slice(4,-4); return id; }); count=total; for(var block in JS){ (function(){ var id=block, echo=function(value){ results[id]=(results[id]||'')+value; }; try{ eval(JS[id]); }catch(err){ error(err); } done(); }()); } }else{ next(); } }; };
JavaScript
0.000001
@@ -283,16 +283,17 @@ var +_ JS=%7B%7D,%0A @@ -307,23 +307,24 @@ -results +_RESULTS =%7B%7D,%0A @@ -336,21 +336,22 @@ -total +_TOTAL =0,%0A @@ -362,21 +362,22 @@ -count +_COUNT ,%0A @@ -386,20 +386,21 @@ -done +_DONE =functio @@ -406,21 +406,22 @@ on()%7B -- -count +_COUNT === 0 & @@ -608,23 +608,24 @@ return -results +_RESULTS %5Bid%5D;%0A @@ -735,21 +735,22 @@ -count +_COUNT +=(typeo @@ -805,20 +805,21 @@ return -done +_DONE ;%0A @@ -921,21 +921,22 @@ ='%7Bjs'+( -total +_TOTAL ++)+'%7D'; @@ -952,16 +952,17 @@ +_ JS%5Bid%5D=b @@ -1039,19 +1039,21 @@ -count=total +_COUNT=_TOTAL ;%0A%0A @@ -1075,17 +1075,19 @@ var -block +_BLOCK in +_ JS)%7B @@ -1144,16 +1144,18 @@ var -id=block +_ID=_BLOCK ,%0A @@ -1230,31 +1230,35 @@ -results%5Bid%5D=(results%5Bid +_RESULTS%5B_ID%5D=(_RESULTS%5B_ID %5D%7C%7C' @@ -1348,21 +1348,23 @@ eval( +_ JS%5B -id +_ID %5D);%0A @@ -1474,12 +1474,13 @@ -done +_DONE ();%0A @@ -1515,17 +1515,16 @@ %7D%0A -%0A
be1319a7eef0e4c6b5f8fe18e55ac749dff52177
normalize prefixes and manifests paths
lib/server.js
lib/server.js
const normalizePath = require('./common').normalizePath; function unifyOptions(options) { options.verbose = (options.verbose || []).reduce(function (opt, val) { if (val === 'all') { opt.local = opt.remote = opt.proxy = true; } else { opt[val] = true; } return opt; }, {}); options.prefixes = [].concat.apply([], options.prefixes); //"flatten" one layer options.manifests = [].concat.apply([], options.manifests); //"flatten" one layer options.urlPath = normalizePath(options.path || '/appsuite'); //default to true, but allow custom option options.rejectUnauthorized = options.rejectUnauthorized === undefined || options.rejectUnauthorized; if (options.server) { options.server = normalizePath(options.server); } return options; } const http = require('http'); const connect = require('connect'); const appsLoadMiddleware = require('./middleware/appsload'); const manifestsMiddleware = require('./middleware/manifests'); const loginMiddleware = require('./middleware/login'); const localFilesMiddleware = require('./middleware/localfiles'); const proxyMiddleware = require('./middleware/proxy'); const preFetchMiddleware = require('./middleware/pre_fetch'); function create(options) { options = unifyOptions(options); const handler = connect() .use(preFetchMiddleware.create(options)) .use(appsLoadMiddleware.create(options)) .use(manifestsMiddleware.create(options)) .use(loginMiddleware.create(options)) .use(localFilesMiddleware.create(options)) .use(proxyMiddleware.create(options)); http.createServer(handler) .listen(options.port || 8337); } module.exports = { create: create, unifyOptions: unifyOptions };
JavaScript
0
@@ -392,39 +392,36 @@ refixes) -; //%22flatten%22 one layer +.map(normalizePath); %0A opt @@ -479,31 +479,28 @@ sts) -; //%22flatten%22 one layer +.map(normalizePath); %0A
24bc0e15ce4bb4b95626f9b5fd93b3da1cc2193c
Add logging system
lib/server.js
lib/server.js
const Hapi = require( 'hapi' ); const Poetry = require( './' ); const port = process.env.PORT || process.env.port || 8080; const server = new Hapi.Server(); server.connection( { port: port } ); server.register( require( 'inert' ), ( err ) => { if ( err ) throw err; } ); server.start( ( err ) => { if ( err ) throw err; Poetry.log( 'HAPI server running at:', server.info.uri ); } ); module.exports = server;
JavaScript
0.000001
@@ -31,22 +31,19 @@ ;%0Aconst -Poetry +Log = requi @@ -49,16 +49,27 @@ ire( './ +methods/log ' );%0A%0Aco @@ -346,16 +346,9 @@ -Poetry.l +L og(
ce2122a86b246f544635e33e2d6ab6a6628b6923
Add warning if execution without captured browser
lib/server.js
lib/server.js
var io = require('socket.io'); var net = require('net'); var cfg = require('./config'); var ws = require('./web-server'); var logger = require('./logger'); var browser = require('./browser'); var STATIC_FOLDER = __dirname + '/../static/'; exports.start = function(configFilePath) { var config = cfg.parseConfig(configFilePath); logger.setLevel(config.logLevel); logger.useColors(config.logColors); var log = logger.create(); var fileGuardian = new cfg.FileGuardian(config.files, config.exclude, config.autoWatch, config.autoWatchInterval); log.info('Starting web server at http://localhost:' + config.port); var webServer = ws.createWebServer(fileGuardian, STATIC_FOLDER).listen(config.port); var socketServer = io.listen(webServer, { logger: logger.create('socket.io', 0), transports: ['websocket', 'xhr-polling', 'jsonp-polling'] }); var capturedBrowsers = new browser.Collection(); var executionScheduled = false; var pendingCount = 0; var lastFailedIds = []; capturedBrowsers.on('change', function() { executionScheduled && tryExecution(); // TODO(vojta): send only to interested browsers socketServer.sockets.emit('info', capturedBrowsers.serialize()); }); var tryExecution = function() { var nonReady = []; if (capturedBrowsers.areAllReady(nonReady)) { log.debug('All browsers are ready, executing'); executionScheduled = false; capturedBrowsers.setAllIsReadyTo(false); capturedBrowsers.clearResults(); pendingCount = capturedBrowsers.length; socketServer.sockets.emit('execute', lastFailedIds); lastFailedIds = []; } else { log.debug('Delaying execution, these browsers are not ready: ' + nonReady.join(', ')); executionScheduled = true; } }; socketServer.sockets.on('connection', function (socket) { log.debug('New browser has connected on socket ' + socket.id); browser.createBrowser(socket, capturedBrowsers); socket.on('complete', function() { pendingCount--; if (!pendingCount) { var results = capturedBrowsers.getResults(); log.info('TOTAL FAILED: %d PASSED: %d', results.failed, results.success); } }); socket.on('result', function(result) { if (!result.success && lastFailedIds.indexOf(result.id) === -1) { lastFailedIds.push(result.id); } }); }); fileGuardian.on('fileModified', function() { log.info('Execution (fired by autoWatch)'); tryExecution(); }); // listen on port, waiting for runner net.createServer(function (socket) { socket.on('data', function(buffer) { log.info('Execution (fired by runner)'); fileGuardian.checkModifications(); tryExecution(); }); }).listen(config.runnerPort); };
JavaScript
0.000001
@@ -1278,16 +1278,137 @@ %0A if +(!capturedBrowsers.length) %7B%0A log.warn('No captured browser, open http://localhost:' + config.port);%0A%0A %7D else if (capture
187940c74d6879386d78547fa625d6397dd19c17
Use server.url config in injected live reload script tag
lib/server.js
lib/server.js
var st = require('st') , http = require('http') , path = require('path') , js = require('atomify-js') , css = require('atomify-css') , open = require('open') , through = require('through') , tinylr = require('tiny-lr-fork') , gaze = require('gaze') , colors = require('colors') , server module.exports = function (args) { console.log('') var mount = st(args.server.st || { path: process.cwd(), cache: false }) , port = args.server.port || 1337 , launch = args.server.open , path = args.server.path || '/default' , lr = args.server.lr if (lr) { lr = typeof lr === 'boolean' ? {} : lr lr.patterns = lr.patterns || lr._ || [] lr.port = lr.port || 35729 startLiveReloadServer(lr) console.log(('Live reload server listening on port ' + lr.port).grey) } if (path.charAt(0) !== '/') path = '/' + path if (!args.js) args.js = {} if (!args.js.alias) args.js.alias = '/' + args.js.entry if (!args.css) args.css = {} if (!args.css.alias) args.css.alias = '/' + args.css.entry http.createServer(function (req, res) { switch (req.url.split('?')[0]) { case args.js.alias || args.js.entry: js(args.js, responder('javascript', res)) break case args.css.alias || args.css.entry: css(args.css, responder('css', res)) break case '/default': serveDefaultPage(res, args, lr) break default: if (lr && req.url.substr(-5) === '.html') res.filter = injectLiveReloadScript(lr) mount(req, res) break } }).listen(port) console.log(('Atomify server listening on port ' + port).grey) console.log('') if (launch) open(args.server.url || 'http://localhost:' + port + path) } function responder (type, res) { return function (err, src) { if (err) console.log(err); if (!res.headersSent) res.setHeader('Content-Type', 'text/' + type) res.end(src) } } function startLiveReloadServer (lr) { server = tinylr() server.listen(lr.port) var patterns = lr.patterns.length ? lr.patterns : ['*.html', '*.js', '*.css'] gaze(patterns, function() { this.on('changed', function (filepath) { if (!lr.quiet) console.log(path.relative(process.cwd(), filepath), 'changed'.grey); server.changed({ body: { files: filepath } }) }) }) } function injectLiveReloadScript (lr) { var buffer = '' , tag = '<script src="http://localhost:' + lr.port + '/livereload.js?snipver=1"></script>\n' return through(function (chunk) { buffer += chunk.toString() }, function () { this.queue(buffer.replace('</body>', tag + '</body>')) this.queue(null) }) } function serveDefaultPage (res, args, lr) { var src = '<html><head>' src += '<title>generated by atomify</title>' src += '<link rel="stylesheet" href="CSS">' src += '</head><body>' src += '<script src="JS"></script>' src += '</body></html>' src = src.replace('JS', args.js.alias) src = src.replace('CSS', args.css.alias) res.setHeader('Content-Type', 'text/html') var thru = lr ? injectLiveReloadScript(lr) : through() thru.pipe(res) thru.write(src) thru.end('\n') }
JavaScript
0.000001
@@ -66,24 +66,49 @@ ire('path')%0A + , url = require('url')%0A , js = req @@ -122,24 +122,24 @@ tomify-js')%0A - , css = re @@ -324,16 +324,28 @@ , server +%0A , baseUrl %0A%0Amodule @@ -608,16 +608,132 @@ ver.lr%0A%0A + args.server.url = args.server.url %7C%7C 'http://localhost:' + port + path%0A baseUrl = parseBaseUrl(args.server.url)%0A%0A if (lr @@ -1853,45 +1853,8 @@ .url - %7C%7C 'http://localhost:' + port + path )%0A%7D%0A @@ -2526,32 +2526,31 @@ pt src=%22 -http://localhost +' + baseUrl + ' :' + lr. @@ -3248,16 +3248,16 @@ te(src)%0A - thru.e @@ -3263,12 +3263,122 @@ end('%5Cn')%0A%7D%0A +%0Afunction parseBaseUrl (urlString) %7B%0A var u = url.parse(urlString)%0A return u.protocol + '//' + u.hostname%0A%7D%0A
20d85d5772e0f2c0841a9399adfc3254e9f13e6f
Add Simple#makeThreads
lib/simple.js
lib/simple.js
/* * CometJS / simple.js * copyright (c) 2014 Susisu */ "use strict"; function end () { module.exports = Object.freeze({ "Simple" : Simple, "ThreadOption": ThreadOption }); } var comet = { "input" : require("./input.js"), "score" : require("./score.js"), "thread": require("./thread.js") }; function Simple(sources) { this.sources = sources; } Object.defineProperties(Simple.prototype, { "makeThreads": { "value": function (options) { // return threads } } }); function ThreadOption(inputDevice, stdDuration, speedMultiplier, entityBuilder) { this.inputDevice = inputDevice; this.stdDuration = stdDuration; this.speedMultiplier = speedMultiplier; this.entityBuilder = entityBuilder; } function EntityBuilder(noteEntityBuilder, longNoteEntityBuilder) { this.noteEntityBuilder = noteEntityBuilder; this.longNoteEntityBuilder = longNoteEntityBuilder; } function NoteThread(source, inputDevice, stdDuration, speedMultiplier, entityBuilder) { this._source = source; this._inputDevice = inputDevice; this._stdDuration = stdDuration; this._entityBuilder = entityBuilder; } NoteThread.prototype = Object.create(comet.thread.IThread.prototype, { "constructor" : NoteThread, "writable" : true, "configurable": true }); Object.defineProperties(NoteThread.prototype, { "init": { "value": function (initialFrame) { } }, "tick": { "value": function (currentFrame) { } } }); function LongNoteThread(source, inputDevice, stdDuration, speedMultiplier, entityBuilder) { this._source = source; this._inputDevice = inputDevice; this._stdDuration = stdDuration; this._entityBuilder = entityBuilder; } LongNoteThread.prototype = Object.create(comet.thread.IThread.prototype, { "constructor" : LongNoteThread, "writable" : true, "configurable": true }); Object.defineProperties(LongNoteThread.prototype, { "init": { "value": function (initialFrame) { } }, "tick": { "value": function (currentFrame) { } } }); function Source(noteSource, longNoteSource) { this.noteSource = noteSource; this.longNoteSource = longNoteSource; } function NoteSource(notes, speedChanges, propertyChanges) { this.notes = notes; this.speedChanges = speedChanges; this.propertyChanges = propertyChanges; } function NoteSource(longNotes, speedChanges, propertyChanges) { this.longNotes = longNotes; this.speedChanges = speedChanges; this.propertyChanges = propertyChanges; } function Note(hitFrame, relSpeed, properties) { this.hitFrame = hitFrame; this.relSpeed = relSpeed; this.appearFrame = 0; this.posCorrection = 0; this.properties = properties; } Object.defineProperties(Note.prototype, { "frame": { "get": function () { return this.hitFrame; } } }); function LongNote(hitFrame, endFrame, relSpeed, properties) { this.hitFrame = hitFrame; this.endFrame = endFrame; this.relSpeed = relSpeed; this.appearFrame = 0; this.length = 0; this.posCorrection = 0; this.properties = properties; } Object.defineProperties(LongNote.prototype, { "frame": { "get": function () { return this.hitFrame; } } }); function SpeedChange(frame, speed) { this.frame = frame; this.speed = speed; } function PropertyChange(frame, name, value) { this.frame = frame; this.name = name; this.value = value; } end();
JavaScript
0
@@ -510,10 +510,884 @@ -// +if (this.options.length %3C this.sources.length) %7B%0A throw new Error(%22%22);%0A %7D%0A var threads = %5B%5D;%0A for (var i = 0; i %3C this.sources.length; i++) %7B%0A var source = this.sources%5Bi%5D;%0A var option = options%5Bi%5D;%0A var noteThread = new NoteThread(%0A source.noteSource,%0A option.inputDevice,%0A option.speedMultiplier,%0A option.entityBuilder.noteEntityBuilder%0A );%0A var longNoteThread = new LongNoteThread(%0A source.longNoteSource,%0A option.inputDevice,%0A option.speedMultiplier,%0A option.entityBuilder.longNoteEntityBuilder%0A );%0A threads.push(noteThread, longNoteThread);%0A %7D%0A ret @@ -1397,16 +1397,17 @@ threads +; %0A
05491d3f51c3844b64aa3a2b03bfd8692581b412
fix external link click catch
main/html/app.js
main/html/app.js
const { h } = require('mutant') const nest = require('depnest') const insertCss = require('insert-css') const Tabs = require('hypertabs') exports.gives = nest('main.html.app') exports.needs = nest({ main: { async: { catchLinkClick: 'first' }, html: { error: 'first', externalConfirm: 'first', search: 'first' }, sync: { catchKeyboardShortcut: 'first' } }, 'router.html.page': 'first', 'styles.css': 'reduce' }) exports.create = function (api) { return nest('main.html.app', app) function app () { const css = values(api.styles.css()).join('\n') insertCss(css) const search = api.main.html.search((path, change) => { if (tabs.has(path)) { tabs.select(path) return true } addPage(path, true, false) return change }) const tabs = Tabs(onSelect, { append: h('div.navExtra', [ search ]) }) function onSelect (indexes) { search.input.value = tabs.get(indexes[0]).content.id } const App = h('App', tabs) function addPage (link, change, split) { const page = api.router.html.page(link) if (!page) return page.id = page.id || link tabs.add(page, change, split) } const initialTabs = ['/public', '/private', '/notifications'] initialTabs.forEach(p => addPage(p)) tabs.select(0) // Catch keyboard shortcuts api.main.sync.catchKeyboardShortcut(window, { tabs, search }) // Catch link clicks api.main.async.catchLinkClick(App, (link, { ctrlKey: openBackground, isExternal }) => { if (isExternal) api.main.html.externalConfirm(link) if (tabs.has(link)) tabs.select(link) else { const changeTab = !openBackground addPage(link, changeTab) } }) // Catch errors var { container: errorPage, content: errorList } = api.router.html.page('/errors') window.addEventListener('error', ev => { if (!tabs.has('/errors')) tabs.add(errorPage, true) const error = api.main.html.error(ev.error || ev) errorList.appendChild(error) }) return App } } function values (object) { const keys = Object.keys(object) return keys.map(k => object[k]) }
JavaScript
0
@@ -1597,16 +1597,23 @@ xternal) + return api.mai
a6260c51ee288d059f5c4660a993df48a48d7276
fix aframe-animation-component regression https://github.com/supermedium/superframe/issues/192
tests/dummy/app/components/a-sky.js
tests/dummy/app/components/a-sky.js
import ASky from 'ember-aframe/components/a-sky'; import stringifyComponent from 'ember-aframe/macros/stringify-component'; import { raw } from 'ember-awesome-macros'; import { task, timeout } from 'ember-concurrency'; import InboundActions from 'ember-component-inbound-actions/inbound-actions'; export default ASky.extend(InboundActions, { attributeBindings: [ 'animation__fade' ], animation__fade: stringifyComponent('animation', { property: raw('material.color'), startEvents: raw('set-image-fade'), dir: raw('alternate'), dur: 'dur', from: raw('#FFF'), to: raw('#000') }), changeMaterialTask: task(function * (src) { this.element.emit('set-image-fade'); yield timeout(this.get('dur')); this.get('changeMaterial')(src); }), actions: { startChangingMaterial(src) { this.get('changeMaterialTask').perform(src); } } });
JavaScript
0.000014
@@ -602,16 +602,128 @@ ('#000') +,%0A%0A // regressed 3.2.5 =%3E 4.0.0-beta1%0A // https://github.com/supermedium/superframe/issues/192%0A loop: 1 %0A %7D),%0A%0A
ec794ed7d194f8a98e920c6e083a6a0652baa0e6
Remove check on grunt.config.data
tasks/update_json_task.js
tasks/update_json_task.js
/* * grunt-update-json * https://github.com/andreaspizsa/grunt-update-json * * Copyright (c) 2013 * Licensed under the MIT license. */ 'use strict'; var _ = require('lodash'), updateJSON = require('./lib/update_json'), defaultOptions = require('./lib/default_options'); module.exports = function(grunt){ var register = grunt.registerMultiTask, task = function(){ updateJSON(grunt, this.files, this.data.fields, this.options()); }; // handle the degenerate case if(!grunt.config.data[updateJSON.taskName]){ register = grunt.registerTask; task = function(target){ // use default options var targets = target ? _.pick(defaultOptions, target) : defaultOptions; _.each(targets, function(obj, key){ updateJSON(grunt, obj.files, obj.fields); }); }; } register(updateJSON.taskName, updateJSON.taskDescription, task); };
JavaScript
0.000001
@@ -456,372 +456,8 @@ %7D; -%0A%0A // handle the degenerate case%0A if(!grunt.config.data%5BupdateJSON.taskName%5D)%7B%0A register = grunt.registerTask;%0A task = function(target)%7B%0A // use default options%0A var targets = target ? _.pick(defaultOptions, target) : defaultOptions;%0A _.each(targets, function(obj, key)%7B%0A updateJSON(grunt, obj.files, obj.fields);%0A %7D);%0A %7D;%0A %7D %0A r
f61deda4e8d8f37ed16605b4f109584a2a5c712e
Fix format detection error in validate logic.
src/verbs/validate.js
src/verbs/validate.js
/** Implementation of the 'validate' verb for HackMyResume. @module validate.js @license MIT. See LICENSE.md for details. */ (function() { var FS = require('fs'); var ResumeFactory = require('../core/resume-factory'); var SyntaxErrorEx = require('../utils/syntax-error-ex'); var chalk = require('chalk'); module.exports = /** Validate 1 to N resumes in either FRESH or JSON Resume format. */ function validate( sources, unused, opts, logger ) { var _log = logger || console.log; if( !sources || !sources.length ) { throw { fluenterror: 6 }; } var isValid = true; var validator = require('is-my-json-valid'); var schemas = { fresh: require('fresca'), jars: require('../core/resume.json') }; var resumes = ResumeFactory.load( sources, { log: _log, format: null, objectify: false, throw: false, muffle: true }); // Load input resumes... resumes.forEach(function( src ) { if( src.error ) { // TODO: Core should not log _log( chalk.white('Validating ') + chalk.gray.bold(src.file) + chalk.white(' against ') + chalk.gray.bold('AUTO') + chalk.white(' schema:') + chalk.red.bold(' BROKEN') ); var ex = src.error; // alias if ( ex instanceof SyntaxError) { var info = new SyntaxErrorEx( ex, src.raw ); _log( chalk.red.bold('--> ' + src.file.toUpperCase() + ' contains invalid JSON on line ' + info.line + ' column ' + info.col + '.' + chalk.red(' Unable to validate.') ) ); _log( chalk.red.bold(' INTERNAL: ' + ex) ); } else { _log(chalk.red.bold('ERROR: ' + ex.toString())); } return; } var json = src.json; var isValid = false; var style = 'green'; var errors = []; var fmt = json.meta && (json.meta.format==='[email protected]') ? 'fresh':'jars'; try { var validate = validator( schemas[ fmt ], { // Note [1] formats: { date: /^\d{4}(?:-(?:0[0-9]{1}|1[0-2]{1})(?:-[0-9]{2})?)?$/ } }); isValid = validate( json ); if( !isValid ) { style = 'yellow'; errors = validate.errors; } } catch(exc) { return; } _log( chalk.white('Validating ') + chalk.white.bold(src.file) + chalk.white(' against ') + chalk.white.bold(fmt.replace('jars','JSON Resume').toUpperCase()) + chalk.white(' schema: ') + chalk[style].bold(isValid ? 'VALID!' : 'INVALID') ); errors.forEach(function(err,idx) { _log( chalk.yellow.bold('--> ') + chalk.yellow(err.field.replace('data.','resume.').toUpperCase() + ' ' + err.message) ); }); }); }; }());
JavaScript
0.000001
@@ -1871,66 +1871,31 @@ son. -meta && (json.meta.format==='[email protected]') ? 'fresh':'jars +basics ? 'jrs' : 'fresh ';%0A%0A
8fa296f83ce103c20054c94f81118d119a0cdbc0
Fix tStep not being added to request properly
worker.js
worker.js
// Include libraries var async = require('async'); var cluster = require('cluster'); var express = require('express'); var mongoose = require('mongoose'); var ds = require('./lib/data-store'); var Predictor = require('./lib/predictor'); var currentDownload = null; setInterval(function() { if(currentDownload === null) { ds.popQueue(updateSounding); } }, 10000); updateSounding = function(error, key) { if(error !== null || key === null) return; currentDownload = key; async.waterfall([ function download(callback) { ds.downloadSounding(key, callback); }, function preprocess(filename, callback) { ds.preprocessSounding(filename, callback); } ], function(err, result) { if(err) { ds.requeue(key); console.log('Error updating ' + key + ' : ' + err); } else { console.log('Updated ' + key); } // Accept a new key now currentDownload = null; }); }; // Create an express application app = express(); // Configure express app.configure(function() { // Simple logger // TODO Replace logger app.use(function(req, res, next) { console.log('%s: %s %s', cluster.worker.process.pid, req.method, req.url); next(); }); // Static file server // TODO Replace express.static with nginx app.use(express.static(__dirname + '/app')); }); app.get('/api/sounding', function(req, res) { var timestring = req.param('time'); var location = req.param('loc'); if(!timestring || !location) { res.send(400, 'Bad Request!'); return; } location = location.split(','); var lat = parseFloat(location[0]); var lng = parseFloat(location[1]); var timestamp = parseInt(timestring, 10); if(isNaN(lat) || isNaN(lng) || isNaN(timestamp)) { res.send(400, 'Bad Request!'); return; } var time = new Date(timestamp); ds.getSounding(time, lat, lng, function(err, sounding) { if(err) { res.send(500, err); } else { res.send(200, JSON.stringify(sounding)); } }); }); app.get('/api/prediction', function(req, res) { var params = {}; // Ensure start location var location = req.param('loc'); location = location.split(','); var lat = parseFloat(location[0]); var lng = parseFloat(location[1]); params.loc = [lng, lat]; // Ensure start time if(Object.prototype.toString.call(req.query.time) !== '[object Date]') { var timestamp = parseInt(req.query.time, 10); if(isNaN(timestamp)) { params.time = new Date(); } else { params.time = new Date(timestamp); } } params.balloon = req.query.balloon; params.parachute = req.query.parachute; params.mass = parseFloat(req.query.mass); params.direction = req.query.direction; var prediction = new Predictor(params); var tStep = 10; if(params.direction === 'quick') tStep = 60; prediction.run({tStep: 10}, function(err, result) { if(err) { res.send(500, err); } else { res.send(200, result); } }); }); // Bind to a port app.listen(global.PORT); // Connect to MongoDB mongoose.connect('mongodb://127.0.0.1/windData'); console.log('Worker ' + cluster.worker.process.pid + ' running.');
JavaScript
0
@@ -2835,18 +2835,21 @@ %7BtStep: -10 +tStep %7D, funct
df52375d11240d356f60b54daf85350daae4e5f9
Update redirect-handler-test.js
tests/unit/redirect-handler-test.js
tests/unit/redirect-handler-test.js
import RedirectHandler from 'torii/redirect-handler'; import { CURRENT_REQUEST_KEY } from 'torii/mixins/ui-service-mixin'; import QUnit from 'qunit'; let { module, test } = QUnit; function buildMockWindow(windowName, url){ return { name: windowName, location: { toString: function(){ return url; } }, localStorage: { setItem: function() {}, getItem: function() {}, removeItem: function() {} }, close: Ember.K }; } module('RedirectHandler - Unit'); test('exists', function(assert){ assert.ok(RedirectHandler); }); test("handles a tori-popup window with a current request key in localStorage and url", function(assert){ assert.expect(2); var keyForReturn = 'some-key'; var url = 'http://authServer?code=1234512345fw'; var mockWindow = buildMockWindow("torii-popup:abc123", url); mockWindow.localStorage.getItem = function(key) { if (key === CURRENT_REQUEST_KEY) { return keyForReturn; } }; mockWindow.localStorage.setItem = function(key, val) { if (key === keyForReturn) { assert.equal(val, url, 'url is set for parent window'); } }; var handler = RedirectHandler.create({windowObject: mockWindow}); Ember.run(function(){ handler.run().then(function(){}, function(){ assert.ok(false, "run handler rejected a basic url"); }); }); assert.ok(!handler.isFulfilled, "hangs the return promise forever"); }); test('rejects the promise if there is no request key', function(assert){ var mockWindow = buildMockWindow("", "http://authServer?code=1234512345fw"); var handler = RedirectHandler.create({windowObject: mockWindow}); Ember.run(function(){ handler.run().then(function(){ assert.ok(false, "run handler succeeded on a url"); }, function(){ assert.ok(true, "run handler rejects a url without data"); }); }); }); test('does not set local storage when not a torii popup', function(assert){ assert.expect(1); var mockWindow = buildMockWindow("", "http://authServer?code=1234512345fw"); mockWindow.localStorage.setItem = function(/* key, value */) { assert.ok(false, "storage was set unexpectedly"); }; var handler = RedirectHandler.create({windowObject: mockWindow}); Ember.run(function(){ handler.run().then(function(){ assert.ok(false, "run handler succeeded on a popup"); }, function(){ assert.ok(true, "run handler rejects a popup without a name"); }); }); }); test('closes the window when a torii popup with request', function(assert){ assert.expect(1); var mockWindow = buildMockWindow("torii-popup:abc123", "http://authServer?code=1234512345fw"); mockWindow.localStorage.getItem = function(key) { if (key === CURRENT_REQUEST_KEY) { return 'some-key'; } }; var handler = RedirectHandler.create({windowObject: mockWindow}); mockWindow.close = function(){ assert.ok(true, "Window was closed"); }; Ember.run(function(){ handler.run(); }); }); test('does not close the window when a not torii popup', function(assert){ assert.expect(1); var mockWindow = buildMockWindow("", "http://authServer?code=1234512345fw"); var handler = RedirectHandler.create({windowObject: mockWindow}); mockWindow.close = function(){ assert.ok(false, "Window was closed unexpectedly"); }; Ember.run(function(){ handler.run().then(function(){}, function(){ assert.ok(true, "error handler is called"); }); }); });
JavaScript
0.000001
@@ -464,15 +464,21 @@ se: -Ember.K +function() %7B%7D %0A %7D
687c6b133942db6ab04a37c7e664d257d8d03448
set up kue config properly
worker.js
worker.js
var _ = require('lodash'), colors = require('colors'), Promise = require('bluebird'), rc = require('rc'), rollbar = require('rollbar'), sails = require('sails'), util = require('util'); // define new jobs here. // each job should return a promise. // use Promise.method if the job is synchronous. // // TODO these job definitions should go elsewhere. // the common case of queueing a class method could also be handled with // a single job. var jobDefinitions = { 'test': Promise.method(function(job) { console.log(new Date().toString().magenta); throw new Error('whoops!'); }), 'Comment.sendNotificationEmail': function(job) { return Comment.sendNotificationEmail(job.data.recipientId, job.data.commentId, job.data.version); }, 'Post.sendNotificationEmail': function(job) { return Post.sendNotificationEmail(job.data.recipientId, job.data.seedId); } }; var Worker = function() { this.queue = require('kue').createQueue(); }; Worker.prototype.start = function() { var queue = this.queue; // load jobs _.forIn(jobDefinitions, function(promise, name) { queue.process(name, function(job, done) { // put common behavior for all jobs here var label = util.format(' Job %s ', job.id).bgBlue.black + ' '; sails.log.info(label + name); promise(job).then(function() { sails.log.info(label + 'done'.green); done(); }) .catch(function(err) { sails.log.error(label + err.message.red); rollbar.handleError(err); done(err); }); }); }); // check for delayed jobs to enqueue. // this must be run in only one process to avoid a race condition: // https://github.com/learnboost/kue#delayed-jobs worker.queue.promote(2000); }; var worker = new Worker(); // set up graceful shutdown. // these have to be defined outside the "sails lift" callback, // otherwise they are overridden by Sails. process.on('SIGINT', function() { console.log(); process.emit('SIGTERM'); return false; }) .on('SIGTERM', function() { sails.log.info("Landing...".yellow); worker.queue.shutdown(function(err) { sails.lower(); sails.log.info("Done".green); }, 5000); }); // go! sails.log.info("Lifting...".yellow); sails.lift(_.merge(rc('sails'), { log: {noShip: true}, hooks: {http: false, sockets: false, views: false} }), function(err) { if (err) { console.error("Couldn't lift Sails: " + err); process.exit(1); } worker.start(); sails.log.info('Aloft.'.blue); });
JavaScript
0
@@ -1,12 +1,38 @@ +require('./config/kue');%0A%0A var _ = requ
4cedf55a502d44d97a1748c3296a43c24804cd01
Fix [CP-86] modifier className update
packages/components/containers/sidebar/StorageSpaceStatus.js
packages/components/containers/sidebar/StorageSpaceStatus.js
import React, { useState } from 'react'; import PropTypes from 'prop-types'; import { c } from 'ttag'; import { CircularProgress, Dropdown, Icon, Loader, generateUID, useUser, usePopperAnchor, useSubscription } from 'react-components'; import humanSize from 'proton-shared/lib/helpers/humanSize'; import { hasVisionary, hasLifetime } from 'proton-shared/lib/helpers/subscription'; import { classnames } from '../../helpers/component'; const StorageSpaceStatus = ({ upgradeButton }) => { const [{ MaxSpace, UsedSpace }] = useUser(); const [subscription, loadingSubscription] = useSubscription(); const [uid] = useState(generateUID('dropdown')); const { anchorRef, isOpen, toggle, close } = usePopperAnchor(); const canUpgradeStorage = !hasVisionary(subscription) && !hasLifetime(subscription); // round with 0.01 precision const usedPercent = Math.round((UsedSpace / MaxSpace) * 10000) / 100; const maxSpaceFormatted = humanSize(MaxSpace); const usedSpaceFormatted = humanSize(UsedSpace); const color = usedPercent < 60 ? 'circle-bar--global-success' : usedPercent < 80 ? 'circle-bar--global-attention' : 'circle-bar--global-warning'; return ( <> <button type="button" aria-describedby={uid} onClick={toggle} ref={anchorRef}> <CircularProgress progress={usedPercent} className={color}> <g className="circle-chart__info"> <rect x="17" y="14" width="1.55" height="9.1" className="circle-chart__percent fill-white" /> <rect x="17" y="11" width="1.55" height="1.53" className="circle-chart__percent fill-white" /> </g> </CircularProgress> <span className="smallest mt0 mb0-5 mlauto mrauto lh100 circle-chart-info opacity-40 bl"> {usedSpaceFormatted} </span> </button> <Dropdown id={uid} isOpen={isOpen} noMaxSize={true} anchorRef={anchorRef} onClose={close} originalPlacement="right-bottom" size="auto" > <div className="absolute top-right mt0-5r mr0-5r"> <button type="button" className="flex flex-items-center" title={c('Action').t`Close`}> <Icon name="close" /> <span className="sr-only">{c('Action').t`Close`}</span> </button> </div> <div className="flex p1"> <div className="pr1 flex flex-items-center"> <div className="relative"> <CircularProgress progress={usedPercent} size={100} className={classnames(['circle-chart__background--bigger', color])} /> <span className="centered-absolute">{usedPercent}%</span> </div> </div> <div className="w150p"> <b className="flex">{c('Title').t`Storage`}</b> <small>{c('Info').jt`${usedSpaceFormatted} of ${maxSpaceFormatted} used`}</small> <div className="mb1"> <span className="opacity-50 small"> {c('Info').t`Your storage space is shared across all Proton products.`} </span> </div> {loadingSubscription ? <Loader /> : canUpgradeStorage ? upgradeButton : null} </div> </div> </Dropdown> </> ); }; StorageSpaceStatus.propTypes = { upgradeButton: PropTypes.node.isRequired }; export default StorageSpaceStatus;
JavaScript
0
@@ -1069,24 +1069,16 @@ color = -%0A usedPer @@ -1086,28 +1086,16 @@ ent %3C 60 -%0A ? 'circ @@ -1106,35 +1106,12 @@ ar-- -g lo -bal-success'%0A +w' : u @@ -1125,28 +1125,16 @@ ent %3C 80 -%0A ? 'circ @@ -1145,37 +1145,15 @@ ar-- -global-attention'%0A +medium' : ' @@ -1168,22 +1168,12 @@ ar-- -global-warning +full ';%0A%0A
6f1526414e019ff54c70ba09febd1219e92ec5bd
add main process compilation notice to browser
template/.electron-vue/dev-client.js
template/.electron-vue/dev-client.js
const hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true') hotClient.subscribe(event => { if (event.action === 'reload') { window.location.reload() } if (event.action === 'compiling') { console.log('restarting soon') } })
JavaScript
0
@@ -114,147 +114,867 @@ %7B%0A -if (event.action === 'reload') %7B%0A window.location.reload()%0A %7D%0A%0A if (event.action === 'compiling') %7B%0A console.log('restarting soon') +/**%0A * Reload browser when HTMLWebpackPlugin emits a new index.html%0A */%0A if (event.action === 'reload') %7B%0A window.location.reload()%0A %7D%0A%0A /**%0A * Notify browser when %60main%60 process is compiling,%0A * giving notice for an expected reload of the %60electron%60 process%0A */%0A if (event.action === 'compiling') %7B%0A document.body.innerHTML += %60%0A %3Cstyle%3E%0A #dev-client %7B%0A background: #4fc08d;%0A border-radius: 4px;%0A bottom: 20px;%0A box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14), 0 1px 10px 0 rgba(0, 0, 0, 0.12), 0 2px 4px -1px rgba(0, 0, 0, 0.3);%0A color: #fff;%0A font-family: 'Source Sans Pro', sans-serif;%0A left: 20px;%0A padding: 8px 12px;%0A position: absolute;%0A %7D%0A %3C/style%3E%0A%0A %3Cdiv id=%22dev-client%22%3E%0A Compiling Main Process...%0A %3C/div%3E%0A %60 %0A %7D
77a6fda36054076eaff11ab5792e914a0f7f1718
add log for model in template
template/src/config/adapter/model.js
template/src/config/adapter/model.js
module.exports = { type: 'mysql', common: { }, mysql: { database: '', prefix: 'think_', encoding: 'utf8', host: '127.0.0.1', port: '', user: 'root', password: 'root' } };
JavaScript
0
@@ -1,8 +1,52 @@ +const isDev = think.env === 'development';%0A%0A module.e @@ -85,16 +85,99 @@ mmon: %7B%0A + logConnect: isDev,%0A logSql: isDev,%0A logger: msg =%3E think.logger.info(msg) %0A %7D,%0A
aef64f550a86e10a0b72115736814ccbcdcc548d
add display_url to sauce name fix browserVersion field
worker.js
worker.js
// // Strider Worker extension for Sauce Labs tests // var check = require('httpcheck') var fs = require('fs') var path = require('path') var request = require('request') var wd = require('wd') // Port on which the application-under-test webserver should bind to on localhost. // Sauce Connector will tunnel from this to Sauce Cloud for Selenium tests var HTTP_PORT // // Path to SauceLabs Connector PID file var PIDFILE = path.join(__dirname, "tunnel.pid") // SauceLabs test timeout in ms // Permits self-healing in worst-case hang var SAUCE_TEST_TIMEOUT = 1000 * 60 * 45 // 45 minutes var connectorProc var cleanupRun = false // Read & parse a JSON file function getJson(filename, cb) { fs.readFile(filename, function(err, data) { if (err) return cb(err, null) try { var json = JSON.parse(data) cb(null, json) } catch(e) { cb(e, null) } }) } // Is Sauce configured for this context? function sauceConfigured(ctx) { var sauceAccessKey = ctx.jobData.repo_config.sauce_access_key var sauceUsername = ctx.jobData.repo_config.sauce_username if (sauceAccessKey === undefined || sauceUsername === undefined) { return false } return true } // This will shut down the tunnel in a nice way function cleanup(ctx, cb) { console.log("sauce") if (!sauceConfigured(ctx)) { return cb(0) } cleanupRun = true var msg = "Shutting down Sauce Connector" console.log(msg) ctx.striderMessage(msg) if (connectorProc) connectorProc.kill("SIGINT") // Give Sauce Connector 5 seconds to gracefully stop before sending SIGKILL setTimeout(function() { if (connectorProc) connectorProc.kill("SIGKILL") fs.unlink(PIDFILE, function() {}) msg = "Sauce Connector successfully shut down" console.log(msg) ctx.striderMessage(msg) return cb(0) }, 5000) } function test(ctx, cb) { console.log("sauce") if (!sauceConfigured(ctx)) { return cb() } var sauceAccessKey = ctx.jobData.repo_config.sauce_access_key var sauceUsername = ctx.jobData.repo_config.sauce_username var sauceBrowsers = ctx.jobData.repo_config.sauce_browsers if (sauceBrowsers === undefined || sauceBrowsers.length === 0) { // Default to latest chrome on Windows Vista sauceBrowsers = [ { browserName:"chrome", version:"", platform:"Windows 2008" } ] } function log(msg) { ctx.striderMessage(msg) console.log(msg) } HTTP_PORT = ctx.browsertestPort || 8031 ctx.striderMessage("Waiting for webserver to come up on localhost:" + HTTP_PORT) check({url:"http://localhost:"+HTTP_PORT+"/", log:log}, function(err) { if (err) { clearInterval(intervalId) return cb(1) } serverUp() }) // Start the Sauce Connector. Returns childProcess object. function startConnector(username, apiKey, exitCb) { var jarPath = path.join(__dirname, "thirdparty", "Sauce-Connect.jar") var jsh = ctx.shellWrap("exec java -Xmx64m -jar " + jarPath + " " + username + " " + apiKey) var done = false ctx.striderMessage("Starting Sauce Connector") var connectorProc = ctx.forkProc(ctx.workingDir, jsh.cmd, jsh.args, exitCb) // Wait until connector outputs "You may start your tests" // before executing Sauce tests connectorProc.stdout.on('data', function(data) { if (/Connected! You may start your tests./.exec(data) !== null) { var resultsReceived = 0 var buildStatus = 0 var resultMessages = [] var finished = false sauceBrowsers.forEach(function(browser) { var worker = wd.remote("ondemand.saucelabs.com", 80, sauceUsername, sauceAccessKey) var browserId = browser.browserName + "-" + browser.browserVersion + "-" + browser.platform.replace(" ", "-") // ctx.browsertestPort and ctx.browsertestPath come from the `prepare` phase test // plugin - e.g. strider-qunit. var testUrl = "http://localhost:" + ctx.browsertestPort + "/" + browserId + ctx.browsertestPath worker.done = false worker.init({ browserName: browser.browserName, version: browser.browserVersion, platform: browser.platform }, function(err) { if (err) { log("Error creating Sauce worker: " + err) return cb(1) } worker.get(testUrl, function() { log("Created Sauce worker: " + browserId) }) }) setTimeout(function() { if (!worker.done) { log("ERROR: Timeout of " + SAUCE_TEST_TIMEOUT + " ms exceeded for " + browserId + " - terminating ") ctx.events.emit('testDone', { id: browserId, total:0, failed:1, passed:0, runtime: SAUCE_TEST_TIMEOUT }) } }, SAUCE_TEST_TIMEOUT) ctx.events.on('testDone', function(result) { if (finished) return if (result.id === browserId && worker && !worker.done) { resultMessages.push("Results for tests on " + result.id + ": " + result.total + " total " + result.failed + " failed " + result.passed + " passed " + result.runtime + " ms runtime") if (result.failed !== 0) { buildStatus = 1 } log("Terminating Sauce worker: " + browserId) worker.quit() worker.done = true resultsReceived++ } // If all the results are in, finish the build if (resultsReceived == sauceBrowsers.length) { finished = true resultMessages.forEach(function(msg) { log(msg) }) cb(buildStatus) } }) }) } }) } // Server is up, start Sauce Connector function serverUp() { console.log("Starting sauce connector") startConnector(sauceUsername, sauceAccessKey, function(exitCode) { console.log("Sauce Connector exited with code: %d", exitCode) // If the connector exited before the cleanup phase has run, it failed to start if (!cleanupRun) { log("Error starting BrowserStack Connector - failing test") cleanupRun = true fs.unlink(PIDFILE, function() {}) return cb(1) } }) } } module.exports = function(ctx, cb) { ctx.addBuildHook({ cleanup:cleanup, test:test }) console.log("strider-sauce worker extension loaded") cb(null, null) }
JavaScript
0
@@ -3755,32 +3755,25 @@ %22 + browser. -browserV +v ersion + %22-%22 @@ -4213,16 +4213,9 @@ ser. -browserV +v ersi @@ -4258,16 +4258,73 @@ platform +,%0A name: ctx.jobData.repo_config.display_url %0A
a1f135bd66ee625ff0299371a63b8b15f88ef1fc
Allow oauth strategy callback method to be customised Closes #1998
packages/node_modules/@node-red/editor-api/lib/auth/index.js
packages/node_modules/@node-red/editor-api/lib/auth/index.js
/** * Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ var passport = require("passport"); var oauth2orize = require("oauth2orize"); var strategies = require("./strategies"); var Tokens = require("./tokens"); var Users = require("./users"); var permissions = require("./permissions"); var theme = require("../editor/theme"); var settings = null; var log = require("@node-red/util").log; // TODO: separate module passport.use(strategies.bearerStrategy.BearerStrategy); passport.use(strategies.clientPasswordStrategy.ClientPasswordStrategy); passport.use(strategies.anonymousStrategy); var server = oauth2orize.createServer(); server.exchange(oauth2orize.exchange.password(strategies.passwordTokenExchange)); function init(_settings,storage) { settings = _settings; if (settings.adminAuth) { var mergedAdminAuth = Object.assign({}, settings.adminAuth, settings.adminAuth.module); Users.init(mergedAdminAuth); Tokens.init(mergedAdminAuth,storage); } } function needsPermission(permission) { return function(req,res,next) { if (settings && settings.adminAuth) { return passport.authenticate(['bearer','anon'],{ session: false })(req,res,function() { if (!req.user) { return next(); } if (permissions.hasPermission(req.authInfo.scope,permission)) { return next(); } log.audit({event: "permission.fail", permissions: permission},req); return res.status(401).end(); }); } else { next(); } } } function ensureClientSecret(req,res,next) { if (!req.body.client_secret) { req.body.client_secret = 'not_available'; } next(); } function authenticateClient(req,res,next) { return passport.authenticate(['oauth2-client-password'], {session: false})(req,res,next); } function getToken(req,res,next) { return server.token()(req,res,next); } function login(req,res) { var response = {}; if (settings.adminAuth) { var mergedAdminAuth = Object.assign({}, settings.adminAuth, settings.adminAuth.module); if (mergedAdminAuth.type === "credentials") { response = { "type":"credentials", "prompts":[{id:"username",type:"text",label:"user.username"},{id:"password",type:"password",label:"user.password"}] } } else if (mergedAdminAuth.type === "strategy") { var urlPrefix = (settings.httpAdminRoot==='/')?"":settings.httpAdminRoot; response = { "type":"strategy", "prompts":[{type:"button",label:mergedAdminAuth.strategy.label, url: urlPrefix + "auth/strategy"}] } if (mergedAdminAuth.strategy.icon) { response.prompts[0].icon = mergedAdminAuth.strategy.icon; } if (mergedAdminAuth.strategy.image) { response.prompts[0].image = theme.serveFile('/login/',mergedAdminAuth.strategy.image); } } if (theme.context().login && theme.context().login.image) { response.image = theme.context().login.image; } } res.json(response); } function revoke(req,res) { var token = req.body.token; // TODO: audit log Tokens.revoke(token).then(function() { log.audit({event: "auth.login.revoke"},req); if (settings.editorTheme && settings.editorTheme.logout && settings.editorTheme.logout.redirect) { res.json({redirect:settings.editorTheme.logout.redirect}); } else { res.status(200).end(); } }); } function completeVerify(profile,done) { Users.authenticate(profile).then(function(user) { if (user) { Tokens.create(user.username,"node-red-editor",user.permissions).then(function(tokens) { log.audit({event: "auth.login",username:user.username,scope:user.permissions}); user.tokens = tokens; done(null,user); }); } else { log.audit({event: "auth.login.fail.oauth",username:typeof profile === "string"?profile:profile.username}); done(null,false); } }); } function genericStrategy(adminApp,strategy) { var crypto = require("crypto") var session = require('express-session') var MemoryStore = require('memorystore')(session) adminApp.use(session({ // As the session is only used across the life-span of an auth // hand-shake, we can use a instance specific random string secret: crypto.randomBytes(20).toString('hex'), resave: false, saveUninitialized: false, store: new MemoryStore({ checkPeriod: 86400000 // prune expired entries every 24h }) })); //TODO: all passport references ought to be in ./auth adminApp.use(passport.initialize()); adminApp.use(passport.session()); var options = strategy.options; passport.use(new strategy.strategy(options, function() { var originalDone = arguments[arguments.length-1]; if (options.verify) { var args = Array.from(arguments); args[args.length-1] = function(err,profile) { if (err) { return originalDone(err); } else { return completeVerify(profile,originalDone); } }; options.verify.apply(null,args); } else { var profile = arguments[arguments.length - 2]; return completeVerify(profile,originalDone); } } )); adminApp.get('/auth/strategy', passport.authenticate(strategy.name, {session:false, failureRedirect: settings.httpAdminRoot }), completeGenerateStrategyAuth ); adminApp.get('/auth/strategy/callback', passport.authenticate(strategy.name, {session:false, failureRedirect: settings.httpAdminRoot }), completeGenerateStrategyAuth ); } function completeGenerateStrategyAuth(req,res) { var tokens = req.user.tokens; delete req.user.tokens; // Successful authentication, redirect home. res.redirect(settings.httpAdminRoot + '?access_token='+tokens.accessToken); } module.exports = { init: init, needsPermission: needsPermission, ensureClientSecret: ensureClientSecret, authenticateClient: authenticateClient, getToken: getToken, errorHandler: function(err,req,res,next) { //TODO: audit log statment //console.log(err.stack); //log.log({level:"audit",type:"auth",msg:err.toString()}); return server.errorHandler()(err,req,res,next); }, login: login, revoke: revoke, genericStrategy: genericStrategy }
JavaScript
0
@@ -6494,32 +6494,182 @@ %0A );%0A +%0A -adminApp.get +var callbackMethodFunc = adminApp.get;%0A if (/%5Epost$/i.test(options.callbackMethod)) %7B%0A callbackMethodFunc = adminApp.post;%0A %7D%0A callbackMethodFunc ('/auth/
3a232c0e1ccae3d908a0569ddad581593da62ed7
Remove unrequired watch on Checklist Controller
static/src/checklist/checklist.js
static/src/checklist/checklist.js
(function () { 'use strict'; // checklist detail page // ============================================================================= angular.module('checklist.detail', [ 'ui.router', 'checklist.common.services' ]) // configure routes // ============================================================================= .config(function ($stateProvider, $urlRouterProvider) { $stateProvider .state('checklist-detail', { url: '/aircraft/:aircraftId', templateUrl: 'static/src/checklist/checklist.html', controller: 'ChecklistDetailCtrl as checklistCtrl', resolve: { checklistData: function($stateParams, ChecklistService) { console.info('fetching checklist data...'); return ChecklistService.get({ id: $stateParams.aircraftId }).$promise; }, runData: function(checklistData, ChecklistRunService) { console.info('fetching checklist run data...'); var run = ChecklistRunService.getRun(checklistData.id); if (!run) { run = ChecklistRunService.newRun(checklistData); } return run; } } }); }) // application run block // ============================================================================= .run(function () { console.log('checklist.detail module running...'); }) // our controller for the map // ============================================================================= .controller('ChecklistDetailCtrl', function ($scope, $state, checklistData, runData, ChecklistRunService) { console.info('ChecklistDetailCtrl'); // Scope properties // ============================= $scope.checklist = checklistData; $scope.run = runData; // Scope watchers // ============================= $scope.$watch('run', this.onRunDataModified, true); // Controller functions // ============================= this.onRunDataModified = function (newValue, oldValue) { console.warn('checklistCtrl:onRunDataModified', newValue, oldValue); if (newValue) { ChecklistRunService.saveRun(newValue); } }; this.newRun = function () { $scope.run = ChecklistRunService.newRun($scope.checklist); }; }); }());
JavaScript
0
@@ -1764,63 +1764,8 @@ ==== -%0A%09%09%09$scope.$watch('run', this.onRunDataModified, true); %0A%0A%09%09 @@ -1829,218 +1829,8 @@ ===%0A -%09%09%09this.onRunDataModified = function (newValue, oldValue) %7B%0A%09%09%09%09console.warn('checklistCtrl:onRunDataModified', newValue, oldValue);%0A%09%09%09%09if (newValue) %7B%0A%09%09%09%09%09ChecklistRunService.saveRun(newValue);%0A%09%09%09%09%7D%0A%09%09%09%7D;%0A%0A %09%09%09t
945e1047d3810fe96270f633f39b669c178bb892
Update link with next single type feature
packages/strapi-admin/admin/src/containers/HomePage/index.js
packages/strapi-admin/admin/src/containers/HomePage/index.js
/* * * HomePage * */ /* eslint-disable */ import React, { memo } from 'react'; import { FormattedMessage } from 'react-intl'; import { get, upperFirst } from 'lodash'; import { auth } from 'strapi-helper-plugin'; import PageTitle from '../../components/PageTitle'; import useFetch from './hooks'; import { ALink, Block, Container, LinkWrapper, P, Wave, Separator, } from './components'; import BlogPost from './BlogPost'; import SocialLink from './SocialLink'; const FIRST_BLOCK_LINKS = [ { link: 'https://strapi.io/documentation/3.0.0-beta.x/getting-started/quick-start.html#_4-create-a-new-content-type', contentId: 'app.components.BlockLink.documentation.content', titleId: 'app.components.BlockLink.documentation', }, { link: 'https://github.com/strapi/foodadvisor', contentId: 'app.components.BlockLink.code.content', titleId: 'app.components.BlockLink.code', }, ]; const SOCIAL_LINKS = [ { name: 'GitHub', link: 'https://github.com/strapi/strapi/', }, { name: 'Slack', link: 'https://slack.strapi.io/', }, { name: 'Medium', link: 'https://medium.com/@strapi', }, { name: 'Twitter', link: 'https://twitter.com/strapijs', }, { name: 'Reddit', link: 'https://www.reddit.com/r/Strapi/', }, { name: 'Stack Overflow', link: 'https://stackoverflow.com/questions/tagged/strapi', }, ]; const HomePage = ({ global: { plugins }, history: { push } }) => { const { error, isLoading, posts } = useFetch(); const handleClick = e => { e.preventDefault(); push( 'plugins/content-type-builder/content-types/plugins::users-permissions.user?modalType=contentType&actionType=create&settingType=base&forTarget=contentType&headerId=content-type-builder.modalForm.contentType.header-create&header_icon_name_1=contentType&header_icon_isCustom_1=false&header_label_1=null' ); }; const hasAlreadyCreatedContentTypes = get( plugins, ['content-manager', 'leftMenuSections', '0', 'links'], [] ).filter(contentType => contentType.isDisplayed === true).length > 1; const headerId = hasAlreadyCreatedContentTypes ? 'HomePage.greetings' : 'app.components.HomePage.welcome'; const username = get(auth.getUserInfo(), 'username', ''); const linkProps = hasAlreadyCreatedContentTypes ? { id: 'app.components.HomePage.button.blog', href: 'https://blog.strapi.io/', onClick: () => {}, type: 'blog', target: '_blank', } : { id: 'app.components.HomePage.create', href: '', onClick: handleClick, type: 'documentation', }; return ( <> <FormattedMessage id="HomePage.helmet.title"> {title => <PageTitle title={title} />} </FormattedMessage> <Container className="container-fluid"> <div className="row"> <div className="col-lg-8 col-md-12"> <Block> <Wave /> <FormattedMessage id={headerId} values={{ name: upperFirst(username), }} > {msg => <h2 id="mainHeader">{msg}</h2>} </FormattedMessage> {hasAlreadyCreatedContentTypes ? ( <FormattedMessage id="app.components.HomePage.welcomeBlock.content.again"> {msg => <P>{msg}</P>} </FormattedMessage> ) : ( <FormattedMessage id="HomePage.welcome.congrats"> {congrats => { return ( <FormattedMessage id="HomePage.welcome.congrats.content"> {content => { return ( <FormattedMessage id="HomePage.welcome.congrats.content.bold"> {boldContent => { return ( <P> <b>{congrats}</b>&nbsp; {content} &nbsp; <b>{boldContent}</b> </P> ); }} </FormattedMessage> ); }} </FormattedMessage> ); }} </FormattedMessage> )} {hasAlreadyCreatedContentTypes && ( <div style={{ marginTop: isLoading ? 60 : 50 }}> {posts.map((post, index) => ( <BlogPost {...post} key={post.link} isFirst={index === 0} isLoading={isLoading} error={error} /> ))} </div> )} <FormattedMessage id={linkProps.id}> {msg => ( <ALink rel="noopener noreferrer" {...linkProps} style={{ verticalAlign: ' bottom', marginBottom: 5 }} > {msg} </ALink> )} </FormattedMessage> <Separator style={{ marginTop: 37, marginBottom: 36 }} /> <div style={{ display: 'flex', justifyContent: 'space-between' }}> {FIRST_BLOCK_LINKS.map((data, index) => { const type = index === 0 ? 'doc' : 'code'; return ( <LinkWrapper href={data.link} target="_blank" key={data.link} type={type} > <FormattedMessage id={data.titleId}> {title => <p className="bold">{title}</p>} </FormattedMessage> <FormattedMessage id={data.contentId}> {content => <p>{content}</p>} </FormattedMessage> </LinkWrapper> ); })} </div> </Block> </div> <div className="col-md-12 col-lg-4"> <Block style={{ paddingRight: 30, paddingBottom: 0 }}> <FormattedMessage id="HomePage.community"> {msg => <h2>{msg}</h2>} </FormattedMessage> <FormattedMessage id="app.components.HomePage.community.content"> {content => ( <P style={{ marginTop: 7, marginBottom: 0 }}>{content}</P> )} </FormattedMessage> <FormattedMessage id="HomePage.roadmap"> {msg => ( <ALink rel="noopener noreferrer" href="https://portal.productboard.com/strapi/1-public-roadmap/tabs/2-under-consideration" target="_blank" > {msg} </ALink> )} </FormattedMessage> <Separator style={{ marginTop: 18 }} /> <div className="row social-wrapper" style={{ display: 'flex', margin: 0, marginTop: 36, marginLeft: -15, }} > {SOCIAL_LINKS.map((value, key) => ( <SocialLink key={key} {...value} /> ))} </div> </Block> </div> </div> </Container> </> ); }; export default memo(HomePage);
JavaScript
0
@@ -1596,16 +1596,17 @@ %0A ' +/ plugins/ @@ -1694,16 +1694,36 @@ entType& +kind=collectionType& actionTy @@ -1853,54 +1853,54 @@ con_ -name_1=contentType&header_icon_isCustom_1=fals +isCustom_1=false&header_icon_name_1=contentTyp e&he
30f6b4c683a2e9652d373e87c5143f2b88ae5d0f
Check for activation mail instead of login
src/adhocracy_frontend/adhocracy_frontend/tests/acceptance/UserLoginSpec.js
src/adhocracy_frontend/adhocracy_frontend/tests/acceptance/UserLoginSpec.js
"use strict"; var UserPages = require("./UserPages.js"); var fs = require("fs"); var _ = require("lodash"); var shared = require("./shared"); describe("user registration", function() { it("can register", function() { browser.get("/"); UserPages.ensureLogout(); UserPages.register("u1", "[email protected]", "password1"); UserPages.logout(); UserPages.login("u1", "password1"); expect(UserPages.isLoggedIn()).toBe(true); }); it("cannot register with wrong password repeat", function() { browser.get("/"); UserPages.ensureLogout(); var page = new UserPages.RegisterPage().get(); page.fill("u2", "[email protected]", "password2", "password3"); expect(page.submitButton.isEnabled()).toBe(false); }); }); describe("user login", function() { it("can login with username", function() { UserPages.login(UserPages.participantName, UserPages.participantPassword); expect(UserPages.isLoggedIn()).toBe(true); UserPages.logout(); }); it("can login with email", function() { UserPages.login(UserPages.participantEmail, UserPages.participantPassword); expect(UserPages.isLoggedIn()).toBe(true); UserPages.logout(); }); it("cannot login with wrong name", function() { UserPages.login("noexist", "password1"); expect(UserPages.isLoggedIn()).toBe(false); }); it("cannot login with wrong password", function() { UserPages.login("participant", "password1"); expect(UserPages.isLoggedIn()).toBe(false); }); it("cannot login with short password", function() { var page = new UserPages.LoginPage().get(); page.loginInput.sendKeys("abc"); page.passwordInput.sendKeys("abc"); expect(page.submitButton.getAttribute("disabled")).toBe("true"); }); it("login is persistent", function() { UserPages.login(UserPages.participantName, UserPages.participantPassword); expect(UserPages.isLoggedIn()).toBe(true); browser.refresh(); browser.waitForAngular(); expect(UserPages.isLoggedIn()).toBe(true); UserPages.logout(); }); }); describe("user password reset", function() { it("email is sent to user", function() { var mailsBeforeMessaging = fs.readdirSync(browser.params.mail.queue_path + "/new"); var page = new UserPages.ResetPasswordCreatePage().get(); page.fill(UserPages.participantEmail); expect(element(by.css(".login-success")).getText()).toContain("SPAM"); var flow = browser.controlFlow(); flow.execute(function() { var mailsAfterMessaging = fs.readdirSync(browser.params.mail.queue_path + "/new"); expect(mailsAfterMessaging.length).toEqual(mailsBeforeMessaging.length + 1); }); }); it("error displayed if the email is not associated to an user", function() { var page = new UserPages.ResetPasswordCreatePage().get(); page.fill("[email protected]"); browser.wait(browser.isElementPresent(element(by.css(".form-error"))), 1000) expect(element(by.css(".form-error")).getText()).toContain("No user"); }); it("recover access with the link contained in the email", function(){ var mailsBeforeMessaging = fs.readdirSync(browser.params.mail.queue_path + "/new"); var page = new UserPages.ResetPasswordCreatePage().get(); var resetUrl = ""; page.fill(UserPages.participantEmail); var flow = browser.controlFlow(); flow.execute(function() { var mailsAfterMessaging = fs.readdirSync(browser.params.mail.queue_path + "/new"); var newMails = _.difference(mailsAfterMessaging, mailsBeforeMessaging); var mailpath = browser.params.mail.queue_path + "/new/" + newMails[0]; shared.parseEmail(mailpath, function(mail) { expect(mail.subject).toContain("Passwor"); expect(mail.to[0].address).toContain("participant"); resetUrl = _.find(mail.text.split("\n"), function(line) {return _.startsWith(line, "http");}); }); }); browser.driver.wait(function() { return resetUrl != ""; }, 1000).then(function() { var resetPage = new UserPages.ResetPasswordPage().get(resetUrl); resetPage.fill('new password'); // After changing the password the user is logged in //expect(UserPages.isLoggedIn()).toBe(true); // and can now login with the new password UserPages.logout(); UserPages.login(UserPages.participantEmail, 'new password'); expect(UserPages.isLoggedIn()).toBe(true); }); }); });
JavaScript
0.000001
@@ -208,32 +208,124 @@ %22, function() %7B%0A + var mailsBeforeMessaging = fs.readdirSync(browser.params.mail.queue_path + %22/new%22);%0A browser. @@ -445,68 +445,167 @@ -UserPages.logout();%0A UserPages.login(%22u1%22, %22password1 +var flow = browser.controlFlow();%0A flow.execute(function() %7B%0A var mailsAfterMessaging = fs.readdirSync(browser.params.mail.queue_path + %22/new %22);%0A @@ -616,48 +616,98 @@ + expect( -UserPages.isLoggedIn()).toBe(true +mailsAfterMessaging.length).toEqual(mailsBeforeMessaging.length + 1);%0A %7D );%0A
1de9f91e186a33a32dc943250967d716f5cc46f9
rename variable
src/javascript/app/pages/user/account/settings/two_factor_authentication.js
src/javascript/app/pages/user/account/settings/two_factor_authentication.js
const QRCode = require('davidshimjs-qrcodejs'); const BinarySocket = require('../../../../base/socket'); const Client = require('../../../../base/client'); const FormManager = require('../../../../common/form_manager'); const getPropertyValue = require('../../../../../_common/utility').getPropertyValue; const localize = require('../../../../../_common/localize').localize; const TwoFactorAuthentication = (() => { const form_id = '#frm_two_factor_auth'; let enabled_state, next_state, qrcode; // eslint-disable-line const onLoad = () => { init(); }; const init = () => { BinarySocket.send({ account_security: 1, totp_action: 'status'}).then((res) => { $('#two_factor_loading').remove(); if (res.error) { handleError('status', res.error.message); return; } enabled_state = res.account_security.totp.is_enabled ? 'enabled' : 'disabled'; next_state = res.account_security.totp.is_enabled ? 'disable' : 'enable'; $(`#${enabled_state}`).setVisibility(1); $('#btn_submit').text(next_state); $(form_id).setVisibility(1); FormManager.init(form_id, [ { selector: '#otp', validations: ['req', 'number'], request_field: 'otp', no_scroll: true }, { request_field: 'account_security', value: 1 }, { request_field: 'totp_action', value: next_state }, ]); FormManager.handleSubmit({ form_selector : form_id, fnc_response_handler: handleSubmitResponse, enable_button : true, }); if (enabled_state === 'disabled') { $('.otp-form-group').css('padding-left', '60px'); initQRCode(); } }); }; const resetComponent = () => { $(`#${enabled_state}`).setVisibility(0); $(form_id).setVisibility(0); $('#qrcode').html(''); $('.otp-form-group').css('padding-left', ''); init(); }; const initQRCode = () => { BinarySocket.send({ account_security: 1, totp_action: 'generate'}).then((res) => { $('#qrcode_loading').setVisibility(0); if (res.error) { handleError('generate', res.error.message); return; } makeQrCode(res.account_security.totp.secret_key); }); }; const makeQrCode = (key) => { const otpAuth = `otpauth://totp/${Client.get('email')}?secret=${key}&issuer=Binary.com`; qrcode = new QRCode(document.getElementById('qrcode'), { text : otpAuth, width : 130, height: 130, }); }; const handleSubmitResponse = (res) => { if ('error' in res) { showFormMessage(getPropertyValue(res, ['error', 'message']) || 'Sorry, an error occurred.'); } else { $('#otp').val(''); showFormMessage(`You have successfully ${next_state}d two-factor authentication for your account`, true); } }; const handleError = (id, err_msg) => { $(`#${id}_error`).setVisibility(1).text(localize(err_msg || 'Sorry, an error occurred.')); }; const showFormMessage = (msg, is_success) => { $('#form_message') .attr('class', is_success ? 'success-msg' : 'error-msg') .html(is_success ? $('<ul/>', { class: 'checked' }).append($('<li/>', { text: localize(msg) })) : localize(msg)) .css('display', 'block') .delay(3000) .fadeOut(1000, is_success? resetComponent: ''); }; return { onLoad, }; })(); module.exports = TwoFactorAuthentication;
JavaScript
0.000018
@@ -2579,23 +2579,20 @@ const -otpAuth +text = %60otpa @@ -2744,19 +2744,8 @@ text - : otpAuth ,%0A
93d2c3b19f4811d99a3de041997183ec48c8e39b
Fix small JS bug
ava/assets/js/signup.js
ava/assets/js/signup.js
function getJsonFromUrl(hashBased) { var query; if (hashBased) { var pos = location.href.indexOf("?"); if (pos==-1) return []; query = location.href.substr(pos+1); } else { query = location.search.substr(1); } var result = {}; query.split("&").forEach(function(part) { if (!part) return; var item = part.split("="); var key = item[0]; var val = decodeURIComponent(item[1]); var from = key.indexOf("["); if (from==-1) { result[key] = val; } else { var to = key.indexOf("]"); var index = key.substring(from+1,to); key = key.substring(0,from); if (!result[key]) { result[key] = []; } if (!index) { result[key].push(val); } else { result[key][index] = val; } } }); return result; } window.onload = function() { var params = getJsonFromUrl(window.location.search); if (document.querySelector("#signup") !== null) { document.querySelector("#flexid").value = params.flexid; document.querySelector("#flexidtype").value = params.flexidtype; var link = document.querySelector("#login"); link.setAttribute("href", link.attributes.href+window.location.search); } else if (document.querySelector("#login") !== null) { var link = document.querySelector("#signup"); link.setAttribute("href", link.attributes.href+window.location.search); } };
JavaScript
0.000011
@@ -1079,35 +1079,24 @@ href%22, link. -attributes. href+window. @@ -1255,19 +1255,8 @@ ink. -attributes. href
94f2b125b591c08c71791d44ba9680ba124bdf2a
Comment out body parsing in use until there is time to update dependencies for switch.
backend/server/mcapi.js
backend/server/mcapi.js
var cliArgs = require('command-line-args'); var mount = require('koa-mount'); var bodyParser = require('koa-bodyparser'); var koa = require('koa'); var app = module.exports = koa(); require('koa-qs')(app); require('./init')(); var model = require('./model-loader')(module.parent); var apikey = require('./apikey')(model.users); var resources = require('./resources')(model); app.use(apikey); app.use(bodyParser()); app.use(mount('/', resources.routes())).use(resources.allowedMethods()); // Look for changes on the access and projects tables. If a change is detected // then invalidate the project access cache so that it will be reloaded. const projectAccessCache = require('./resources/project-access-cache')(model.access); model.r.table('access').changes().toStream().on('data', function() { projectAccessCache.clear(); }); model.r.table('projects').changes().toStream().on('data', function() { projectAccessCache.clear(); }); // Look for changes on the users table. If a change it detected then invalidate // the apikey cache so it will be reloaded. const apikeyCache = require('./apikey-cache')(model.users); model.r.table('users').changes().toStream().on('data', function() { apikeyCache.clear() }); var server = require('http').createServer(app.callback()); var io = require('socket.io')(server); if (!module.parent) { var cli = cliArgs([ {name: 'port', type: Number, alias: 'p', description: 'Port to listen on'} ]); var options = cli.parse(); var port = options.port || 3000; //io.set('origins', `http://localhost:${port}`); io.on('connection', function(socket) { console.log('socket.io connection'); socket.emit('event', {msg: 'you are connected'}); }); console.log('Listening on port: ' + port + ' pid: ' + process.pid); server.listen(port); } ////////////////////// // var Bus = require('busmq'); // var bus = Bus.create({redis: ['redis://localhost:6379']}); // var q; // bus.on('online', function() { // q = bus.queue('samples'); // q.attach(); // });
JavaScript
0
@@ -67,24 +67,26 @@ oa-mount');%0A +// var bodyPars @@ -389,16 +389,18 @@ pikey);%0A +// app.use(
1dac498d8f0cee11241ab49bddd2cb98442b7a8e
Update from travis build of arcgis-dijit-drilldown
Drilldown/Drilldown/Drilldown.js
Drilldown/Drilldown/Drilldown.js
Function.prototype.bind||(Function.prototype.bind=function(a){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var b=Array.prototype.slice.call(arguments,1),c=this,d=function(){},e=function(){return c.apply(this instanceof d?this:a,b.concat(Array.prototype.slice.call(arguments)))};return this.prototype&&(d.prototype=this.prototype),e.prototype=new d,e}),define(["dojo/_base/declare","dijit/_Widget","dijit/_TemplatedMixin","dijit/_WidgetsInTemplateMixin","esri/dijit/Search","dojo/dom-construct","dijit/layout/ContentPane","dijit/TitlePane","dojox/widget/TitleGroup","dojo/on","dojo/Deferred","dojo/query","dojo/dom-style","dojo/NodeList-data"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){var n=function(a){return void 0===a||null===a||""===a},o=function(a,b){var c=f.toDom("<span class='drilldownResult'>"+a+"</span>");return l(c).data("result",b),c},p=function(a,b){return!n(a)&&a.length>0&&b?"<span class='drilldownCount'>"+a.length+"</span>":""},q=function(a,b,c){var d=0,e=0,f=new i,j=a.Addresses;for(d=0,e=j.length;e>d;d+=1)f.addChild(new g({content:["<span class='drilldownResultIcon'></span>",o(j[d].address,j[d])]}));b.addChild(new h({title:p(j,c)+"<span class='drilldownTitle'>"+a.Description+"</span>",content:f,open:!1}))},r=function(a,b){var c,d,e=0,f=0,h=new i;if(!n(a.Addresses)&&a.Addresses.length>1){for(c=a.Addresses,e=0,f=c.length;f>e;e++)!n(c[e].Addresses)&&c[e].Addresses.length>1?q(c[e],h,b):(d=n(c[e].address)?o(c[e].Addresses[0].address,c[e].Addresses[0]):o(c[e].address,c[e]),h.addChild(new g({content:["<span class='drilldownResultIcon'></span>",d]})));h.startup()}else n(a.Addresses[0].address)?!n(a.Addresses[0].Addresses)&&a.Addresses[0].Addresses.length>0&&q(a.Addresses[0],h):h=new g({content:o(a.Addresses[0].address,a.Addresses[0])});return h},s=function(a,b){this.get("contentSet")===!1&&(this.set("content",r(a,b)),this.set("contentSet",!0))};return a([b,c,d,e],{baseClass:"drilldown",widgetsInTemplate:!0,resultsElement:null,_titleGroups:[],showCounts:!1,constructor:function(b){a.safeMixin(this,b)},destroy:function(){this._clearPicklist(),this.inherited(arguments)},search:function(){var a=this,b=new k;return this.inherited(arguments).then(function(c){a._buildPickListUi(c),b.resolve()}),b.promise},clear:function(){this._clearPicklist(),this.inherited(arguments)},_hydrateResults:function(a){return a.PickListItems?a:this.inherited(arguments)},_formatResults:function(a,b,c){var d={activeSourceIndex:b,value:c,numResults:0,numErrors:0,errors:null,results:null},e={},f={},g=0;if(a){if(b===this._allIndex){for(g=0;g<a.length;g++)n(this.sources[g].locator.locatorType)?d=this.inherited(arguments):(f[b]=a[0],d.numResults+=a[0].PickListItems.length);return d.results=f,d.err=e,d}return n(this.activeSource.locator.locatorType)?this.inherited(arguments):(f[b]=a[0],d.numResults+=a[0].PickListItems.length,d.results=f,d.err=e,d)}return d},_clearPicklist:function(){var a,b;if(this._titleGroups.length>0){for(a=0,b=this._titleGroups.length;b>a;a++)this._titleGroups[a].destroy();this._titleGroups=[],n(this.resultsElement)||m.set(this.resultsElement,"height",0)}},_showNoResults:function(){this._noResults(this.value),this._showNoResultsMenu()},_isSingleResult:function(a){var b,c,d,e=0;for(d in a)a.hasOwnProperty(d)&&(e++,c=d);if(1===e){if(b=a[c].PickListItems,1===b.length&&1===b[0].Addresses.length){if(n(b[0].Addresses[0].Addresses))return!0;if(!n(b[0].Addresses[0].Addresses)&&1===b[0].Addresses[0].Addresses.length)return!0}return!1}return!1},_buildPickListUi:function(a){var b,c,d,e,g,m,o=this,q=0,t=0,u=!1,v=new k;if(this._clearPicklist(),f.destroy(this.resultsElement),this.resultsElement=f.create("div",{"class":"arcgisSearch searchGroup picklistResults"},this.domNode,"last"),o.activeSourceIndex!==this._allIndex&&this._isSingleResult(a))e=this._hydrateResult(a[o.activeSourceIndex].PickListItems[0].Addresses[0],o.activeSourceIndex,!1),this.select(e);else{if(!n(a)){for(d in a)if(a.hasOwnProperty(d))if(n(a[d])||n(a[d].PickListItems))u=!0;else if(b=a[d].PickListItems,t=b.length,t>0)for(g=f.create("div",{id:d},this.resultsElement,"last"),c=new i(null,g),this._titleGroups.push(c),q=0;t>q;q+=1)m=new h({title:p(b[q].Addresses,this.showCounts)+"<span class='drilldownTitle'>"+b[q].Description+"</span>",open:!1,contentSet:!1}),1===t?(m.set("open",!0),m.set("contentSet",!0),m.set("content",r(b[q],this.showCounts))):m.own(m.on("click",s.bind(m,b[q],this.showCounts))),c.addChild(m),u=!1;else u=!0;v.resolve()}u&&this._showNoResults(),n(this.resultsElement)||j(this.resultsElement,".drilldownResult:click",function(){var a=l(this).data()[0],b=o._hydrateResult(a.result,o.activeSourceIndex,!1);o.select(b),o._clearPicklist()})}return v.promise}})});
JavaScript
0
@@ -3638,16 +3638,40 @@ klist(), +n(this.resultsElement)%7C%7C f.destro
64d952934054ed6fd0b3f946b488294d712779f0
Add request method for save exercise-group.
server/static/lecturer/js/store/components/group.js
server/static/lecturer/js/store/components/group.js
/** * Created by Elors on 2017/1/3. * Exercise-Group component */ define(['Exercise'], function () { Vue.component('exercise-group', { template: '\ <div class="row store-row content-pane">\ <el-form ref="form" :model="form" label-width="0px" class="page-pane">\ <el-form-item label-width="0px" class="text item-input" v-show="shouldShow">\ <el-input v-model="form.title" class="input" id="ex-title"></el-input>\ </el-form-item>\ <el-form-item label-width="0px" class="text item-input" v-show="shouldShow">\ <el-input v-model="form.desc" class="input" id="ex-desc"></el-input>\ </el-form-item>\ <transition-group name="list" tag="div">\ <store-exercise\ v-for="(exercise, index) in form.exercises"\ v-bind:list="form.exercises"\ v-bind:exercise="exercise"\ v-bind:index="index"\ :key="index+\'ex\'">\ </store-exercise>\ </transition-group>\ <el-form-item class="item-submit" v-show="shouldShow">\ <el-button type="success" icon="plus" @click="onInsert">新增习题</el-button>\ <el-button type="primary" icon="edit" @click="onSave">保存题组</el-button>\ </el-form-item>\ </el-form>\ </div>\ ', data: function () { return { form: {}, shouldShow: false } }, methods: { // Events Handle Method onInsert () { this.form.exercises.push(this.defaultExercise()); }, onSave () { console.log(this.form.exercises) }, // Public Method loadGroup (data) { let group = this; $.ajax({ async: false, dataType: "json", url: '/lecturer/api/exercise/store?action=group&gid=' + data.id, success: function (json) { if (json && json.ok) { group.form = group.handleData(json.data); group.shouldShow = true; } } }); }, createGroup () { this.form = this.defaultGroup(); this.shouldShow = true; }, // Private Method handleData (json) { // format json.exercises = json.questions; delete json.questions; // set solution string for (exercise of json.exercises) { for (option of exercise.options) { if (exercise.solution === option.id) { exercise.solution = option.text; } } } return json }, defaultGroup () { return { id: '', title: '题组名称', desc: '题组描述', exercises: [ this.defaultExercise() ] } }, defaultExercise () { return { id: '', title: '题目', solution: '选项1', analyse: '题目解析', options: [ { id: '', text: '选项1' }, { id: '', text: '选项2' }, { id: '', text: '选项3' }, { id: '', text: '选项4' } ] } } } }); });
JavaScript
0
@@ -1614,28 +1614,323 @@ log( -this.form.exercises) +JSON.stringify(this.form));%0A%0A $.ajax(%7B%0A type: %22POST%22,%0A async: false,%0A dataType: %22json%22,%0A url: '/lecturer/api/exercise/store',%0A data: %7B'group': JSON.stringify(this.form)%7D,%0A success: function (json) %7B%0A console.log(json);%0A %7D%0A %7D);%0A %0A
5b39034ab7bfcb48b42230302c04ad515fdd7932
Refresh images first
static/js/panoptes.js
static/js/panoptes.js
function add_chat_item(name, msg, time){ item = '<li><img class="avatar" alt="" src="/static/img/pan.png">'; item = item + '<span class="message">'; item = item + '<span class="label label-primary">' + time + '</span> &nbsp;'; item = item + '<span class="text">' + msg + '</span>'; item = item + '</span></li>'; $('#bot_chat').prepend(item); } // Find all the elements with the class that matches a return value // and update their html function update_info(status){ $.each(status, function(key, val){ $('.' + key).each(function(idx, elem){ $(elem).html(val); }) }); } var messageContainer = document.getElementById('ws_status'); function WebSocketTest(server) { if ("WebSocket" in window) { var ws = new WebSocket("ws://" + server + "/ws/"); ws.onopen = function() { // messageContainer.innerHTML = "Connection open..."; ws.send("Connection established"); }; ws.onmessage = function (evt) { var type = evt.data.split(' ', 1)[0]; var received_msg = evt.data.substring(evt.data.indexOf(' ') + 1) // console.log(type); // console.log(received_msg); var msg = jQuery.parseJSON(received_msg); if (type == 'PAN001'){ add_chat_item(type, msg.message, msg.timestamp); } if (type == 'STATUS'){ update_info(msg['observatory']); $('.current_state').html(msg['state']); refresh_images(); } if (type == 'STATE'){ $('.current_state').html(msg['state']); refresh_images(); } }; ws.onclose = function() { messageContainer.innerHTML = "Connection is closed..."; }; } else { messageContainer.innerHTML = "WebSocket NOT supported by your Browser!"; } } // Refresh all images with `img_refresh` container class function refresh_images(){ console.log("Refreshing images") $.each($('.img_refresh img'), function(idx, img){ reload_img(img); }); } // Reload individual image function reload_img(img){ base = $(img).attr('src').split('?')[0]; // Hack for others if(base.startsWith('http')){ new_src = $(img).attr('src'); } else { new_src = base + '?' + Math.random() } $(img).attr('src', new_src); } // Startup $( document ).ready(function() { // Image refresh timer second = 1000; WebSocketTest(window.location.host); // Refresh images // setInterval(refresh_images, 15 * second); })
JavaScript
0
@@ -1414,24 +1414,58 @@ 'STATUS')%7B%0A + refresh_images();%0A @@ -1497,24 +1497,24 @@ rvatory'%5D);%0A - @@ -1561,42 +1561,8 @@ %5D);%0A - refresh_images();%0A @@ -1601,24 +1601,58 @@ = 'STATE')%7B%0A + refresh_images();%0A @@ -1699,42 +1699,8 @@ %5D);%0A - refresh_images();%0A
5b6a3078b31dc346e5ce7b86837d6abbe7a18bbd
update broken build in commit 7c293e721bd1e95be6f82475d295b9b10e3b584e
test/e2e/integration/profile_spec.js
test/e2e/integration/profile_spec.js
/// <reference types="Cypress" /> describe('/profile behaviour', () => { before(() => { cy.dbReset() }) after(() => { cy.dbReset() }) afterEach(() => { cy.visitPage('/logout') }) it('Should redirect if the user has not logged in', () => { cy.visitPage('/profile') cy.url().should('include', 'login') }) it('Should be accesible for logged user', () => { cy.userSignIn() cy.visitPage('/profile') cy.url().should('include', 'profile') }) it('Should be a form with inputs', () => { cy.userSignIn() cy.visitPage('/profile') cy.get('form[role="form"]') .find('input') .should('have.length', 8) }) it('Should first name be modified', () => { const newName = 'My new name!' const bankRouting = '0198212#' cy.userSignIn() cy.visitPage('/profile') cy.get('#firstName') .clear() .type(newName) cy.get('#bankRouting') .clear() .type(bankRouting) cy.get('button[type="submit"]') .first() .click() cy.url().should('include', 'profile') cy.get('.alert-success') .should('be.visible') // @TODO: Just commented for CI, this MUST be improved /* cy.get('#firstName') .invoke('val') .should('eq', newName) */ }) it('Google search this profile by name', () => { cy.userSignIn() cy.visitPage('/profile') cy.get('form[role="form"] a') .should('be.visible') .should('have.attr', 'href') }) })
JavaScript
0.000002
@@ -662,17 +662,17 @@ ength', -8 +9 )%0A %7D)%0A%0A
4dee45e4eeed0cf057581560c7a7d07ea461fe11
Fix linter
test/hyperbahn-client/unadvertise.js
test/hyperbahn-client/unadvertise.js
// Copyright (c) 2015 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var DebugLogtron = require('debug-logtron'); var setTimeout = require('timers').setTimeout; var HyperbahnClient = require('tchannel/hyperbahn/index.js'); var TChannelJSON = require('tchannel/as/json'); // var timers = TimeMock(Date.now()); module.exports = runTests; if (require.main === module) { runTests(require('../lib/test-cluster.js')); } function runTests(HyperbahnCluster) { HyperbahnCluster.test('advertise and forward', { size: 5, servicePurgePeriod: 50 }, function t(cluster, assert) { var steve = cluster.remotes.steve; var bob = cluster.remotes.bob; var tchannelJSON = TChannelJSON({ logger: cluster.logger }); var steveHyperbahnClient = new HyperbahnClient({ serviceName: steve.serviceName, callerName: 'forward-test', hostPortList: cluster.hostPortList, tchannel: steve.channel, advertiseInterval: 2, logger: DebugLogtron('hyperbahnClient') }); steveHyperbahnClient.once('advertised', onAdvertised); steveHyperbahnClient.advertise(); function onAdvertised() { assert.equal(steveHyperbahnClient.state, 'ADVERTISED', 'state should be ADVERTISED'); setTimeout(function onSend() { tchannelJSON.send(bob.clientChannel.request({ timeout: 5000, serviceName: steve.serviceName }), 'echo', null, 'oh hi lol', onForwarded); }, 55); } function onForwarded(err, resp) { assert.ifError(err); assert.equal(String(resp.body), 'oh hi lol'); steveHyperbahnClient.destroy(); assert.end(); } }); HyperbahnCluster.test('advertise, unadvertise and forward', { size: 5, servicePurgePeriod: 50 }, function t(cluster, assert) { var steve = cluster.remotes.steve; var bob = cluster.remotes.bob; var tchannelJSON = TChannelJSON({ logger: cluster.logger }); var steveHyperbahnClient = new HyperbahnClient({ serviceName: steve.serviceName, callerName: 'forward-test', hostPortList: cluster.hostPortList, tchannel: steve.channel, advertiseInterval: 2, logger: DebugLogtron('hyperbahnClient') }); steveHyperbahnClient.once('advertised', onAdvertised); steveHyperbahnClient.advertise(); function onAdvertised() { assert.equal(steveHyperbahnClient.state, 'ADVERTISED', 'state should be ADVERTISED'); untilAllInConnsRemoved(steve, function onSend() { fwdreq = bob.clientChannel.request({ timeout: 5000, serviceName: steve.serviceName }); tchannelJSON.send(fwdreq, 'echo', null, 'oh hi lol', onForwarded); }); steveHyperbahnClient.once('unadvertised', onUnadvertised); steveHyperbahnClient.unadvertise(); } var fwdreq; function onUnadvertised() { assert.equal(steveHyperbahnClient.latestAdvertisementResult, null, 'latestAdvertisementResult is null'); assert.equal(steveHyperbahnClient.state, 'UNADVERTISED', 'state should be UNADVERTISED'); } function onForwarded(err, resp) { assert.ok(err && err.type === 'tchannel.declined' && err.message === 'no peer available for request'); steveHyperbahnClient.destroy(); assert.end(); } }); HyperbahnCluster.test('advertise, unadvertise and re-advertise', { size: 5 }, function t(cluster, assert) { var steve = cluster.remotes.steve; var steveHyperbahnClient = new HyperbahnClient({ serviceName: steve.serviceName, callerName: 'forward-test', hostPortList: cluster.hostPortList, tchannel: steve.channel, advertiseInterval: 2, logger: DebugLogtron('hyperbahnClient') }); steveHyperbahnClient.once('advertised', onAdvertised); steveHyperbahnClient.advertise(); function onAdvertised() { assert.equal(steveHyperbahnClient.state, 'ADVERTISED', 'state should be ADVERTISED'); untilAllInConnsRemoved(steve, function readvertise() { steveHyperbahnClient.once('advertised', onReadvertised); steveHyperbahnClient.advertise(); }); steveHyperbahnClient.once('unadvertised', onUnadvertised); steveHyperbahnClient.unadvertise(); } function onUnadvertised() { assert.equal(steveHyperbahnClient.latestAdvertisementResult, null, 'latestAdvertisementResult is null'); assert.equal(steveHyperbahnClient.state, 'UNADVERTISED', 'state should be UNADVERTISED'); } function onReadvertised() { assert.equal(steveHyperbahnClient.state, 'ADVERTISED', 'state should be ADVERTISED'); steveHyperbahnClient.destroy(); assert.end(); } }); function untilAllInConnsRemoved(remote, callback) { var peers = remote.channel.peers.values(); var count = 0; peers.forEach(function eachPeer(peer) { peer.connections.forEach(function eachConn(conn) { if (conn.direction === 'in') { count++; } }); peer.removeConnectionEvent.on(onRemove); }); function onRemove(conn) { if (conn.direction === 'in') { if (--count <= 0) { callback(null); } } } } }
JavaScript
0.000002
@@ -3647,32 +3647,53 @@ t.advertise();%0A%0A + var fwdreq;%0A%0A function @@ -4258,36 +4258,16 @@ %7D%0A%0A - var fwdreq;%0A
074d22a0ca697381b3c8bf799d6af2be43d4d259
add title for moveToDebug
src/main/resources/public/js/src/launches/launchLevel/LaunchItemMenuView.js
src/main/resources/public/js/src/launches/launchLevel/LaunchItemMenuView.js
/* * Copyright 2016 EPAM Systems * * * This file is part of EPAM Report Portal. * https://github.com/epam/ReportPortal * * Report Portal is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Report Portal is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Report Portal. If not, see <http://www.gnu.org/licenses/>. */ define(function (require, exports, module) { 'use strict'; var $ = require('jquery'); var Backbone = require('backbone'); var Epoxy = require('backbone-epoxy'); var Util = require('util'); // var Editor = require('launchEditor'); var Urls = require('dataUrlResolver'); var Service = require('coreService'); var Localization = require('localization'); var App = require('app'); var ChangeModeAction = require('launches/multipleActions/changeModeAction'); var RemoveAction = require('launches/multipleActions/removeAction'); var ForceFinish = require('launches/multipleActions/forceFinishAction'); var config = App.getInstance(); var ItemMenuView = Epoxy.View.extend({ className: 'dropdown-menu launches-item-menu', tagName: 'ul', template: 'tpl-launch-edit-menu', events: { 'click [data-js-edit-item]': 'showEdit', 'click [data-js-start-analyze]': 'startAnalyzeAction', 'click [data-js-finish]': 'finishLaunch', 'click [data-js-switch-mode]': 'switchLaunchMode', 'click [data-js-remove]': 'onClickRemove', 'click [data-js-export-format]': 'onClickExport' }, bindings: { '[data-js-finish]': 'attr:{title: titleForceFinish, disabled: any(titleForceFinish)}', '[data-js-export-format]': 'attr:{disabled:not(isExport)}', '[data-js-can-match]': 'attr:{disabled:not(isMatchIssues)}', '[data-js-can-analyze]': 'attr:{disabled:not(isAnalyze)}', '[data-js-switch-mode]': 'text:itemModeText, attr:{disabled:not(isChangeMode)}', '[data-js-remove]': 'attr: {title: removeTitle, disabled: any(removeTitle)}', }, initialize: function(options) { this.model = options.model; this.exportFormats = { 'pdf': {name: 'PDF', code: 30}, 'xls': {name: 'XLS', code: 31}, 'html': {name: 'HTML', code: 32} }; this.render(); }, computeds: { isAnalyze: { deps: ['launch_isProcessing'], get: function(launch_isProcessing) { return !launch_isProcessing; } }, isChangeMode: { deps: ['launch_owner'], get: function () { return !this.model.validate.changeMode(); } }, titleForceFinish: { deps: ['status', 'launch_owner'], get: function() { return this.model.validate.forceFinish(); } }, isExport: { deps: ['launch_status'], get: function(launchStatus) { return (launchStatus != 'IN_PROGRESS'); } }, removeTitle: { deps: ['launch_owner', 'status'], get: function() { return this.model.validate.remove(); } }, itemModeText: { deps: ['mode'], get: function(mode) { return (mode == 'DEBUG') ? Localization.launches.shiftToLaunches : Localization.launches.shiftToDebug; } }, isMatchIssues: { deps: ['launch_status', 'launch_isProcessing', 'launch_toInvestigate'], get: function(launchStatus, launchIsProcessing, launch_toInvestigate) { return (launchStatus != 'IN_PROGRESS' && !launchIsProcessing && launch_toInvestigate > 0); } }, }, render: function() { var model = this.model.toJSON({computed: true}); this.$el.html(Util.templates(this.template, { isDebug: this.isDebug(), isCustomer: Util.isCustomer(), getExportUrl: Urls.exportLaunchUrl, updateImagePath: Util.updateImagePath, exportFormats: this.exportFormats, item: model })); }, isDebug: function(){ return this.model.get('mode') === 'DEBUG'; }, startAnalyzeAction: function (e) { e.preventDefault(); var self = this, el = $(e.currentTarget), id = this.model.get('id'), isLaunchAnalyze = el.data('analyze-type') === "analyze", type = isLaunchAnalyze ? "startLaunchAnalyze" : "startLaunchMatch"; if (!el.hasClass('disabled')) { config.trackingDispatcher.trackEventNumber(isLaunchAnalyze ? 28 : 27); Service[type](id) .done(function(response){ self.model.set('isProcessing', true); Util.ajaxSuccessMessenger("startAnalyzeAction"); }) .fail(function (error) { Util.ajaxFailMessenger(error, "startAnalyzeAction"); }) } else { e.stopPropagation(); } }, finishLaunch: function(){ config.trackingDispatcher.trackEventNumber(26); var self = this; ForceFinish({items: [this.model]}).done(function() { self.model.collection.load(true); }); }, onClickRemove: function() { config.trackingDispatcher.trackEventNumber(29); var self = this; RemoveAction({items: [this.model]}).done(function() { self.model.collection.load(true); }); }, onClickExport: function(e){ var $el = $(e.currentTarget), format = $el.data('js-export-format'); config.trackingDispatcher.trackEventNumber(this.exportFormats[format].code); }, switchLaunchMode: function () { config.trackingDispatcher.trackEventNumber(25); var self = this; ChangeModeAction({items: [this.model]}).done(function() { self.model.collection.load(true); }); }, destroy: function () { this.undelegateEvents(); this.stopListening(); this.unbind(); this.$el.html(''); delete this; } }); return ItemMenuView; });
JavaScript
0
@@ -2399,24 +2399,48 @@ Text, attr:%7B +title: titleChangeMode, disabled:not @@ -3289,32 +3289,232 @@ %0A %7D,%0A + titleChangeMode: %7B%0A deps: %5B'launch_owner'%5D,%0A get: function () %7B%0A return this.model.validate.changeMode();%0A %7D%0A %7D,%0A titl
571a9101eb68ab1a57c6b2f6601f7237a6273650
Remove content rules
Nope.safariextension/global.js
Nope.safariextension/global.js
safari.extension.settings.addEventListener("change", settingsChangeHandler, false); safari.application.addEventListener("command", commandHandler, false); safari.application.addEventListener("validate", validateHandler, false); var allRules = advertisingRules.concat(analyticsRules, contentRules, socialRules) var yepDomains = safari.extension.settings.whiteListedDomains; var yepArray = _getWhiteListedDomains(); var veryNopeDomains = safari.extension.settings.blackListedDomains; var veryNopeArray = _getBlackListedDomains(); function _getWhiteListedDomains() { if (yepDomains && yepDomains != "") { return yepDomains.split(",").map(function(string) { return string.replace(/ /, "") }) } else { return [] } } function _getBlackListedDomains() { if (veryNopeDomains && veryNopeDomains != "") { return veryNopeDomains.split(",").map(function(string) { return string.replace(/ /, "") }) } else { return [] } } function _currentTabURL() { return safari.application.activeBrowserWindow.activeTab.url; } function settingsChangeHandler(event) { if (event.key === "whiteListedDomains" || event.key === "isPaused" || event.key === "blackListedDomains") { loadRules(); } } function commandHandler(event) { if (event.command === "whiteListSite") { toggleWhiteListForSite(_currentTabURL()); } else if (event.command === "blackListSite") { toggleBlackListForSite(_currentTabURL()); } else if (event.command === "pause") { safari.extension.settings.isPaused = !safari.extension.settings.isPaused; updateMenuButtonIcon(safari.extension.toolbarItems[0]) } } function validateHandler(event) { var currentURL = _currentTabURL(); var domain = extractDomain(currentURL); if (event.target.identifier == "menuButton") { event.target.disabled = (typeof currentURL === "undefined"); updateMenuButtonIcon(event.target); } else if (event.target.identifier == "whiteListSite") { event.target.checkedState = arrayContains(yepArray, domain); event.target.title = "Yep to " + domain; } else if (event.target.identifier == "blackListSite") { event.target.checkedState = arrayContains(veryNopeArray, domain); event.target.title = "Very Nope to " + domain; } else if (event.target.identifier == "pause") { event.target.checkedState = safari.extension.settings.isPaused; } } function updateMenuButtonIcon(target) { var imageName = safari.extension.settings.isPaused ? "icon-paused.png" : "icon.png"; target.image = safari.extension.baseURI + "assets/" + imageName; } function loadRules() { console.log("Loading rules..."); var userRules = allRules; if (safari.extension.settings.isPaused) { userRules = [{ "action": {"type": "ignore-previous-rules"}, "trigger": {"url-filter": ".*"} }]; setContentBlocker(userRules); return; } if (yepArray.length > 0) { var ignoreRule = { "action": {"type": "ignore-previous-rules"}, "trigger": { "url-filter": ".*", "if-domain": yepArray } }; userRules = userRules.concat([ignoreRule]); } if (veryNopeArray.length > 0) { var veryNopeRules = [ {"action": {"type": "block-cookies"}, "trigger": { "url-filter": ".*", "if-domain": veryNopeArray} }, {"action": {"type": "block"}, "trigger": { "url-filter": ".*", "if-domain": veryNopeArray, "resource-type": ["script", "raw", "popup"], "load-type": ["third-party"]} } ]; userRules = veryNopeRules.concat(userRules) } setContentBlocker(userRules); } function setContentBlocker(customRules) { safari.extension.setContentBlocker(customRules); } function toggleWhiteListForSite(siteURL) { var domain = extractDomain(siteURL); if (arrayContains(yepArray, domain)) { arrayRemove(yepArray, domain) } else { yepArray.push(domain) if (arrayContains(veryNopeArray, domain)) { arrayRemove(veryNopeArray, domain) safari.extension.settings.blackListedDomains = veryNopeArray.join(", "); } } safari.extension.settings.whiteListedDomains = yepArray.join(", "); } function toggleBlackListForSite(siteURL) { var domain = extractDomain(siteURL); if (arrayContains(veryNopeArray, domain)) { arrayRemove(veryNopeArray, domain) } else { veryNopeArray.push(domain) if (arrayContains(yepArray, domain)) { arrayRemove(yepArray, domain) safari.extension.settings.whiteListedDomains = yepArray.join(", "); } } safari.extension.settings.blackListedDomains = veryNopeArray.join(", "); } function extractDomain(url) { if (typeof url === "undefined") { return } var domain; if (url.indexOf("://") > -1) { domain = url.split('/')[2]; } else { domain = url.split('/')[0]; } domain = domain.split(':')[0]; return domain; } function arrayContains(array, element) { return (array.indexOf(element) > -1); } function arrayRemove(array, element) { var index = array.indexOf(element); if (index > -1) { array.splice(index, 1); } } function initSettings() { if (typeof safari.extension.settings.isPaused === "undefined") { safari.extension.settings.isPaused = false; } } loadRules(); initSettings();
JavaScript
0.000001
@@ -280,22 +280,8 @@ les, - contentRules, soc
f155048e8b5942ab46a68ea8e567547b861544ac
add drawPiece function
tetroggleable/app/assets/javascripts/game.js
tetroggleable/app/assets/javascripts/game.js
var ROWS = 20; var COLS = 10; var SIZE = 32; var canvas; var context; var lineScore; var currentBlock; $(document).ready(function(){ canvas = document.getElementById('gameCanvas'); context = canvas.getContext('2d'); lineScore = $('#lines'); // startGame(); // drawBoard(); }) function startGame() { var r, c; currentLines = 0; isGameOver = false; gameData = new Array(); for(r = 0; r < ROWS; r++) { gameData[r] = new Array(); for(c = 0; c < COLS; c++) { // gameData[r].push(0); gameData[r][c] = 0; } } currentBlock = getRandomBlock(); var requestAnimFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; window.requestAnimationFrame = requestAnimFrame; // requestAnimationFrame(update); } function drawBoard() { // context.drawImage(bgImg, 0, 0, 320, 640, 0, 0, 320, 640); context.rect(0, 0, 320, 640); context.fillStyle="blue"; context.fill(); context.lineWidth = "2"; context.strokeStyle = "yellow"; context.stroke(); for(var row = 0; row < ROWS; row++) { for(var col = 0; col < COLS; col++) { if(gameData[row][col] != 0) { // context.drawImage(blockImg, (gameData[row][col] - 1) * SIZE, 0, SIZE, SIZE, col * SIZE, row * SIZE, SIZE, SIZE); --> context.rect(col * SIZE, row * SIZE, SIZE, SIZE); context.fillStyle="red"; context.fill(); } } } }
JavaScript
0.000001
@@ -274,16 +274,49 @@ Board(); +%0A%09// drawBlock(getRandomBlock()); %0A%0A%7D)%0A%0A%0Af @@ -1475,8 +1475,653 @@ %7D%0A%09%7D%0A%7D%0A%0A +function drawBlock(block) %7B%0A%09var drawX = block.gridX;%0A%09var drawY = block.gridY;%0A%09var rotation = block.currentRotation;%0A%09%0A%09for(var row = 0, len = block.rotations%5Brotation%5D.length; row %3C len; row++) %7B%0A%09%09for(var col = 0, len2 = block.rotations%5Brotation%5D%5Brow%5D.length; col %3C len2; col++) %7B%0A%09%09%09if(block.rotations%5Brotation%5D%5Brow%5D%5Bcol%5D == 1 && drawY %3E= 0) %7B%0A%09%09%09%09// context.drawImage(blockImg, block.color * SIZE, 0, SIZE, SIZE, drawX * SIZE, drawY * SIZE, SIZE, SIZE);%0A%09%09%09%09context.rect(drawX * SIZE, drawY * SIZE , SIZE, SIZE);%0A%09%09%09%09context.fillStyle=%22green%22;%0A%09%09%09%09context.fill();%0A%09%09%09%7D%0A%09%09%09%0A%09%09%09drawX += 1;%0A%09%09%7D%0A%09%09%0A%09%09drawX = block.gridx;%0A%09%09drawY += 1;%0A%09%7D%0A%0A%7D%0A%0A
804435b0a603f0555beb4a3836fcbbb02241244c
Remove payload from logout
client/app/common/authentication/authentication.service.js
client/app/common/authentication/authentication.service.js
class AuthenticationService { constructor($http) { "ngInject"; this.$http = $http; } login(email,password) { return this.$http.post("/api/auth/", { email,password }) .then((data) => data.data); } update() { return this.$http.get("/api/auth/status/") .then((data) => data.data); } logout() { let email = "",password = ""; return this.$http.post("/api/auth/logout/", { email,password }); } } export default AuthenticationService;
JavaScript
0.000003
@@ -334,42 +334,8 @@ ) %7B%0A - let email = %22%22,password = %22%22;%0A @@ -379,32 +379,16 @@ out/%22, %7B - email,password %7D);%0A %7D%0A
650373d1fc96052315b8edfe41be4559715ce71e
correct intendation
1.3/directive.extended.template.js
1.3/directive.extended.template.js
/** * Created by ${USER} on ${DATE}. */ (function() { 'use strict'; var MODULE_NAME = '${Module_name}'; var DIRECTIVE_HTML_NAME = '${Directive_HTML_name}'; var DIRECTIVE_NAME = _getDirectiveName(); describe(('${Test_category}' || MODULE_NAME), function() { var ${DS}q = null; var ${DS}rootScope = null; var ${DS}compile = null; var ${DS}timeout = null; var ${DS}httpBackend = null; var element = null; var controller = null; var ${DS}parentScope = null; var ${DS}scope = null; function MockedService() { } function MockedDirectiveController() { } /** * Template wrapper for registering mocked services */ beforeEach(angular.mock.module(MODULE_NAME, function(${DS}provide, ${DS}compileProvider) { ${DS}provide.service('mockedService', MockedService); mockDirective(${DS}compileProvider, 'mockedDirective', MockedDirectiveController); })); describe(('${Test_description}' || DIRECTIVE_HTML_NAME), function() { // Unit Tests for "${Directive_HTML_name}" Directive, "${Module_name}" module describe('When ', function() { beforeEach(function() { }); it('should ', function() { }); }); //End /** * Mock directive template and pre-configure */ beforeEach(inject([ function() { ${DS}httpBackend.whenGET(new RegExp(DIRECTIVE_NAME+'\\.directive\\.html${DS}')).respond(200, '<div/>'); } ])); /** * Create and initialize Directive */ beforeEach(createEnvironment); /** * Additional beforeEach wrapper for custom services and configuration */ beforeEach(inject([ function() { } ])); afterEach(destroyEnvironment); }); /** * Create environment and new directive instance */ function createEnvironment() { ${DS}parentScope = ${DS}rootScope.${DS}new(true); element = createDirective(); controller = element.controller(DIRECTIVE_NAME); ${DS}scope = element.isolateScope(); } function createDirective() { var element = angular.element('<' + DIRECTIVE_HTML_NAME + '></' + DIRECTIVE_HTML_NAME + '>'); ${DS}compile(element)(${DS}parentScope); ${DS}httpBackend.flush(); configureDirective(); ${DS}parentScope.${DS}digest(); return element; } /** * Dynamic function that can hold additional configuration for directive that will be added right after its creation * @type {Function} */ var configureDirective = function () { // anything that should be available to directive through ${DS}parentScope }; /** * Clear test, remove created scope and other objects */ function destroyEnvironment() { if (${DS}parentScope) { ${DS}parentScope.${DS}destroy(); ${DS}parentScope = null; } ${DS}rootScope = null; ${DS}scope = null; controller = null; element = null; } /** * Add basic services for directives */ beforeEach(inject([ '${DS}q', '${DS}rootScope', '${DS}compile', '${DS}httpBackend', '${DS}timeout', function(_${DS}q_, _${DS}rootScope_, _${DS}compile_, _${DS}httpBackend_, _${DS}timeout_) { ${DS}q = _${DS}q_; ${DS}rootScope = _${DS}rootScope_; ${DS}compile = _${DS}compile_; ${DS}httpBackend = _${DS}httpBackend_; ${DS}timeout = _${DS}timeout_; } ])); }); /** * Wrapper for ${DS}compileProvider.directive(), that allows to mock directives preventing their execution while unit-tests */ function mockDirective(${DS}compileProvider, name, controller, link){ ${DS}compileProvider.directive(name, function(){ return { priority: 4092, name: name, terminal: true, restrict:'AE', link: link, controller: controller }; }); } function _getDirectiveName() { var list = DIRECTIVE_HTML_NAME.split('-'); var name = list.shift(); while (list.length) { var item = list.shift(); name += item[0].toUpperCase() + item.substr(1); } return name; } })();
JavaScript
0.000126
@@ -843,9 +843,12 @@ e);%0A -%09 + mo
ad5cb926cdccb84f4a9457575db6c5fce52be24c
change text on banner ;
actor-apps/app-web/src/app/components/common/Banner.react.js
actor-apps/app-web/src/app/components/common/Banner.react.js
import React from 'react'; import BannerActionCreators from 'actions/BannerActionCreators'; class Banner extends React.Component { constructor(props) { super(props); if (window.localStorage.getItem('banner_jump') === null) { BannerActionCreators.show(); } } onClose = () => { BannerActionCreators.hide(); }; onJump = (os) => { BannerActionCreators.jump(os); this.onClose(); }; render() { return ( <section className="banner"> <p> Welcome to <b>Actor Network</b>! Don't forget to install mobile apps! &nbsp; <a href="//actor.im/ios" onClick={this.onJump.bind(this, 'IOS')} target="_blank">iPhone</a> &nbsp;|&nbsp; <a href="//actor.im/android" onClick={this.onJump.bind(this, 'ANDROID')} target="_blank">Android</a> </p> <a className="banner__hide" onClick={this.onClose}> <i className="material-icons">close</i> </a> </section> ); } } export default Banner;
JavaScript
0
@@ -537,71 +537,21 @@ b%3E! -Don't forget to install mobile apps!%0A &nbsp;%0A +Chech out our %3Ca @@ -642,42 +642,12 @@ %3C/a%3E -%0A &nbsp;%7C&nbsp;%0A + and %3Ca @@ -739,24 +739,30 @@ %3EAndroid%3C/a%3E + apps! %0A %3C/p
7a56b76539cb836e7fce5ad03a85e5a28b27cf53
create new course traceback issue
addons/website_slides/static/src/js/website_slides.editor.js
addons/website_slides/static/src/js/website_slides.editor.js
odoo.define('website_slides.editor', function (require) { "use strict"; var core = require('web.core'); var Dialog = require('web.Dialog'); var QWeb = core.qweb; var WebsiteNewMenu = require('website.newMenu'); var wUtils = require('website.utils'); var _t = core._t; var ChannelCreateDialog = Dialog.extend({ template: 'website.slide.channel.create', /** * @override * @param {Object} parent * @param {Object} options */ init: function (parent, options) { options = _.defaults(options || {}, { title: _t("New Course"), size: 'medium', buttons: [{ text: _t("Create"), classes: 'btn-primary', click: this._onClickFormSubmit.bind(this) }, { text: _t("Discard"), close: true },] }); this._super(parent, options); }, start: function () { var self = this; return this._super.apply(this, arguments).then(function () { var $input = self.$('#tag_ids'); $input.select2({ width: '100%', allowClear: true, formatNoMatches: false, multiple: true, selection_data: false, fill_data: function (query, data) { var that = this, tags = {results: []}; _.each(data, function (obj) { if (that.matcher(query.term, obj.name)) { tags.results.push({id: obj.id, text: obj.name}); } }); query.callback(tags); }, query: function (query) { var that = this; // fetch data only once and store it if (!this.selection_data) { self._rpc({ route: '/slides/channel/tag/search_read', params: { fields: ['name'], domain: [], } }).then(function (data) { that.can_create = data.can_create; that.fill_data(query, data.read_results); that.selection_data = data.read_results; }); } else { this.fill_data(query, this.selection_data); } } }); }); }, _onClickFormSubmit: function (ev) { var $form = this.$("#slide_channel_add_form"); var $title = this.$("#title"); if (!$title[0].value){ $title.addClass('border-danger'); this.$("#title-required").removeClass('d-none'); } else { $form.submit(); } }, }); WebsiteNewMenu.include({ actions: _.extend({}, WebsiteNewMenu.prototype.actions || {}, { new_slide_channel: '_createNewSlideChannel', }), xmlDependencies: WebsiteNewMenu.prototype.xmlDependencies.concat( ['/website_slides/static/src/xml/website_slides_channel.xml'] ), //-------------------------------------------------------------------------- // Actions //-------------------------------------------------------------------------- /** * Displays the popup to create a new slide channel, * and redirects the user to this channel. * * @private * @returns {Promise} Unresolved if there is a redirection */ _createNewSlideChannel: function () { var self = this; var def = new Promise(function (resolve) { var dialog = new ChannelCreateDialog(self, {}); dialog.open(); dialog.on('closed', self, resolve); }); return def; }, }); });
JavaScript
0
@@ -353,16 +353,155 @@ reate',%0A + xmlDependencies: Dialog.prototype.xmlDependencies.concat(%0A %5B'/website_slides/static/src/xml/website_slides_channel.xml'%5D%0A ),%0A /**%0A @@ -3265,155 +3265,8 @@ %7D), -%0A xmlDependencies: WebsiteNewMenu.prototype.xmlDependencies.concat(%0A %5B'/website_slides/static/src/xml/website_slides_channel.xml'%5D%0A ), %0A%0A
07883f5a18838f4e9bc0b815866f172cb2e47ac5
Simplify code
imagebox.js
imagebox.js
;(function() { function applyEach (collection, callbackEach) { for (var i = 0; i < collection.length; i++) { callbackEach(collection[i]); } } function isNullOrUndefined(o) { return typeof o === 'undefined' || o === null; } function hasClass(el, className) { return el.className.match(new RegExp('(^| )' + className + '( |$)')); } function ImageBox(selector, options) { var self = this; selector = selector || '.imagebox-container'; options = options || {}; if (!isNullOrUndefined(selector) && typeof selector !== 'string') { // config object options = selector; selector = undefined; } var elements = document.querySelectorAll(selector); if (elements.length === 0) { throw new Error("No elements found with selector: "+selector); } else if (elements.length > 1) { applyEach(elements, function(element) { new ImageBox(element, options); }); return; } this.container = elements[0]; this.image = document.querySelector(selector + " > img"); if (isNullOrUndefined(this.container) || isNullOrUndefined(this.image)) { throw new Error("Container or img not found."); } this.imageWidth = options.imageWidth || this.image.getAttribute('data-width'); this.imageHeight = options.imageHeight || this.image.getAttribute('data-height'); if (isNullOrUndefined(this.imageWidth) || isNullOrUndefined(this.imageHeight)) { throw new Error("Must specify image width and height"); } this.scalingType = options.defaultScaling || "fit"; if(!hasClass(this.container, "imagebox-container")) { this.container.className += " imagebox-container"; } window.addEventListener('resize', function(){ self.resize(); }, false); this.resize(); } ImageBox.prototype.resize = function() { if(this.scalingType === "horizontalFill") { this.resizeHorizontalFill(); } else { this.resizeFit(); } }; ImageBox.prototype.resizeHorizontalFill = function() { // Reset styles that may be set from other resize this.image.style.height = ""; this.image.style.width = this.container.clientWidth + "px"; this.verticallyCenter(); }; ImageBox.prototype.resizeFit = function() { var newPaddingTop = 0, newWidth = this.imageWidth, newHeight = this.imageHeight, containerWidth = this.container.clientWidth, containerHeight = this.container.clientHeight, imageAspectRatio = this.imageWidth / this.imageHeight; var containerAspectRatio = containerWidth / containerHeight; if (imageAspectRatio >= containerAspectRatio) { if (this.imageWidth >= containerWidth) { newWidth = containerWidth; newHeight = this.imageHeight * (containerWidth / this.imageWidth); } } else { if (this.imageHeight >= containerHeight) { newWidth = this.imageWidth * (containerHeight / this.imageHeight); newHeight = containerHeight; } } if (newHeight < containerHeight) { newPaddingTop = (containerHeight - newHeight) / 2; } this.image.style.width = newWidth + "px"; this.image.style.height = newHeight + "px"; this.verticallyCenter(); }; ImageBox.prototype.verticallyCenter = function() { var newPaddingTop = 0, resizedImageHeight = this.image.height, containerHeight = this.container.clientHeight; if(resizedImageHeight < containerHeight) { newPaddingTop = (containerHeight - resizedImageHeight) / 2; } this.image.style.paddingTop = newPaddingTop + "px"; }; if (typeof module === 'object' && typeof module.exports === 'object') { // CommonJS module.exports = exports = ImageBox; } else if (typeof define === 'function' && define.amd) { // AMD define(function () { return ImageBox; }); } else { window.ImageBox = ImageBox; } })();
JavaScript
0.041259
@@ -12,154 +12,8 @@ ) %7B%0A - function applyEach (collection, callbackEach) %7B%0A for (var i = 0; i %3C collection.length; i++) %7B%0A callbackEach(collection%5Bi%5D);%0A %7D%0A %7D%0A%0A fu @@ -234,24 +234,18 @@ mageBox( -s el -ector , option @@ -274,58 +274,8 @@ is;%0A - selector = selector %7C%7C '.imagebox-container';%0A @@ -312,68 +312,30 @@ if ( -!isNullOrUndefined(selector) && typeof -s el -ector !== ' + === %22 string -' +%22 ) %7B%0A @@ -344,412 +344,144 @@ -// config object%0A options = selector;%0A selector = undefined;%0A %7D%0A%0A var elements = document.querySelectorAll(selector);%0A if (elements.length === 0) %7B%0A throw new Error(%22No elements found with selector: %22+selector);%0A %7D%0A else if (elements.length %3E 1) %7B%0A applyEach(elements, function(element) %7B%0A new ImageBox(element, options);%0A %7D);%0A return;%0A %7D%0A%0A this. +el = document.querySelector(el);%0A %7D%0A%0A this.container = el;%0A if (isNullOrUndefined(this.container)) %7B%0A throw new Error(%22No cont @@ -489,18 +489,16 @@ iner - = element s%5B0%5D @@ -497,13 +497,29 @@ ment -s%5B0%5D; + specified.%22);%0A %7D%0A %0A @@ -532,24 +532,18 @@ image = -document +el .querySe @@ -553,23 +553,9 @@ tor( -selector + %22 %3E +%22 img%22 @@ -592,104 +592,80 @@ his. -container) %7C%7C isNullOrUndefined(this.image)) %7B%0A throw new Error(%22Container or img not found +image)) %7B%0A throw new Error(%22No %3Cimg%3E found inside container element .%22);
edf2e9130cbb5d2c62abdcac10ecfb1199c2f212
Fix whitescreen in wallet selection (#1915)
app/components/views/GetStartedPage/WalletSelection/index.js
app/components/views/GetStartedPage/WalletSelection/index.js
import { WalletSelectionFormBody } from "./Form"; import { createWallet } from "connectors"; @autobind class WalletSelectionBody extends React.Component { constructor(props) { super(props); this.state = this.getInitialState(); } getInitialState() { return { editWallets: false, createNewWallet: true, createWalletForm: false, newWalletName: "", selectedWallet: this.props.availableWallets ? this.props.availableWallets[0] : null, hasFailedAttempt: false, isWatchingOnly: false, walletMasterPubKey: "", masterPubKeyError: false, walletNameError: null, isTrezor: false, }; } componentDidUpdate(prevProps) { if (this.props.availableWallets.length > 0 && prevProps.availableWallets.length !== this.props.availableWallets.length) { this.setState({ selectedWallet: this.props.availableWallets[0] }); } else { for (var i = 0; i < prevProps.availableWallets.length; i++) { if (this.props.availableWallets[i].label !== prevProps.availableWallets[i].label) { this.setState({ selectedWallet: this.props.availableWallets[0] }); } } } } componentWillUnmount() { this.resetState(); } render() { const { getDaemonSynced, maxWalletCount, isSPV } = this.props; const { onChangeAvailableWallets, startWallet, createWallet, onChangeCreateWalletName, showCreateWalletForm, hideCreateWalletForm, onEditWallets, onCloseEditWallets, toggleWatchOnly, onChangeCreateWalletMasterPubKey, toggleTrezor, } = this; const { selectedWallet, sideActive, newWalletName, newWalletNetwork, createWalletForm, createNewWallet, editWallets, hasFailedAttemptName, hasFailedAttemptPubKey, isWatchingOnly, walletMasterPubKey, masterPubKeyError, walletNameError, } = this.state; return ( <WalletSelectionFormBody {...{ sideActive, onChangeAvailableWallets, onChangeCreateWalletName, startWallet, createWallet, createWalletForm, createNewWallet, showCreateWalletForm, hideCreateWalletForm, selectedWallet, newWalletName, hasFailedAttemptName, hasFailedAttemptPubKey, newWalletNetwork, onEditWallets, onCloseEditWallets, editWallets, networkSelected: newWalletNetwork == "mainnet", getDaemonSynced, toggleWatchOnly, isWatchingOnly, onChangeCreateWalletMasterPubKey, walletMasterPubKey, masterPubKeyError, walletNameError, maxWalletCount, isSPV, toggleTrezor, ...this.props, ...this.state, }} /> ); } onEditWallets() { this.setState({ editWallets: true }); } onCloseEditWallets() { this.setState({ editWallets: false }); } showCreateWalletForm(createNewWallet) { this.setState({ createNewWallet, createWalletForm: true }); } hideCreateWalletForm() { if (this.state.isTrezor) { this.props.trezorDisable(); } this.setState({ hasFailedAttemptName: false, hasFailedAttemptPubKey: false, createWalletForm: false, newWalletName: "", isWatchingOnly: false, isTrezor: false, walletMasterPubKey: "", }); } onChangeAvailableWallets(selectedWallet) { this.setState({ selectedWallet }); } onChangeCreateWalletName(newWalletName) { const { availableWallets } = this.props; this.setState({ hasFailedAttemptName: true }); var nameAvailable = true; // replace all special path symbols newWalletName = newWalletName.replace(/[/\\.;:~]/g, ""); for (var i = 0; i < availableWallets.length; i++) { if (newWalletName == availableWallets[i].value.wallet) { nameAvailable = false; this.setState({ walletNameError: true }); } } if (nameAvailable) { this.setState({ walletNameError: false }); } this.setState({ newWalletName }); } createWallet() { const { newWalletName, createNewWallet, isWatchingOnly, masterPubKeyError, walletMasterPubKey, walletNameError, isTrezor } = this.state; if (newWalletName == "" || walletNameError) { this.setState({ hasFailedAttemptName: true }); return; } if (isWatchingOnly) { if (masterPubKeyError || !walletMasterPubKey) { this.setState({ hasFailedAttemptPubKey: true }); return; } } if (isTrezor && !this.props.trezorDevice) { this.props.trezorAlertNoConnectedDevice(); return; } if (isTrezor) { this.props.trezorGetWalletCreationMasterPubKey() .then(() => { this.props.onCreateWallet( createNewWallet, { label: newWalletName, value: { wallet: newWalletName, watchingOnly: true, isTrezor } } ); }); } else { this.props.onCreateWallet( createNewWallet, { label: newWalletName, value: { wallet: newWalletName, watchingOnly: isWatchingOnly, isTrezor } } ); } } toggleWatchOnly() { const { isWatchingOnly } = this.state; this.setState({ isWatchingOnly : !isWatchingOnly, isTrezor: false }); } toggleTrezor() { const isTrezor = !this.state.isTrezor; this.setState({ isTrezor, isWatchingOnly: false }); if (isTrezor) { this.props.trezorEnable(); } else { this.props.trezorDisable(); } } async onChangeCreateWalletMasterPubKey(walletMasterPubKey) { if (walletMasterPubKey === "") { this.setState({ hasFailedAttemptPubKey: true }); } const { isValid } = await this.props.validateMasterPubKey(walletMasterPubKey); if (!isValid) { this.setState({ masterPubKeyError: true }); } else { this.setState({ masterPubKeyError: false }); } this.setState({ walletMasterPubKey }); } startWallet() { this.props.onStartWallet(this.state.selectedWallet); } resetState() { this.setState(this.getInitialState()); } } export default createWallet(WalletSelectionBody);
JavaScript
0
@@ -714,39 +714,132 @@ ops. -availableWallets.length %3E 0 && +selectedWallet && this.props.availableWallets.length === 0) %7B%0A this.setState(%7B selectedWallet: null %7D);%0A %7D else if ( prev @@ -1229,24 +1229,41 @@ lets%5B0%5D %7D);%0A + break;%0A %7D%0A
c884310dabf7199a70c0dfacfd2fede8b856fe16
Add countModels test helper
test/integration/helpers/index.js
test/integration/helpers/index.js
var _ = require('lodash'); exports.formatNumber = function(dialect) { return { mysql: _.identity, sqlite3: _.identity, postgresql: function(count) { return count.toString() } }[dialect]; }
JavaScript
0.000001
@@ -199,8 +199,139 @@ ect%5D;%0A%7D%0A +%0Aexports.countModels = function countModels(Model, options) %7B%0A return function() %7B%0A return Model.forge().count(options);%0A %7D%0A%7D%0A
6827bd3d15e9393d7de2b940ee35b77c07453de8
Update for cheerio api change
test/integration/schemaOrgInfo.js
test/integration/schemaOrgInfo.js
const chai = require('chai'); const chaiHttp = require('chai-http'); const cheerio = require('cheerio'); const app = require('../../server'); const constants = require('../../app/lib/constants'); const expect = chai.expect; chai.use(chaiHttp); describe('app', () => { describe('Schema.org information', () => { it('should be contained in the page', (done) => { chai.request(app) .get(`${constants.SITE_ROOT}/41772`) .end((err, res) => { expect(err).to.equal(null); expect(res).to.have.status(200); const $ = cheerio.load(res.text); const jsonLdText = $('script[type="application/ld+json"]').text(); const jsonLd = JSON.parse(jsonLdText); expect(jsonLd['@context']).to.equal('http://schema.org'); expect(jsonLd['@type']).to.equal('Physician'); expect(jsonLd.address['@type']).to.equal('PostalAddress'); expect(jsonLd.address.streetAddress).to.equal('Guisborough'); expect(jsonLd.address.addressLocality).to.equal(''); expect(jsonLd.address.postalCode).to.equal('TS14 7DJ'); expect(jsonLd.email).to.equal('[email protected]'); expect(jsonLd.faxNumber).to.equal('01287 619613'); expect(jsonLd.geo['@type']).to.equal('GeoCoordinates'); expect(jsonLd.geo.latitude).to.equal('54.532600402832'); expect(jsonLd.geo.longitude).to.equal('-1.05542838573456'); expect(jsonLd.identifier).to.equal('A81005'); expect(jsonLd.isAcceptingNewPatients).to.equal('true'); expect(jsonLd.name).to.equal('Springwood Surgery'); expect(jsonLd.telephone).to.equal('01287 619611'); expect(jsonLd.url).to.equal('http://www.springwoodsurgery.co.uk/'); done(); }); }); }); });
JavaScript
0
@@ -656,20 +656,20 @@ son%22%5D'). -text +html ();%0A%0A
02685d114793424e24504364e4342ffca1b5c1a3
Update tools-collapsing-spec.js
test/lib/tools-collapsing-spec.js
test/lib/tools-collapsing-spec.js
import tools from '../../src/tools'; import chai from 'chai'; import sinon from 'sinon'; var { expect } = chai; var { zeroRemove, zeroFill, addNeighbors, collapseRow, collapseRight, collapseLeft } = tools; describe('Tools : collapsing', () => { describe('addNeighbors(row)', () => { it('adds like numbers', () => expect(addNeighbors([2, 2, 4, 4], zeroDiff)).to.deep.equal([4, 8])); it('adds numbers at the beginning only', () => expect(addNeighbors([2, 2, 8, 0])).to.deep.equal([4, 8])); it('adds numbers to the end only', () => expect(addNeighbors([2, 8, 8, 2])).to.deep.equal([2, 16, 2])); it('adds numbers with 0s appropratly', () => expect(addNeighbors([0, 0, 2, 2])).to.deep.equal([4])); it('does not add numbers', () => expect(addNeighbors([2, 4, 8, 2])).to.deep.equal([2, 4, 8, 2])); }); describe('collapseRow(row)', () => { it('collapses full row correctly', () => expect(collapseRow([2, 2, 128, 128, 64, 64])).to.deep.equal([4, 256, 128, 0, 0, 0])); it('collapses through 0s correctly', () => expect(collapseRow([0, 256, 256], zeroFill, addNeighbors)).to.deep.equal([512, 0, 0])); it('collapses entire rows correctly', () => expect(collapseRow([2, 2, 2, 2])).to.deep.equal([4, 4, 0, 0])); it('collapses through 0s correctly', () => expect(collapseRow([0, 2, 0, 2])).to.deep.equal([4, 0, 0, 0])); it('does not collapse full mismatched row', () => expect(collapseRow([4, 2, 8, 64, 128])).to.deep.equal([4, 2, 8, 64, 128])); }); describe('collapseRight(collapseFunction)', () => { it('returns a function', () => expect(collapseRight()).to.be.a('function')); }); describe('collapseLeft(collapseFunction)', function () { it('returns a function', () => expect(collapseLeft()).to.be.a('function')); it('should invoke collapse function', () => { let callback = sinon.spy(); collapseLeft(callback)(); expect(callback.called).to.equal(true); }); it('should send the appropriate object', () => { let callback = sinon.spy(); collapseLeft(callback)({row: 'row'}); expect(callback.calledWith({row: 'row'})); }); }); });
JavaScript
0
@@ -114,20 +114,8 @@ ar %7B - zeroRemove, zer @@ -344,18 +344,8 @@ , 4%5D -, zeroDiff )).t
66710ddce0a08d6c4feb809a96fd2b0bd7b1f86c
Remove unneccessary steps.
assets/js/googlesitekit/datastore/site/notifications.test.js
assets/js/googlesitekit/datastore/site/notifications.test.js
/** * `core/site` data store: notifications. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Internal dependencies */ import { actions, selectors } from './index'; import { createTestRegistry, unsubscribeFromAll, } from '../../../../../tests/js/utils'; import { CORE_SITE } from './constants'; describe( 'core/site notifications', () => { let registry; beforeEach( () => { registry = createTestRegistry(); const response = true; fetchMock.post( /^\/google-site-kit\/v1\/core\/site\/data\/mark-notification/, { body: JSON.stringify( response ), status: 200 } ); } ); afterEach( () => { unsubscribeFromAll( registry ); } ); describe( 'actions', () => { describe( 'fetchMarkNotification', () => { it.each( [ [ 'abc', 'accepted' ], [ 'abc', 'dismissed' ], ] )( 'properly marks a notification when the notification ID is "%s" and notification state is "%s".', ( notificationID, notificationState ) => { expect( () => registry.dispatch( CORE_SITE ).fetchMarkNotification( { notificationID, notificationState, } ) ).not.toThrow(); } ); it.each( [ [ 'abc', 'test' ], [ 'abc', undefined ], [ undefined, 'accepted' ], ] )( 'throws an error while trying to marks a notification when the notification ID is "%s" and notification state is "%s".', ( notificationID, notificationState ) => { expect( () => registry.dispatch( CORE_SITE ).fetchMarkNotification( { notificationID, notificationState, } ) ).toThrow(); } ); } ); describe( 'acceptNotification', () => { it.each( [ [ 'abc' ] ] )( 'properly accepts a notification when the notification ID is "%s".', ( notificationID ) => { expect( () => registry .dispatch( CORE_SITE ) .acceptNotification( notificationID ) ).not.toThrow(); } ); it.each( [ [ undefined, true ] ] )( 'throws an error when trying to accept a notification when the notification ID is "%s".', ( notificationID ) => { expect( () => registry .dispatch( CORE_SITE ) .acceptNotification( notificationID ) ).toThrow(); } ); } ); describe( 'dismissNotification', () => { it.each( [ [ 'abc' ] ] )( 'properly dismisses a notification when the notification ID is "%s".', ( notificationID ) => { expect( () => registry .dispatch( CORE_SITE ) .dismissNotification( notificationID ) ).not.toThrow(); } ); it.each( [ [ undefined, true ] ] )( 'throws an error when trying to dismiss a notification when the notification ID is "%s".', ( notificationID ) => { expect( () => registry .dispatch( CORE_SITE ) .dismissNotification( notificationID ) ).toThrow(); } ); } ); it( 'has appropriate notification actions', () => { const actionsToExpect = [ 'acceptNotification', 'addNotification', 'dismissNotification', 'fetchMarkNotification', 'removeNotification', ]; expect( Object.keys( actions ) ).toEqual( expect.arrayContaining( actionsToExpect ) ); } ); } ); describe( 'selectors', () => { it( 'has appropriate notification selectors', () => { const selectorsToExpect = [ 'getNotifications', 'isFetchingGetNotifications', 'isFetchingMarkNotification', ]; expect( Object.keys( selectors ) ).toEqual( expect.arrayContaining( selectorsToExpect ) ); } ); } ); } );
JavaScript
0.001648
@@ -989,33 +989,8 @@ ();%0A -%09%09const response = true;%0A %09%09fe @@ -1084,34 +1084,14 @@ dy: -JSON.stringify( response ) +'true' , st
2f58bac8452ec8981b5e8cc0ed45434768bf63ef
Add relations between Campgrounds and User models.
models/campground.js
models/campground.js
var mongoose = require('mongoose'); // SCHEMA SETUP: var campgroundSchema = new mongoose.Schema({ name: String, image: String, description: String, comments: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' } ] }); module.exports = mongoose.model('Campground', campgroundSchema);
JavaScript
0
@@ -150,24 +150,148 @@ on: String,%0A + author: %7B%0A %09id: %7B%0A %09%09type: mongoose.Schema.Types.ObjectId,%0A %09%09ref: 'User'%0A %09%7D,%0A %09username: String%0A %7D,%0A comments
d78916f85f541770cedd8f13906727704420d736
Fix the error occuring during permission check (#1510)
test/red/api/editor/index_spec.js
test/red/api/editor/index_spec.js
/** * Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ var should = require("should"); var sinon = require("sinon"); var request = require("supertest"); var express = require("express"); var editorApi = require("../../../../red/api/editor"); var comms = require("../../../../red/api/editor/comms"); var info = require("../../../../red/api/editor/settings"); describe("api/editor/index", function() { var app; describe("disabled the editor", function() { beforeEach(function() { sinon.stub(comms,'init', function(){}); sinon.stub(info,'init', function(){}); }); afterEach(function() { comms.init.restore(); info.init.restore(); }); it("disables the editor", function() { var editorApp = editorApi.init({},{ settings:{disableEditor:true} }); should.not.exist(editorApp); comms.init.called.should.be.false(); info.init.called.should.be.false(); }); }); describe("enables the editor", function() { var mockList = [ 'library','theme','locales','credentials','comms' ] var isStarted = true; var errors = []; before(function() { mockList.forEach(function(m) { sinon.stub(require("../../../../red/api/editor/"+m),"init",function(){}); }); sinon.stub(require("../../../../red/api/editor/theme"),"app",function(){ return express()}); }); after(function() { mockList.forEach(function(m) { require("../../../../red/api/editor/"+m).init.restore(); }) require("../../../../red/api/editor/theme").app.restore(); }); before(function() { app = editorApi.init({},{ log:{audit:function(){},error:function(msg){errors.push(msg)}}, settings:{httpNodeRoot:true, httpAdminRoot: true,disableEditor:false,exportNodeSettings:function(){}}, events:{on:function(){},removeListener:function(){}}, isStarted: function() { return isStarted; }, nodes: {paletteEditorEnabled: function() { return false }} }); }); it('serves the editor', function(done) { request(app) .get("/") .expect(200) .end(function(err,res) { if (err) { return done(err); } // Index page should probably mention Node-RED somewhere res.text.indexOf("Node-RED").should.not.eql(-1); done(); }); }); it('serves icons', function(done) { request(app) .get("/icons/inject.png") .expect("Content-Type", /image\/png/) .expect(200,done) }); it('handles page not there', function(done) { request(app) .get("/foo") .expect(404,done) }); it('warns if runtime not started', function(done) { isStarted = false; request(app) .get("/") .expect(503) .end(function(err,res) { if (err) { return done(err); } res.text.should.eql("Not started"); errors.should.have.lengthOf(1); errors[0].should.eql("Node-RED runtime not started"); done(); }); }); it('GET /settings', function(done) { request(app).get("/settings").expect(200).end(function(err,res) { if (err) { return done(err); } // permissionChecks.should.have.property('settings.read',1); done(); }) }); }); });
JavaScript
0.000001
@@ -932,16 +932,92 @@ ings%22);%0A +var auth = require(%22../../../../red/api/auth%22);%0Avar when = require(%22when%22);%0A %0A%0Adescri @@ -1886,16 +1886,47 @@ s = %5B%5D;%0A + var session_data = %7B%7D;%0A @@ -2453,16 +2453,16 @@ %7D);%0A%0A - @@ -2473,32 +2473,748 @@ re(function() %7B%0A + auth.init(%7B%0A settings:%7B%0A adminAuth: %7B%0A default: %7B%0A permissions: %5B'read'%5D%0A %7D%0A %7D,%0A storage: %7B%0A getSessions: function()%7B%0A return when.resolve(session_data);%0A %7D,%0A setSessions: function(_session) %7B%0A session_data = _session;%0A return when.resolve();%0A %7D%0A %7D,%0A log:%7Baudit:function()%7B%7D,error:function(msg)%7Berrors.push(msg)%7D%7D%0A %7D%0A %7D);%0A app
c09d4dd4656fee10787743ef541124665094559b
call generateButtonsInfo
avBooth/success-screen-directive/success-screen-directive.js
avBooth/success-screen-directive/success-screen-directive.js
/** * This file is part of agora-gui-booth. * Copyright (C) 2015-2016 Agora Voting SL <[email protected]> * agora-gui-booth is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License. * agora-gui-booth is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with agora-gui-booth. If not, see <http://www.gnu.org/licenses/>. **/ /* * Error indicator directive. */ angular.module('avBooth') .directive('avbSuccessScreen', function(ConfigService, $interpolate) { function link(scope, element, attrs) { var text = $interpolate(ConfigService.success.text); scope.organization = ConfigService.organization; function generateButtonsInfo() { scope.buttonsInfo = []; var data = scope.election.presentation.share_text; for(var i = 0, length = data.length; i < length; i++) { var p = data[i]; var buttonInfo = { link: '', img: '', button_text: p.button_text, class: 'btn btn-primary' }; if('Facebook' === p.network) { buttonInfo.link = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(p.social_message); buttonInfo.img = '/booth/img/facebook_logo_50.png'; buttonInfo.class = buttonInfo.class + ' btn-facebook'; } else if('Twitter' === p.network) { buttonInfo.link = 'https://twitter.com/intent/tweet?text=' + encodeURIComponent(p.social_message) + '&source=webclient'; buttonInfo.img = '/booth/img/twitter_logo_48.png'; buttonInfo.class = buttonInfo.class + ' btn-twitter'; } scope.buttonsInfo.push(buttonInfo); } } scope.successText = text({electionId: scope.election.id}); } return { restrict: 'AE', link: link, templateUrl: 'avBooth/success-screen-directive/success-screen-directive.html' }; });
JavaScript
0.000001
@@ -1042,15 +1042,8 @@ n;%0A%0A - %0A @@ -2096,24 +2096,54 @@ %7D%0A %7D%0A%0A + generateButtonsInfo();%0A%0A scope.