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
4b7278c2f06a5c977f4121af0f88327b69233fa6
Remove shutdown function as it is not needed now as FileInputHandler is removed.
game/states/editor.js
game/states/editor.js
'use strict'; var GameDataCreator = require('../gamedatacreator'); var PointView = require('../prefabs/pointview'); var MapView = require('../prefabs/mapview'); var Constants = require('../constants'); //State for setting GamePoints and MajorPoints on the game map. function Editor() {} Editor.prototype = { create: function() { this.game.add.image(0, 0, 'frame'); this.mapView = new MapView(this.game, this.removePoint, this); this.mapView.toggleInputOnPointViews(false); this.game.add.existing(this.mapView); this.buttonGroup = this.game.add.group(); this.addButtons(); }, update: function() { }, shutdown: function() { this.fileInputHandler.remove(); }, addButtons: function() { var addStartPointButton = this.game.add.button(162, 649, 'add-startpoint', this.changeAction, this, 1, 0); this.buttonGroup.add(addStartPointButton); var addEndPointButton = this.game.add.button(343, 649, 'add-startpoint', this.changeAction, this, 1, 0); this.buttonGroup.add(addEndPointButton); var addPointsButton = this.game.add.button(527, 649, 'add-point', this.changeAction, this, 1, 0); this.buttonGroup.add(addPointsButton); var removePointsButton = this.game.add.button(708, 649, 'remove-point', this.changeAction, this, 1, 0); this.buttonGroup.add(removePointsButton); this.game.add.button(895, 644, 'next-state', this.moveToNextState, this, 1, 0, 2, 0); }, //Changes the current action that happens on click based on the button that has been pressed. changeAction: function(button) { this.buttonGroup.setAll('frame', 0); this.buttonGroup.setAll('freezeFrames', false); button.freezeFrames = true; button.frame = 1; this.mapView.toggleInputOnPointViews(false); this.mapView.events.onInputDown.removeAll(); var buttonIndex = this.buttonGroup.getChildIndex(button); switch (buttonIndex) { case 0: this.mapView.events.onInputDown.add(this.addStartPoint, this); break; case 1: this.mapView.events.onInputDown.add(this.addEndPoint, this); break; case 2: this.mapView.events.onInputDown.add(this.addPoint, this); break; case 3: this.mapView.toggleInputOnPointViews(true); break; default: console.log('Invalid button index encountered, how the heck did that happen?'); } }, addPoint: function(sprite, pointer) { if (sprite.withinBounds(pointer)) { var x = this.scaleUp(pointer.x - this.mapView.x); var y = this.scaleUp(pointer.y - this.mapView.y); var newPoint = new GameDataCreator.GamePoint(x, y, Constants.pointStates.UNVISITED); if (this.game.data.points.length === 0) { newPoint.state = Constants.pointStates.NEXT; } this.game.data.points.push(newPoint); var pointSprite = new PointView(this.game, newPoint, this.game.data.points, this.removePoint, this); this.mapView.addPointView(pointSprite); this.updatePreviewText(); } }, removePoint: function(pointView) { var indexToRemove = this.game.data.points.indexOf(pointView.pointData); this.game.data.points.splice(indexToRemove, 1); this.mapView.updatePointViews(); this.updatePreviewText(); pointView.kill(); }, addStartPoint: function(sprite, pointer) { if (sprite.withinBounds(pointer)) { this.game.data.startPoint.x = this.scaleUp(pointer.x - this.mapView.x); this.game.data.startPoint.y = this.scaleUp(pointer.y - this.mapView.y); this.mapView.updateStartPoint(); this.updatePreviewText(); } }, addEndPoint: function(sprite, pointer) { if (sprite.withinBounds(pointer)) { this.game.data.endPoint.x = this.scaleUp(pointer.x - this.mapView.x); this.game.data.endPoint.y = this.scaleUp(pointer.y - this.mapView.y); this.mapView.updateEndPoint(); this.updatePreviewText(); } }, updatePreviewText: function() { var textArea = window.document.getElementById('outputJSON'); textArea.value = JSON.stringify(this.game.data, null, 2); }, //Scales up point related numbers from the 0.75 scale of the displayed game area //to the correct game area size used in the game scaleUp: function(number) { var scaleCorrectedNumber = (number / 3) * 4; return Math.floor(scaleCorrectedNumber); }, moveToNextState: function() { this.game.state.start('phase2'); } }; module.exports = Editor;
JavaScript
0
@@ -629,74 +629,8 @@ %7D,%0A - shutdown: function() %7B%0A this.fileInputHandler.remove();%0A %7D,%0A ad
e25ae990be0aa3650fd0a3282334c7a6cbbe3a37
use new-date, to fix incorrect date in firefox
lib/facade.js
lib/facade.js
var clone = require('./utils').clone; var isEnabled = require('./is-enabled'); var objCase = require('obj-case'); var traverse = require('isodate-traverse'); /** * Expose `Facade`. */ module.exports = Facade; /** * Initialize a new `Facade` with an `obj` of arguments. * * @param {Object} obj */ function Facade (obj) { if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date(); else obj.timestamp = new Date(obj.timestamp); this.obj = obj; } /** * Return a proxy function for a `field` that will attempt to first use methods, * and fallback to accessing the underlying object directly. You can specify * deeply nested fields too like: * * this.proxy('options.Librato'); * * @param {String} field */ Facade.prototype.proxy = function (field) { var fields = field.split('.'); field = fields.shift(); // Call a function at the beginning to take advantage of facaded fields var obj = this[field] || this.field(field); if (!obj) return obj; if (typeof obj === 'function') obj = obj.call(this) || {}; if (fields.length === 0) return transform(obj); obj = objCase(obj, fields.join('.')); return transform(obj); }; /** * Directly access a specific `field` from the underlying object, returning a * clone so outsiders don't mess with stuff. * * @param {String} field * @return {Mixed} */ Facade.prototype.field = function (field) { var obj = this.obj[field]; return transform(obj); }; /** * Utility method to always proxy a particular `field`. You can specify deeply * nested fields too like: * * Facade.proxy('options.Librato'); * * @param {String} field * @return {Function} */ Facade.proxy = function (field) { return function () { return this.proxy(field); }; }; /** * Utility method to directly access a `field`. * * @param {String} field * @return {Function} */ Facade.field = function (field) { return function () { return this.field(field); }; }; /** * Get the basic json object of this facade. * * @return {Object} */ Facade.prototype.json = function () { var ret = clone(this.obj); if (this.type) ret.type = this.type(); return ret; }; /** * Get the options of a call (formerly called "context"). If you pass an * integration name, it will get the options for that specific integration, or * undefined if the integration is not enabled. * * @param {String} integration (optional) * @return {Object or Null} */ Facade.prototype.context = Facade.prototype.options = function (integration) { var options = clone(this.obj.options || this.obj.context) || {}; if (!integration) return clone(options); if (!this.enabled(integration)) return; var integrations = this.integrations(); var value = integrations[integration] || objCase(integrations, integration); if ('boolean' == typeof value) value = {}; return value || {}; }; /** * Check whether an integration is enabled. * * @param {String} integration * @return {Boolean} */ Facade.prototype.enabled = function (integration) { var allEnabled = this.proxy('options.providers.all'); if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('options.all'); if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('integrations.all'); if (typeof allEnabled !== 'boolean') allEnabled = true; var enabled = allEnabled && isEnabled(integration); var options = this.integrations(); // If the integration is explicitly enabled or disabled, use that // First, check options.providers for backwards compatibility if (options.providers && options.providers.hasOwnProperty(integration)) { enabled = options.providers[integration]; } // Next, check for the integration's existence in 'options' to enable it. // If the settings are a boolean, use that, otherwise it should be enabled. if (options.hasOwnProperty(integration)) { var settings = options[integration]; if (typeof settings === 'boolean') { enabled = settings; } else { enabled = true; } } return enabled ? true : false; }; /** * Get all `integration` options. * * @param {String} integration * @return {Object} * @api private */ Facade.prototype.integrations = function(){ return this.obj.integrations || this.proxy('options.providers') || this.options(); }; /** * Check whether the user is active. * * @return {Boolean} */ Facade.prototype.active = function () { var active = this.proxy('options.active'); if (active === null || active === undefined) active = true; return active; }; /** * Get `sessionId / anonymousId`. * * @return {Mixed} * @api public */ Facade.prototype.sessionId = Facade.prototype.anonymousId = function(){ return this.field('anonymousId') || this.field('sessionId'); }; /** * Get `groupId` from `context.groupId`. * * @return {String} * @api public */ Facade.prototype.groupId = Facade.proxy('options.groupId'); /** * Get the call's "super properties" which are just traits that have been * passed in as if from an identify call. * * @param {Object} aliases * @return {Object} */ Facade.prototype.traits = function (aliases) { var ret = this.proxy('options.traits') || {}; var id = this.userId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('options.traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Add a convenient way to get the library name and version */ Facade.prototype.library = function(){ var library = this.proxy('options.library'); if (!library) return { name: 'unknown', version: null }; if (typeof library === 'string') return { name: library, version: null }; return library; }; /** * Setup some basic proxies. */ Facade.prototype.userId = Facade.field('userId'); Facade.prototype.channel = Facade.field('channel'); Facade.prototype.timestamp = Facade.field('timestamp'); Facade.prototype.userAgent = Facade.proxy('options.userAgent'); Facade.prototype.ip = Facade.proxy('options.ip'); /** * Return the cloned and traversed object * * @param {Mixed} obj * @return {Mixed} */ function transform(obj){ var cloned = clone(obj); traverse(cloned); return cloned; }
JavaScript
0.000006
@@ -151,16 +151,51 @@ verse'); +%0Avar newDate = require('new-date'); %0A%0A/**%0A * @@ -449,25 +449,24 @@ estamp = new - Date(obj.tim
00b916c49f1f4b1704d087f0ad3bf8c689aae1d1
Update install script to check man path using the new mechanism
scripts/install-docs.js
scripts/install-docs.js
// a helper install script to install the documentation along with the program // this runs whenever npm is activated or deactivated, so that the docs always // reflect the current command. var event = process.env.npm_lifecycle_event , exec = require("../lib/utils/exec") , log = require("../lib/utils/log") , fs = require("fs") , path = require("path") , rm = require("../lib/utils/rm-rf") , mkdir = require("../lib/utils/mkdir-p") , manTarget = path.join(process.installPrefix, "share/man/man1") , exec = require("../lib/utils/exec") log(event, "docs") function dontPanic (er) { log(er, "doc install failed") log("probably still ok otherwise, though", "don't panic") } exec("manpath", [], function (er, code, stdout, stderr) { var manpath = er ? [] : stdout.trim().split(":") if (manpath.indexOf(path.dirname(manTarget)) === -1) { log("It seems " + manTarget + " might not be visible to man", "!") log("For greater justice, please add it to your man path", "!") log("See: man man", "!") } mkdir(manTarget, function (er) { if (er) dontPanic(er) else installDocs() }) }) function installDocs () { fs.readdir(path.join(process.cwd(), "man"), function (er, docs) { log(path.join(process.cwd(), "man"), "docs") log(manTarget, "docs") if (er) return ;(function R (doc) { if (!doc) return log("done", "docs") if (doc === "." || doc === "..") return R(docs.pop()) var target = path.join(manTarget, "npm-"+doc) target = target.replace(/npm-npm\.1$/, "npm.1") switch (event) { case "activate": rm( target , function () { fs.symlink ( path.join(process.cwd(), "man", doc) , target , function (er, ok) { if (er) dontPanic(er) else R(docs.pop()) } ) } ) break case "deactivate": rm( target, function (er) { R(docs.pop()) }) break default: throw new Error("invalid state"); break } })(docs.pop()) }) }
JavaScript
0
@@ -708,16 +708,28 @@ th%22, %5B%5D, + null, true, functio
f1009212cfb269ab51c9da235195e92023aa7916
Update script for polling
www/assets/javascript/script.js
www/assets/javascript/script.js
Walrus.init({ ajaxNavigation: true, lazyLoad: true }); $('#post').click(function () { $('#post-pop').toggleClass('expand'); }); $('#post-pop form').submit(function (e) { $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), success: function () { $('#post-pop').toggleClass('expand'); var node = $('#userBar').find('.infos .stat:first .value'); node[0].innerHTML = parseInt(node[0].innerHTML) + 1; } }); e.preventDefault(); e.stopPropagation(); return false; }); Walrus.pollingRegister('posts', function (data) { console.log(data); }); Walrus.polling('api/polling/run');
JavaScript
0
@@ -543,61 +543,8 @@ %7D);%0D -%0A%0D%0A e.preventDefault();%0D%0A e.stopPropagation();%0D %0A @@ -625,25 +625,173 @@ -console.log(data) +var tpl = '', item;%0D%0A for (item in data) %7B%0D%0A tpl += Walrus.compile(document.getElementById('templating-msg').innerHTML, data%5Bitem%5D);%0D%0A %7D%0D%0A return tpl ;%0D%0A%7D @@ -828,8 +828,10 @@ g/run'); +%0D%0A
899c323a6db0cde8f464bcf4aee0acf147e6b929
Add fallback mechanism in case there's no valid input field
public/ajax.sjs
public/ajax.sjs
const Cc = Components.classes; const CC = Components.Constructor; const Ci = Components.interfaces; const Cu = Components.utils; Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); const { SystemAppProxy } = Cu.import("resource://gre/modules/SystemAppProxy.jsm"); const DEBUG = true; function debug (message) { if (DEBUG) { dump(message + '\n'); } } function handleClickEvent (event) { let type = 'navigator:browser'; let shell = Services.wm.getMostRecentWindow(type); let document = shell.document; let systemApp = document.getElementsByTagName("HTML:IFRAME")[0]; var domWindowUtils = shell.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindowUtils); var x = isNaN(getState("x")) ? shell.innerWidth/2 : parseInt(getState("x")); var y = isNaN(getState("y")) ? shell.innerHeight/2 : parseInt(getState("y")); ["mousedown", "mouseup"].forEach(function(mouseType) { domWindowUtils.sendMouseEvent ( mouseType, x, y, 0, 0, 0, true ); }); } function handleTouchEvent (event) { let type = 'navigator:browser'; let shell = Services.wm.getMostRecentWindow(type); let document = shell.document; let systemApp = document.getElementsByTagName("HTML:IFRAME")[0]; var domWindowUtils = shell.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindowUtils); var x = isNaN(getState("x")) ? shell.innerWidth/2 : parseInt(getState("x")); var y = isNaN(getState("y")) ? shell.innerHeight/2 : parseInt(getState("y")); var startX = 0; var startY = 0; let etype; switch (event.type) { case "touchstart": etype = "mousedown"; startX = x; startY = y; setState("startX", startX.toString()); setState("startY", startY.toString()); break; case "touchmove": etype = "mousemove"; startX = parseInt(getState("startX")); startY = parseInt(getState("startY")); break; case "touchend": etype = "mouseup"; startX = parseInt(getState("startX")); startY = parseInt(getState("startY")); break; default: return; } let detail = event.detail; x = startX + detail.dx; y = startY + detail.dy; setState ("x", x.toString()); setState ("y", y.toString()); domWindowUtils.sendMouseEvent ( etype, x, y, 0, 0, 0, true ); // Use SystemAppProxy send SystemAppProxy._sendCustomEvent('remote-control-event', { x: x, y: y }); } function handleKeyboardEvent (keyCodeName) { debug('key: ' + keyCodeName); const nsIDOMKeyEvent = Ci.nsIDOMKeyEvent; let type = "navigator:browser"; let shell = Services.wm.getMostRecentWindow(type); var utils = shell.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIDOMWindowUtils); ["keydown", "keyup"].forEach(function(keyType) { var keyCode = nsIDOMKeyEvent[keyCodeName]; var modifiers = 0; var happened = utils.sendKeyEvent(keyType, keyCode, 0, modifiers); }); } function handleInputEvent (detail) { debug('input: ' + JSON.stringify(detail)); let sysApp = SystemAppProxy.getFrame().contentWindow; let mozIM = sysApp.navigator.mozInputMethod; mozIM.setActive(true); mozIM.addEventListener('inputcontextchange', function icchangehandler() { mozIM.removeEventListener('inputcontextchange', icchangehandler); let inputcontext = mozIM.inputcontext; if (inputcontext) { debug(inputcontext.textAfterCursor); if (detail.string) { lengthBeforeCursor = inputcontext.textBeforeCursor.length; lengthAfterCursor = inputcontext.textAfterCursor.length; inputcontext.replaceSurroundingText( detail.string, -1 * lengthBeforeCursor, lengthBeforeCursor + lengthAfterCursor ); } else if (detail.keycode) { inputcontext.sendKey(detail.keycode); } } else { debug('ERROR: No inputcontext!'); } mozIM.setActive(false); }); } function handleRequest(request, response) { var queryString = decodeURIComponent(request.queryString.replace(/\+/g, "%20")); response.setHeader("Content-Type", "text/html", false); response.write(queryString); // Split JSON header "message=" var event = JSON.parse(queryString.substring(8)); switch (event.type) { case "echo": debug(event.detail); break; case "keypress": handleKeyboardEvent(event.detail); break; case "touchstart": case "touchmove": case "touchend": handleTouchEvent (event); break; case "click": handleClickEvent (event); break; case "input": handleInputEvent(event.detail); break; } }
JavaScript
0.000029
@@ -3392,80 +3392,40 @@ od;%0A -%0A -mozIM.setActive(true);%0A mozIM.addEventListener('inputcontextchange', +let icChangeTimeout = null;%0A%0A fun @@ -3432,23 +3432,23 @@ ction ic -c +C hange -h +H andler() @@ -3508,23 +3508,130 @@ , ic -c +C hange -handler); +Handler);%0A if (icChangeTimeout) %7B%0A sysApp.clearTimeout(icChangeTimeout);%0A icChangeTimeout = null;%0A %7D %0A%0A @@ -3699,52 +3699,8 @@ ) %7B%0A - debug(inputcontext.textAfterCursor);%0A%0A @@ -4195,24 +4195,175 @@ (false);%0A %7D +%0A%0A mozIM.setActive(true);%0A mozIM.addEventListener('inputcontextchange', icChangeHandler);%0A icChangeTimeout = sysApp.setTimeout(icChangeHandler, 1000 );%0A%7D%0A%0Afuncti
b26650143136122bdf360587da1e5758cce765aa
Add getDataFromStorage() function to retrieve data from storage.
public/index.js
public/index.js
(function ($) { "use strict"; addAnswersToSessionStorage(); $('.carousel').carousel({ indicators: true, shift: 100 }); [ "send-email-button" ].forEach(function(button){ var node = document.getElementsByClassName(button)[0]; if (node){ node.addEventListener('click', function(){ sendMail() }); } }); function addAnswersToSessionStorage(){ var personality = []; var hobbies = []; [ "strange", "happy", "angry", "fun", "boring", "kind", "sad" ].forEach(function(emotion){ var node = document.getElementById(emotion); addClassToNode(node, 'pop'); addClickEventArray('personality', node, emotion, personality); }); [ "sad-emoji", "happy-emoji", "indifferent-emoji" ].forEach(function(emoji){ var node = document.getElementsByClassName(emoji)[0]; addClickEventSingle('feelings', node, emoji.match(/^[a-z]+/)); }); [ "name", "age" ].forEach(function(inputField){ var node = document.getElementsByClassName(inputField)[0]; addKeyupEvent(inputField, node); }); [ "football", "tennis", "gymnastics", "dance", "drawing", "photography", "cooking", "gardening", "puzzles", "camping", "fishing", "walking", "gymnastics-mobile", "photography-mobile", "walking-mobile", "puzzles-mobile" ].forEach(function(hobby){ var node = document.getElementsByClassName(hobby)[0]; addClassToNode(node, 'js-chosen'); addClickEventArray('hobbies', node, hobby, hobbies); }); [ "sleep__range", "friends__range", "school__range" ].forEach(function(range){ var node = document.getElementsByClassName(range)[0]; if (node) { if (range === "sleep__range") { addOnInputToElement( node, sleepingLion ); } else { addOnInputToElement( node, emojiSprite ); } } }); }); function addKeyupEvent(key, element){ if(!element){ return; } element.addEventListener("keyup", function(){ addSingleValueToStorage(key, element.value); }); } function addClickEventSingle(key, element, value){ if(!element){ return; } element.addEventListener("click", function(){ addSingleValueToStorage(key, value); }); } function addClickEventArray(key, element, value, array){ if(!element){ return; } element.addEventListener("click", function(){ addValueToArray(key, value, array); }); } function addValueToArray(key, value, array){ array.push(value); addArrayToStorage(key, array); } function addSingleValueToStorage(key, value){ sessionStorage.setItem(key, value); } // JSON.stringify() is used here as session storage only supports strings function addArrayToStorage(key, array){ sessionStorage.setItem(key, JSON.stringify(array)); } } // Adds a class to node function addClassToNode(node, className){ if (!node){ return; } node.addEventListener("click", function(){ node.classList.add(className); }); } function addOnInputToElement(element, func){ element.oninput = function(){ func() } } function sleepingLion(){ var value = document.getElementsByClassName("sleep__range")[0].value; var element = document.getElementsByClassName("sleep__sleeping-lion")[0]; changeBackgroundPosition(element, value, -332) } function changeBackgroundPosition(element, value, illustrationSize){ element.style.backgroundPosition = parseInt(value) * illustrationSize + "px"; } function emojiSprite(){ var value = document.getElementsByClassName("range")[0].value; var element = document.getElementsByClassName("friends__emoji-sprite")[0]; changeBackgroundPosition(element, value, -180) } function emailValidator(emailAddress){ var regex = RegExp( '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".' + '+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-z' + 'A-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$' ) return regex.test(emailAddress); } function sendMail(){ var emailRecipient = document.getElementsByClassName("finish__email-input")[0]; if (!emailValidator(emailRecipient.value)){ emailRecipient.value = 'Please enter a valid email address.' return; } var emailAddress = emailRecipient.value; var http = new XMLHttpRequest(); http.open("POST", '/finished', true); http.send(emailAddress); } })(jQuery);
JavaScript
0
@@ -2049,23 +2049,8 @@ %7D);%0A - %0A %7D);%0A %0A @@ -4263,32 +4263,193 @@ lAddress);%0A %7D%0A%0A + function getDataFromStorage()%7B%0A var data = %7B%7D;%0A for (var key in sessionStorage)%7B%0A data%5Bkey%5D = sessionStorage%5Bkey%5D%0A %7D%0A console.log(data);%0A %7D%0A%0A function sendM @@ -4823,24 +4823,49 @@ ilAddress);%0A + getDataFromStorage()%0A %7D%0A%7D)(jQuer
b5d30ae1311a1064953b24c3e57b7d5f2b6882df
Test improvements
test/indexes.js
test/indexes.js
var _ = require('lodash'); var expect = require('chai').expect; var monoxide = require('..'); var testSetup = require('./setup'); describe('monoxide indexes', function() { before(testSetup.init); after(testSetup.teardown); var userIndexes; before('get user indexes', function(finish) { monoxide.models.users.getIndexes(function(err, res) { if (err) return finish(err); userIndexes = res; finish(); }); }); it('should retrieve the indexes of a Mongo model', function(finish) { monoxide.models.users.getIndexes(function(err, res) { if (err) return finish(err); expect(res).to.be.an('array'); expect(res).to.have.length(1); expect(res[0]).to.have.property('name', '_id_'); expect(res[0]).to.have.property('ns'); expect(res[0].ns).to.match(/\.users$/); finish(); }); }); it('should retrieve the ideal indexes of a declared schema', function(finish) { monoxide.models.users.getSchemaIndexes(function(err, res) { if (err) return finish(err); expect(res).to.be.an('array'); expect(res).to.have.length(1); expect(res[0]).to.have.property('name', '_id_'); finish(); }); }); it('should check the status of indexes when given an omitted index', function(finish) { monoxide.models.users.checkIndexes([ // Glue a fake index to the list we are checking against {key: {role: 1}, name: 'role', ns: userIndexes[0].ns.replace('_id', 'role')}, ...userIndexes ], function(err, res) { if (err) return finish(err); res = _.sortBy(res, 'name'); expect(res[0]).to.have.property('name', '_id_'); expect(res[0]).to.have.property('status', 'ok'); expect(res[1]).to.have.property('name', 'role'); expect(res[1]).to.have.property('status', 'missing'); finish(); }); }); });
JavaScript
0.000001
@@ -635,33 +635,33 @@ .to.have.length( -1 +2 );%0A%09%09%09expect(res @@ -1048,17 +1048,17 @@ .length( -1 +2 );%0A%09%09%09ex @@ -1121,32 +1121,381 @@ ();%0A%09%09%7D);%0A%09%7D);%0A%0A +%09it('should create multi-field indexes', function(finish) %7B%0A%09%09this.timeout(10 * 1000);%0A%0A%09%09monoxide.models.widgets.index(%5B'status', 'color'%5D, function(err) %7B%0A%09%09%09if (err) return finish(err);%0A%0A%09%09%09monoxide.models.widgets.checkIndexes(%5B%7Bkey: %7Bstatus: 1, color: 1%7D%7D%5D, function(err, res) %7B%0A%09%09%09%09if (err) return finish(err);%0A%09%09%09%09finish();%0A%09%09%09%7D);%0A%09%09%7D);%0A%09%7D);%0A%0A %09it('should chec @@ -2060,15 +2060,10 @@ ', ' -missing +ok ');%0A
d106b26d51dda4362f7e072e3982bd84069b9e4b
Fix distancemodel parameter case
scripts/remoteplayer.js
scripts/remoteplayer.js
elation.require(['janusweb.janusghost', 'engine.things.maskgenerator', 'engine.things.sound', 'janusweb.external.JanusVOIP'], function() { elation.component.add('engine.things.remoteplayer', function() { this.postinit = function() { elation.engine.things.remoteplayer.extendclass.postinit.call(this); this.defineProperties({ startposition: {type: 'vector3', default: new THREE.Vector3()}, pickable: {type: 'boolean', default: false}, collidable: {type: 'boolean', default: false}, player_id: {type: 'string', default: 'UnknownPlayer'}, player_name: {type: 'string', default: 'UnknownPlayer'}, }); this.properties.ghost_id = this.properties.player_name; }; /* this.createObject3D = function() { var geo = new THREE.CylinderGeometry(1, 1, 4, 8), mat = new THREE.MeshPhongMaterial({ color: 0x000000, transparent: true, opacity: 0.7 }), mesh = new THREE.Mesh(geo, mat); return mesh; }; */ this.createChildren = function() { elation.engine.things.remoteplayer.extendclass.createChildren.call(this); this.torso = this.spawn('janusbase', this.properties.player_name + '_torso', { 'position': [0,1,0], 'parent': this, 'janus': this.janus, 'room': this.room }); this.shoulders = this.torso.spawn('janusbase', this.properties.player_id + '_shoulders', { 'position': [0,0.6,-0.0], 'parent': this, 'janus': this.janus, 'room': this.room }); this.neck = this.torso.spawn('janusbase', this.properties.player_name + '_neck', { 'position': [0,0.4,0], 'parent': this, 'janus': this.janus, 'room': this.room }); this.head = this.spawn('janusbase', this.properties.player_name + '_head', { 'position': [0,1.4,0], 'parent': this, 'janus': this.janus, 'room': this.room }); /* this.face = this.head.spawn('maskgenerator', this.properties.player_name + '_mask', { 'seed': this.properties.player_name, 'position': [0,0,-0.025], collidable: false, 'tilesize': 0.05, 'player_id': this.properties.player_name, pickable: false, collidable: false }); */ /* this.label = this.createObject('text', { size: .1, thickness: .002, align: 'center', collidable: false, text: this.player_name, position: [0,2,0], orientation: [0,1,0,0], pickable: false, collidable: false, billboard: 'y' }); */ } }; this.speak = function(noise) { this.voip.speak(noise); if (!this.mouth.audio.playing) { this.mouth.audio.play(); } this.label.material.color.setHex(0x00ff00); if (this.talktimer) { clearTimeout(this.talktimer); } this.talktimer = setTimeout(elation.bind(this, this.shutup), this.bufferlength * 500); } this.shutup = function() { this.voip.silence(); /* if (this.mouth.audio.playing) { this.mouth.audio.stop(); } var bufferLeft = this.rawbuffer.getChannelData(0); var bufferRight = this.rawbuffer.getChannelData(1); for (var i = 0; i < bufferLeft.length; i++) { bufferLeft[i] = bufferRight[i] = 0; } this.bufferoffset = 0; */ this.label.material.color.setHex(0xcccccc); } this.handleVoipData = function(ev) { //this.mouth.audio.source.loopEnd = ev.data.end; if (!this.mouth.audio.isPlaying) { //this.mouth.audio.play(ev.data.start, ev.data.end); } else { //console.log('already playing'); } } this.addVoice = async function(stream) { this.mouth = this.createObject('sound', { pos: V(0, 0, 0), distanceModel: 'exponential', dist: 8, rolloff: 0.75, }); this.head.add(this.mouth._target); if (this.engine.systems.sound.canPlaySound) { this.createVoiceAudio(stream); } else { elation.events.add(this.engine.systems.sound, 'sound_enabled', async (ev) => { this.createVoiceAudio(stream); }); } } this.createVoiceAudio = async function(stream) { let listener = this.engine.systems.sound.getRealListener(); await this.mouth.createAudio(null, {listener}); let panner = this.mouth.audio.panner, context = panner.context, source = context.createMediaStreamSource(stream); source.connect(panner); this.audionodes = { listener, panner, context, source }; this.mouth.audio.play(); } this.setVolume = async function(volume) { if (this.mouth) { if (!this.mouth.audio) { await this.mout.createAudio(null, listener); } this.mouth.audio.gain.gain.value = volume; } } }, elation.engine.things.janusghost); });
JavaScript
0.000001
@@ -3651,17 +3651,17 @@ distance -M +m odel: 'e
3416f1b77f623e0823f695750545874377d8d5a3
did this
mandrill.js
mandrill.js
var mandrill= (function(){ // Currently accepted verification types and their associated regex + error var types = { "email": { "error": "Please enter valid email", "regex":/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/ }, "required": { "error":"This field is required", "regex":/\S/ }, "min": { "error": "Too short. Minimum length of ", "regex":/^min\:\s*(\d*)/i }, "max": { "error": "Too Long. Maximum length of ", "regex":/^max\:\s*(\d*)/i }, "number": { "error": "Not a number value", "regex":/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/ }, "integer": { "error": "not an integer value", "regex":/^-?\d+$/ }, "digits": { "error": "not a digit value", "regex":/^\d+$/ }, "url": { "error": "Invalid URL", "regex":/^https?:\/\/[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|]/ }, "alphanumeric": { "error": "Only use numbers and letters", "regex":/^[0-9A-Za-z]+$/ } }; var variable_types = ["min", "max"]; var exist = "ERROR: Verification type does not exist: " return { /***************************************************************************************** * FLOW Called by verify_attribute and check_types. Used to return type of variability param * INPUT Attribute to be checked for variability param. * RETURNS returns the type of veriability param or "undefined" * @example Given "max: 25", this function will return "max" as the type ****************************************************************************************/ verify_variable_attribute: function(attribute){ var type = undefined; if(attribute.match(/min/i)){ type = "min"; }else if(attribute.match(/max/i)){ type = "max"; } return type; }, /***************************************************************************************** * FLOW Called by verify_field for basic error checking. Length and existance of attribute * INPUT Attributes to be verified. Checks for existance and non-empty SEE ABOVE IN TYPES * RETURNS returns either "true" or "false" depending on verification ****************************************************************************************/ verify_attributes: function(attributes){ // Check if attributes exist when calling if(attributes.length === 0){ console.log("Error: No attributes assigned to 'data-verify'"); return false; } for(i = 0; i < attributes.length; ++i){ var type = attributes[i].trim(); // TODO: replace with a variable loop if(mandrill.verify_variable_attribute(type) == undefined && types[type] == undefined){ console.log(exist + type); return false } } return true; }, /***************************************************************************************** * FLOW Called by verify_fields to check the regex of accepted verification types * INPUT Input to be verified, and the type of verification object. SEE ABOVE IN TYPES * RETURNS returns either "true" or a error message * NOTES This is the bulk of the functionality in this switch. Most generic error handling * and data prep is done outside this function however ****************************************************************************************/ check_types: function(verify_input, type){ var temp_type = mandrill.verify_variable_attribute(type); var variable_type = undefined; if (temp_type != undefined){ variable_type = type; type = temp_type; } switch(type){ case "max": var status = true; var max = parseInt(types[type]["regex"].exec(variable_type)[1]); var length = verify_input.length; if(isNaN(max)== true){ console.log("Invalid max value, NaN: " + temp_type) }else if(length > max){ status = types[type]["error"] + max; } return status; case "min": var status = true; var min = parseInt(types[type]["regex"].exec(variable_type)[1]); var length = verify_input.length; if(isNaN(min)== true){ console.log("Invalid max value, NaN: " + temp_type) }else if(length < min){ status = types[type]["error"] + min; } return status; default: var status = types[type]["regex"].test(verify_input); if(status === false){status = types[type]["error"];} return status; } }, /***************************************************************************************** * FLOW Called by verify_field for basic error checking. Length and existance of attribute * INPUT Attributes to be verified. Checks for existance and non-empty SEE ABOVE IN TYPES * RETURNS returns either "true" or "false" depending on verification ****************************************************************************************/ verify_field: function(input){ var verify_object = $(input); var verify_input = verify_object.val(); var verification_type = verify_object.data('verify'); var attributes = verification_type.split(','); // Check base cases and return false if invalid if(mandrill.verify_attributes(attributes) === false){ return false; } // For every attribute in data-verify do associated verification for(i = 0; i < attributes.length; ++i){ type = attributes[i].trim(); var verify_status = mandrill.check_types(verify_input, type) if(verify_status != true){ return verify_status; } } return true; }, /***************************************************************************************** * FLOW Called by the verify or single_verify to handle and display errors * INPUT The element and status to display in case of error * RETURNS true if verified or false if error displayed ****************************************************************************************/ error_check: function(element, status){ if(status != true){ $(element).notify(status); return false; } return true; }, /***************************************************************************************** * FLOW Called by the entry point function verify_set or single_verify * INPUT The element to be verified * RETURNS true or error status * NOTE This function is the root of most work, it calls children to error check then * verify the content of the fields ****************************************************************************************/ verify: function(parent, callback){ var verified = true; var verification_status = ""; var last_element = undefined; // look at each child of the parent element passed in parent.find('[data-verify]').each(function() { last_element = this; // Call verification on each element verification_status = mandrill.verify_field(this); // If an error is returned, set verified to false and halt each function if(verification_status != mandrill.error_check(this, verification_status)){ verified = false; } }); // Successful verification process results in callback called if(verified === true){ // Check callback and apply arbitrary amount of arguments if(typeof callback === 'function'){ callback.apply(arguments); } return true; // Failed verification process results in first error being displayed }else{ // TODO: do notify of error console.log(verification_status); return false; } }, /***************************************************************************************** * TAG ENTRY POINT * FLOW Entry point into mandrill.js on a single element * INPUT Element to be verified. SEE ABOVE IN TYPES * RETURNS returns either "true" or "false" depending on verification and handles notifyjs ****************************************************************************************/ single_verify: function(element){ var status = mandrill.verify_field(element); return mandrill.error_check(element, status); } } })();
JavaScript
0.96984
@@ -3752,62 +3752,8 @@ m(); -%0A // TODO: replace with a variable loop %0A%0A
e37ed1f88f1959b85538ccdd675d3d28bb24062f
Undo cancel function name change.
src/angular-external-link-interceptor.js
src/angular-external-link-interceptor.js
(function (angular) { 'use strict'; var module = angular.module('externalLinkInterceptor', [ 'ngRoute', 'ui.bootstrap.modal' ]); module.config([ '$routeProvider', function ($routeProvider) { $routeProvider .when('/external-link/', { templateUrl: 'templates/external_link/page.html', controller: 'ExternalLinkCtrl' }); } ]); module.run([ '$templateCache', function ($templateCache) { $templateCache.put('templates/external_link/message.html', '<p>You are now leaving this website.</p>' + '<div>' + '<a ng-href="{{ externalUrl }}" target="{{ target }}" allow-external="true" ng-click="dismissModal()">Continue</a>' + '<span ng-click="dismissModal()">Cancel</span>' + '</div>' ); $templateCache.put('templates/external_link/page.html', '<div ng-include src="\'templates/external_link/page.html\'"></div>' ); } ]); module.controller('ExternalLinkCtrl', [ '$scope', '$location', function ($scope, $location) { $scope.externalUrl = $location.$$search.next; $scope.cancel = function () { if ($location.$$search.prev) { $location.url($location.$$search.prev); } else { $location.url('/'); } }; } ]); module.service('ExternalLinkService', [ '$filter', '$location', '$uibModal', function ($filter, $location, $uibModal) { var ExternalLinkService = { externalLinkRE: new RegExp(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/), // External url testing function from http://stackoverflow.com/a/6238456 isExternal: function (url) { var match = url.match(ExternalLinkService.externalLinkRE); if (typeof match[1] === 'string' && match[1].length > 0) { if (match[1] === 'mailto:' || match[1] === 'tel:') { return false; } if (match[1].toLowerCase() !== location.protocol) { return true; } } if (typeof match[2] === 'string' && match[2].length > 0 && match[2].replace(new RegExp(':(' + { 'http:': 80, 'https:': 443 }[location.protocol] + ')?$'), '') !== location.host) { return true; } return false; }, externalModal: function (e, href) { e.preventDefault(); // Because the model is opened later the currentTarget mey get set to null. var currentTarget = e.currentTarget; // Open a bootstrap-ui modal. $uibModal.open({ templateUrl: 'templates/external_link/message.html', resolve: { externalUrl: function () { return href; } }, controller: [ '$scope', '$uibModalInstance', 'externalUrl', function ($scope, $uibModalInstance, externalUrl) { $scope.externalUrl = externalUrl; $scope.dismissModal = function () { $uibModalInstance.dismiss('cancel'); }; // Pass through target attribute, so links that // should open in a new window can. var element = angular.element(currentTarget); $scope.target = element.attr('target'); } ] }); }, bindModal: function (element, newValue, previousClickFunction) { // The click event may have been bound based on a // previous href value. element.off('click', previousClickFunction); var clickFunction = function (e) { ExternalLinkService.externalModal(e, newValue); }; if (newValue) { // If the link is external. if (ExternalLinkService.isExternal(newValue)) { // Rewrite the url to go to the external link route. // Adds a `next` parameter containing the external link and // a `prev` parameter containing the current path, so that // we can navigate back to where the user came from. element.attr('href', $filter('reverseUrl')('ExternalLinkCtrl') + '?next=' + encodeURI(newValue) + '&prev=' + encodeURI($location.path())); element.on('click', clickFunction); } } return clickFunction; } }; return ExternalLinkService; } ]); module.directive('a', [ 'ExternalLinkService', function (ExternalLinkService) { return { restrict: 'E', link: function (scope, element, attrs) { var clickHandler; // If the link does not have an attribute to allow it to by-pass the warning. if (!attrs.allowExternal) { attrs.$observe('href', function (newValue) { clickHandler = ExternalLinkService.bindModal(element, newValue, clickHandler); }); } } }; } ]); }(window.angular));
JavaScript
0
@@ -800,34 +800,8 @@ rue%22 - ng-click=%22dismissModal()%22 %3ECon @@ -850,27 +850,21 @@ -click=%22 -dismissModa +cance l()%22%3ECan @@ -3677,19 +3677,13 @@ ope. -dismissModa +cance l =
729ee3f83fb1746cd9de18554856f39cb96c0ea4
Optimise layer toggling, don't recalculate site pins if not necessary
www/js/adapters/SitesAdapter.js
www/js/adapters/SitesAdapter.js
define(['views/SitesView'], function (SitesView) { /** * @param {number} price * @returns {string} */ function formatPrice(price) { return "£"+price.toFixed(2); } /** * @param {string} url * @param {string} text * @returns {string} */ function createLink(url, text) { return "<a href=\"http://brewmook.wordpress.com" + url + "\">" + text + "</a>"; } /** * @param {Site} site * @returns {string} */ function bubbleHtml(site) { var pub = site.history[0]; var text = "<b>" + pub.name + "</b>"; if (pub.visits.length > 0) { var visit = pub.visits[0]; if (visit.link) text = createLink(visit.link, text); if (visit.comment) text += "<br/><em>" + visit.comment + "</em>"; if (visit.price > 0) text += "<br/>Price: " + formatPrice(visit.price); } if (site.history.length > 1) { var previous = []; var link; for (var i = 1; i < site.history.length; ++i) { link = site.history[i].visits.length ? site.history[i].visits[0].link : ''; previous.push(createLink(link, site.history[i].name)); } text += "<br/>Previously known as " + previous.join(', ') + "."; } if (pub.tags.length > 0) { text += "<br/>Tags: " + pub.tags.join(', '); } return text; } /** * @param {Site} site * @return {SitesView.Site} */ function createViewSite(site) { return new SitesView.Site( site.history[0].name, site.lat, site.lon, bubbleHtml(site) ); } /** * @param {SitesModel} sitesModel * @param {SitesView} view * @param {Grouper} grouper * @constructor */ function SitesAdapter(sitesModel, view, grouper) { view.visibleGroups.subscribe(function(groupLabels) { var groups = groupLabels.map(function(label) { var x = label.indexOf(' ('); return label.substring(0, x); }); sitesModel.setVisibleGroups(groups); }); sitesModel.sites.subscribe(function(sites) { var groups = grouper.groupSites(sites); view.groups.forEach(function(viewGroup) { var group = groups.filter(function(g) { return viewGroup.label.indexOf(g.label) == 0; })[0]; viewGroup.setSites(group.sites.map(createViewSite)); }); }); } return SitesAdapter; });
JavaScript
0
@@ -1978,32 +1978,78 @@ grouper)%0A %7B%0A + var suppressViewGroupUpdate = false;%0A%0A view.vis @@ -2251,32 +2251,76 @@ %7D);%0A + suppressViewGroupUpdate = true;%0A site @@ -2348,24 +2348,69 @@ ps(groups);%0A + suppressViewGroupUpdate = false;%0A %7D);%0A @@ -2459,24 +2459,73 @@ on(sites) %7B%0A + if (suppressViewGroupUpdate) return;%0A
c8c4bef2cfe2ae5b0899992e6a43804554eebd0d
Fix bug in AutoFlattrer
scripts/AutoFlattrer.js
scripts/AutoFlattrer.js
var AutoFlattrer = { thingForCurrentTrack: null, init: function() { EventSystem.addEventListener('video_started_playing_successfully', function(data) { AutoFlattrer.thingForCurrentTrack = false; }); EventSystem.addEventListener('flattr_thing_for_track_found', function(data) { AutoFlattrer.thingForCurrentTrack = data; }); EventSystem.addEventListener('song_almost_done_playing', function(data) { if (has_flattr_access_token && settingsFromServer.flattr_automatically && AutoFlattrer.thingForCurrentTrack) { AutoFlattrer.makeFlattrClick(AutoFlattrer.thingForCurrentTrack); } }); }, makeFlattrClick: function(thingData) { var url; var postParams; if (thingData.thingId) { url = '/flattrclick'; postParams = { videoTitle: thingData.videoTitle, thing_id: thingData.thingId }; } else { url = '/flattrautosubmit'; postParams = { videoTitle: thingData.videoTitle, url: thingData.sourceUrl }; } $.post(url, postParams, function(data) { if (data === null) { console.log("Error: response from Flattr was null"); } else if (data.hasOwnProperty('error_description')) { console.log("Flattr error", data.error_description); } else { EventSystem.callEventListeners('flattr_click_made', data); } }); } };
JavaScript
0
@@ -485,31 +485,73 @@ if ( -has_flattr_access_token +UserManager.currentUser && UserManager.currentUser.flattrUserName &&
d0f84cd599f5e482967129a69827ec7e2c2d2a78
Fix bug in playlist view
scripts/PlaylistView.js
scripts/PlaylistView.js
var PlaylistView = { updatePlaylistBar: function(playlist) { var i = 0, $playlistBar = $('#right > .playlists .info'); $playlistBar.data('model', playlist); $playlistBar.find('.title').text(playlist.title); $playlistBar.find('.owner').hide(); $playlistBar.find('.copy').hide().unbind('click'); $playlistBar.find('.sync').hide().unbind('click'); $playlistBar.find('.subscribe').hide().unbind('click'); if (playlist.owner) { $playlistBar.find('.owner').click(function() { history.pushState(null, null, '/users/' + playlist.owner.id); Menu.deSelectAll(); UserManager.loadProfile(playlist.owner.id); }).text(playlist.owner.displayName).show(); // Add save button if not already saved if (!playlistManager.getPlaylistsMap().hasOwnProperty(playlist.remoteId)) { $playlistBar.find('.copy').show().one('click', PlaylistView.savePlaylistButtonClicked); } /* Show subscription button */ if (Number(playlist.owner.id) !== Number(UserManager.currentUser.id) && logged_in && playlist.isSubscription === false) { for (i = 0; i < playlist.followers.length; i+=1) { if (Number(playlist.followers[i].id) === Number(UserManager.currentUser.id)) { return; } } $playlistBar.find('.subscribe').click(function() { playlist.subscribe(function() { PlaylistView.loadPlaylistView(playlist); }); }).show(); } } else if (logged_in) { $playlistBar.find('.sync').show().one('click', PlaylistView.syncPlaylistButtonClicked); } }, loadPlaylistView: function(playlist) { $('#right > div').hide(); $('#right > .playlists .pane').hide().removeClass('active'); $('#left .menu li').removeClass('selected'); playlist.playlistDOMHandle.addClass('active'); playlist.leftMenuDOMHandle.addClass('selected'); PlaylistView.updatePlaylistBar(playlist); if (playlist.playlistDOMHandle.find('.video').length !== playlist.videos.length) { playlist.playlistDOMHandle.html(''); $.each(playlist.videos, function(i, item) { if (item) { $video = item.createListView(); $video.addClass('droppable'); $video.addClass('draggable'); if (!playlist.isSubscription) { $video.data('additionalMenuButtons', [{ title: 'Delete', args: $video, callback: PlaylistView.deleteVideoButtonClicked }]); $video.addClass('reorderable'); } $video.appendTo(playlist.playlistDOMHandle); } }); } playlist.playlistDOMHandle.show(); $('#right > .playlists').show(); }, savePlaylistButtonClicked: function(event) { var $playlistBar = $('#right > .playlists .info'); var playlist = $playlistBar.data('model'); var newPlaylist = playlist.copy(); // create copy without connection to remote newPlaylist.createViews(); playlistManager.addPlaylist(newPlaylist); newPlaylist.getMenuView().appendTo('#left .playlists ul'); if (logged_in) { newPlaylist.createNewPlaylistOnRemote(function() { playlistManager.save(); newPlaylist.getMenuView().addClass('remote'); }); } else { playlistManager.save(); } $playlistBar.find('.copy').hide(); }, syncPlaylistButtonClicked: function(event) { var playlist = playlistManager.getCurrentlySelectedPlaylist(); console.log('syncing playlist ' + playlist.title); playlist.sync(function() { PlaylistView.updatePlaylistBar(playlist); playlistManager.save(); playlist.getMenuView().addClass('remote'); history.pushState(null, null, playlist.getUrl()); }); }, showPlaylistSharePopup: function(playlist, elem, arrowDirection) { $('#share-playlist-popup .link input').val(playlist.getUrl()); $('#share-playlist-popup .twitter') .unbind('click') .click(function(event) { event.preventDefault(); window.open(playlist.getTwitterShareUrl(), 'Share playlist on Twitter', 400, 400); return false; }); $('#share-playlist-popup .facebook') .unbind('click') .click(function(event) { event.preventDefault(); window.open(playlist.getFacebookShareUrl(), 'Share playlist on Facebook', 400, 400); return false; }); elem.arrowPopup('#share-playlist-popup', arrowDirection); }, shareButtonClicked: function(event) { var playlistBar = $(this).parent(); var playlist = playlistBar.data('playlist'); PlaylistView.showPlaylistSharePopup(playlist, $(this), 'up'); } }
JavaScript
0
@@ -1104,32 +1104,45 @@ if ( +logged_in && Number(playlist.
810ea1f3eb8854e7931092e20fd943b14ab9e061
include *.svelte files into package
scripts/build-svelte.js
scripts/build-svelte.js
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ /* eslint no-console: "off" */ const exec = require('exec-sh'); const fs = require('fs'); const svelte = require('svelte/compiler'); const bannerSvelte = require('./banner-svelte.js'); async function buildSvelte(format, cb) { const env = process.env.NODE_ENV || 'development'; const outputDir = env === 'development' ? 'build' : 'package'; // Babel await exec.promise( `cross-env MODULES=${format} npx babel --config-file ./babel.config.svelte.js src/svelte --out-dir ${outputDir}/${format}/svelte`, ); await exec.promise( `cross-env MODULES=${format} npx babel --config-file ./babel.config.svelte.js src/swiper-svelte.js --out-file ${outputDir}/swiper-svelte.${format}.js`, ); // Fix import paths let fileContent = fs.readFileSync(`./${outputDir}/swiper-svelte.${format}.js`, 'utf-8'); fileContent = fileContent .replace(/require\(".\/svelte\//g, `require("./${format}/svelte/`) .replace(/from '.\/svelte\//g, `from './${format}/svelte/`); fileContent = `${bannerSvelte}\n${fileContent}`; fs.writeFileSync(`./${outputDir}/swiper-svelte.${format}.js`, fileContent); // Transform svelte files let swiper = fs.readFileSync('./src/svelte/swiper.svelte', 'utf8'); const swiperResult = svelte.compile(swiper, { format, filename: 'swiper.svelte', }); swiper = swiperResult.js.code; fs.writeFileSync(`./${outputDir}/${format}/svelte/swiper.js`, swiper); let swiperSlide = fs.readFileSync('./src/svelte/swiper-slide.svelte', 'utf8'); const swiperSlideResult = svelte.compile(swiperSlide, { format, filename: 'swiper.svelte', }); swiperSlide = swiperSlideResult.js.code; fs.writeFileSync(`./${outputDir}/${format}/svelte/swiper-slide.js`, swiperSlide); try { fs.unlinkSync(`./${outputDir}/svelte/swiper-slide.svelte`); fs.unlinkSync(`./${outputDir}/svelte/swiper.svelte`); } catch (err) { // no files } if (cb) cb(); } function build() { buildSvelte('esm', () => {}); buildSvelte('cjs', () => {}); } module.exports = build;
JavaScript
0
@@ -1809,177 +1809,8 @@ );%0A%0A - try %7B%0A fs.unlinkSync(%60./$%7BoutputDir%7D/svelte/swiper-slide.svelte%60);%0A fs.unlinkSync(%60./$%7BoutputDir%7D/svelte/swiper.svelte%60);%0A %7D catch (err) %7B%0A // no files%0A %7D%0A%0A if
c949f5ba20058d6ad5646923138ca3f06c40a514
Use `babel` plugin replace `includes` (#6659)
scripts/build/config.js
scripts/build/config.js
"use strict"; const path = require("path"); const PROJECT_ROOT = path.resolve(__dirname, "../.."); /** * @typedef {Object} Bundle * @property {string} input - input of the bundle * @property {string?} output - path of the output file in the `dist/` folder * @property {string?} name - name for the UMD bundle (for plugins, it'll be `prettierPlugins.${name}`) * @property {'node' | 'universal'} target - should generate a CJS only for node or UMD bundle * @property {'core' | 'plugin'} type - it's a plugin bundle or core part of prettier * @property {'rollup' | 'webpack'} [bundler='rollup'] - define which bundler to use * @property {CommonJSConfig} [commonjs={}] - options for `rollup-plugin-commonjs` * @property {string[]} externals - array of paths that should not be included in the final bundle * @property {Object.<string, string>} replace - map of strings to replace when processing the bundle * @property {string[]} babelPlugins - babel plugins * @property {Object?} terserOptions - options for `terser` * @typedef {Object} CommonJSConfig * @property {Object} namedExports - for cases where rollup can't infer what's exported * @property {string[]} ignore - paths of CJS modules to ignore */ /** @type {Bundle[]} */ const parsers = [ { input: "src/language-js/parser-babylon.js", target: "universal", babelPlugins: [ require.resolve("./babel-plugins/replace-array-includes-with-indexof") ] }, { input: "src/language-js/parser-flow.js", target: "universal", strict: false }, { input: "src/language-js/parser-typescript.js", target: "universal", replace: { // node v4 compatibility for @typescript-eslint/typescript-estree "(!unique.includes(raw))": "(unique.indexOf(raw) === -1)" }, commonjs: { ignore: [ // Optional package for TypeScript that logs ETW events (a Windows-only technology). "@microsoft/typescript-etw" ] } }, { input: "src/language-js/parser-angular.js", target: "universal", alias: { // Force using the CJS file, instead of ESM; i.e. get the file // from `"main"` instead of `"module"` (rollup default) of package.json entries: [ { find: "lines-and-columns", replacement: require.resolve("lines-and-columns") }, { find: "@angular/compiler/src", replacement: path.resolve( `${PROJECT_ROOT}/node_modules/@angular/compiler/esm2015/src` ) } ] } }, { input: "src/language-css/parser-postcss.js", target: "universal", // postcss has dependency cycles that don't work with rollup bundler: "webpack", // postcss need keep_fnames when minify terserOptions: { mangle: { keep_fnames: true } } }, { input: "src/language-graphql/parser-graphql.js", target: "universal" }, { input: "src/language-markdown/parser-markdown.js", target: "universal" }, { input: "src/language-handlebars/parser-glimmer.js", target: "universal", commonjs: { namedExports: { "node_modules/handlebars/lib/index.js": ["parse"], "node_modules/@glimmer/syntax/dist/modules/es2017/index.js": "default" }, ignore: ["source-map"] } }, { input: "src/language-html/parser-html.js", target: "universal" }, { input: "src/language-yaml/parser-yaml.js", target: "universal", alias: { // Force using the CJS file, instead of ESM; i.e. get the file // from `"main"` instead of `"module"` (rollup default) of package.json entries: [ { find: "lines-and-columns", replacement: require.resolve("lines-and-columns") } ] }, babelPlugins: [ require.resolve("./babel-plugins/replace-array-includes-with-indexof") ] } ].map(parser => { const name = getFileOutput(parser) .replace(/\.js$/, "") .split("-")[1]; return Object.assign(parser, { type: "plugin", name }); }); /** @type {Bundle[]} */ const coreBundles = [ { input: "index.js", type: "core", target: "node", externals: [path.resolve("src/common/third-party.js")], replace: { // from @iarna/toml/parse-string "eval(\"require('util').inspect\")": "require('util').inspect" } }, { input: "src/doc/index.js", name: "doc", type: "core", output: "doc.js", target: "universal" }, { input: "standalone.js", name: "prettier", type: "core", target: "universal" }, { input: "bin/prettier.js", type: "core", output: "bin-prettier.js", target: "node", externals: [path.resolve("src/common/third-party.js")] }, { input: "src/common/third-party.js", type: "core", target: "node", replace: { // cosmiconfig@5 -> import-fresh uses `require` to resolve js config, which caused Error: // Dynamic requires are not currently supported by rollup-plugin-commonjs. "require(filePath)": "eval('require')(filePath)", "require.cache": "eval('require').cache" } } ]; function getFileOutput(bundle) { return bundle.output || path.basename(bundle.input); } module.exports = coreBundles .concat(parsers) .map(b => Object.assign(b, { output: getFileOutput(b) }));
JavaScript
0
@@ -1627,160 +1627,106 @@ -replace: %7B +babelPlugins: %5B %0A -// node v4 compatibility for @typescript-eslint/typescript-estree%0A %22(!unique.includes(raw))%22: %22(unique.indexOf(raw) === -1)%22 +require.resolve(%22./babel-plugins/replace-array-includes-with-indexof%22) %0A -%7D +%5D ,%0A
f3e43f94f3ff463746fb104348f777623177f38a
update trello oauth
scripts/trello-oauth.js
scripts/trello-oauth.js
module.exports = function(robot) { robot.respond(/trello/i, function(res_r) { var express = require('express'); var http = require('http') var OAuth = require('oauth').OAuth var url = require('url') /* / Express Server Setup */ var app = express(); app.use(express.static('public')); var server = app.listen(3000, function () { console.log('Server up and running...🏃🏃'); console.log("Listening on port %s", server.address().port); }); var port = process.env.PORT || 3000; app.listen(port) /* / OAuth Setup and Functions */ const requestURL = "https://trello.com/1/OAuthGetRequestToken"; const accessURL = "https://trello.com/1/OAuthGetAccessToken"; const authorizeURL = "https://trello.com/1/OAuthAuthorizeToken"; const appName = "anbot team"; // Be sure to include your key and secret in 🗝.env ↖️ over there. // You can get your key and secret from Trello at: https://trello.com/app-key const key = process.env.HUBOT_TRELLO_KEY; //const token = process.env.HUBOT_TRELLO_TOKEN; const secret = process.env.HUBOT_TRELLO_OAUTH; // Trello redirects the user here after authentication const loginCallback = "https://andreasbot.herokuapp.com/hubot/trello-oauth"; // You should {"token": "tokenSecret"} pairs in a real application // Storage should be more permanent (redis would be a good choice) const oauth_secrets = {}; const oauth = new OAuth(requestURL, accessURL, key, secret, "1.0A", loginCallback, "HMAC-SHA1") const login = function(req, res) { oauth.getOAuthRequestToken(function(error, token, tokenSecret, results){ // console.log(`in getOAuthRequestToken - token: ${token}, tokenSecret: ${tokenSecret}, resultes ${JSON.stringify(results)}, error: ${JSON.stringify(error)}`); oauth_secrets[token] = tokenSecret; res.redirect(`${authorizeURL}?oauth_token=${token}&name=${appName}`); }); }; var callback = function(request, response) { const query = url.parse(request.url, true).query; const token = query.oauth_token; const tokenSecret = oauth_secrets[token]; const verifier = query.oauth_verifier; oauth.getOAuthAccessToken(token, tokenSecret, verifier, function(error, accessToken, accessTokenSecret, results){ // In a real app, the accessToken and accessTokenSecret should be stored console.log(`in getOAuthAccessToken - accessToken: ${accessToken}, accessTokenSecret: ${accessTokenSecret}, error: ${error}`); oauth.getProtectedResource("https://api.trello.com/1/members/me", "GET", accessToken, accessTokenSecret, function(error, data, response){ // Now we can respond with data to show that we have access to your Trello account via OAuth console.log(`in getProtectedResource - accessToken: ${accessToken}, accessTokenSecret: ${accessTokenSecret}`); response.send(data) }); }); }; /* / Routes */ res_r.send("localhost:3000"); // app.get("/", function (request, response) { // console.log(`GET '/' 🤠 ${Date()}`); // response.send("<h1>Oh, hello there!</h1><a href='./login'>Login with OAuth!</a>"); // }); app.get("/", function (request, response) { console.log(`GET '/' ${Date()}`); login(request, response); }); app.get("/callback", function (request, response) { console.log(`GET '/callback' ${Date()}`); callback(request, response); }); }) }
JavaScript
0.000001
@@ -362,20 +362,55 @@ .listen( +'https://andreasbot.herokuapp.com: 3000 +' , functi @@ -543,71 +543,8 @@ %7D); -%0A var port = process.env.PORT %7C%7C 3000; %0A app.listen(port) %0A%0A
19a4855ec5c8fff32801e5a80cb717b498462b51
Update house_points.js
scripts/house_points.js
scripts/house_points.js
const helpers = require(`${__dirname}/../helpers/`); const MongoClient = require('mongodb').MongoClient; const mongourl = process.env.MONGODB_URI; function points(event) { let msg = ''; if (event.pm === true) { msg = 'S-sorry, you can\'t do that in a PM with me. ;w;'; event.bot.sendMessage({ to: event.channelID, message: msg, }); } else { const check = helpers.roleCheck(event, 'headmaster'); if (check === true) { // jscs:disable const resOne = /points <@(?:!|&)?([0-9]*)> (-[0-9]*|\+?[0-9]*)/i; const resTwo = /<@(?:!|&)?([0-9]*)> (-[0-9]*|\+?[0-9]*|a) points?/i; // jshint ignore:line const resThree = /(-[0-9]*|\+?[0-9]*|a) points? (?:to|from) <@(?:!|&)?([0-9]*)>/i; // jshint ignore:line // jscs:enable let recipient = ''; let amount = 0; let res = []; if (resOne.test(event.message)) { res = event.message.match(resOne); recipient = res[1]; amount = parseInt(res[2], 10); } else if (resTwo.test(event.message)) { res = event.message.match(resTwo); recipient = res[1]; amount = parseInt(res[2], 10); if (res[2] === 'a') { amount = 1; } } else if (resThree.test(event.message)) { res = event.message.match(resThree); recipient = res[2]; amount = parseInt(res[1], 10); if (res[1] === 'a') { amount = 1; } } MongoClient.connect(mongourl, (err, db) => { const col = db.collection('users'); col.find({ userID: recipient }).limit(1).each((e, user) => { if (user) { if (user.house) { if (amount < 0) { msg = `<@${recipient}> has been punished with \``; msg += `${amount}\` point(s) taken away from `; msg += helpers.houseDetail(user.house); msg += ` by <@${event.userID}>. =w=`; } else { msg = `<@${recipient}> has been awarded with \``; msg += `${amount}\` point(s) given to `; msg += helpers.houseDetail(user.house); msg += ` by <@${event.userID}>. \`^w^\``; } helpers.points(event, user.house, amount); } else { msg = 'Uhm... I don\'t think '; msg += `<@${recipient}> has sorted themselves into a house, <@`; msg += `${event.userID}>. .w.\n`; msg += 'Use `!house set [g|h|r|s]` for that, '; msg += `<@${recipient}>! \`^w^\``; } event.bot.sendMessage({ to: event.channelID, message: msg, }); db.close(); } }); }); } else { msg = `I'm afraid you can't do that, <@${event.userID}>. .w.`; event.bot.sendMessage({ to: event.channelID, message: msg, }); } } } module.exports = { name: 'points', author: 'thattacoguy', syntax: 'points', hidden: true, patterns: [/points <@(?:!|&)?([0-9]*)> (\+?[0-9]*|-[0-9]*)/i, /<@(?:!|&)?([0-9]*)> (-[0-9]*|\+?[0-9]*|a) points?/i, /(-[0-9]*|\+?[0-9]*|a) points? (?:to|from) <@(?:!|&)?([0-9]*)>/i, ], description: '[Admin Only] Give points to users!', command: points, };
JavaScript
0.000001
@@ -2484,17 +2484,30 @@ = 'Use %60 -! +@WolfBot#8759 house se
4ab24a5beb20dc77ab6954b99f2e4d0e2e4f9764
Update MultiModuleFactory.js
lib/MultiModuleFactory.js
lib/MultiModuleFactory.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const Tapable = require("tapable"); const MultiModule = require("./MultiModule"); module.exports = class MultiModuleFactory extends Tapable { constructor() { super(); } create(data, callback) { const dependency = data.dependencies[0]; callback(null, new MultiModule(data.context, dependency.dependencies, dependency.name)); } };
JavaScript
0
@@ -255,10 +255,9 @@ e %7B%0A - +%09 cons
993f14f446b5d85f18162a4d55b1fdca6cc653cc
update to wpcom.reqt method
lib/follow.js
lib/follow.js
/** * Module dependencies. */ var request = require('./util/request'); var debug = require('debug')('wpcom:follow'); /** * Follow * * @param {String} site_id - site id * @param {WPCOM} wpcom * @api public */ function Follow(site_id, wpcom) { if (!site_id) { throw new Error('`site id` is not correctly defined'); } if (!(this instanceof Follow)) { return new Follow(site_id, wpcom); } this.wpcom = wpcom; this._sid = site_id; } /** * Follow the site * * @param {Object} [query] * @param {Function} fn */ Follow.prototype.follow = Follow.prototype.add = function (query, fn) { var path = '/sites/' + this._sid + '/follows/new'; return request.put(this.wpcom, null, path, query, null, fn); }; /** * Unfollow the site * * @param {Object} [query] * @param {Function} fn */ Follow.prototype.unfollow = Follow.prototype.del = function (query, fn) { var path = '/sites/' + this._sid + '/follows/mine/delete'; return request.put(this.wpcom, null, path, query, null, fn); }; /** * Get the follow status for current * user on current blog site * * @param {Object} [query] * @param {Function} fn */ Follow.prototype.state = Follow.prototype.mine = function (query, fn) { var path = '/sites/' + this._sid + '/follows/mine'; return request.get(this.wpcom, null, path, query, fn); }; /** * Expose `Follow` module */ module.exports = Follow;
JavaScript
0.000002
@@ -669,36 +669,24 @@ ';%0A return -request.put( this.wpcom, @@ -679,32 +679,33 @@ n this.wpcom -, null, +.req.put( path, query, @@ -952,20 +952,8 @@ urn -request.put( this @@ -954,32 +954,33 @@ n this.wpcom -, null, +.req.del( path, query, @@ -1061,24 +1061,25 @@ nt blog site +s %0A *%0A * @para @@ -1265,20 +1265,8 @@ urn -request.get( this @@ -1271,24 +1271,25 @@ is.wpcom -, null, +.req.get( path, qu
dcb04711124fba0b8b29dd018b8065268bfc541c
fix gamebreaking typos
classes/Player.js
classes/Player.js
Weapon = require("./Weapon") var settings = require("../settings"); // Class for the player actor in the game var Player = function (game, connection, name, color) { // Attributes I might want to tweak var maxhp = settings.player.maxHP; var speedcap = settings.player.speedCap; var hacceleration = settings.player.hacceleration; var hdeceleration = settings.player.hdeceleration; var jumpspeed = settings.player.jumpSpeed; var gravity = settings.player.gravity; var size = settings.player.hitBoxSize; // Customizations this.name = name; this.color = color; // constanst for states STANDING = 0; WALKING = 1; JUMPING = 2; // Won't update if this is false this.active = false; // Will be removed on next update if this is true this.remove = false; // Game related stuff this.speed = [0, 0]; this.hp = maxhp; this.weapon = new Weapon(game, "default", this); this.pos = game.map.getPlayerSpawn(); this.type = "player"; this.state = STANDING; // Helper reference to better access statistics from other classes this.profile = connection.profile; var multiKillTimer = -1; var multiKillCount = 0; var killStreak = 0; var lasthitby = null; this.lasthitby = {"name": "", "weapon": ""}; var holdingClick = false; this.setLastHitBy = function (player, weapon) { this.lasthitby = {"name": player.name, "weapon": weapon}; lasthitby = player } this.increaseScore = function(number, weapon) { if (!number) number = 1; // number is optional connection.score += number; // increase score // Process killstreaks and multikills killStreak++; multiKillCount++; multiKillTimer = settings.player.multiKillTimer; var numberWords = settings.strings.multiKillNumbers; var message = settings.strings.multiKill; // Post multikill message if (multiKillCount > 1) game.messages.push(message.replace("{name}", this.name).replace("{number}", numberWords[multiKillCount-1])); // post Killstreak message if (killStreak > 1) { var message = (killStreak <= settings.strings.killStreak.length) ? settings.strings.killStreak[killStreak+1] : settings.strings.killStreak[settings.strings.killStreak.length-1]; if (message) { game.messages.push(message.replace("{name}", this.name)); } } // Update Profile connection.profile.statistics.totalKills += 1; switch (weapon) { case "Flamethrower": connection.profile.statistics.flameKills += 1; break; case "Laser": connection.profile.statistics.laserKills += 1; break; case "Shotgun": connection.profile.statistics.shotgunKills += 1; break; case "Grenade": connection.profile.statistics.grenadeKills += 1; break; case "Gun": connection.statistics.gunKills += 1; break; default: break; } connection.profile.multiKills[multiKillCount] += 1; if (connection.profile.maxKillStreak < killStreak) connection.profile.maxKillStreak = killStreak; } this.decreaseScore = function(number) { if (!number) number = 1; connection.score -= number; } // Called every tick this.update = function () { // Get our current inputs var keys = connection.keys; var cursor = connection.cursor; // See above if (this.remove) return 0; // Jump if we're not jumping already if (keys.up && this.state != JUMPING) { this.speed[1] += jumpspeed; } // Move if (keys.left) { this.speed[0] = Math.max(-1*speedcap, this.speed[0]-hacceleration); } else if (keys.right) { this.speed[0] = Math.min(speedcap, this.speed[0]+hacceleration); } else { // Or slow down this.speed[0] = (this.speed[0] > 0) ? Math.max(0, this.speed[0] - hdeceleration) : Math.min(0, this.speed[0] + hdeceleration); } // Shoot if (keys.space) { var success = this.weapon.shoot(this, this.pos, cursor) if (!success && !holdingClick) connection.sounds.push("cd"); holdingClick = true; } else { holdingClick = false; } // process ammo reload this.weapon.updateAmmo(keys.space) // Fall this.speed[1] -= gravity; // Calculate new position based on what happened before.. var newpos = [this.pos[0]+this.speed[0], this.pos[1]+this.speed[1]]; hit = game.playerCollision(this.pos, newpos, size) if (hit[0]) { this.pos = hit[1]; } else { this.pos = newpos; } // stop moving on the axis we're colliding on col = hit[2]; if (col[0]) { this.speed[0] = 0; } if (col[1]) { this.state = 0; this.speed[1] = 0; } else { this.state = JUMPING; } game.map.checkBounds(this.pos, size, this); game.map.checkKillzones(this); // Process Multikills and Killstreaks if (multiKillTimer-- == 0) { multiKillCount = 0; } // die if we're dead if (this.hp <= 0) { // output kill message if (this.lasthitby.name == "") { game.messages.push(this.name +" committed suicide."); } else { game.messages.push(this.lasthitby.name +" killed "+ this.name + " (Weapon: "+this.lasthitby.weapon+")"); } // give points if (lasthitby) { lasthitby.increaseScore(1, this.lastHitby.weapon); } else { this.decreaseScore(); // Update Stats connection.profile.statistics.totalSuicides += 1; } this.active = false; // probably unneeded // Update statistics switch (this.lasthitby.weapon) { case "Flamethrower": connection.profile.statistics.flameDeaths += 1; break; case "Laser": connection.profile.statistics.laserDeaths += 1; break; case "Shotgun": connection.profile.statistics.shotgunDeaths += 1; break; case "Grenade": connection.profile.statistics.grenadeDeaths += 1; break; case "Gun": connection.statistics.gunDeaths += 1; break; default: break; } connection.profile.statistics.totalDeaths += 1; // make death sound game.sounds.push("death"); return 0; } return 1; } this.pack = function () { var pack = { "color": this.color, "hp": this.hp, "name": this.name, "pos": this.pos, "type": this.type, "weaponColor": this.weapon.weaponColor, "uID": connection.uid } return pack; } // add this to actors list game.addActor(this); } module.exports = Player;
JavaScript
0.999083
@@ -3208,33 +3208,32 @@ reak;%0A %7D%0A -%0A connecti @@ -3243,16 +3243,27 @@ profile. +statistics. multiKil @@ -3310,32 +3310,43 @@ nection.profile. +statistics. maxKillStreak %3C @@ -6017,17 +6017,17 @@ his.last -H +h itby.wea
e42c40d889f4bb152337898bb309e3ff78a9d068
modify format
lib/format.js
lib/format.js
/** * 十六进制以空格分开。 * * @example * * 120e320a -> 12 0e 32 0a * * @param hexString * @returns {string|undefined} */ exports.pretty = function (hexString) { if (!hexString || hexString.length === 0) { return; } let output = ''; for (let i = 0; i < hexString.length; i++) { output += hexString[i]; if (i % 2 != 0 && i < hexString.length - 1) { output += ' '; } } return output; }; exports.array = function (hexString) { if (!hexString || hexString.length === 0) { return; } let output = '['; for (let i = 0; i < hexString.length; i++) { if (i % 2 == 0) { output += '0x'; } output += hexString[i]; if (i % 2 != 0 && i < hexString.length - 1) { output += ', '; } } output += ']'; return output; }; var zero = function (n, max) { n = n.toString(16).toUpperCase(); while (n.length < max) { n = '0' + n; } return n; }; /** * Print buffer to hex map. * * @see [gagle/node-hex: Pretty-prints a Buffer.](https://github.com/gagle/node-hex) * @param buffer * */ exports.map = function (buffer) { var rows = Math.ceil(buffer.length / 16); var last = buffer.length % 16 || 16; var offsetLength = buffer.length.toString(16).length; if (offsetLength < 6) offsetLength = 6; var str = 'Offset'; while (str.length < offsetLength) { str += ' '; } str = '\u001b[36m' + str + ' '; var i; for (i = 0; i < 16; i++) { str += ' ' + zero(i, 2); } str += '\u001b[0m\n'; if (buffer.length) str += '\n'; var b = 0; var lastBytes; var lastSpaces; var v; for (i = 0; i < rows; i++) { str += '\u001b[36m' + zero(b, offsetLength) + '\u001b[0m '; lastBytes = i === rows - 1 ? last : 16; lastSpaces = 16 - lastBytes; var j; for (j = 0; j < lastBytes; j++) { str += ' ' + zero(buffer[b], 2); b++; } for (j = 0; j < lastSpaces; j++) { str += ' '; } b -= lastBytes; str += ' '; for (j = 0; j < lastBytes; j++) { v = buffer[b]; str += (v > 31 && v < 127) || v > 159 ? String.fromCharCode(v) : '.'; b++; } str += '\n'; } return str; };
JavaScript
0.000003
@@ -221,35 +221,35 @@ urn;%0A %7D%0A%0A -let +var output = '';%0A%0A @@ -248,35 +248,35 @@ = '';%0A%0A for ( -let +var i = 0; i %3C hexS @@ -565,19 +565,19 @@ %7D%0A%0A -let +var output @@ -597,11 +597,11 @@ or ( -let +var i =
426968466ecded7cf39e4e1460cc46af893e0e09
add route change
client/app/app.js
client/app/app.js
angular.module('zibzoo', [ 'zibzoo.vendorsList', 'ui.router', 'mm.foundation', 'zibzoo.navbar.directive', 'zibzoo.vendors.directive', 'zibzoo.landing', 'zibzoo.vendorsList', 'zibzoo.vendor' ]) .config(function ($stateProvider, $urlRouterProvider, $httpProvider) { $stateProvider .state('landing', { templateUrl: 'app/landing/landing.html', url: '/', controller: 'LandingController' }) .state('vendors', { templateUrl: 'app/vendors/VendorsList/vendorsList.html', url: '/vendors', controller: 'VendorsListController', }) .state('vendor', { templateUrl: 'app/vendors/vendor/vendor.html', url: '/vendor/:vendorId', controller: 'VendorController' }) .state('vendor.menu', { templateUrl: 'app/vendors/vendor/menu.html', url: '/vendor/:vendorId/menu', controller: 'VendorMenuController' }) .state('merchant', { templateUrl: 'app/merchants/merchant/merchant.html', url: '/merchant/:merchantId/', controller: 'MerchantController', authenticate: true }) .state('merchant.menu', { templateUrl: 'app/merchants/merchant/menu.html', url: '/merchant/:merchantId/menu', controller: 'MerchantMenuController', authenticate: true }) .state('merchant.orders', { templateUrl: 'app/merchants/merchant/orders.html', url: '/merchant/:merchantId/orders', controller: 'MerchantOrdersController', authenticate: true }); $urlRouterProvider.otherwise('/'); }) .run(function ($rootScope, $state) { $rootScope.$state = $state; });
JavaScript
0
@@ -198,16 +198,44 @@ .vendor' +,%0A 'zibzoo.merchantProfile' %0A%5D)%0A%0A.co @@ -1044,17 +1044,16 @@ rchantId -/ ',%0A
7b68e8662128fb0ebd2c2cd990cb152b077c234e
remove old console log
client/app/app.js
client/app/app.js
angular.module('zeus', [ 'zeus.landing', 'zeus.results', 'zeus.details', 'zeus.services', 'zeus.user', 'zeus.account', 'zeus.reviews', 'zeus.editReview', 'auth0.lock', 'angular-jwt', 'ui.router' ]) .controller('zeusController', function($scope, $location, authService, $http, User) { $scope.searchQuery = ''; $scope.search = function(search) { if (search.length < 1) { return; } $location.path('/results/' + search + '/1'); $scope.searchQuery = ''; }; $scope.login = authService.login; $scope.logout = function() { authService.logout(); }; //Gets user profile when logged in. authService.getProfileDeferred().then(function (profile) { console.log(profile); $scope.profile = profile; if (profile) { User.checkUser(profile); } }); }) .config(function($stateProvider, $urlRouterProvider, $locationProvider, lockProvider, jwtOptionsProvider, $httpProvider) { var landingState = { name: 'landing', url: '/', templateUrl: 'app/landing/landing.html', controller: 'LandingController', controllerAs: 'LandingVm', authenticate: false }; var resultsState = { name: 'results', url: '/results/:search/:page', templateUrl: 'app/results/results.html', controller: 'ResultsController', controllerAs: 'ResultsVm', authenticate: false }; var detailsState = { name: 'details', url: '/details/:type/:id', templateUrl: 'app/details/details.html', controller: 'DetailsController', controllerAs: 'DetailsVm', authenticate: false }; var userState = { name: 'user', url: '/user/:username', templateUrl: 'app/user/user.html', controller: 'UserController', controllerAs: 'UserVm', //need to set this up authenticate: false }; var accountState = { name: 'account', url: '/account', templateUrl: 'app/account/account.html', controller: 'AccountController', //controllerAs: 'AccountVm', //need to set this up authenticate: true }; var reviewsState = { name: 'reviews', url: '/review/:id', templateUrl: 'app/reviews/reviews.html', controller: 'ReviewsController', controllerAs: 'ReviewsVm', authenticate: false }; var editReviewState = { name: 'editReview', url: '/review/:id/edit', templateUrl: 'app/reviews/editReview.html', controller: 'editReviewController', controllerAs: 'EditReviewVm', authenticate: true }; $stateProvider.state(landingState); $stateProvider.state(resultsState); $stateProvider.state(detailsState); $stateProvider.state(userState); $stateProvider.state(accountState); $stateProvider.state(reviewsState); $stateProvider.state(editReviewState); $urlRouterProvider.otherwise('/'); //Auth 0 account info lockProvider.init({ clientID: 'GaWAS7TybB6Fqwa9uBw2SDVMPRGSAVDK', domain: 'hughes89.auth0.com' }); // Sets HTML5 Mode to true, removes # from url //$locationProvider.html5Mode(true); jwtOptionsProvider.config({ tokenGetter: ['options', function (options) { if (options && options.url.substr(options.url.length - 5) === '.html') { return null; } return localStorage.getItem('id_token'); }], whiteListedDomains: ['localhost:3000'], unauthenticatedRedirectPath: '/login' }); //Attatches token to each HTTP call $httpProvider.interceptors.push('jwtInterceptor'); }) .run(function ($rootScope, authService, lock, authManager) { // Put the authService on $rootScope so its methods // can be accessed from the nav bar $rootScope.authService = authService; // Register the authentication listener that is // set up in auth.service.js authService.registerAuthenticationListener(); // Use the authManager from angular-jwt to check for // the user's authentication state when the page is // refreshed and maintain authentication authManager.checkAuthOnRefresh(); // Register synchronous hash parser lock.interceptHash(); });
JavaScript
0.000002
@@ -702,34 +702,8 @@ ) %7B%0A - console.log(profile);%0A
bffd724ed5fd72bc4e39faf4cd50fef117f1917c
Allow debug logger to output at lowest level
lib/logger.js
lib/logger.js
var winston = require('winston'), mongoLog = require('winston-mongodb').MongoDB, config = require('../config'), muri = require('muri'), parsed = muri(config.db.URL), _ = require('underscore'), logger; /** * Config to connect to DB for the debug logger */ var debugDBConfig = { level: 'error', db: parsed.db, collection: 'logDebug', host: parsed.hosts[0].host, port: parsed.hosts[0].port, username: parsed.auth ? parsed.auth.user : '', password: parsed.auth ? parsed.auth.pass : '' }; /** * Config to connect to DB for track logger, * same as debug logger but different collection */ var trackDBConfig = _.clone(debugDBConfig); trackDBConfig.collection = 'logTrack'; trackDBConfig.level = 'info'; /** * Debug logger, stored in DB and console for error tracking */ winston.loggers.add('debug', { transports: [ new (winston.transports.Console)({ level: 'error', colorize: 'true' }), new mongoLog(debugDBConfig) ] }); /** * Track logger, used to track API route usage */ winston.loggers.add('track', { transports: [ new mongoLog(trackDBConfig) ] }); /** * Expose `debug` logger */ exports.debug = (function () { var ret = {}; if (config.isTest) { ret.warn = ret.debug = ret.error = noop; } else { ret = winston.loggers.get('debug'); } return ret; function noop () {} })(); /** * Expose `track` logger */ var track = winston.loggers.get('track'); exports.track = config.isTest ? function () {} : function (message, meta) { track.info(message, meta); };
JavaScript
0.000002
@@ -923,21 +923,20 @@ level: ' -error +info ', color @@ -944,14 +944,12 @@ ze: -' true -' %7D),
d5230d343f8bfa3c33d0e0e05d34d4dbbe509b11
remove sample logs
lib/logger.js
lib/logger.js
var chalk = require('chalk'); var util = require('util'); var _ = require('lodash'); var levels = { 'debug': 1, 'verbose': 2, 'info': 3, 'success': 4, 'warn': 4, 'error': 5, }; var colors = { 'debug': chalk.gray, 'verbose': chalk.white, 'info': chalk.cyan, 'success': chalk.green, 'warn': chalk.white.bgYellow, 'error': chalk.white.bgRed }; function pad(string, to){ if(string.length < to){ return new Array(to-string.length).join(' '); } return ''; } function Logger (level) { this.log = level; this.warn('sample', 'sample message'); this.success('sample', 'success message'); this.error('sample', 'error message'); } Logger.prototype._log = function(level, category, message){ if(levels[this.log] <= levels[level]){ var rest = Array.prototype.slice.call(arguments, 3); var prefix = pad(category, 10) + colors[level]('%s'); var args = ([prefix + ' ' + message, category]).concat(rest); var text = util.format.apply(this, args); process.stdout.write(text + '\n'); } }; _.each(levels, function(level, name){ Logger.prototype[name] = function(category, message){ var rest = Array.prototype.slice.call(arguments, 2); var args = [name, category, message].concat(rest); this._log.apply(this, args); }; }, this); module.exports = Logger;
JavaScript
0
@@ -533,135 +533,8 @@ el;%0A - this.warn('sample', 'sample message');%0A this.success('sample', 'success message');%0A this.error('sample', 'error message');%0A %7D%0A%0AL
55cdc64f7c08c33bddf414fd414b58bef6650242
Update mapKey to allow setting title on construct
lib/mapKey.js
lib/mapKey.js
'use strict'; var fs = require('fs') var template = fs.readFileSync(__dirname + '/../templates/key.html', 'utf8') var handlebars = require('handlebars') var keyTemplate = handlebars.compile(template) var assert = require('assert') var domWrapper = require('../wrappers/dom') var EventEmitter = require('events').EventEmitter var dom class Item extends EventEmitter { constructor(key, text, checked) { this.key = key this.text = text this.checked = checked || false } click() { this.checked = !this.checked this.emit('change', { key: this.key, text: this.text, checked: this.checked }) } } /** * Class to handle reading and writing to the map key dom structure */ class MapKey extends EventEmitter { /** * @constructor */ constructor(config) { this.config = config this.title_ = '' this.items = [] this.domElement = dom.getElementById(config.domElement) this.domElement.innerHTML = keyTemplate() } /** * Used to set the title of the key * @param {string} title */ set title(title) { assert.equal(typeof title, 'string', '`title` must be a string') this.title_ = title this.domElement.querySelector('.title').innerHTML = title } /** * Returns the title of the key */ get title() { return this.title_ } /** * Clears all key dom elements. Explicit unsets to avoid memory leaks * in hateful ie. */ clearDomElements() { var itemContainer = this.domElement.querySelector('.items') var items = this.domElement.querySelectorAll('li') items.forEach((item) => { item.querySelector('checkbox').onclick = null item.innerHTML = null item = null }) itemContainer.innerHTML = null } /** * Renders all key item data from memory onto the dom * creates a dom node for each item and inserts into list */ renderDomElements() { this.items.forEach((item) => { this.renderDomElement(item) }) } /** * Renders a single dom list element into items list from item object * @param {object} item */ renderDomElement(item) { var li = dom.createElement('li') var checkbox = dom.createElement('input') var text = dom.createTextNode(item.text) var label = dom.createElement('label') if (item.checked) checkbox.setAttribute('checked', true) else checkbox.removeAttribute('checked') checkbox.setAttribute('type', 'checkbox') checkbox.onclick = item.click.bind(item) label.appendChild(checkbox) label.appendChild(text) li.appendChild(label) this.domElement.querySelector('.items').appendChild(li) } /** * Adds item by some unique id. Stores the item by id and renders item * to the dom * @param {string} id * @param {string} text * @param {boolean} checked */ addItem(id, text, checked = false) { assert.equal(typeof id, 'string', '`id` must be a string') assert.equal(typeof text, 'string', '`text` must be a string') var item = new Item(id, text, checked) item.on('change', this.emit.bind(this, 'layerToggle')) this.items.push(item) this.renderDomElement(item) } /** * Removes an item by unique id. Trims back the internal collection of items * before clearing and re-rendering the collection to the dom * @param {string} id */ removeItem(id) { assert.equal(typeof id, 'string', '`id` must be a string') var length = this.items.length this.items = this.items.filter((item) => { if (item.key === id) { item.removeAllListeners('click') return false } return true }) if (length !== this.items.length) { this.clearDomElements() this.renderDomElements() } } } module.exports = function (config) { dom = domWrapper() assert.equal(typeof config, 'object', '`config` must be an object') assert.ok(!!config.domElement, '`config.domElement` must be defined') return new MapKey(config) }
JavaScript
0
@@ -871,16 +871,32 @@ title_ = + config.title %7C%7C ''%0A
88355aa909e6eb0e0e5b42dc3651a85989fe1613
change from localhost to mongolab
server/config/config.js
server/config/config.js
(function() { 'use strict'; module.exports = { // 'database' : 'mongodb://root:[email protected]:11158/dmsapp', 'database': '127.0.0.1:27017', 'port': process.env.PORT || 3000, 'secretKey': '#Kenya2030' }; })();
JavaScript
0.000002
@@ -51,11 +51,8 @@ %0A - // 'da @@ -120,24 +120,27 @@ dmsapp',%0A + // 'database':
98014d02692c45f10f098eb9eaeb2d484bebceb2
tweak to native Client#query overload
lib/native.js
lib/native.js
//require the c++ bindings & export to javascript var sys = require('sys'); var EventEmitter = require('events').EventEmitter; var binding = require(__dirname + '/../build/default/binding'); var utils = require(__dirname + "/utils"); var types = require(__dirname + "/types"); var Connection = binding.Connection; var p = Connection.prototype; var nativeConnect = p.connect; p.connect = function() { var self = this; utils.buildLibpqConnectionString(this._config, function(err, conString) { if(err) return self.emit('error', err); nativeConnect.call(self, conString); }) } p.query = function(config, values, callback) { var q = new NativeQuery(config, values, callback); this._queryQueue.push(q); this._pulseQueryQueue(); return q; } p._pulseQueryQueue = function(initialConnection) { if(!this._connected) { return; } if(this._activeQuery) { return; } var query = this._queryQueue.shift(); if(!query) { if(!initialConnection) { this.emit('drain'); } return; } this._activeQuery = query; if(query.name) { if(this._namedQueries[query.name]) { this._sendQueryPrepared(query.name, query.values||[]); } else { this._namedQuery = true; this._namedQueries[query.name] = true; this._sendPrepare(query.name, query.text, (query.values||[]).length); } } else if(query.values) { //call native function this._sendQueryWithParams(query.text, query.values) } else { //call native function this._sendQuery(query.text); } } var ctor = function(config) { config = config || {}; var connection = new Connection(); connection._queryQueue = []; connection._namedQueries = {}; connection._activeQuery = null; connection._config = utils.normalizeConnectionInfo(config); connection.on('connect', function() { connection._connected = true; connection._pulseQueryQueue(true); }); //proxy some events to active query connection.on('_row', function(row) { connection._activeQuery.handleRow(row); }) connection.on('_error', function(err) { //give up on trying to wait for named query prepare this._namedQuery = false; if(connection._activeQuery) { connection._activeQuery.handleError(err); } else { connection.emit('error', err); } }) connection.on('_readyForQuery', function() { var q = this._activeQuery; //a named query finished being prepared if(this._namedQuery) { this._namedQuery = false; this._sendQueryPrepared(q.name, q.values||[]); } else { connection._activeQuery.handleReadyForQuery(); connection._activeQuery = null; connection._pulseQueryQueue(); } }); return connection; }; //event emitter proxy var NativeQuery = function(text, values, callback) { //TODO there are better ways to detect overloads if(typeof text == 'object') { this.text = text.text; this.values = text.values; this.name = text.name; if(typeof values === 'function') { this.callback = values; } else if(typeof values !== 'undefined') { this.values = values; this.callback = callback; } } else { this.text = text; this.values = values; this.callback = callback; if(typeof values == 'function') { this.values = null; this.callback = values; } } if(this.callback) { this.rows = []; } //normalize values if(this.values) { for(var i = 0, len = this.values.length; i < len; i++) { var item = this.values[i]; switch(typeof item) { case 'undefined': this.values[i] = null; break; case 'object': this.values[i] = item === null ? null : JSON.stringify(item); break; case 'string': //value already string break; default: //numbers this.values[i] = item.toString(); } } } EventEmitter.call(this); }; sys.inherits(NativeQuery, EventEmitter); var p = NativeQuery.prototype; //maps from native rowdata into api compatible row object var mapRowData = function(row) { var result = {}; for(var i = 0, len = row.length; i < len; i++) { var item = row[i]; result[item.name] = item.value == null ? null : types.getStringTypeParser(item.type)(item.value); } return result; } p.handleRow = function(rowData) { var row = mapRowData(rowData); if(this.callback) { this.rows.push(row); } this.emit('row', row); }; p.handleError = function(error) { if(this.callback) { this.callback(error); this.callback = null; } else { this.emit('error', error); } } p.handleReadyForQuery = function() { if(this.callback) { this.callback(null, { rows: this.rows }); } this.emit('end'); }; module.exports = ctor;
JavaScript
0
@@ -3044,37 +3044,14 @@ if( -typeof values !== 'undefined' +values ) %7B%0A
dba4fbf003a0b5fa1734405985a1ae48a949ac35
change config js and remove env
server/configuration.js
server/configuration.js
const path = require("path"); const app_root = path.dirname(__dirname); // Parent of the directory where this file is module.exports = { /** Port on which the application will listen */ PORT: parseInt(process.env["PORT"]) || 8080, /** Host on which the application will listen (defaults to undefined, hence listen on all interfaces on all IP addresses, but could also be '127.0.0.1' **/ HOST: process.env["HOST"] || undefined, /** Path to the directory where boards will be saved by default */ HISTORY_DIR: process.env["WBO_HISTORY_DIR"] || path.join(app_root, "server-data"), /** Folder from which static files will be served */ WEBROOT: process.env["WBO_WEBROOT"] || path.join(app_root, "client-data"), /** Number of milliseconds of inactivity after which the board should be saved to a file */ SAVE_INTERVAL: parseInt(process.env["WBO_SAVE_INTERVAL"]) || 1000 * 2, // Save after 2 seconds of inactivity /** Periodicity at which the board should be saved when it is being actively used (milliseconds) */ MAX_SAVE_DELAY: parseInt(process.env["WBO_MAX_SAVE_DELAY"]) || 1000 * 60, // Save after 60 seconds even if there is still activity /** Maximal number of items to keep in the board. When there are more items, the oldest ones are deleted */ MAX_ITEM_COUNT: parseInt(process.env["WBO_MAX_ITEM_COUNT"]) || 32768, /** Max number of sub-items in an item. This prevents flooding */ MAX_CHILDREN: parseInt(process.env["WBO_MAX_CHILDREN"]) || 192, /** Maximum value for any x or y on the board */ MAX_BOARD_SIZE: parseInt(process.env["WBO_MAX_BOARD_SIZE"]) || 65536, /** Maximum messages per user over the given time period before banning them */ MAX_EMIT_COUNT: parseInt(process.env["WBO_MAX_EMIT_COUNT"]) || 192, /** Duration after which the emit count is reset in miliseconds */ MAX_EMIT_COUNT_PERIOD: parseInt(process.env["WBO_MAX_EMIT_COUNT_PERIOD"]) || 4096, /** Blocked Tools. A comma-separated list of tools that should not appear on boards. */ BLOCKED_TOOLS: (process.env["WBO_BLOCKED_TOOLS"] || "").split(","), /** Selection Buttons. A comma-separated list of selection buttons that should not be available. */ BLOCKED_SELECTION_BUTTONS: (process.env["WBO_BLOCKED_SELECTION_BUTTONS"] || "").split(","), /** Automatically switch to White-out on finger touch after drawing with Pencil using a stylus. Only supported on iPad with Apple Pencil. */ AUTO_FINGER_WHITEOUT: process.env["AUTO_FINGER_WHITEOUT"] !== "disabled", /** If this variable is set, it should point to a statsd listener that will * receive WBO's monitoring information. * example: udp://127.0.0.1 */ STATSD_URL: process.env["STATSD_URL"], /** Secret key for jwt */ AUTH_SECRET_KEY: (process.env["AUTH_SECRET_KEY"] || ""), CHECK_BOARDNAME_IN_JWT: (process.env["CHECK_BOARDNAME_IN_JWT"] || false), };
JavaScript
0.000001
@@ -2810,84 +2810,8 @@ %22%22), -%0A CHECK_BOARDNAME_IN_JWT: (process.env%5B%22CHECK_BOARDNAME_IN_JWT%22%5D %7C%7C false), %0A%0A%7D;
c89401e12d79786cfbceab560a14b4f4baa5bee0
fix var name
server/forum/section.js
server/forum/section.js
"use strict"; /*global nodeca, _*/ var NLib = require('nlib'); var Async = NLib.Vendor.Async; var Section = nodeca.models.forum.Section; var Thread = nodeca.models.forum.Thread; var forum_breadcrumbs = require('../../lib/breadcrumbs.js').forum; var thread_fields = { '_id': 1, 'id': 1, 'title': 1, 'prefix': 1, 'forum_id': 1, 'cache': 1 }; // prefetch forum to simplify permisson check nodeca.filters.before('@', function (params, next) { var env = this; env.extras.puncher.start('Forum info prefetch'); Section.findOne({id: params.id}).setOptions({lean: true }).exec(function(err, forum) { if (err) { next(err); return } // No forum -> "Not Found" status if (!forum) { next({ statusCode: 404 }); return; } env.data.section = forum; env.extras.puncher.stop(); next(err); }); }); // fetch and prepare threads and sub-forums // ToDo pagination // // ##### params // // - `id` forum id module.exports = function (params, next) { var env = this; Async.series([ function(callback){ // prepare sub-forums var root = env.data.section._id; var deep = env.data.section.level + 2; // need two next levels env.extras.puncher.start('Get subforums'); Section.build_tree(env, root, deep, function(err) { env.extras.puncher.stop(); callback(err); }); }, function (callback) { // fetch and prepare threads env.data.users = env.data.users || []; var query = {forum_id: params.id}; env.extras.puncher.start('Get threads'); Thread.find(query).select(thread_fields).setOptions({lean: true }) .exec(function(err, docs){ if (!err) { env.response.data.threads = docs.map(function(doc) { if (doc.cache.real.first_user) { env.data.users.push(doc.cache.real.first_user); } if (doc.cache.real.last_user) { env.data.users.push(doc.cache.real.last_user); } if (env.session.hb) { doc.cache.real = doc.cache.hb; } return doc; }); } env.extras.puncher.stop(_.isArray(docs) ? { count: docs.length} : null); callback(err); }); } ], next); }; // fetch forums for breadcrumbs build // prepare buand head meta nodeca.filters.after('@', function (params, next) { var env = this; var data = this.response.data; var forum = this.data.section; // prepare page title data.head.title = forum.title; // prepare forum info data.forum = { id: params.id, title: forum.title, description: forum.description, }; if (this.session.hb) { data.forum['thread_count'] = forum.cache.hb.thread_count; } else { data.forum['thread_count'] = forum.cache.real.thread_count; } var query = { _id: { $in: forum.parent_list } }; var fields = { '_id' : 1, 'id' : 1, 'title' : 1 }; env.extras.puncher.start('Build breadcrumbs'); Section.find(query).select(fields) .setOptions({lean:true}).exec(function(err, docs){ if (err) { next(err); return; } data.widgets.breadcrumbs = forum_breadcrumbs(env, docs); env.extras.puncher.stop(); next(); }); });
JavaScript
0.999765
@@ -2619,22 +2619,21 @@ id: -params +forum .id,%0A
99725d2401dece06df35cdcc63d8e8cbc9d74879
Use Object.create instead of __proto__
lib/object.js
lib/object.js
'use strict'; var d = require('es5-ext/lib/Object/descriptor') , forEach = require('es5-ext/lib/Object/for-each') , isObject = require('es5-ext/lib/Object/is-object') , isString = require('es5-ext/lib/String/is-string') , uuid = require('time-uuid') , base = require('./base') , defineProperties = Object.defineProperties , object, getConstructor; getConstructor = function () { return function Self(data) { var errors, error; if (isString(data) && Self.propertyIsEnumerable(data)) return Self[data]; if (!isObject(data) || data.__id) return Self.validate(data); if (!this || (this.constructor !== Self)) return new Self(data); base.transaction(function () { defineProperties(this, { __id: d(uuid()), __created: d(base.lock), __ns: d(Self) }); // Define by predefined schema forEach(Self.prototype, function (value, name) { if (value.__id && value.__isNS) { try { value._defineProperty(this, name, data[name], 'e'); } catch (e) { if (!errors) (errors = []); errors.push(e); } } }, this); if (errors) { error = new TypeError("Could not define properties"); error.subErrors = errors; throw error; } forEach(data, function (value, name) { if (!this.hasOwnProperty(name)) this.set(name, value, 'e'); }, this); }.bind(this)); Self[this.__id] = this; return this; }; }; module.exports = object = base.create('object', getConstructor()); defineProperties(object, { create: d(function (name, properties) { return base.transaction(function () { var constructor = base.create.call(this, name, getConstructor()); constructor.prototype.__proto__ = this.prototype; if (properties) { forEach(properties, function (value, name) { this.set(name, value, 'e'); }, constructor.prototype); } return constructor; }.bind(this)); }), validate: d(function (value) { if (value == null) return null; if (!value || !value.__id || !this.propertyIsEnumerable(value.__id) || (this[value.__id] !== value)) { throw new TypeError(value + "doesn't represent valid dbjs." + this.__id + " object"); } return value; }), normalize: d(function (value) { if (value == null) return value; if (isString(value)) { return this.propertyIsEnumerable(value) ? this[value] : null; } if (value.__id && this.propertyIsEnumerable(value.__id) && (this[value.__id] === value)) { return value; } return null; }) }); defineProperties(object.prototype, { set: d(object.set) });
JavaScript
0.000001
@@ -298,16 +298,83 @@ base')%0A%0A + , create = Object.create, defineProperty = Object.defineProperty%0A , defi @@ -1759,35 +1759,106 @@ type -.__proto__ = this.prototype + = create(this.prototype);%0A%09%09%09defineProperty(constructor.prototype, 'constructor', d(constructor)) ;%0A%09%09
8b2b451e0376fb018ca60b842e92c6d3ca2dc5ed
Remove unused variable
lib/output.js
lib/output.js
'use strict'; const chalk = require('chalk'); const bold = chalk.bold; const red = chalk.red; const cyan = chalk.cyan; const grey = chalk.grey; const green = chalk.green; /** * Print given object as JSON. * @param {Object} obj * @return {String} */ function printJSON(obj) { return console.log(JSON.stringify(obj, null, ' ')); } /** * Get singular or plural form of given word. * @param {Number} num * @param {String} [singular] * @param {String} [plural] * @return {String} */ function s(num, singular, plural) { return num <= 1 ? (singular || '') : (plural || 's'); } /** * Print module dependency graph as indented text (or JSON). * @param {Object} modules * @param {Object} opts * @return {undefined} */ module.exports.list = function (modules, opts) { opts = opts || {}; if (opts.json) { return printJSON(modules); } Object.keys(modules).forEach((id) => { console.log(cyan.bold(id)); modules[id].forEach((depId) => { console.log(grey(` ${depId}`)); }); }); }; /** * Print a summary of module dependencies. * @param {Object} modules * @param {Object} opts * @return {undefined} */ module.exports.summary = function (modules, opts) { const o = {}; opts = opts || {}; Object.keys(modules).sort((a, b) => { return modules[b].length - modules[a].length; }).forEach((id) => { if (opts.json) { o[id] = modules[id].length; } else { console.log(`${id}: ${cyan.bold(modules[id].length)}`); } }); if (opts.json) { return printJSON(o); } }; /** * Print the result from Madge.circular(). * @param {Object} res * @param {Array} circular * @param {Object} opts * @return {undefined} */ module.exports.circular = function (res, circular, opts) { if (opts.json) { return printJSON(circular); } const warningCount = res.warnings().skipped.length; const fileCount = Object.keys(res.obj()).length; const cyclicCount = Object.keys(circular).length; const statusMsg = `(${fileCount} file${s(fileCount)}, ${warningCount} warning${s(warningCount)})`; if (!circular.length) { console.log(green.bold(`✔ No circular dependency ${statusMsg}`)); } else { console.log(red.bold(`✖ ${cyclicCount} circular dependenc${s(cyclicCount, 'y', 'ies')} ${statusMsg}\n`)); circular.forEach((path, idx) => { path.forEach((module, idx) => { if (idx) { process.stdout.write(red.bold(' > ')); } process.stdout.write(red(module)); }); process.stdout.write('\n'); }); process.stdout.write('\n'); } }; /** * Print the result from Madge.depends(). * @param {Array} depends * @param {Object} opts * @return {undefined} */ module.exports.depends = function (depends, opts) { if (opts.json) { return printJSON(depends); } depends.forEach((id) => { console.log(id); }); }; /** * Print warnings to the console. * @param {Object} res * @return {undefined} */ module.exports.warnings = function (res) { const skipped = res.warnings().skipped; if (skipped.length) { console.log(red.bold(`✖ Skipped ${skipped.length} file${s(skipped.length)}\n`)); skipped.forEach((file) => { console.log(red(file)); }); process.stdout.write('\n'); } }; /** * Print error to the console. * @param {Object} err * @param {Object} opts * @return {undefined} */ module.exports.error = function (err) { console.log(red(err.stack ? err.stack : err)); };
JavaScript
0.000015
@@ -45,33 +45,8 @@ );%0A%0A -const bold = chalk.bold;%0A cons
ffa5d3722b3085bfbe6d448f6bebf2705112e2ad
Remove unused variable this._buffer.
lib/parser.js
lib/parser.js
/** * Modules dependencies */ var EventEmitter = require('events').EventEmitter, util = require('util'); module.exports = Parser; function Parser(options){ EventEmitter.call(this); this.delimiter = options.delimiter || ','; this.endLine = options.endLine || '\n'; this.columns = options.columns || []; this._defaultColumns = !!options.columns; this._currentColumn = 0; this._index = 0; this._line = {}; this._text = ''; this._paused = false; } // Inherits from EventEmitter util.inherits(Parser,EventEmitter); Parser.prototype.write = function(buffer,encoding){ if(this._paused) return false; var s = buffer.toString(encoding); this._parse(s); } Parser.prototype.destroy = function(){ this._buffer = null; this.emit('close'); } Parser.prototype.end = function(buffer,encoding){ this.write(buffer,encoding); this._buffer = null; this.emit('end'); } Parser.prototype.pause = function(){ this._paused = true; } Parser.prototype._parse = function(s){ for(var i = 0; i < s.length; i++){ var c = s[i]; switch(c){ case this.delimiter : if(this._index === 0 && !this._defaultColumns){ this.columns[this._currentColumn] = this._text; }else{ this.emit('column',this.columns[this._currentColumn],this._text); this._line[this.columns[this._currentColumn]] = this._text; } this._text = ''; this._currentColumn++; break; case this.endLine : //CRLF if(this._text.charAt(this._text.length -1) === '\r') this._text = this._text.slice(0,this._text.length - 1); if(this._index === 0 && !this._defaultColumns){ this.columns[this._currentColumn] = this._text; }else{ this.emit('column',this.columns[this._currentColumn],this._text); this._line[this.columns[this._currentColumn]] = this._text; } this.emit('data',this._line); this._index++; this._currentColumn = 0; this._line = {}; break; default : this._text = this._text + c; } } }
JavaScript
0
@@ -701,38 +701,16 @@ tion()%7B%0A -%09this._buffer = null;%0A %09this.em @@ -809,30 +809,8 @@ g);%0A -%09this._buffer = null;%0A %09thi
dd1f3f2214b90c8404c4a23899504fe5922ece3a
fix txt, mx and add srv and soa to state machine
lib/parser.js
lib/parser.js
var name_unpack = require('./fields').name_unpack; var ipaddr = require('./ipaddr'); var BufferStream = require('./bufferstream'); var consts = require('./consts'); var Parser = module.exports = function (msg) { var state, len, pos, val, rdata_len, rdata, section, count; var packet = {}; packet.header = {}; packet.question = []; packet.answer = []; packet.authority = []; packet.additional = []; pos = label_pos = 0; state = "HEADER"; msg = BufferStream(msg); len = msg.length; while (true) { switch (state) { case "HEADER": packet.header.id = msg.readUInt16BE(); val = msg.readUInt16BE(); packet.header.qr = (val & 0x8000) >> 15; packet.header.opcode = (val & 0x7800) >> 11; packet.header.aa = (val & 0x400) >> 10; packet.header.tc = (val & 0x200) >> 9; packet.header.rd = (val & 0x100) >> 8; packet.header.ra = (val & 0x80) >> 7; packet.header.res1 = (val & 0x40) >> 6; packet.header.res2 = (val & 0x20) >> 5; packet.header.res3 = (val & 0x10) >> 4; packet.header.rcode = (val & 0xF); packet.header.qdcount = msg.readUInt16BE(); packet.header.ancount = msg.readUInt16BE(); packet.header.nscount = msg.readUInt16BE(); packet.header.arcount = msg.readUInt16BE(); state = "QUESTION"; break; case "QUESTION": pos = msg.tell(); val = name_unpack(msg.buffer, pos) msg.seek(pos + val.read); val = { name: val.value }; val.type = msg.readUInt16BE(); val.class = msg.readUInt16BE(); packet.question.push(val); // TODO handle qdcount > 0 in practice no one sends this state = "RESOURCE_RECORD"; section = "answer"; count = "ancount"; break; case "RESOURCE_RECORD": if (packet.header[count] === packet[section].length) { switch (section) { case "answer": section = "authority"; count = "nscount"; break; case "authority": section = "additional"; count = "arcount"; break; case "additional": state = "END"; break; } } else { state = "RR_UNPACK"; } break; case "RR_UNPACK": pos = msg.tell(); val = name_unpack(msg.buffer, pos); msg.seek(pos + val.read); val = { name: val.value }; val.type = msg.readUInt16BE(); val.class = msg.readUInt16BE(); val.ttl = msg.readUInt32BE(); rdata_len = msg.readUInt16BE(); rdata = msg.slice(rdata_len); state = consts.QTYPE_TO_NAME[val.type]; if (!state) state = "RESOURCE_DONE"; break; case "RESOURCE_DONE": packet[section].push(val); state = "RESOURCE_RECORD"; break; case "A": val.address = new ipaddr.IPv4(rdata.toByteArray()); val.address = val.address.toString(); state = "RESOURCE_DONE"; break; case "AAAA": val.address = new ipaddr.IPv6(rdata.toByteArray('readUInt16BE')); val.address = val.address.toString(); state = "RESOURCE_DONE"; break; case "NS": case "CNAME": case "PTR": val.data = name_unpack(msg.buffer, msg.tell() - rdata_len).value; state = "RESOURCE_DONE"; break; case "TXT": val.data = name_unpack(rdata.buffer, 0).value; state = "RESOURCE_DONE"; break; case "MX": val.priority = msg.readUInt16BE(); val.exchange = name_unpack(msg.buffer, msg.tell() - rdata_len).value; state = "RESOURCE_DONE"; break; case "END": return packet; break; default: console.log(state, val); state = "RESOURCE_DONE"; break; } }; };
JavaScript
0
@@ -3534,32 +3534,231 @@ val.data = + rdata.buffer.toString('ascii', 1, rdata.buffer.readUInt8(0) + 1);%0A state = %22RESOURCE_DONE%22;%0A break;%0A case %22MX%22:%0A val.priority = rdata.readUInt16BE();%0A val.exchange = name_unpack(rda @@ -3754,21 +3754,19 @@ _unpack( -rdata +msg .buffer, @@ -3766,17 +3766,42 @@ buffer, -0 +msg.tell() - rdata_len + 2 ).value; @@ -3853,34 +3853,35 @@ ak;%0A case %22 -MX +SRV %22:%0A val.p @@ -3894,104 +3894,780 @@ y = -msg.readUInt16BE();%0A val.exchange = name_unpack(msg.buffer, msg.tell() - rdata_len).value +rdata.readUInt16BE();%0A val.weight = rdata.readUInt16BE();%0A val.port = rdata.readUInt16BE();%0A pos = msg.tell() - rdata_len + rdata.tell();%0A val.target = name_unpack(msg.buffer, pos).value;%0A state = %22RESOURCE_DONE%22;%0A break;%0A case %22SOA%22:%0A pos = name_unpack(msg.buffer, msg.tell() - rdata_len);%0A val.primary = pos.value;%0A rdata.seek(pos.read);%0A pos = name_unpack(msg.buffer, msg.tell() - rdata_len + pos.read);%0A val.admin = pos.value;%0A rdata.seek(rdata.tell() + pos.read);%0A val.serial = rdata.readUInt32BE();%0A val.refresh = rdata.readInt32BE();%0A val.retry = rdata.readInt32BE();%0A val.expiration = rdata.readInt32BE();%0A val.minimum = rdata.readInt32BE() ;%0A
ce88863f56420effef284a73bc33b1fdc7efae71
Align objects
lib/player.js
lib/player.js
var cp = require('child_process'), fs = require('fs'), log = require('./logger'), path = require('path'); var config = null, mediaPath = ''; function setConfig(cfg) { config = cfg; mediaPath = normalizePath(config.mediaPath); } function normalizePath(p, isFile) { return path.normalize(p).replace(/\/+$/, '') + (isFile ? '' : '/'); } function validatePath(pathParam, isFile) { var absPath = normalizePath(path.join(mediaPath, pathParam), isFile); if (absPath.substring(0, mediaPath.length) !== mediaPath) { throw new Error('Access to that path is prohibited.'); } var relPath = absPath.substring(mediaPath.length); return { abs: absPath, rel: relPath }; } var nowPlaying = {}; function getBrowseData(pathParam) { var pathInfo = validatePath(pathParam); var data = { directory: pathInfo.rel, parent: (pathInfo.abs === mediaPath ? null : path.dirname(pathInfo.rel)), dirs: [], files: [], seekCommands: [] }; var dirEntries = fs.readdirSync(pathInfo.abs); dirEntries.sort(function(a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }); for (var i = 0; i < dirEntries.length; i++) { if (fs.statSync(pathInfo.abs + dirEntries[i]).isDirectory()) { data.dirs.push(dirEntries[i]); } else { data.files.push(dirEntries[i]); } } if (nowPlaying.child) { data.playing = true; data.currentFilename = nowPlaying.filename; data.paused = nowPlaying.paused; } for (var n in config.controls.seek) { data.seekCommands.push({ value: n, text: (n < 0 ? 'back ' : 'forward ') + Math.abs(n) + 's' }); } return data; } function handleBrowseRequest(req, res, pathParam) { browsePath(pathParam, function(html) { res.send(html); }); } function playFile(filePath, cb) { if (nowPlaying.child) { sendCommand('exit', function() { playFileInternal(filePath); cb(); }); } else { playFileInternal(filePath); process.nextTick(cb); } } function playFileInternal(filePath) { log.info('Playing file:', filePath); nowPlaying.child = cp.exec( config.commands.start.replace('%f', filePath.abs), function(err, stdout, stderr) { log.info('Player process terminated'); if (err) { log.error('Error:', err); } log.info('Stdout:', stdout.toString('utf8')); log.info('Stderr:', stderr.toString('utf8')); }); nowPlaying.child.on('exit', function() { nowPlaying = {}; }); nowPlaying.filename = filePath.rel; nowPlaying.started = new Date(); nowPlaying.paused = false; } function sendCommand(command, cb, params) { if (!nowPlaying.child) { throw new Error('No player to control!'); } switch (command) { case 'exit': var killTimeout; nowPlaying.child.on('exit', function() { clearTimeout(killTimeout); cb(); }); killTimeout = setTimeout(function() { log.warn('Player process did not exit; killing'); if (config.commands.kill) { cp.exec(config.commands.kill); } else { nowPlaying.child.kill('SIGTERM'); } }, config.exitTimeout); break; case 'pause': nowPlaying.paused = true; break; case 'play': nowPlaying.paused = false; break; } var commandString = config.controls[command]; if (command == 'seek') { commandString = commandString[params.n]; } log.info('Sending player command "' + command + '": ' + JSON.stringify(commandString)); nowPlaying.child.stdin.write(commandString); if (command != 'exit') { cb(); } } exports.setConfig = setConfig; exports.getBrowseData = getBrowseData; exports.playFile = playFile; exports.validatePath = validatePath; exports.sendCommand = sendCommand;
JavaScript
0.000005
@@ -696,16 +696,17 @@ abs + : absPat @@ -719,16 +719,17 @@ rel + : relPat @@ -877,16 +877,20 @@ irectory + : pathIn @@ -911,16 +911,23 @@ parent + : (pathI @@ -998,16 +998,25 @@ dirs + : %5B%5D,%0A @@ -1026,16 +1026,24 @@ files + : %5B%5D,%0A @@ -1060,16 +1060,17 @@ Commands + : %5B%5D%0A @@ -1725,16 +1725,17 @@ value + : n,%0A @@ -1747,16 +1747,18 @@ text + : (n %3C 0
cd38670640b7ef22c975fc966cf16bf9865357b0
Update lexer states example
examples/lexer-start-conditions.g.js
examples/lexer-start-conditions.g.js
/** * Start conditions of lex rules. Tokenizer states. * * Tokenizer rules may provide start conditions. Such rules are executed * only when lexer enters the state corresponding to the names of the * start conditions. * * Start conditions can be inclusive (%s, 0), and exclusive (%x, 1). * Inclusive conditions also include rules without any start conditions. * Exclusive conditions do not include other rules when the parser enter * this state. The rules with `*` condition are always included. * * https://gist.github.com/DmitrySoshnikov/f5e2583b37e8f758c789cea9dcdf238a * * When a grammar is defined in the JSON format, the start conditions are * specified as: * * "startConditions": { * "name": 1, // exclusive * "other": 0, // inclusive * } * * And a rule itself may specify a list of start conditions as the * first element: * * // This lex-rule is applied only when parser enters `name` state. * * [["name"], "\w+", "return 'NAME'"] * * At the beginning a lexer is in the `INITIAL` state. A new state is * entered either using `this.pushState(name)` or `this.begin(name)`. To * exit a state, use `this.popState()`. * * In the grammar below we has `comment` tokenizer state, which allows us * to skip all the comment characters, but still to count number of lines. * * ./bin/syntax -g examples/lexer-start-conditions.g -f ~/test.js */ // Example of ~/test.js // // 1. // 2. /* Hello world // 3. privet // 4. // 5. OK **/ // 6. // 7. Main // 8. // // Number of lines: 8 { "moduleInclude": ` let lines = 1; yyparse.onParseBegin = (string) => { // Print the string with line numbers. let code = string .split('\\n') .map((s, line) => (line + 1) + '. ' + s) .join('\\n'); console.log(code + '\\n'); }; yyparse.onParseEnd = () => { console.log('Number of lines: ' + lines + '\\n'); }; `, "lex": { "startConditions": { "comment": 1, // exclusive }, "rules": [ // On `/*` we enter the comment state: ["\\/\\*", "this.pushState('comment'); /* skip comments */"], // On `*/` being in `comment` state we return to the initial state: [["comment"], "\\*+\\/", "this.popState(); /* skip comments */"], // Being inside the `comment` state, skip all chars, except new lines // which we count. [["comment"], "[^*\\n]*", "/* skip comments */"], [["comment"], "\\*+[^*/\\n]*", "/* skip comments */"], // Count lines in comments. [["comment"], "\\n", "lines++; /* skip new lines in comments */"], // In INITIAL state, count line numbers as well: ["\\n", "lines++ /* skip new lines */"], [["*"], " +", "/* skip spaces in any state */"], // Main program consisting only of one word "Main" ["Main", "return 'MAIN'"], // EOF [["*"], "\\$", "return 'EOF'"], ], }, "bnf": { "Program": ["MAIN"], } }
JavaScript
0
@@ -1373,16 +1373,24 @@ tions.g +-m slr1 -f ~/tes @@ -2127,16 +2127,21 @@ mment'); + /* skip @@ -2449,34 +2449,32 @@ - %22/* skip comment @@ -2513,26 +2513,24 @@ +%5B%5E*/%5C%5Cn%5D*%22, - @@ -2631,34 +2631,32 @@ ++; - - /* skip new line @@ -2767,16 +2767,20 @@ %22lines++ + @@ -2843,32 +2843,36 @@ + %22/* skip spaces @@ -2962,25 +2962,16 @@ %5B%22Main%22, - %22return @@ -2984,63 +2984,8 @@ '%22%5D, -%0A%0A // EOF%0A %5B%5B%22*%22%5D, %22%5C%5C$%22, %22return 'EOF'%22%5D, %0A
f9bcfda39780e8e96cb9e398036bb5a2e413a4bb
Add websocket; update SubscriptionClient
client/src/App.js
client/src/App.js
import React, { Component } from 'react'; import { BrowserRouter, Link, Route, Switch, } from 'react-router-dom'; import { ApolloClient, ApolloProvider, createNetworkInterface, toIdValue, } from 'react-apollo'; import { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-ws'; import ChannelsListWithData from './components/ChannelsListWithData'; import NotFound from './components/NotFound'; import ChannelDetails from './components/ChannelDetails'; import './App.css'; const networkInterface = createNetworkInterface({ uri: 'http://localhost:4000/graphql' }); networkInterface.use([{ applyMiddleware(req, next) { setTimeout(next, 500); }, }]); const wsClient = new SubscriptionClient(`ws://localhost:4000/subscriptions`, { reconnect: true }); const networkInterfaceWithSubscriptions = addGraphQLSubscriptions( networkInterface, wsClient ); function dataIdFromObject (result) { if (result.__typename) { if (result.id !== undefined) { return `${result.__typename}:${result.id}`; } } return null; } const client = new ApolloClient({ networkInterface: networkInterfaceWithSubscriptions, customResolvers: { Query: { channel: (_, args) => { return toIdValue(dataIdFromObject({ __typename: 'Channel', id: args['id'] })) }, }, }, dataIdFromObject, }); class App extends Component { render() { return ( <ApolloProvider client={client}> <BrowserRouter> <div className="App"> <Link to="/" className="navbar">React + GraphQL App</Link> <Switch> <Route exact path="/" component={ChannelsListWithData}/> <Route path="/channel/:channelId" component={ChannelDetails}/> <Route component={ NotFound }/> </Switch> </div> </BrowserRouter> </ApolloProvider> ); } } export default App;
JavaScript
0
@@ -309,16 +309,142 @@ ort-ws'; +%0Aimport ws from 'ws';%0A// import %7B SubscriptionClient, addGraphQLSubscriptions %7D from 'subscriptions-transport-ws/dist/client'; %0A%0Aimport @@ -912,18 +912,23 @@ ct: true +, %0A%7D +, ws );%0A%0Acons
539113a6cfa67e907de168b5d3d0477f5e407303
Simplify attribute rendering step
lib/render.js
lib/render.js
/* Module dependencies */ var _ = require('underscore'); var utils = require('./utils'); var encode = utils.encode; /* Boolean Attributes */ var rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i; /* Format attributes */ var formatAttrs = function(attributes) { if (!attributes) return ''; var output = [], value; // Loop through the attributes for (var key in attributes) { value = attributes[key]; if (!value && (rboolean.test(key) || key === '/')) { output.push(key); } else { output.push(key + '="' + encode(value) + '"'); } } return output.join(' '); }; /* Self-enclosing tags (stolen from node-htmlparser) */ var singleTag = { area: 1, base: 1, basefont: 1, br: 1, col: 1, frame: 1, hr: 1, img: 1, input: 1, isindex: 1, link: 1, meta: 1, param: 1, embed: 1, include: 1, 'yield': 1 }; /* Tag types from htmlparser */ var tagType = { tag: 1, script: 1, link: 1, style: 1, template: 1 }; var render = module.exports = function(dom, opts) { if (!Array.isArray(dom) && !dom.cheerio) dom = [dom]; opts = opts || {}; var output = [], xmlMode = opts.xmlMode || false; _.each(dom, function(elem) { var pushVal; if (tagType[elem.type]) pushVal = renderTag(elem, xmlMode); else if (elem.type === 'directive') pushVal = renderDirective(elem); else if (elem.type === 'comment') pushVal = renderComment(elem); else pushVal = renderText(elem); // Push rendered DOM node output.push(pushVal); if (elem.children) output.push(render(elem.children, opts)); if ((!singleTag[elem.name] || xmlMode) && tagType[elem.type]) { if (!isClosedTag(elem, xmlMode)) { output.push('</' + elem.name + '>'); } } }); return output.join(''); }; var isClosedTag = function(elem, xmlMode){ return (xmlMode && (!elem.children || elem.children.length === 0)); }; var renderTag = function(elem, xmlMode) { var tag = '<' + elem.name; if (elem.attribs && _.size(elem.attribs)) { tag += ' ' + formatAttrs(elem.attribs); } if (isClosedTag(elem, xmlMode)) { tag += '/'; } return tag + '>'; }; var renderDirective = function(elem) { return '<' + elem.data + '>'; }; var renderText = function(elem) { return elem.data; }; var renderComment = function(elem) { return '<!--' + elem.data + '-->'; }; // module.exports = $.extend(exports);
JavaScript
0.999711
@@ -379,11 +379,8 @@ turn - '' ;%0A%0A @@ -2104,53 +2104,68 @@ name -;%0A%0A if (elem.attribs && _.size(elem. +,%0A attribs = formatAttrs(elem.attribs);%0A%0A if ( attribs) ) %7B%0A @@ -2160,17 +2160,16 @@ attribs) -) %7B%0A t @@ -2184,33 +2184,15 @@ ' + -formatAttrs(elem. attribs -) ;%0A
8391f308b791f6b782a592ecaab13e1fa4e99b67
use new VirtualConsole constructor
lib/render.js
lib/render.js
'use strict' import ansiHTML from 'ansi-html' import co from 'co' import serialize from 'serialize-javascript' import { getContext, setAnsiColors, encodeHtml } from './utils' const debug = require('debug')('nuxt:render') // force blue color debug.color = 4 setAnsiColors(ansiHTML) export function render (req, res) { if (!this.renderer && !this.dev) { console.error('> No build files found, please run `nuxt build` before launching `nuxt start`') // eslint-disable-line no-console process.exit(1) } /* istanbul ignore if */ if (!this.renderer || !this.appTemplate) { return new Promise((resolve) => { setTimeout(() => { resolve(this.render(req, res)) }, 1000) }) } const self = this const context = getContext(req, res) return co(function * () { res.statusCode = 200 if (self.dev) { // Call webpack middleware only in development yield self.webpackDevMiddleware(req, res) yield self.webpackHotMiddleware(req, res) } if (!self.dev && self.options.performance.gzip) { yield self.gzipMiddleware(req, res) } // If base in req.url, remove it for the middleware and vue-router if (self.options.router.base !== '/' && req.url.indexOf(self.options.router.base) === 0) { // Compatibility with base url for dev server req.url = req.url.replace(self.options.router.base, '/') } // Serve static/ files yield self.serveStatic(req, res) // Serve .nuxt/dist/ files (only for production) if (!self.dev && req.url.indexOf(self.options.build.publicPath) === 0) { const url = req.url req.url = req.url.replace(self.options.build.publicPath, '/') yield self.serveStaticNuxt(req, res) /* istanbul ignore next */ req.url = url } }) .then(() => { /* istanbul ignore if */ if (this.dev && req.url.indexOf(self.options.build.publicPath) === 0 && req.url.includes('.hot-update.json')) { res.statusCode = 404 return { html: '' } } return this.renderRoute(req.url, context) }) .then(({ html, error, redirected }) => { if (redirected) { return html } if (error) { res.statusCode = context.nuxt.error.statusCode || 500 } res.setHeader('Content-Type', 'text/html; charset=utf-8') res.setHeader('Content-Length', Buffer.byteLength(html)) res.end(html, 'utf8') return html }) .catch((err) => { /* istanbul ignore if */ if (context.redirected) { console.error(err) // eslint-disable-line no-console return err } const html = this.errorTemplate({ error: err, stack: ansiHTML(encodeHtml(err.stack)) }) res.statusCode = 500 res.setHeader('Content-Type', 'text/html; charset=utf-8') res.setHeader('Content-Length', Buffer.byteLength(html)) res.end(html, 'utf8') return err }) } export function renderRoute (url, context = {}) { debug(`Rendering url ${url}`) // Add url and isSever to the context context.url = url context.isServer = true // Call renderToSting from the bundleRenderer and generate the HTML (will update the context as well) const self = this return co(function * () { let APP = yield self.renderToString(context) if (!context.nuxt.serverRendered) { APP = '<div id="__nuxt"></div>' } const m = context.meta.inject() let HEAD = m.meta.text() + m.title.text() + m.link.text() + m.style.text() + m.script.text() + m.noscript.text() if (self.options.router.base !== '/') { HEAD += `<base href="${self.options.router.base}">` } HEAD += context.renderResourceHints() + context.renderStyles() APP += `<script type="text/javascript">window.__NUXT__=${serialize(context.nuxt, { isJSON: true })}</script>` APP += context.renderScripts() const html = self.appTemplate({ HTML_ATTRS: 'data-n-head-ssr ' + m.htmlAttrs.text(), BODY_ATTRS: m.bodyAttrs.text(), HEAD, APP }) return { html, error: context.nuxt.error, redirected: context.redirected } }) } // Function used to do dom checking via jsdom let jsdom = null export function renderAndGetWindow (url, opts = {}) { /* istanbul ignore if */ if (!jsdom) { try { jsdom = require('jsdom') } catch (e) { console.error('Fail when calling nuxt.renderAndGetWindow(url)') // eslint-disable-line no-console console.error('jsdom module is not installed') // eslint-disable-line no-console console.error('Please install jsdom with: npm install --save-dev jsdom') // eslint-disable-line no-console process.exit(1) } } let virtualConsole = jsdom.createVirtualConsole().sendTo(console) if (opts.virtualConsole === false) { virtualConsole = undefined } url = url || 'http://localhost:3000' return new Promise((resolve, reject) => { jsdom.env({ url: url, features: { FetchExternalResources: ['script', 'link'], ProcessExternalResources: ['script'] }, virtualConsole, done (err, window) { if (err) return reject(err) // Mock window.scrollTo window.scrollTo = function () {} // If Nuxt could not be loaded (error from the server-side) if (!window.__NUXT__) { let error = new Error('Could not load the nuxt app') error.body = window.document.getElementsByTagName('body')[0].innerHTML return reject(error) } // Used by nuxt.js to say when the components are loaded and the app ready window.onNuxtReady(() => { resolve(window) }) } }) }) }
JavaScript
0
@@ -4638,21 +4638,19 @@ le = + new jsdom. -create Virt
955221a2d3bbab6099a1a4678608c2e244003a6c
Use UTF-8 when render html template.
lib/render.js
lib/render.js
var fs = require('fs'), hogan = require('hogan.js'), log4js = require('log4js'), mime = require('mime'), path = require('path'), url = require('url'), util = require('util'); var logger = log4js.getLogger('crossweb'); var ObjectRender = function ObjectRender (object) { this.object = object; } ObjectRender.prototype.render = function (request, response, callback) { callback = callback || function () {}; var object = this.object; if (object) { if (typeof(object) === 'string') { response.writeHead(200, { 'Content-Type': 'text/plain' }); response.write(object); } else { response.writeHead(200, { 'Content-Type': 'application/json' }); response.write(JSON.stringify(object)); } } response.end(); callback(); } var FileRender = function FileRender(file) { this.file = file; } FileRender.prototype.render = function (request, response, callback) { callback = callback || function () {}; var file = this.file; if (file && path.existsSync(file)) { var stat = fs.statSync(file); if (stat.isDirectory()) { var resource = url.parse(request.url); response.writeHead(301, { 'Location': url.resolve(resource.pathname, '/index.html') }); response.end(); callback(); } else { response.writeHead(200, { 'Content-Type': mime.lookup(file), 'Content-Length': stat.size, 'Cache-Control': 'public, max-age=3600' }); var stream = fs.createReadStream(file); stream.on('data', function (data) { response.write(data); }); stream.on('end', function () { response.end(); callback(); }); } } else { response.writeHead(404, { 'Content-Type': 'text/plain' }); response.end(); callback(); } } var RedirectRender = function RedirectRender(url, type) { this.url = url; this.type = type || RedirectRender.PERMANENT; } RedirectRender.PERMANENT = 301; RedirectRender.TEMPORARY = 302; RedirectRender.prototype.render = function (request, response, callback) { callback = callback || function () {}; var url = this.url; var type = this.type; if (url && type) { response.writeHead(type, { 'Location': url }); } else { response.writeHead(503, {}); } response.end(); callback(); } var HoganRender = function HoganRender(file, object) { this.file = file; this.object = object; } HoganRender.cache = {}; HoganRender.prototype.render = function (request, response, callback) { callback = callback || function () {}; var file = this.file; var object = this.object; response.writeHead(200, { 'Content-Type': 'text/html' }); if (file && path.existsSync(file) && object && typeof(object) === 'object') { if (HoganRender.cache[file]) { var template = HoganRender.cache[file]; var output = template.render(object); response.end(output); } else { var save = function (file, callback) { fs.readFile(file, 'utf8', function (error, data) { var template = hogan.compile(data); HoganRender.cache[file] = template; callback(template); }); } fs.watch(file, function (event, filename) { save(file, function (template) { logger.debug ('Reload template'); }); }); save(file, function (template) { var output = template.render(object); response.end(output); callback(); }); } } else { response.writeHead(503, {}); response.end(); callback(); } } exports.FileRender = FileRender; exports.HoganRender = HoganRender; exports.ObjectRender = ObjectRender; exports.RedirectRender = RedirectRender;
JavaScript
0
@@ -2768,16 +2768,31 @@ ext/html +; charset=UTF-8 '%0A %7D);%0A
8176f75ade3ff0a641700c74cf5e02e0668d7ccf
fix router
lib/router.js
lib/router.js
FlowRouter.route('/', { name: 'start', action: function(params, queryParams) { BlazeLayout.render('layout', { footer: 'footer', main: 'start', nav: 'header', }); } }); var privateRoutes = FlowRouter.group({ triggersEnter: [requireLogin] }); privateRoutes.route('/basic-info', { name: 'basicInfo', action: function(params, queryParams) { BlazeLayout.render('layout', { footer: 'footer', main: 'basicInfo', nav: 'header', }); } }); privateRoutes.route('/sports-configuration', { name: 'sportsConfiguration', action: function(params, queryParams) { BlazeLayout.render('layout', { footer: 'footer', main: 'sportsConfiguration', nav: 'header', }); }, //subscriptions: function(params) { // this.register('allActivity', Meteor.subscribe('allActivity')); //}, }); privateRoutes.route('/activityconfiguration/:id', { name: 'activityConfiguration', action: function(params, queryParams) { BlazeLayout.render('layout', { footer: 'footer', main: 'activityConfiguration', nav: 'header', }); }, //subscriptions: function(params) { // this.register('allActivity', Meteor.subscribe('allActivity')); //}, }); privateRoutes.route('/activityconfiguration', { name: 'activityOverview', action: function(params, queryParams) { BlazeLayout.render('layout', { footer: 'footer', main: 'activityOverview', nav: 'header', }); }, //subscriptions: function(params) { // this.register('allActivity', Meteor.subscribe('allActivity')); //}, }); privateRoutes.route('/commit-configuration', { name: 'commmitConfiguration', action: function(params, queryParams) { BlazeLayout.render('layout', { footer: 'footer', main: 'commitConfiguration', nav: 'header', }); } }); privateRoutes.route('/activity-dashboard', { name: 'activityDashboard', action: function(params, queryParams) { BlazeLayout.render('layout', { footer: 'footer', main: 'activityDashboard', nav: 'header', }); subscriptions: function(params) { this.register('userSessionData', Meteor.subscribe('userSessionData')); }, } }); FlowRouter.notFound = { action: function() { BlazeLayout.render('layout', { footer: 'footer', main: 'notFound', nav: 'header', }); } }; function requireLogin(context, redirect, stop) { if (Meteor.userId()) { } else { FlowRouter.go('/'); } }
JavaScript
0.000001
@@ -2339,24 +2339,27 @@ %7D);%0A +%7D,%0A subscrip @@ -2380,28 +2380,24 @@ n(params) %7B%0A - this @@ -2471,20 +2471,10 @@ - %7D,%0A %7D +, %0A%7D); @@ -2749,21 +2749,16 @@ rId()) %7B -%0A %7D else %7B
98d9e1351488830eefc1f525e93c883bb475cb49
Fix gulp jekyll and watch
Gulpfile.js
Gulpfile.js
const child = require('child_process'); const browserSync = require('browser-sync').create(); const gulp = require('gulp'); const gutil = require('gulp-util'); const sass = require('gulp-sass'); const siteRoot = '_site'; const cssFiles = 'scss/app.scss'; gulp.task('css', () => { gulp.src(cssFiles) .pipe(sass({ "includePaths": [ './node_modules/foundation-sites/scss', './node_modules/normalize-scss/sass' ] })) .pipe(gulp.dest('css')); }); gulp.task('jekyll', () => { const jekyll = child.spawn('bundler', ['exec', 'jekyll', 'build', '--incremental-rebuild' ]); const jekyllLogger = (buffer) => { buffer.toString() .split(/\n/) .forEach((message) => gutil.log('Jekyll: ' + message)); }; jekyll.stdout.on('data', jekyllLogger); jekyll.stderr.on('data', jekyllLogger); }); gulp.task('jekyll', () => { const jekyll = child.spawn('jekyll', ['build']); const jekyllLogger = (buffer) => { buffer.toString() .split(/\n/) .forEach((message) => gutil.log('Jekyll: ' + message)); }; jekyll.stdout.on('data', jekyllLogger); jekyll.stderr.on('data', jekyllLogger); }); gulp.task('serve', () => { browserSync.init({ files: [siteRoot + '/**'], port: 4000, server: { baseDir: siteRoot } }); gulp.watch(cssFiles, ['css']); }); gulp.task('default', ['css', 'jekyll', 'serve']); gulp.task('build', ['css', 'jekyll-build']);
JavaScript
0
@@ -620,24 +620,16 @@ 'build', -%0A '--incr @@ -639,22 +639,20 @@ ntal --rebuild'%0A +', '--watch' %5D);%0A @@ -920,32 +920,38 @@ ulp.task('jekyll +-build ', () =%3E %7B%0A c @@ -976,16 +976,36 @@ d.spawn( +'bundler', %5B'exec', 'jekyll' @@ -1006,17 +1006,16 @@ ekyll', -%5B 'build'%5D @@ -1464,24 +1464,29 @@ p.watch( +'s css -Files +/*.scss' , %5B'css'
3b839ac963e45182d959ad1593d11988345220cd
remove duplicate undefined check
lib/router.js
lib/router.js
// global configuration Router.waitOn(function() { return Meteor.subscribe('allplaylists'); }); // route specific configuration Router.map(function() { this.route('home', {path: '/'}); this.route('playlists', { data: { playlists: function() { return Playlists.find({},{sort: {createdAt: -1}, limit: 5}); } }, }); this.route('playlist', { path: '/playlist/:_id', waitOn: function() { return Meteor.subscribe('playlist',this.params._id); }, onBeforeAction: function() { if(this.data()) { var playlist = this.data(); if (!playlist) return; var songs = playlist.songs || []; //add another subscription to waiting list this.subscribe('songs', songs).wait(); } }, loadingTemplate: 'playlist', notFoundTemplate: 'playlistNotFound', data: function() { //return all current client side playlists (just one ;) return Playlists.findOne(this.params._id); }, }); this.route('loved', { data: { lovedSongs: function() { //get current user var user = Meteor.users.findOne({_id: Meteor.userId()}); //find song info in the cache for each song return Songs.find({_id:{$in:user.profile.lovedSongs}}); } } }); this.route('friends'); });
JavaScript
0.000008
@@ -427,18 +427,22 @@ ion() %7B%0A -%09%09 + return M @@ -493,17 +493,20 @@ %0A %7D,%0A -%09 + onBefore @@ -530,30 +530,8 @@ ) %7B%0A -%09%09if(this.data()) %7B%0A%09%09 @@ -560,19 +560,20 @@ data();%0A -%09%09%09 + if (!p @@ -585,20 +585,24 @@ st)%0A -%09%09%09%09 + return;%0A %09%09%09 @@ -597,19 +597,20 @@ return;%0A -%09%09%09 + var so @@ -637,19 +637,20 @@ %7C%7C %5B%5D;%0A -%09%09%09 + //add @@ -686,19 +686,20 @@ ng list%0A -%09%09%09 + this.s @@ -735,13 +735,12 @@ ();%0A -%09%09%7D%0A%09 + %7D,%0A @@ -1224,18 +1224,16 @@ %7D%0A %7D);%0A - %0A this.
76d8ea64b99f39f6a7d4c53facff385765439db2
Allow threshold stage to be applied to unresizeables
Gulpfile.js
Gulpfile.js
/* ----------------------------------------------------------------------------- * VARS * -------------------------------------------------------------------------- */ // Project base paths // ----------------------------------------------------------------------------- var basePaths = { src: 'Source/', dest: 'Compiled Size Packs/' }, // Paths for file assets // ----------------------------------------------------------------------------- paths = { img: { src: basePaths.src, dest: basePaths.dest } }, // custom plugin settings // ----------------------------------------------------------------------------- settings = { imagemin: { // Default is 3 (16 trials) optimizationLevel: 3 } }, // watched filename patterns // ----------------------------------------------------------------------------- watchedPatterns = { img: paths.img.src + '**/*.png' }; /* ----------------------------------------------------------------------------- * GULP PLUGINS * -------------------------------------------------------------------------- */ var gulp = require('gulp'), $ = require('gulp-load-plugins')({ pattern: '*', camelize: true }); /* ----------------------------------------------------------------------------- * Global Functions * -------------------------------------------------------------------------- */ /* ----------------------------------------------------------------------------- * TASKS * -------------------------------------------------------------------------- */ /* ----------------------------------------------------------------------------- * Task - optimise * -------------------------------------------------------------------------- */ gulp.task('optimise', function() { var initialSize = 512, // Define original base texture size suff = 'x', // suffix to add onto created size pack directories fileStream = gulp.src(paths.img.src + '**', // source everything { base: paths.img.src } ); function resizeStream (stream, size) { var pctScale = (size / initialSize * 100).toString() + '%', customDirname = size.toString() + suff + '/', ignoreStuff = $.ignore('**/*.{psb,psd}'), filterPNG = $.filter(['**/*.png'], { restore: true }), filterResizeables = $.filter(['**/*.png', '!**/{gui,guis,font,fonts}/**/*.png', '!**/pack.png'], { restore: true }); return stream .pipe(ignoreStuff) .pipe($.clone()) .pipe($.rename(function (path) { // { dirname: 'Example Project 2', // basename: 'test1', // extname: '.png' } path.dirname = customDirname + path.dirname; })) .pipe($.newer(paths.img.dest)) // Cache everything past this point, name the cache using dirname .pipe($.cached(customDirname)) // Do the following steps to PNGs only( i.e. no .txt, .mcmeta files) .pipe(filterPNG) // Do the following to ONLY resizeables .pipe(filterResizeables) // Use gulp-gm to resize and apply threshold (remove transparency) to images .pipe($.gm(function (imageFile) { return imageFile // Ensure 8-bit RGB .bitdepth(8) // Bilinear .filter('Triangle') // Resize to % scale .resize(pctScale, '%') // Ensure no transparent edges .operator('Opacity', 'Threshold', 50, '%'); })) .pipe(filterResizeables.restore) // pass all images through gulp-imagemin .pipe($.imagemin(settings.imagemin)) // Restore non-PNG files to stream .pipe(filterPNG.restore) .pipe(gulp.dest(paths.img.dest)); } // /function resizeStream return $.mergeStream( resizeStream(fileStream, 512), resizeStream(fileStream, 256), resizeStream(fileStream, 128), resizeStream(fileStream, 64), resizeStream(fileStream, 32) ); }); // default task // ----------------------------------------------------------------------------- gulp.task('default', function () { console.log('\nWatching for changes:\n'); // Watch Images // ------------------------------------------------------------------------- console.log('- IMG Files: ' + watchedPatterns.img); gulp.watch(watchedPatterns.img, ['optimise']); console.log('\n'); }); // /default
JavaScript
0.000001
@@ -3217,53 +3217,8 @@ ize -and apply threshold (remove transparency) to imag @@ -3591,21 +3591,274 @@ le, '%25') +; %0A + %7D))%0A .pipe(filterResizeables.restore)%0A // Use gulp-gm to apply threshold to (remove partial transparency from) images%0A .pipe($.gm(function (imageFile) %7B%0A return imageFile%0A @@ -3903,21 +3903,29 @@ nt edges -%0A + on all PNGs%0A @@ -4004,63 +4004,10 @@ - %7D))%0A .pipe(filterResizeables.restore +%7D) )%0A
66af19a0b95b7b3f8f64c1d23bd5a11e5ad73b5c
Fix login screen
lib/router.js
lib/router.js
Router.configure({ layoutTemplate: 'layout', waitOn: function() { var userId = Meteor.userId(); return [Meteor.subscribe('userCourses', userId), Meteor.subscribe('userNotifications', userId), Meteor.subscribe('recentQuestions')] } // loadingTemplate: 'loading', }); Router.map(function() { this.route('home', { path : '/activity', loadingTemplate: 'activityLoading', after: function() { if (!(Meteor.loggingIn() || Meteor.user())) { this.redirect('login'); } } }); this.route('questionsList', { path : '/courses/:_id/questions', loadingTemplate: 'questionsListLoading', waitOn: function() { return Meteor.subscribe('courseQuestions', this.params._id); }, data : function() { return { questions : Questions.find( { courseId : this.params._id }, {sort: {date: -1}} ) , _id : this.params._id }; } }); this.route('newQuestion' ,{ path : '/courses/:_id/questions/create', data : function() { return Courses.findOne(this.params._id); } }); this.route('question', { path : '/courses/:courseId/questions/:_id', loadingTemplate: 'questionLoading', waitOn: function() { return Meteor.subscribe('questionAnswers', this.params._id); }, data : function() { return Questions.findOne(this.params._id); } }); this.route('newAnswer', { path : '/courses/:courseId/questions/:_id/answer', data : function() { return Questions.findOne(this.params._id); } }); this.route('login', { layoutTemplate: 'layout', loadingTemplate: 'loginLoading', path: '/', after: function() { if (Meteor.loggingIn() || Meteor.user()) { //cleanPreviousRoutes(); this.redirect('home'); } } }); this.route('auth', { path: '/auth/callback', action: function () { Meteor.call('authenticate', this.params.code, function(err, username) { console.log(username); Meteor.loginWithPassword({ username: username }, 'cerberus', function(err) { console.log('Problem with login: ', err); }); }); this.redirect(Router.routes.home.path()); } }); this.route('logout', { action: function() { Meteor.logout(function (err) { if (err) { console.error(err); } }); //cleanPreviousRoutes(); this.redirect(Router.routes.login.path()); } }); this.route('profile', { }); this.route('courses', { loadingTemplate: 'coursesLoading', waitOn: function() { return Meteor.subscribe('allCourses'); } }); this.route('userProfile', { path: '/users/:_id/profile', waitOn: function() { return Meteor.subscribe('user', this.params._id); }, data: function() { return { user: Meteor.users.findOne(this.params._id) }; } }); }); function PreviousRoute(routeName, routeParams) { var route = { route: routeName, params: routeParams || {} }; var previousRoutes = Session.get('previousRoutes') || []; previousRoutes.push(route); Session.set('previousRoutes', previousRoutes); } function cleanPreviousRoutes() { Session.set('previousRoutes', []); }
JavaScript
0.000061
@@ -1784,32 +1784,34 @@ ayout',%0A +// loadingTemplate:
fc8990fc45aaedafc436baf963fb005d0dbe1530
Add subscriptions
lib/router.js
lib/router.js
var subscriptions = new SubsManager(); Router.configure({ loadingTemplate: 'loading', notFoundTemplate: 'notFound', }); Router.route('/', { layoutTemplate: 'layout', name: 'home', waitOn: function() { return subscriptions.subscribe('allVolunteers'); }, fastRender: true }); Router.route('/myProfile', { layoutTemplate: 'layout', name: 'myProfile', waitOn: function() { return subscriptions.subscribe('oneQuestionAtATime', Meteor.userId()); }, data: function() { return UserQuestions.findOne({ userId: Meteor.userId(), answered: false, deprecated: false }, { sort: { level: 1, version: 1 } }); }, fastRender: false }); Router.route('/myDay', { layoutTemplate: 'layout', name: 'myDay', fastRender: false }); Router.route('/meeting', { layoutTemplate: 'layout', name: 'meeting', fastRender: false }); Router.route('/admin', { layoutTemplate: 'adminLayout', name: 'admin', waitOn: function() { return [subscriptions.subscribe('allUniverses'), subscriptions.subscribe('allWorkshops'), subscriptions.subscribe('allQuestionsGroups'), subscriptions.subscribe('allEkloreQuestions')]; }, fastRender: true }); Router.route('/admin/universes/new', { layoutTemplate: 'adminLayout', name: 'newUniverse', fastRender: false }); Router.route('/admin/universes/:_id/edit', { layoutTemplate: 'adminLayout', name: 'editUniverse', waitOn: function() { return [subscriptions.subscribe('anUniverse', this.params._id), subscriptions.subscribe('allWorkshops')]; }, data: function() { return Universes.findOne(this.params._id); }, fastRender: true }); Router.route('/admin/workshops/new', { layoutTemplate: 'adminLayout', name: 'newWorkshop', fastRender: false }); Router.route('/admin/workshops/:_id/edit', { layoutTemplate: 'adminLayout', name: 'editWorkshop', waitOn: function() { return [subscriptions.subscribe('aWorkshop', this.params._id), subscriptions.subscribe('allUniverses')]; }, data: function() { return Workshops.findOne(this.params._id); }, fastRender: true }); Router.route('/admin/questionsGroups/new', { layoutTemplate: 'adminLayout', name: 'newQuestionsGroup', fastRender: false }); Router.route('/admin/questionsGroups/:_id/edit', { layoutTemplate: 'adminLayout', name: 'editQuestionsGroup', waitOn: function() { return [subscriptions.subscribe('aQuestionsGroup', this.params._id), subscriptions.subscribe('allEkloreQuestions')]; }, data: function() { return QuestionsGroups.findOne(this.params._id); }, fastRender: true }); Router.route('/admin/ekloreQuestions/new', { layoutTemplate: 'adminLayout', name: 'newEkloreQuestion', fastRender: false }); Router.route('/admin/ekloreQuestions/:_id/edit', { layoutTemplate: 'adminLayout', name: 'editEkloreQuestion', waitOn: function() { return [subscriptions.subscribe('aQuestionsGroup', this.params._id), subscriptions.subscribe('allEkloreQuestions')]; }, data: function() { return QuestionsGroups.findOne(this.params._id); }, fastRender: true });
JavaScript
0.000001
@@ -2633,16 +2633,135 @@ stion',%0A +%09waitOn: function() %7B%0A%09%09return %5Bsubscriptions.subscribe('allUniverses'), subscriptions.subscribe('allWorkshops')%5D;%0A%09%7D,%0A %09fastRen
c26ac4a4519fb70f3aad8492e129cef9c2615428
Remove wreck module
lib/routes.js
lib/routes.js
import Path from 'path'; import wreck from 'wreck'; module.exports = [ // Client routes { method: 'GET', path: '/', handler(request, reply) { reply.view('index.html'); } }, { method: 'PUT', path: '/widgets/{widget_id}/edit', handler: { proxy: { mapUri: (request, callback) => { callback(null, 'http://spa.tglrw.com:4000/widgets/' + request.params.widget_id); }, passThrough: true, xforward: true } } }, // Serve static assets { method: 'GET', path: '/{path*}', handler: { directory: { path: [ Path.join(process.cwd(), 'dist'), Path.join(process.cwd(), 'public') ] } } } ];
JavaScript
0
@@ -21,35 +21,8 @@ th'; -%0Aimport wreck from 'wreck'; %0A%0Amo
d1b496a3e0773dafebb4685433d00b5f22e16cd5
create article
app/actions/articles.js
app/actions/articles.js
/* eslint consistent-return: 0, no-else-return: 0*/ import { polyfill } from 'es6-promise'; import request from 'axios'; import md5 from 'spark-md5'; import * as types from 'types'; polyfill(); /* * Utility function to make AJAX requests using isomorphic fetch. * You can also use jquery's $.ajax({}) if you do not want to use the * /fetch API. * Note: this function relies on an external variable `API_ENDPOINT` * and isn't a pure function * @param Object Data you wish to pass to the server * @param String HTTP method, e.g. post, get, put, delete * @param String endpoint * @return Promise */ function makeArticleRequest(method, title, data, api = '/article') { return request[method](api + (title ? ('/' + title) : ''), data); } /* * @param data * @return a simple JS object */ function createArticleRequest(data) { return { type: types.CREATE_ARTICLE_REQUEST, title: data.title, content: data.content }; } function createArticleSuccess() { return { type: types.CREATE_ARTICLE_SUCCESS }; } function createArticleFailure(data) { return { type: types.CREATE_ARTICLE_FAILURE, title: data.title, error: data.error }; } function createArticleDuplicate() { return { type: types.CREATE_ARTICLE_DUPLICATE }; } // This action creator returns a function, // which will get executed by Redux-Thunk mtitledleware // This function does not need to be pure, and thus allowed // to have stitlee effects, including executing asynchronous API calls. export function createArticle(content) { return (dispatch, getState) => { // If the content box is empty if (content.trim().length <= 0) return; const title = md5.hash(content); // Redux thunk's mtitledleware receives the store methods `dispatch` // and `getState` as parameters const { article } = getState(); const data = { count: 1, title, content }; // Conditional dispatch // If the article already exists, make sure we emit a dispatch event if (article.articles.filter(articleItem => articleItem.title === title).length > 0) { // Currently there is no reducer that changes state for this // For production you would titleeally have a message reducer that // notifies the user of a duplicate article return dispatch(createArticleDuplicate()); } // First dispatch an optimistic update dispatch(createArticleRequest(data)); return makeArticleRequest('post', title, data) .then(res => { if (res.status === 200) { // We can actually dispatch a CREATE_ARTICLE_SUCCESS // on success, but I've opted to leave that out // since we already dtitle an optimistic update // We could return res.json(); return dispatch(createArticleSuccess()); } }) .catch(() => { return dispatch(createArticleFailure({ title, error: 'Oops! Something went wrong and we couldn\'t create your article'})); }); }; } // Fetch posts logic export function fetchArticles() { return { type: types.GET_ARTICLES, promise: makeArticleRequest('get') }; } export function destroyArticle(title, index) { return dispatch => { dispatch(destroy(index)); return makeArticleRequest('delete', title); // do something with the ajax response // You can also dispatch here // E.g. // .then(response => {}); }; }
JavaScript
0.000006
@@ -1537,16 +1537,23 @@ Article( +title, content) @@ -1669,24 +1669,27 @@ return;%0A%0A + // const title @@ -1878,24 +1878,8 @@ = %7B%0A - count: 1,%0A
a385f45371e9467f7d2ef8dab7b9422625671c76
add all intrinsic functions to schema
lib/schema.js
lib/schema.js
var yaml = require('js-yaml'), _ = require('lodash'); var tags = [ { short: 'Include', full: 'Fn::Include', type: 'scalar' }, { short: 'Include', full: 'Fn::Include', type: 'mapping' }, { short: 'Map', full: 'Fn::Map', type: 'sequence' }, /* Map: 'sequence', Flatten: 'sequence', Merge: 'sequence', // http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html Base64': 'sequence', FindInMap, GetAtt, GetAZs, ImportValue, Join, Select, Sub,*/ ].map(function(fn) { return new yaml.Type('!' + fn.short, { kind: fn.type, resolve: function() { console.log('foo') return true; }, represent: function() { console.log('foo') return true; }, construct: function(obj) { return _.fromPairs([[fn.full, obj]]); } }); }); module.exports = yaml.Schema.create(tags);
JavaScript
0.000003
@@ -245,39 +245,53 @@ ,%0A -/*%0A Map: 'sequence',%0A Flatten +%7B short: 'Flatten', full: 'Fn::Flatten', type : 's @@ -302,16 +302,54 @@ nce' + %7D ,%0A -Merg +%7B short: 'Merge', full: 'Fn::Merge', typ e: ' @@ -353,24 +353,26 @@ : 'sequence' + %7D ,%0A // http: @@ -468,277 +468,975 @@ l%0A -Base64': 'sequence',%0A FindInMap,%0A GetAtt,%0A GetAZs,%0A ImportValue,%0A Join,%0A Select,%0A Sub,*/%0A%5D.map(function(fn) %7B%0A return new yaml.Type('!' + fn.short, %7B%0A kind: fn.type,%0A resolve: function() %7B%0A console.log('foo')%0A return true;%0A %7D,%0A represent: +%7B short: 'Base64', full: 'Fn::Base64', type: 'scalar' %7D,%0A %7B short: 'Base64', full: 'Fn::Base64', type: 'mapping' %7D,%0A %7B short: 'FindInMap', full: 'Fn::FindInMap', type: 'sequence' %7D,%0A %7B short: 'GetAtt', full: 'Fn::GetAtt', type: 'sequence' %7D,%0A %7B short: 'GetAZs', full: 'Fn::GetAZs', type: 'sequence' %7D,%0A %7B short: 'ImportValue', full: 'Fn::ImportValue', type: 'scalar' %7D,%0A %7B short: 'ImportValue', full: 'Fn::ImportValue', type: 'mapping' %7D,%0A %7B short: 'Join', full: 'Fn::Join', type: 'sequence' %7D,%0A %7B short: 'Select', full: 'Fn::Select', type: 'sequence' %7D,%0A %7B short: 'Sub', full: 'Fn::Sub', type: 'sequence' %7D,%0A %7B short: 'Sub', full: 'Fn::Sub', type: 'mapping' %7D,%0A %7B short: 'Sub', full: 'Fn::Sub', type: 'scalar' %7D,%0A %7B short: 'Ref', full: 'Ref', type: 'scalar' %7D,%0A // http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/continuous-delivery-codepipeline-action-reference.html%0A %7B short: 'GetParam', full: 'Fn::GetParam', type: 'sequence' %7D,%0A%5D.map( func @@ -1444,61 +1444,72 @@ ion( +fn ) %7B%0A - console.log('foo')%0A return true;%0A %7D +return new yaml.Type('!' + fn.short, %7B%0A kind: fn.type ,%0A
7190431213cf4051f7d46a5ca5ce152a879e1dc8
Change Scribe chain cleanup
lib/scribe.js
lib/scribe.js
'use strict'; if (process.env['NODE_ENV'] === 'debug') { require('debug-trace')({ always: true }); } const crypto = require('crypto'); const monitor = require('fast-json-patch'); // Fabric Components const State = require('./state'); /** * Simple tag-based recordkeeper. * @property {Object} config Current configuration. */ class Scribe extends State { /** * The "Scribe" is a simple tag-based recordkeeper. * @param {Object} config General configuration object. * @param {Boolean} config.verbose Should the Scribe be noisy? */ constructor (config) { super(config); // assign the defaults; this.config = Object.assign({ verbose: true, path: './data/scribe' }, config); this.tags = []; this.state = new State(config); // monitor for changes this.observer = monitor.observe(this.state['@data']); // signal ready this.status = 'ready'; Object.defineProperty(this, 'tags', { enumerable: false }); return this; } now () { // return new Date().toISOString(); return new Date().getTime(); } sha256 (data) { return crypto.createHash('sha256').update(data).digest('hex'); } /** * Blindly bind event handlers to the {@link Source}. * @param {Source} source Event stream. * @return {Scribe} Instance of the {@link Scribe}. */ trust (source) { source.on('changes', async function (changes) { console.log('[SCRIBE]', '[EVENT:CHANGES]', 'apply these changes to local state:', changes); }); source.on('message', async function (message) { console.log('[SCRIBE]', '[EVENT:MESSAGE]', 'source emitted message:', message); }); source.on('transaction', async function (transaction) { console.log('[SCRIBE]', '[EVENT:TRANSACTION]', 'apply this transaction to local state:', transaction); console.log('[PROPOSAL]', 'apply this transaction to local state:', transaction); }); return this; } /** * Use an existing Scribe instance as a parent. * @param {Scribe} scribe Instance of Scribe to use as parent. * @return {Scribe} The configured instance of the Scribe. */ inherits (scribe) { return this.tags.push(scribe.config.namespace); } log (...inputs) { let now = this.now(); inputs.unshift(`[${this.constructor.name.toUpperCase()}]`); inputs.unshift(`[${now}]`); if (this.config && this.config.verbose) { console.log.apply(null, this.tags.concat(inputs)); } return this.emit('info', this.tags.concat(inputs)); } error (...inputs) { let now = this.now(); inputs.unshift(`[${this.constructor.name.toUpperCase()}]`); inputs.unshift(`[${now}]`); if (this.config.verbose) { console.error.apply(null, this.tags.concat(inputs)); } return this.emit('error', this.tags.concat(inputs)); } warn (...inputs) { let now = this.now(); inputs.unshift(`[${this.constructor.name.toUpperCase()}]`); inputs.unshift(`[${now}]`); if (this.config.verbose) { console.warn.apply(null, this.tags.concat(inputs)); } return this.emit('warning', this.tags.concat(inputs)); } debug (...inputs) { let now = this.now(); inputs.unshift(`[${this.constructor.name.toUpperCase()}]`); inputs.unshift(`[${now}]`); if (this.config.verbose) { console.debug.apply(null, this.tags.concat(inputs)); } return this.emit('debug', this.tags.concat(inputs)); } async open () { this.status = 'opened'; return this; } async close () { this.status = 'closed'; return this; } async start () { // console.log('[SCRIBE]', `[${this.constructor.name.toUpperCase()}]`, 'starting with state:', this.state); this.state.on('changes', function (changes) { console.log('got changes in scribe:', changes); monitor.applyPatches(this.state['@data'], changes); }); this.status = 'started'; return this; } async stop () { this.status = 'stopped'; return this; } } module.exports = Scribe;
JavaScript
0
@@ -3651,116 +3651,33 @@ -// console.log('%5BSCRIBE%5D', %60%5B$%7Bthis.constructor.name.toUpperCase()%7D%5D%60, 'starting with state:', this.state);%0A +this.status = 'starting'; %0A @@ -3758,20 +3758,19 @@ ges in s -crib +tat e:', cha @@ -3803,30 +3803,24 @@ Patches(this -.state %5B'@data'%5D, c @@ -3832,24 +3832,46 @@ s);%0A %7D);%0A + await this.open(); %0A this.st @@ -3888,17 +3888,16 @@ arted';%0A -%0A retu @@ -3924,24 +3924,78 @@ c stop () %7B%0A + this.status = 'stopping';%0A await this.close();%0A this.sta
6b62359be282ea58f7fc8fd5a86c600ac0983fb2
Label had the wrong text
app/components/Login.js
app/components/Login.js
import React, {Component, PropTypes} from 'react'; import {Alert, Button, ControlLabel, FormGroup, FormControl} from 'react-bootstrap'; import ErrorMsg from './ErrorMsg'; import Icon from './Icon'; const STR_MISSING_CREDENTIALS = 'Please enter both your username and password'; export default class Login extends Component { constructor(props, context) { super(props, context); this.state = { password: '', username: '' }; } handleChange = (event) => { var {currentTarget: {id, value}} = event; this.setState( { [id]: value } ); } handleSubmit = (event) => { event.preventDefault(); var {password, username} = this.state; password = password.trim(); username = username.trim(); if (!username || !password) { this.props.loginFailure( { errors: STR_MISSING_CREDENTIALS } ); } else { this.props.login(username, password); } } render() { var props = this.props; let {loginErrors, loading, online} = props; let {password, username} = this.state; var {errors} = loginErrors; var loginErrorsEl; if (errors) { var title = errors === STR_MISSING_CREDENTIALS ? 'Oops! Missing a field.' : 'Github responded with:'; if (loginErrors.response && loginErrors.response.errorText) { title = loginErrors.response.errorText; } loginErrorsEl = ( <ErrorMsg displayReload={false} id="loginErrors" message={errors} statusText={title} /> ); } var cssClass = 'app-container login'; cssClass += props.loading ? ' loading' : ' loaded'; cssClass += !props.online ? ' status-offline' : ''; return <div className={cssClass}> <form action="" id="fm" onSubmit={this.handleSubmit}> <h1 id="pullsTitle">{'Github Pulls'}</h1> {loginErrorsEl} <FormGroup className={username ? 'has-value' : null} controlId="username"> <ControlLabel>Github username</ControlLabel> <FormControl onChange={this.handleChange} placeholder="Github username" ref="username" type="text" value={username} /> </FormGroup> <FormGroup className={password ? 'has-value' : null} controlId="password"> <ControlLabel>Github username</ControlLabel> <FormControl onChange={this.handleChange} placeholder="Github password" ref="password" type="password" value={password} /> </FormGroup> <Button bsStyle="primary" type="submit">{'Login'}</Button> </form> <div className="loading-bar"></div> </div>; } } Login.defaultProps = { message: '', statusText: '' }; Login.propTypes = { login: PropTypes.func.isRequired };
JavaScript
0.998516
@@ -2122,32 +2122,32 @@ abel%3EGithub -username +password %3C/ControlLab
75bfdba081b068502bb437568eb5e629e295ba1e
Tweak previous commit.
lib/search.js
lib/search.js
'use strict'; const index = require('config').get('elasticsearch.index'); const config = require('config').get('search'); const isNumber = require('./util/isNumber'); const fields = ['name', 'version', 'description', 'keywords', 'publisher', 'evaluation', 'score']; class Search { constructor(client) { this.client = client; } get(value, from, size, effect, weights) { // Validation and defaults value = typeof value === 'string' ? value : ''; from = isNumber(from) ? Number(from) : 0; size = isNumber(size) ? Number(size) : config.get('size'); effect = isNumber(effect) ? Number(effect) : config.get('effect'); weights = typeof weights === 'object' ? weights : {}; weights = { quality: isNumber(weights.quality) ? Number(weights.quality) : config.get('weights.quality'), popularity: isNumber(weights.popularity) ? Number(weights.popularity) : config.get('weights.popularity'), maintenance: isNumber(weights.maintenance) ? Number(weights.maintenance) : config.get('weights.maintenance'), }; // Search /* eslint camelcase: 0 */ return this.client.search({ index, body: { _source: fields, size, from, query: { function_score: { query: { bool: { should: [ { multi_match: { query: value, operator: 'and', fields: [ 'name.identifier_edge_ngram^4', 'description.identifier_edge_ngram', 'keywords.identifier_edge_ngram^3', ], analyzer: 'identifier', type: 'phrase', slop: 3, boost: 9, }, }, { multi_match: { query: value, operator: 'and', fields: [ 'name.identifier_english_docs^4', 'description.identifier_english_docs', 'keywords.identifier_english_docs^3', ], type: 'cross_fields', boost: 3, }, }, { multi_match: { query: value, operator: 'and', fields: [ 'name.identifier_english_aggressive_docs^4', 'description.identifier_english_aggressive_docs', 'keywords.identifier_english_aggressive_docs^3', ], type: 'cross_fields', }, }, ], }, }, script_score: { lang: 'groovy', script: 'pow(' + 'doc["score.detail.popularity"].value * weightPopularity + ' + 'doc["score.detail.quality"].value * weightQuality + ' + 'doc["score.detail.maintenance"].value * weightMaintenance, ' + 'effect)', params: { effect, weightPopularity: weights.popularity, weightQuality: weights.quality, weightMaintenance: weights.maintenance, }, }, }, }, }, }); } } module.exports = Search;
JavaScript
0
@@ -1485,24 +1485,1031 @@ should: %5B%0A + // Give boost to exact matches (phrase)%0A %7B%0A multi_match: %7B%0A query: value,%0A operator: 'and',%0A fields: %5B%0A 'name.identifier_english%5E4',%0A 'description.identifier_english',%0A 'keywords.identifier_english%5E3',%0A %5D,%0A analyzer: 'identifier',%0A type: 'phrase',%0A slop: 3,%0A boost: 9,%0A %7D,%0A %7D,%0A%0A // Prefix exact matches%0A @@ -2526,32 +2526,32 @@ %7B%0A - @@ -3282,33 +3282,33 @@ boost: -9 +3 ,%0A @@ -3366,32 +3366,90 @@ %7D, +%0A%0A // Normal term match %0A @@ -4156,32 +4156,32 @@ %7D,%0A - @@ -4194,32 +4194,140 @@ %7D, +%0A%0A // Normal term match with a more aggressive stemmer (not so important) %0A
73726d3f355f5a8dd64b6c627d38c5c1591be498
Add api_key
lib/search.js
lib/search.js
'use strict'; /** * Module dependencies. */ var http = require('json-http'); var validator = require('./validator'); /** * Validate the parameters for the search request. * * @param {Object} params * @return {Object} validation state * @api private */ var _validateParams = function(params) { if (!params) { return { error: 'params cannot be null.' }; } // query is mandatory if (!params.hasOwnProperty('query')) { return { error: 'query param required.' }; } if (!validator.isString(params.query)) { return { error: 'query must be a string.' }; } if (!validator.isValidType(params)) { return { error: 'type must be: movie, series, episode.' }; } if (params.hasOwnProperty('year') && !validator.isNumber(params.year)) { return { error: 'year must be a valid number' }; } }; /** * Build the url string from the parameters. * * @param {Object} params * @return {String} url to call omdbapi.com * @api private */ var _createUrl = function(params) { var baseUrl = 'http://www.omdbapi.com/'; var query = '?'; // mandatory query += 's='.concat(encodeURIComponent(params.query)); if (params.year) { query += '&y='.concat(params.year); } if (params.type) { query += '&type='.concat(params.type); } return baseUrl.concat(query, '&r=json&v=1'); }; /** * Search film content from the imdb http service. * * @param {Object} params * @param {Function} callback * @api public */ module.exports = function(params, callback) { var validate = _validateParams(params); var timeout = (params) ? params.timeout || 10000 : 10000; if (validate) { callback(validate.error, null); return; } http.getJson(_createUrl(params), timeout, function handleResponse(err, data) { if (err) { callback(err, null); return; } if (data.Error) { callback(data.Error, null); } else { callback(null, data); } }); };
JavaScript
0.000002
@@ -1199,16 +1199,95 @@ y));%0A %0A + if (params.api_key) %7B%0A query += 'api_key='.concat(params.api_key);%0A %7D%0A %0A if (pa
02bfe40b33e3ba5972d5f2ab9c407518a494c879
Remove silly space
lib/sender.js
lib/sender.js
/*! * node-gcm * Copyright(c) 2013 Marcus Farkas <[email protected]> * MIT Licensed */ var Constants = require('./constants'); var req = require('request'); var debug = require('debug')('node-gcm'); function Sender(key , options) { if (!(this instanceof Sender)) { return new Sender(key, options); } this.key = key; this.options = options; } var parseAndRespond = function(resBody, callback) { var resBodyJSON; try { resBodyJSON = JSON.parse(resBody); } catch (e) { debug("Error parsing GCM response " + e); callback("Error parsing GCM response"); return; } callback(null, resBodyJSON); }; Sender.prototype.sendNoRetry = function(message, registrationIds, callback) { if(!callback) { callback = function() {}; } if(typeof registrationIds == "string") { registrationIds = [registrationIds]; } var body = {}, requestBody, post_options, post_req, timeout; body[Constants.JSON_REGISTRATION_IDS] = registrationIds; if (message.delayWhileIdle !== undefined) { body[Constants.PARAM_DELAY_WHILE_IDLE] = message.delayWhileIdle; } if (message.collapseKey !== undefined) { body[Constants.PARAM_COLLAPSE_KEY] = message.collapseKey; } if (message.timeToLive !== undefined) { body[Constants.PARAM_TIME_TO_LIVE] = message.timeToLive; } if (message.dryRun !== undefined) { body[Constants.PARAM_DRY_RUN] = message.dryRun; } if (Object.keys(message.data)) { body[Constants.PARAM_PAYLOAD_KEY] = message.data; } if (message.notification && Object.keys(message.notification)) { body[Constants.PARAM_NOTIFICATION_KEY] = message.notification; } requestBody = JSON.stringify(body); post_options = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-length': Buffer.byteLength(requestBody, 'utf8'), 'Authorization': 'key=' + this.key }, uri: Constants.GCM_SEND_URI, body: requestBody }; if (this.options && this.options.proxy) { post_options.proxy = this.options.proxy; } if (this.options && this.options.maxSockets) { post_options.maxSockets = this.options.maxSockets; } timeout = Constants.SOCKET_TIMEOUT; if (this.options && this.options.timeout) { timeout = this.options.timeout; } post_options.timeout = timeout; post_req = req(post_options, function (err, res, resBody) { if (err) { return callback(err, null); } if (!res) { return callback('response is null', null); } if (res.statusCode >= 500) { debug('GCM service is unavailable (500)'); return callback(res.statusCode, null); } else if (res.statusCode === 401) { debug('Unauthorized (401). Check that your API token is correct.'); return callback(res.statusCode, null); } else if (res.statusCode !== 200) { debug('Invalid request (' + res.statusCode + '): ' + resBody); return callback(res.statusCode, null); } parseAndRespond(resBody, callback); }); }; Sender.prototype.send = function(message, registrationIds, options, callback) { var backoff, retries; if(typeof options == "object") { retries = options.retries; backoff = options.backoff; if(typeof options.retries != "number") { retries = 5; } if(typeof options.backoff != "number") { backoff = Constants.BACKOFF_INITIAL_DELAY; } } else if(typeof options == "function") { retries = 5; backoff = Constants.BACKOFF_INITIAL_DELAY; callback = options; } else if(typeof options == "number") { retries = options; backoff = Constants.BACKOFF_INITIAL_DELAY; } if(!callback) { callback = function() {}; } if(typeof registrationIds == "string") { registrationIds = [registrationIds]; } if (!registrationIds.length) { debug('No RegistrationIds given!'); return process.nextTick(callback.bind(this, 'No RegistrationIds given!', null)); } if(retries == 0) { return this.sendNoRetry(message, registrationIds, callback); } if (backoff > Constants.MAX_BACKOFF_DELAY) { backoff = Constants.MAX_BACKOFF_DELAY; } var self = this; this.sendNoRetry(message, registrationIds, function(err, result) { // if we err'd resend them all if (err) { return setTimeout(function() { self.send(message, registrationIds, { retries: retries - 1, backoff: backoff * 2 }, callback); }, backoff); } // check for bad ids var unsentRegIds = [], regIdPositionMap = []; for (var i = 0; i < registrationIds.length; i++) { if (result.results[i].error === 'Unavailable') { regIdPositionMap.push(i); unsentRegIds.push(registrationIds[i]); } } if (!unsentRegIds.length) { return callback(err, result); } debug("Results received but not all successful", result); setTimeout(function () { debug("Retrying unsent registration ids"); self.send(message, unsentRegIds, { retries: retries - 1, backoff: backoff * 2 }, function(err, retriedResult) { //If the recursive call err'd completely, our current result is the best available if(err) { return callback(null, result); } //Map retried results onto their previous positions in the full array var retriedResults = retriedResult.results; for(var i = 0; i < result.results.length; i++) { var oldIndex = regIdPositionMap[i]; result.results[oldIndex] = retriedResults[i]; } //Update the fields on the result depending on newly returned value result.success += retriedResult.success; result.canonical_ids += retriedResult.canonical_ids; result.failure -= unsentRegIds.length - retriedResult.failure; callback(null, result); }); }, backoff); }); }; module.exports = Sender;
JavaScript
0.998015
@@ -226,17 +226,16 @@ nder(key - , option
c71214a1e99a598560dd2e7e3a9b687cf4d95450
Fix node-v6 not providing hasOwnProperty for EventEmitter._events
lib/server.js
lib/server.js
var http = require('http') , https = require('https') , url = require('url') , EventEmitter = require('events').EventEmitter , Serializer = require('./serializer') , Deserializer = require('./deserializer') /** * Creates a new Server object. Also creates an HTTP server to start listening * for XML-RPC method calls. Will emit an event with the XML-RPC call's method * name when receiving a method call. * * @constructor * @param {Object|String} options - The HTTP server options. Either a URI string * (e.g. 'http://localhost:9090') or an object * with fields: * - {String} host - (optional) * - {Number} port * @param {Boolean} isSecure - True if using https for making calls, * otherwise false. * @return {Server} */ function Server(options, isSecure, onListening) { if (false === (this instanceof Server)) { return new Server(options, isSecure) } onListening = onListening || function() {} var that = this // If a string URI is passed in, converts to URI fields if (typeof options === 'string') { options = url.parse(options) options.host = options.hostname options.path = options.pathname } function handleMethodCall(request, response) { var deserializer = new Deserializer() deserializer.deserializeMethodCall(request, function(error, methodName, params) { if (that._events.hasOwnProperty(methodName)) { that.emit(methodName, null, params, function(error, value) { var xml = null if (error !== null) { xml = Serializer.serializeFault(error) } else { xml = Serializer.serializeMethodResponse(value) } response.writeHead(200, {'Content-Type': 'text/xml', 'Content-Length': xml.length}) response.end(xml) }) } else { that.emit('NotFound', methodName, params) var xml = Serializer.serializeMethodResponse('') response.writeHead(200, {'Content-Type': 'text/xml', 'Content-Length': xml.length}) response.end(xml) } }) } this.httpServer = isSecure ? https.createServer(options, handleMethodCall) : http.createServer(handleMethodCall) process.nextTick(function() { this.httpServer.listen(options.port, options.host, onListening) }.bind(this)) this.close = function(callback) { this.httpServer.once('close', callback) this.httpServer.close() }.bind(this) } // Inherit from EventEmitter to emit and listen Server.prototype.__proto__ = EventEmitter.prototype module.exports = Server
JavaScript
0.00002
@@ -1509,36 +1509,59 @@ if ( -that._events.hasOwnProperty( +Object.prototype.hasOwnProperty.call(that._events, meth
980bbc377be282ae85ab4abc8481bd45a730daa5
Call toString on the error.
lib/server.js
lib/server.js
/** * Copyright 2012 Tomaz Muraus * * 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 path = require('path'); var httpProxy = require('http-proxy'); var async = require('async'); var log = require('logmagic').local('lib.server'); var constants = require('./constants'); var fsUtil = require('./util/fs'); /** * Reverse proxy server. * * @param {Object} options Options object. */ function ReverseProxyServer(options) { this._options = options; this._server = httpProxy.createServer(this.processRequest.bind(this)); this._proxyOptions = {'host': this._options.target.host, 'port': this._options.target.port}; this._middleware = {}; } /** * Run the server. * * @param {Function} callback Callback called when the server has been started * and bound to the port. */ ReverseProxyServer.prototype.run = function(callback) { var self = this; async.waterfall([ this._initialize.bind(this), this._listen.bind(this, this._options.server.host, this._options.server.port) ], function(err) { if (err) { log.errorf('Failed to start the server: ${err}', {'err': err}); } else { log.infof('Server listening on ${host}:${port}', {'host': self._options.server.host, 'port': self._options.server.port}); } callback(err); }); }; ReverseProxyServer.prototype._initialize = function(callback) { async.waterfall([ this._loadMiddleware.bind(this) ], callback); }; /** * Load and register all the set up middleware. * * @param {Function} callback Callback called when all the modules have been * loaded. */ ReverseProxyServer.prototype._loadMiddleware = function(callback) { var self = this; async.waterfall([ fsUtil.getMatchingFiles.bind(null, constants.MIDDLEWARE_PATH, /\.js$/, {}), function load(filePaths, callback) { async.forEach(filePaths, self._loadAndRegisterMiddleware.bind(self), callback); } ], callback); }; ReverseProxyServer.prototype._loadAndRegisterMiddleware = function(filePath, callback) { var moduleName, module; moduleName = path.basename(filePath).replace(/\.js$/, ''); try { module = require(filePath); } catch (e) { log.errorf('Failed to load middleware "${module}": ' + e.toString(), {'module': moduleName}); callback(); return; } if (!module.hasOwnProperty('processRequest')) { log.errorf('Module "${module}" is missing "processRequest" function, ignoring...', {'module': moduleName}); callback(); return; } this._middleware[moduleName] = module; log.infof('Sucesfully loaded module "${module}"', {'module': moduleName}); callback(); }; ReverseProxyServer.prototype.processRequest = function(req, res, proxy) { var self = this, ops = {}, i, len, name, dependencies, func; log.debug('Received request', {'url': req.url, 'headers': req.headers}); // TODO: Don't build the list on every request for (i = 0, len = this._options.target.middleware_run_list.length; i < len; i++) { name = this._options.target.middleware_run_list[i]; dependencies = this._options.middleware[name].depends || []; func = this._middleware[name].processRequest.bind(null, req, res); if (dependencies.length === 0) { ops[name] = func; } else { ops[name] = dependencies.concat([func]); } } async.auto(ops, function(err) { if (err) { log.error('Middleware returning an error, request won\'t be proxied...', {'err': err}); } else { log.debug('Proxying request to the worker...', {'url': req.url, 'headers': req.headers, 'worker_host': self._options.target.host, 'worker_port': self._options.target.port}); proxy.proxyRequest(req, res, self._proxyOptions); } }); }; ReverseProxyServer.prototype._listen = function(host, port, callback) { this._server.listen(port, host, callback || function() {}); }; exports.ReverseProxyServer = ReverseProxyServer;
JavaScript
0
@@ -3992,32 +3992,43 @@ ..', %7B'err': err +.toString() %7D);%0A %7D%0A el
3bc4205af956ad44fad87de8ca72e85ad7541eb6
Add NAt support for HTTP server
lib/server.js
lib/server.js
module.exports = Server var arrayRemove = require('unordered-array-remove') var debug = require('debug')('webtorrent:server') var http = require('http') var mime = require('mime') var pump = require('pump') var rangeParser = require('range-parser') var url = require('url') function Server (torrent, opts) { var server = http.createServer(opts) var sockets = [] var pendingReady = [] var closed = false server.on('connection', onConnection) server.on('request', onRequest) var _close = server.close server.close = function (cb) { closed = true torrent = null server.removeListener('connection', onConnection) server.removeListener('request', onRequest) while (pendingReady.length) { var onReady = pendingReady.pop() torrent.removeListener('ready', onReady) } _close.call(server, cb) } server.destroy = function (cb) { sockets.forEach(function (socket) { socket.destroy() }) // Only call `server.close` if user has not called it already if (closed) process.nextTick(cb) else server.close(cb) } function onConnection (socket) { socket.setTimeout(36000000) sockets.push(socket) socket.once('close', function () { arrayRemove(sockets, sockets.indexOf(socket)) }) } function onRequest (req, res) { debug('onRequest') // Allow CORS requests to specify arbitrary headers, e.g. 'Range', // by responding to the OPTIONS preflight request with the specified // origin and requested headers. if (req.method === 'OPTIONS' && req.headers['access-control-request-headers']) { res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') res.setHeader( 'Access-Control-Allow-Headers', req.headers['access-control-request-headers'] ) res.setHeader('Access-Control-Max-Age', '1728000') return res.end() } if (req.headers.origin) { res.setHeader('Access-Control-Allow-Origin', req.headers.origin) } var pathname = url.parse(req.url).pathname if (pathname === '/favicon.ico') return res.end() if (torrent.ready) { onReady() } else { pendingReady.push(onReady) torrent.once('ready', onReady) } function onReady () { arrayRemove(pendingReady, pendingReady.indexOf(onReady)) if (pathname === '/') { res.setHeader('Content-Type', 'text/html') var listHtml = torrent.files.map(function (file, i) { return '<li><a download="' + file.name + '" href="/' + i + '">' + file.path + '</a> ' + '(' + file.length + ' bytes)</li>' }).join('<br>') var html = '<h1>' + torrent.name + '</h1><ol>' + listHtml + '</ol>' return res.end(html) } var index = Number(pathname.slice(1)) if (Number.isNaN(index) || index >= torrent.files.length) { res.statusCode = 404 return res.end('404 Not Found') } var file = torrent.files[index] res.setHeader('Accept-Ranges', 'bytes') res.setHeader('Content-Type', mime.lookup(file.name)) res.statusCode = 200 // Support DLNA streaming res.setHeader('transferMode.dlna.org', 'Streaming') res.setHeader( 'contentFeatures.dlna.org', 'DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000' ) var range if (req.headers.range) { res.statusCode = 206 // no support for multi-range reqs range = rangeParser(file.length, req.headers.range)[0] debug('range %s', JSON.stringify(range)) res.setHeader( 'Content-Range', 'bytes ' + range.start + '-' + range.end + '/' + file.length ) res.setHeader('Content-Length', range.end - range.start + 1) } else { res.setHeader('Content-Length', file.length) } if (req.method === 'HEAD') { return res.end() } pump(file.createReadStream(range), res) } } return server }
JavaScript
0
@@ -341,16 +341,64 @@ er(opts) +%0A var natTraversal = require('./nat-traversal') %0A%0A var @@ -529,16 +529,54 @@ Request) +%0A server.on('listening', onListening) %0A%0A var @@ -1034,16 +1034,107 @@ %7D)%0A%0A + if (server.address()) %7B%0A natTraversal.portUnMapping(server.address().port)%0A %7D%0A%0A // O @@ -4157,16 +4157,101 @@ %7D%0A %7D%0A%0A + function onListening () %7B%0A natTraversal.portMapping(server.address().port)%0A %7D%0A%0A return
eb410646fe83df3754e397bb0ba38f734cc1fde3
Send with clientId only and no message returns a send function bound to a specific clientId
lib/server.js
lib/server.js
'use strict'; var WebSocketServer = require('websocket').server; var EventEmitter = require('events').EventEmitter; var util = require('./common.js'); var serve = function(opts) { var server = new WebSocketServer(opts); var connectEvents = new EventEmitter(); var messageEvents = new EventEmitter(); var replyEvents = {}; if (opts.maxListeners !== undefined) { messageEvents.setMaxListeners(opts.maxListeners); connectEvents.setMaxListeners(opts.maxListeners); } var timeout = opts.timeout || 5000; var numClients = 0; var clients = {}; var sendFns = {}; var clientIdCounter = 0; server.on('request', function(request) { var ws = request.accept(opts.protocol || 'json-socket'); var id = clientIdCounter++; var socketReplyEvents = new EventEmitter(); socketReplyEvents.setMaxListeners(1); numClients++; ws.name = 'Client #' + id; ws.id = id; clients[id] = ws; replyEvents[id] = socketReplyEvents; sendFns[id] = util.send(ws, socketReplyEvents); util.log(ws.name + ' connected', opts); ws.on('message', util.receive(messageEvents, ws, socketReplyEvents)); ws.on('close', function() { util.log('Client #' + id + ' disconnected', opts); connectEvents.emit('disconnect', id); numClients--; delete clients[id]; delete replyEvents[id]; delete sendFns[id]; //TODO: error out all existing replyEvent listeners when a socket disconnects }); connectEvents.emit('connect', id, request.remoteAddress); }); var send = function(clientId, type) { if (typeof type !== 'string') { throw new Error('Message type must be a string'); } var args = Array.prototype.slice.call(arguments, 1); sendFns[clientId].apply(undefined, args); }; messageEvents.send = send; messageEvents.clients = clients; messageEvents.numClients = numClients; messageEvents.connect = connectEvents; return messageEvents; }; module.exports = serve;
JavaScript
0
@@ -1556,16 +1556,21 @@ function + send (clientI @@ -1576,24 +1576,193 @@ Id, type) %7B%0A + if (arguments.length === 1) %7B%0A return function(type) %7B%0A send.apply(undefined, %5BclientId%5D.concat(Array.prototype.slice.call(arguments)));%0A %7D;%0A %7D%0A%0A if (type @@ -1860,18 +1860,42 @@ -var args = +sendFns%5BclientId%5D.apply(undefined, Arr @@ -1935,54 +1935,8 @@ , 1) -;%0A%0A sendFns%5BclientId%5D.apply(undefined, args );%0A
54ace608da6729fa3f91829fcdda27cbf31108d4
FIX (tags): wrap long tags
src/components/common/Taglist.js
src/components/common/Taglist.js
import React from 'react'; import PropTypes from 'prop-types'; import { getSnippets } from 'selectors/snippets'; import { connect } from 'react-redux'; import * as snippetActions from 'actions/snippets'; import { compact, filter, flattenDeep, flow, isEmpty, map, uniq } from 'lodash/fp'; import styled from 'styled-components'; import { baseAppColor, headerBgLightest } from 'constants/colors'; const Pill = styled.span` border: 1px solid ${headerBgLightest}; color: ${baseAppColor}; padding: 5px; border-radius: 3px; &:hover { border: 1px solid ${baseAppColor}; } `; export const Taglist = ({ snippets, searchTags, searchByTags }) => { const getTags = () => { const tags = map('tags', snippets); const tagList = flow([ flattenDeep, uniq, compact ])(tags); if (!isEmpty(searchTags)) { return filter((tag) => { const regex = new RegExp(searchTags, 'gi'); return tag.match(regex); }, tagList.sort()); } return tagList.sort(); }; return ( <React.Fragment> { map((tag) => ( <Pill key={ tag } onClick={ () => searchByTags(tag) }> { tag } </Pill> ), getTags()) } </React.Fragment> ); }; Taglist.propTypes = { snippets: PropTypes.object, searchTags: PropTypes.string, searchByTags: PropTypes.func }; const mapStateToProps = (state) => ({ snippets: getSnippets(state) }); export default connect(mapStateToProps, { searchByTags: snippetActions.filterSnippetsByTags })(Taglist);
JavaScript
0.000001
@@ -529,55 +529,531 @@ ;%0A -&:hover %7B%0A border: 1px solid $%7BbaseAppColor%7D +position: relative;%0A text-overflow: clip;%0A overflow: hidden;%0A &:hover %7B%0A border: 1px solid $%7BbaseAppColor%7D;%0A %7D%0A %0A &:after %7B%0A content: %22%22;%0A width: 30px;%0A height: 20px;%0A position: absolute;%0A top: 3px;%0A right: 0;%0A background: -webkit-gradient(linear,left top,right top,color-stop(0%25,rgba(255,255,255,0)),color-stop(56%25,rgba(255,255,255,1)),color-stop(100%25,rgba(255,255,255,1)));%0A background: -webkit-linear-gradient(left,rgba(255,255,255,0) 0%25,rgba(255,255,255,1) 56%25,rgba(255,255,255,1) 100%25) ;%0A @@ -1612,16 +1612,30 @@ ags(tag) + %7D title=%7B tag %7D%3E%0A
9734ea16a41e0e0fb2b84fbe6e1be2c04cf38498
Add parse url function
scripts/routes/index.js
scripts/routes/index.js
const PARAMETER_REGEXP = /([:*])(\w+)/g; const WILDCARD_REGEXP = /\*/g; const REPLACE_VARIABLE_REGEXP = '([^\/]+)'; const REPLACE_WILDCARD = '(?:.*)'; const FOLLOWED_BY_SLASH_REGEXP = '(?:\/$|$)'; const MATCH_REGEXP_FLAGS = ''; let _routes = []; export function add(routes) { routes.forEach(route => { _routes.push(route); }); } export default { map(routes) { add(routes); }, routes(index) { if (index && _routes[index]) { return _routes[index]; } return _routes; } };
JavaScript
0.000019
@@ -1,12 +1,95 @@ +import %7B $unserialize %7D from 'core/types';%0Aimport %7B _doc %7D from 'core/variables';%0A%0A const PARAME @@ -308,34 +308,140 @@ '';%0A -let _routes = %5B%5D;%0A%0Aexport +const REMOVE_SLASHES_REGEXP = /%5E%5C/%7C%5C/$/g;%0Alet _routes = %5B%5D;%0A%0A/**%0A * Add a route to routes array%0A *%0A * @private%0A * @param routes%0A */%0A func @@ -445,16 +445,17 @@ unction +_ add(rout @@ -518,16 +518,644 @@ %09%7D);%0A%7D%0A%0A +/**%0A * Parse url and return results%0A *%0A * @private%0A * @param value%0A * @returns %7B%7Bfull: string, hash: (Blob%7Cstring%7C*%7CArrayBuffer%7CArray.%3CT%3E%7C$), path: string, query: %7B%7D, segments: Array, url: (*%7CLocation%7CString%7Cstring), port%7D%7D%0A * @private%0A */%0Afunction _parseUrl(value) %7B%0A%09const a = _doc.createElement('a');%0A%09a.href = value %7C%7C window.location;%0A%0A%09const search = a.search,%0A%09%09path = a.pathname.replace(REMOVE_SLASHES_REGEXP, '');%0A%0A%09return %7B%0A%09%09full: '/' + path + search + a.hash,%0A%09%09hash: a.hash.slice(1),%0A%09%09path: '/' + path,%0A%09%09query: search ? $unserialize(search) : %7B%7D,%0A%09%09segments: path.split('/'),%0A%09%09url: a.href,%0A%09%09port: a.port%0A%09%7D;%0A%7D%0A%0A export d @@ -1180,16 +1180,17 @@ es) %7B%0A%09%09 +_ add(rout @@ -1193,16 +1193,32 @@ routes); +%0A%0A%09%09return this; %0A%09%7D,%0A%09ro @@ -1313,13 +1313,76 @@ routes;%0A +%09%7D,%0A%09run() %7B%0A%09%09//%0A%09%7D,%0A%09uri(value) %7B%0A%09%09return _parseUrl(value);%0A %09%7D%0A%7D;
8565201c742eed026a4d755b480ba022fa62d6bf
Use view2DState in ol.interaction.DragPan
src/ol/interaction/dragpaninteraction.js
src/ol/interaction/dragpaninteraction.js
// FIXME works for View2D only goog.provide('ol.interaction.DragPan'); goog.require('goog.asserts'); goog.require('ol.Kinetic'); goog.require('ol.PreRenderFunction'); goog.require('ol.View2D'); goog.require('ol.coordinate'); goog.require('ol.interaction.ConditionType'); goog.require('ol.interaction.Drag'); goog.require('ol.interaction.condition'); /** * @constructor * @extends {ol.interaction.Drag} * @param {ol.interaction.DragPanOptions=} opt_options Options. */ ol.interaction.DragPan = function(opt_options) { goog.base(this); var options = goog.isDef(opt_options) ? opt_options : {}; /** * @private * @type {ol.interaction.ConditionType} */ this.condition_ = goog.isDef(options.condition) ? options.condition : ol.interaction.condition.noModifierKeys; /** * @private * @type {ol.Kinetic|undefined} */ this.kinetic_ = options.kinetic; /** * @private * @type {?ol.PreRenderFunction} */ this.kineticPreRenderFn_ = null; }; goog.inherits(ol.interaction.DragPan, ol.interaction.Drag); /** * @inheritDoc */ ol.interaction.DragPan.prototype.handleDrag = function(mapBrowserEvent) { if (this.kinetic_) { this.kinetic_.update( mapBrowserEvent.browserEvent.clientX, mapBrowserEvent.browserEvent.clientY); } var map = mapBrowserEvent.map; // FIXME works for View2D only var view = map.getView(); goog.asserts.assertInstanceof(view, ol.View2D); var view2DState = view.getView2DState(); var newCenter = [ -view2DState.resolution * this.deltaX, view2DState.resolution * this.deltaY ]; ol.coordinate.rotate(newCenter, view2DState.rotation); ol.coordinate.add(newCenter, this.startCenter); map.requestRenderFrame(); view.setCenter(newCenter); }; /** * @inheritDoc */ ol.interaction.DragPan.prototype.handleDragEnd = function(mapBrowserEvent) { // FIXME works for View2D only var map = mapBrowserEvent.map; var view = map.getView(); if (this.kinetic_ && this.kinetic_.end()) { var distance = this.kinetic_.getDistance(); var angle = this.kinetic_.getAngle(); var center = view.getCenter(); this.kineticPreRenderFn_ = this.kinetic_.pan(center); map.addPreRenderFunction(this.kineticPreRenderFn_); var centerpx = map.getPixelFromCoordinate(center); var dest = map.getCoordinateFromPixel([ centerpx[0] - distance * Math.cos(angle), centerpx[1] - distance * Math.sin(angle) ]); view.setCenter(dest); } map.requestRenderFrame(); }; /** * @inheritDoc */ ol.interaction.DragPan.prototype.handleDragStart = function(mapBrowserEvent) { var browserEvent = mapBrowserEvent.browserEvent; if (browserEvent.isMouseActionButton() && this.condition_(browserEvent)) { if (this.kinetic_) { this.kinetic_.begin(); this.kinetic_.update(browserEvent.clientX, browserEvent.clientY); } var map = mapBrowserEvent.map; map.requestRenderFrame(); return true; } else { return false; } }; /** * @inheritDoc */ ol.interaction.DragPan.prototype.handleDown = function(mapBrowserEvent) { var map = mapBrowserEvent.map; // FIXME works for View2D only var view = map.getView(); goog.asserts.assertInstanceof(view, ol.View2D); goog.asserts.assert(!goog.isNull(mapBrowserEvent.frameState)); if (!goog.isNull(this.kineticPreRenderFn_) && map.removePreRenderFunction(this.kineticPreRenderFn_)) { map.requestRenderFrame(); view.setCenter(mapBrowserEvent.frameState.view2DState.center); this.kineticPreRenderFn_ = null; } };
JavaScript
0
@@ -1949,16 +1949,28 @@ etView() +.getView2D() ;%0A%0A if @@ -2006,24 +2006,69 @@ c_.end()) %7B%0A + var view2DState = view.getView2DState();%0A var dist @@ -2149,43 +2149,8 @@ ();%0A - var center = view.getCenter();%0A @@ -2194,16 +2194,28 @@ ic_.pan( +view2DState. center); @@ -2318,16 +2318,28 @@ rdinate( +view2DState. center);
9a16b97ca5b401e6984294a2abd73d4c7471f217
Fix UserSubscriptionsRoute image preload paths
src/app/routes/UserSubscriptionsRoute.js
src/app/routes/UserSubscriptionsRoute.js
define([ "ember", "routes/UserIndexRoute", "mixins/ChannelMixin", "mixins/InfiniteScrollRouteMixin", "utils/preload" ], function( Ember, UserIndexRoute, ChannelMixin, InfiniteScrollRouteMixin, preload ) { var get = Ember.get; return UserIndexRoute.extend( ChannelMixin, InfiniteScrollRouteMixin, { itemSelector: ".stream-component", model: function() { var self = this; return this.store.findQuery( "twitchTicket", { offset: get( this, "offset" ), limit : get( this, "limit" ), unended: true }) .then(function( data ) { return data.toArray().filterBy( "product.ticket_type", "chansub" ); }) .then(function( data ) { // The partner_login (channel) reference is loaded asynchronously // just get the PromiseProxy object and wait for it to resolve var promises = data.mapBy( "product.partner_login" ); return Promise.all( promises ) .then(function( channels ) { // Also load the UserSubscription record (needed for subscription date) // Sadly, this can't be loaded in parallel (channel needs to be loaded) return Promise.all( channels.map(function( channel ) { return self.checkUserSubscribesChannel( channel ); }) ); }) .then(function() { return data; }); }) .then( preload([ "@each.product.partner_login.logo", "@each.product.partner_login.profile_banner", "@[email protected][email protected]" ]) ); } }); });
JavaScript
0.000003
@@ -1332,32 +1332,38 @@ %09%[email protected]. +@each. partner_login.lo @@ -1360,16 +1360,22 @@ r_login. +@each. logo%22,%0A%09 @@ -1385,32 +1385,38 @@ %09%[email protected]. +@each. partner_login.pr @@ -1413,16 +1413,22 @@ r_login. +@each. profile_ @@ -1472,16 +1472,28 @@ oticons. +firstObject. @each.ur
553f2648cd989c1b85860d94ffc7857156d00774
remove Trans macro from heading
plugins/services/src/js/components/modals/ServiceScaleFormModal.js
plugins/services/src/js/components/modals/ServiceScaleFormModal.js
import { Trans } from "@lingui/macro"; import PropTypes from "prop-types"; import React from "react"; import PureRender from "react-addons-pure-render-mixin"; import FormModal from "#SRC/js/components/FormModal"; import ModalHeading from "#SRC/js/components/modals/ModalHeading"; import AppLockedMessage from "./AppLockedMessage"; import Pod from "../../structs/Pod"; import Service from "../../structs/Service"; import ServiceTree from "../../structs/ServiceTree"; class ServiceScaleFormModal extends React.Component { constructor() { super(...arguments); this.state = { errorMsg: null }; this.shouldComponentUpdate = PureRender.shouldComponentUpdate.bind(this); } componentWillUpdate(nextProps) { const requestCompleted = this.props.isPending && !nextProps.isPending; const shouldClose = requestCompleted && !nextProps.errors; if (shouldClose) { this.props.onClose(); } } componentWillReceiveProps(nextProps) { const { errors } = nextProps; if (!errors) { this.setState({ errorMsg: null }); return; } if (typeof errors === "string") { this.setState({ errorMsg: errors }); return; } let { message: errorMsg = "", details } = errors; const hasDetails = details && details.length !== 0; if (hasDetails) { errorMsg = details.reduce(function(memo, error) { return `${memo} ${error.errors.join(" ")}`; }, ""); } if (!errorMsg || !errorMsg.length) { errorMsg = null; } this.setState({ errorMsg }); } shouldForceUpdate() { return this.state.errorMsg && /force=true/.test(this.state.errorMsg); } getErrorMessage() { const { errorMsg = null } = this.state; if (!errorMsg) { return null; } if (this.shouldForceUpdate()) { return <AppLockedMessage service={this.props.service} />; } return ( <h4 className="text-align-center text-danger flush-top">{errorMsg}</h4> ); } getScaleFormDefinition() { const { service } = this.props; let instancesCount = service.getInstancesCount(); if (service instanceof ServiceTree) { instancesCount = "1.0"; } return [ { fieldType: "number", min: 0, name: "instances", placeholder: instancesCount, value: instancesCount.toString(), required: true, showLabel: false, writeType: "input" } ]; } getHeader() { let headerText = "Service"; if (this.props.service instanceof Pod) { headerText = "Pod"; } if (this.props.service instanceof ServiceTree) { headerText = "Group"; } return ( <ModalHeading> <Trans render="span">Scale {headerText}</Trans> </ModalHeading> ); } getBodyText() { if (this.props.service instanceof ServiceTree) { return ( <Trans render="p"> By which factor would you like to scale all applications within this{" "} group? </Trans> ); } return <Trans render="p">How many instances?</Trans>; } render() { const { clearError, isPending, onClose, open } = this.props; const buttonDefinition = [ { text: "Cancel", className: "button button-primary-link flush-left", isClose: true }, { text: "Scale Service", className: "button button-primary", isSubmit: true } ]; const onSubmit = model => { this.props.scaleItem(model.instances, this.shouldForceUpdate()); }; return ( <FormModal buttonDefinition={buttonDefinition} definition={this.getScaleFormDefinition()} modalProps={{ header: this.getHeader(), showHeader: true }} disabled={isPending} onClose={onClose} onSubmit={onSubmit} onChange={clearError} open={open} > {this.getBodyText()} {this.getErrorMessage()} </FormModal> ); } } ServiceScaleFormModal.propTypes = { scaleItem: PropTypes.func.isRequired, errors: PropTypes.oneOfType([PropTypes.object, PropTypes.string]), isPending: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, open: PropTypes.bool.isRequired, service: PropTypes.oneOfType([ PropTypes.instanceOf(ServiceTree), PropTypes.instanceOf(Service) ]).isRequired }; module.exports = ServiceScaleFormModal;
JavaScript
0
@@ -2478,26 +2478,27 @@ let -headerText +serviceType = %22Serv @@ -2551,34 +2551,35 @@ od) %7B%0A -headerText +serviceType = %22Pod%22;%0A @@ -2642,26 +2642,27 @@ %7B%0A -headerText +serviceType = %22Grou @@ -2675,105 +2675,93 @@ %7D%0A -%0A -return (%0A %3CModalHeading%3E%0A %3CTrans render=%22span%22%3EScale %7BheaderText%7D%3C/Trans%3E%0A +const headerText = %60Scale $%7BserviceType%7D%60;%0A%0A return %3CModalHeading%3E%7BheaderText%7D %3C/Mo @@ -2771,22 +2771,16 @@ Heading%3E -%0A ) ;%0A %7D%0A%0A
46382b5a45b5ed16adb01b6d8009fa7c4eb24c2b
Remove spaces around named imports
src/components/import_preview.js
src/components/import_preview.js
import React, {PureComponent, Fragment} from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; export default class ImportPreview extends PureComponent { static propTypes = { cssPath: PropTypes.string, reactPath: PropTypes.string, reactComponents: PropTypes.object }; static defaultProps = { reactComponents: {} }; render() { const {cssPath, reactPath, reactComponents} = this.props; if (!cssPath && !reactPath) return null; const componentNames = Object.keys(reactComponents); const reactImport = reactPath && `import { ${componentNames.join(', ')} } from '${reactPath}';`; const cssImport = cssPath && `import '${cssPath}';`; const multipleComponents = componentNames.length > 1; return ( <Fragment> {reactPath && ( <div {...{className: 'border styleguide-import-preview'}}> <div className="border-bottom em-high pal bg-neutral-10">{`Import React component${multipleComponents ? 's' : ''}`}</div> <pre className="pre-unstyled man md-pre language-js"><code className="styleguide-import-preview-code">{reactImport}</code></pre> </div> )} {cssPath && ( <div {...{className: classnames('border styleguide-import-preview', {'mtxxxl': reactPath})}}> <div className="border-bottom em-high pal bg-neutral-10">{`Import CSS${reactPath ? ' only' : ''}`}</div> <pre className="pre-unstyled man md-pre language-js"><code className="styleguide-import-preview-code">{cssImport}</code></pre> </div> )} </Fragment> ); } }
JavaScript
0.999764
@@ -591,17 +591,16 @@ import %7B - $%7Bcompon @@ -619,17 +619,16 @@ n(', ')%7D - %7D from '
7fb41a4f10d7815c488262a614347aaecc8c4fe9
Add test for undefined rule nodes
test/nesting.js
test/nesting.js
var assert = require('assert'); var postcss = require('postcss'); var getSelectors = require('../lib/get-selectors'); describe('getSelectors', function() { var root, componentRoot; beforeEach(function() { root = postcss.root(); componentRoot = postcss.rule({selector: '.Component'}); root.append(componentRoot); }); it('should return the selector', function() { assert.deepEqual(getSelectors(componentRoot), ['.Component']); }); describe('ruleset declarations with nested rulesets', function() { it('should ignore a ruleset that has no declarations', function() { componentRoot.append({selector: '.Component-d'}); componentRoot.append({text: 'comment'}); assert.deepEqual(getSelectors(componentRoot), []); }); it('should return a selector if the ruleset has declarations', function() { componentRoot.append({prop: 'color', value: 'green'}); componentRoot.append({selector: '.Component-d'}); componentRoot.append({text: 'comment'}); assert.deepEqual(getSelectors(componentRoot), ['.Component']); }); }); describe('nested rulesets', function() { it('should unwrap selectors down from the parent to the current rule', function() { var rule = postcss.rule({selector: '.Component-d'}); componentRoot.append(rule); assert.deepEqual(getSelectors(rule), ['.Component .Component-d']); }); it('should unwrap `&` selectors', function() { var rule = postcss.rule({selector: '&.is-active'}); componentRoot.append(rule); assert.deepEqual(getSelectors(rule), ['.Component.is-active']); }); it('should unwrap multiple levels of nested rulesets and skip rules with no declarations', function() { var descendant = postcss.rule({selector: '.Component-d'}); var hover = postcss.rule({selector: '&:hover'}); var state = postcss.rule({selector: '&.is-active'}); descendant.append([hover, state]); componentRoot.append(descendant); assert.deepEqual(getSelectors(componentRoot), []); assert.deepEqual(getSelectors(descendant), []); assert.deepEqual(getSelectors(hover), ['.Component .Component-d:hover']); assert.deepEqual(getSelectors(state), ['.Component .Component-d.is-active']); }); describe('grouped selectors', function() { it('should unwrap grouped selectors without declarations', function() { var componentRoot = postcss.rule({selector: '.Component, .Component-d'}); var hover = postcss.rule({selector: '&:hover'}); var state = postcss.rule({selector: '&.is-active'}); componentRoot.append([hover, state]); root.append(componentRoot); assert.deepEqual(getSelectors(componentRoot), []); assert.deepEqual(getSelectors(hover), ['.Component:hover', '.Component-d:hover']); assert.deepEqual(getSelectors(state), ['.Component.is-active', '.Component-d.is-active']); }); it('should unwrap grouped selectors with declarations', function() { var componentRoot = postcss.rule({selector: '.Component, .Component-d'}); var hover = postcss.rule({selector: '&:hover'}); var state = postcss.rule({selector: '&.is-active'}); componentRoot.append({prop: 'color', value: 'green'}); componentRoot.append([hover, state]); root.append(componentRoot); assert.deepEqual(getSelectors(componentRoot), ['.Component', '.Component-d']); assert.deepEqual(getSelectors(hover), ['.Component:hover', '.Component-d:hover']); assert.deepEqual(getSelectors(state), ['.Component.is-active', '.Component-d.is-active']); }); }); }); describe('ruleset within an atrule block', function() { it('should unwrap selectors as normal', function() { var rule = postcss.rule({selector: '.Component-d'}); var media = postcss.atRule({name: 'media'}); componentRoot.append(rule); media.append(componentRoot); assert.deepEqual(getSelectors(componentRoot), []); assert.deepEqual(getSelectors(rule), ['.Component .Component-d']); }); }); describe('media queries nested in a ruleset', function() { it('should return a selector for a child rule inside a nested media query', function() { var rule = postcss.rule({selector: '.Component-d'}); var media = postcss.atRule({name: 'media'}); media.append(rule); componentRoot.append(media); assert.deepEqual(getSelectors(rule), ['.Component .Component-d']); assert.deepEqual(getSelectors(componentRoot), []); }); it('should return a selector for a ruleset with declarations and nested media query', function() { componentRoot.append({prop: 'color', value: 'green'}); var rule = postcss.rule({selector: '.Component-d'}); var media = postcss.atRule({name: 'media'}); media.append(rule); componentRoot.append(media); assert.deepEqual(getSelectors(rule), ['.Component .Component-d']); assert.deepEqual(getSelectors(componentRoot), ['.Component']); }); }) });
JavaScript
0.000001
@@ -444,32 +444,295 @@ nent'%5D);%0A %7D);%0A%0A + it('should check for the existence of child nodes', function() %7B%0A var rule = postcss.rule(%7Bselector: '.Component-d'%7D);%0A rule.nodes = undefined;%0A componentRoot.append(rule);%0A%0A assert.deepEqual(getSelectors(rule), %5B'.Component .Component-d'%5D);%0A %7D);%0A%0A describe('rule
4d48f689a23170ebf39fe4485cedf95d206dc805
update test code
src/ax5ui-combobox/test/test.combobox.js
src/ax5ui-combobox/test/test.combobox.js
/* * Copyright (c) 2017. [email protected] * - github.com/thomasjang * - www.axisj.com */ describe('ax5combobox TEST', function () { var myUI; var options = []; options.push({value: "1", text: "string"}); options.push({value: "2", text: "number"}); options.push({value: "3", text: "substr"}); options.push({value: "4", text: "substring"}); options.push({value: "search", text: "search"}); options.push({value: "parseInt", text: "parseInt"}); options.push({value: "toFixed", text: "toFixed"}); options.push({value: "min", text: "min"}); options.push({value: "max", text: "max"}); var tmpl = '<div class="form-group">' + '<div data-ax5combobox="combobox1" data-ax5combobox-config="{}"></div>' + '</div>'; $(document.body).append(tmpl); /// it('new ax5combobox', function (done) { try { myUI = new ax5.ui.combobox(); done(); } catch (e) { done(e); } }); it('bind combobox', function (done) { myUI.bind({ target: $('[data-ax5combobox="combobox1"]'), options: options, onChange: function () { }, onStateChanged: function () { } }); done(); }); it('open combobox', function (done) { myUI.open($('[data-ax5combobox="combobox1"]')); done(myUI.queue[0].$display.attr("data-combobox-option-group-opened") === "true" ? "" : "open error"); }); it('close combobox', function (done) { myUI.close($('[data-ax5combobox="combobox1"]')); done(typeof myUI.queue[0].$display.attr("data-combobox-option-group-opened") === "undefined" ? "" : "close error"); }); it('setValue combobox', function (done) { myUI.setValue($('[data-ax5combobox="combobox1"]'), 2); var selectedItem = myUI.getSelectedOption($('[data-ax5combobox="combobox1"]'))[0]; if (selectedItem.value == 2 && selectedItem.selected) { done(); } else { done("setValue error"); } }); it('setText combobox', function (done) { myUI.setText($('[data-ax5combobox="combobox1"]'), "number"); var selectedItem = myUI.getSelectedOption($('[data-ax5combobox="combobox1"]'))[0]; if (selectedItem.text == "number" && selectedItem.selected) { done(); } else { done("setText error"); } }); it('disable combobox', function (done) { myUI.disable($('[data-ax5combobox="combobox1"]')); done(myUI.queue[0].$display.attr("disabled") === "disabled" ? "" : "disabled error"); }); it('enable combobox', function (done) { myUI.enable($('[data-ax5combobox="combobox1"]')); done(typeof myUI.queue[0].$display.attr("disabled") === "undefined" ? "" : "enable error"); }); });
JavaScript
0.000001
@@ -986,25 +986,24 @@ %7D%0A %7D);%0A%0A -%0A it('bind @@ -2876,12 +2876,637 @@ %0A %7D); +%0A%0A it('update combobox', function (done) %7B%0A myUI.update(%7B%0A target: $('%5Bdata-ax5combobox=%22combobox1%22%5D'),%0A options: options.concat(%7Bvalue: %22world%22, text: %22hello-world!%22%7D)%0A %7D);%0A%0A done(myUI.queue%5B0%5D.options.length == 10 ? %22%22 : %22update error%22);%0A %7D);%0A%0A it('align combobox', function (done) %7B%0A myUI.update(%7B%0A target: $('%5Bdata-ax5combobox=%22combobox1%22%5D'),%0A minWidth: 120%0A %7D);%0A %0A done(myUI.queue%5B0%5D.$display.css(%22minWidth%22) == %22120px%22 ? %22%22 : %22align error%22);%0A %7D);%0A%0A after(function () %7B%0A $(%22.form-group%22).remove();%0A %7D); %0A%7D);
c0752c78695944eb86060becf7bceb1827e316da
add test
test/plugins.js
test/plugins.js
const expect = require('chai').expect; var T = require('../lib'); var BemEntity = require('@bem/entity-name'); describe('pluginis', () => { describe('whiteList', () => { it('without opts', () => { var res = T() .use(T.plugins.whiteList()) .process({ block: 'button2' }); expect(res.JSX).to.equal( '<Button2/>' ); }); it('whiteList', () => { var res = T() .use(T.plugins.whiteList({ entities: [{ block: 'button2' }].map(BemEntity.create) })) .process({ block: 'button2', content: [{ block: 'menu' }, { block: 'selec' }] }); expect(res.JSX).to.equal( '<Button2/>' ); }); }); describe('camelCaseProps', () => { it('should transform mod-name to modName', () => { var res = T().process({ block: 'button2', mods: { 'has-clear': 'yes' } }); expect(res.JSX).to.equal( `<Button2 hasClear='yes'/>` ); }); it('should transform several mod-names to modName', () => { var res = T().process({ block: 'button2', mods: { 'has-clear': 'yes', 'has-tick': 'too' } }); expect(res.JSX).to.equal( `<Button2 hasClear='yes' hasTick='too'/>` ); }); it('should distinguish mod-name and modname', () => { var res = T().process({ block: 'button2', mods: { 'has-clear': 'yes', 'hasclear': 'yes' } }); expect(res.JSX).to.equal( `<Button2 hasClear='yes' hasclear='yes'/>` ); }); }); describe('stylePropToObj', () => { it('styleProp to obj', () => { var res = T().process({ block: 'button2', style: 'width:200px' }); expect(res.JSX).to.equal( `<Button2 style={{ 'width': '200px' }}/>` ); }); it('attrs style to obj', () => { var res = T().process({ block: 'button2', attrs: { style: 'width:200px' } }); expect(res.JSX).to.equal( `<Button2 style={{ 'width': '200px' }} attrs={{ 'style': { 'width': '200px' } }}/>` ); }); }); describe('keepWhiteSpaces', () => { it('should keep spaces before simple text', () => { var res = T().process({ block: 'button2', content: ' space before' }); expect(res.JSX).to.equal( `<Button2>\n{' space before'}\n</Button2>` ); }); it('should keep spaces after simple text', () => { var res = T().process({ block: 'button2', content: 'space after ' }); expect(res.JSX).to.equal( `<Button2>\n{'space after '}\n</Button2>` ); }); it('should keep spaces before & after simple text', () => { var res = T().process({ block: 'button2', content: ' space before & after ' }); expect(res.JSX).to.equal( `<Button2>\n{' space before & after '}\n</Button2>` ); }); it('should keep spaces in only spaces simple text', () => { var res = T().process({ block: 'button2', content: [' ', ' ', ' ']}); expect(res.JSX).to.equal( `<Button2>\n{' '}\n{' '}\n{' '}\n</Button2>` ); }); }); });
JavaScript
0
@@ -137,16 +137,831 @@ ) =%3E %7B%0A%0A + describe('copyMods', () =%3E %7B%0A it('without elem', () =%3E %7B%0A var res = T().process(%7B%0A block: 'button2',%0A mods: %7Bsize: 'm', theme: 'normal'%7D,%0A elemMods: %7Bsize: 'l', theme: 'dark'%7D%0A %7D);%0A%0A expect(res.JSX).to.equal(%0A %60%3CButton2 size='m' theme='normal'/%3E%60%0A );%0A %7D);%0A%0A it('with elem', () =%3E %7B%0A var res = T()%0A .process(%7B%0A block: 'button2',%0A elem: 'text',%0A mods: %7Bsize: 'm', theme: 'normal'%7D,%0A elemMods: %7Bsize: 'l', theme: 'dark'%7D%0A %7D);%0A%0A expect(res.JSX).to.equal(%0A %60%3CButton2Text size='l' theme='dark'/%3E%60%0A );%0A %7D);%0A %7D);%0A%0A desc
1f30bd685f713f26ab7c6f6c9951d2bd2cd6e048
fix spelling
scripts/waffle-board.js
scripts/waffle-board.js
// Description: // Report current work in progress on github projects. // // Dependencies: // githubot - see https://github.com/iangreenleaf/githubot // underscore // // Configuration // HUBOT_GITHUB_TOKEN=your github auth token // HUBOT_GITHUB_USER=default organization for github projects // HUBOT_GITHUB_WIP_LABEL=name of label for work in progress issues // HUBOT_GITHUB_REVIEW_LABEL=name of label for issues in review // HUBOT_GITHUB_WORKFLOW_LABELS=comma separated list of labels used for workflow (ex: Backlog, In Progress) // // Commands: // Hubot waffle board <user_or_organization>/<project> - query for recent project activity // Hubot waffle board <project> - query for recent project activity w/ default organization // Hubot waffle board <project> - query for recent project activity w/ default organization // // Author: // Ryan Sonnek var githubAuthToken = process.env.HUBOT_GITHUB_TOKEN; var defaultGithubOrganization = process.env.HUBOT_GITHUB_USER; var wipLabel = process.env.HUBOT_GITHUB_WIP_LABEL; var reviewLabel = process.env.HUBOT_GITHUB_REVEIW_LABEL; var workflowLabels = (process.env.HUBOT_GITHUB_WORKFLOW_LABELS || '').split(','); module.exports = function(robot) { var github = require('githubot')(robot); var _ = require('underscore'); var moment = require('moment'); function rejectPullRequests(issues) { var issuesWithoutPullRequests = _.filter(issues, function(issue) { return !issue.pull_request; }); return issuesWithoutPullRequests; } // see https://developer.github.com/v3/issues/#list-issues function issueToString(issue) { var labels = _.reject(issue.labels, function(label) { return _.contains(workflowLabels, label.name) }); var hashtags = _.map(labels, function(label) { return '#' + label.name; }).sort().join(' '); var lastUpdatedAt = moment(issue.closed_at || issue.updated_at); var daysSinceUpdated = moment().diff(lastUpdatedAt, 'days'); var owner = issue.assignee || issue.user; var parts = []; parts.push('#' + issue.number); if (daysSinceUpdated > 0) { parts.push('[' + daysSinceUpdated + 'd]'); } parts.push('@' + owner.login); parts.push(issue.title); parts.push(hashtags); return parts.join(' '); } // see https://developer.github.com/v3/issues/#list-issues function inProgressReport(orgProject, callback) { github.get('/repos/' + orgProject + '/issues?filter=all&labels=' + wipLabel + '&sort=updated&direction=asc', function(issues) { var issuesWithoutPullRequests = rejectPullRequests(issues); printIssues('in progress issues', issuesWithoutPullRequests, orgProject, callback); }); } // see https://developer.github.com/v3/issues/#list-issues function inReviewReport(orgProject, callback) { github.get('/repos/' + orgProject + '/issues?filter=all&labels=' + reviewLabel + '&sort=updated&direction=asc', function(issues) { var issuesWithoutPullRequests = rejectPullRequests(issues); printIssues('issues in review', issuesWithoutPullRequests, orgProject, callback); }); } // see http://stackoverflow.com/questions/1296358/subtract-days-from-a-date-in-javascript function lastWeek() { var date = new Date(); date.setDate(date.getDate() - 7); return date; } function printIssues(label, issues, orgProject, callback) { if (issues.length === 0) { callback('No ' + label + ' were found for ' + orgProject); } else { var message = 'These ' + label + ' were found for ' + orgProject + ':'; issues.forEach(function(issue) { message += "\n* " + issueToString(issue); }); callback(message); } } // list recently closed issues (in the past week) // see https://developer.github.com/v3/issues/#list-issues function recentClosedIssuesReport(orgProject, callback) { github.get('/repos/' + orgProject + '/issues?filter=all&state=closed&sort=updated&direction=desc&per_page=10&since=' + lastWeek().toISOString(), function(issues) { var issuesWithoutPullRequests = rejectPullRequests(issues); printIssues('recently closed issues', issuesWithoutPullRequests, orgProject, callback); }); } // see https://developer.github.com/v3/search/#search-issues // example query: -label:"2 - Working" -label:"1 - Ready" -label:"0 - Backlog" repo:betterup/myproject is:open type:issue function inboxIssues(orgProject, callback) { var queryParts = [ 'type:issue', 'is:open' ]; queryParts.push('repo:' + orgProject); workflowLabels.forEach(function(label) { queryParts.push('-label:"' + label + '"'); }); github.get('/search/issues?sort=created&order=asc&q=' + queryParts.join(' '), function(results) { var issues = results.items; printIssues('new issues', issues, orgProject, callback); }); } // see https://developer.github.com/v3/pulls/#list-pull-requests function openPullRequests(orgProject, callback) { github.get('/repos/' + orgProject + '/pulls?sort=updated&direction=asc', function(pullRequests) { printIssues('open pull requests', pullRequests, orgProject, callback); }); } var handler = function(msg) { var projectWithOrganization = msg.match[1].split('/'); var organization = projectWithOrganization[projectWithOrganization.length - 2] || defaultGithubOrganization; var project = projectWithOrganization[projectWithOrganization.length - 1] var orgProject = organization + '/' + project; msg.send('Generating project snapshot for ' + orgProject + '...'); msg.send('https://waffle.io/' + orgProject); recentClosedIssuesReport(orgProject, function(closedIssuesMessage) { msg.send(closedIssuesMessage); inReviewReport(orgProject, function(inReviewMessage) { msg.send(inReviewMessage); openPullRequests(orgProject, function(pullRequestsMessage) { msg.send(pullRequestsMessage); inProgressReport(orgProject, function(inProgressMessage) { msg.send(inProgressMessage); inboxIssues(orgProject, function(inboxMessage) { msg.send(inboxMessage); }); }); }); }); }); }; robot.respond(/waffle board (\S+)/i, handler); };
JavaScript
0.999999
@@ -1087,10 +1087,10 @@ _REV -E I +E W_LA
7ff88f80a3fdc650aa49da8fd6711027d295f251
fix `Socket#ack`
lib/socket.js
lib/socket.js
/** * Module dependencies. */ var parser = require('socket.io-parser') , Emitter = require('./emitter') , toArray = require('to-array') , debug = require('debug')('socket.io-client:socket') , on = require('./on') , bind; /** * Module exports. */ module.exports = exports = Socket; /** * Internal events (blacklisted). * These events can't be emitted by the user. */ var events = exports.events = [ 'connect', 'disconnect', 'error' ]; /** * Shortcut to `Emitter#emit`. */ var emit = Emitter.prototype.emit; /** * `Socket` constructor. * * @api public */ function Socket(io, nsp){ this.io = io; this.nsp = nsp; this.json = this; // compat this.ids = 0; this.acks = {}; this.open(); this.buffer = []; this.connected = false; } /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Called upon engine `open`. * * @api private */ Socket.prototype.open = Socket.prototype.connect = function(){ var io = this.io; io.open(); // ensure open if ('open' == this.io.readyState) this.onopen(); this.subs = [ on(io, 'open', bind(this, 'onopen')), on(io, 'error', bind(this, 'onerror')) ]; }; /** * Sends a `message` event. * * @return {Socket} self * @api public */ Socket.prototype.send = function(){ var args = toArray(arguments); args.unshift('message'); this.emit.apply(this, args); return this; }; /** * Override `emit`. * If the event is in `events`, it's emitted normally. * * @param {String} event name * @return {Socket} self * @api public */ Socket.prototype.emit = function(ev){ if (~events.indexOf(ev)) { emit.apply(this, arguments); } else { var args = toArray(arguments); var packet = { type: parser.EVENT, data: args }; // event ack callback if ('function' == typeof args[args.length - 1]) { debug('emitting packet with ack id %d', this.ids); this.acks[this.ids] = args.pop(); packet.id = this.ids++; } this.packet(packet); } return this; }; /** * Sends a packet. * * @param {Object} packet * @api private */ Socket.prototype.packet = function(packet){ packet.nsp = this.nsp; this.io.packet(packet); }; /** * Called upon `error`. * * @param {Object} data * @api private */ Socket.prototype.onerror = function(data){ this.emit('error', data); }; /** * "Opens" the socket. * * @api private */ Socket.prototype.onopen = function(){ debug('transport is open - connecting'); // write connect packet if necessary if ('/' != this.nsp) { this.packet({ type: parser.CONNECT }); } // subscribe var io = this.io; this.subs.push( on(io, 'packet', bind(this, 'onpacket')), on(io, 'close', bind(this, 'onclose')) ); }; /** * Called upon engine `close`. * * @param {String} reason * @api private */ Socket.prototype.onclose = function(reason){ debug('close (%s)', reason); this.emit('disconnect', reason); }; /** * Called with socket packet. * * @param {Object} packet * @api private */ Socket.prototype.onpacket = function(packet){ if (packet.nsp != this.nsp) return; switch (packet.type) { case parser.CONNECT: this.onconnect(); break; case parser.EVENT: this.onevent(packet); break; case parser.ACK: this.onack(packet); break; case parser.DISCONNECT: this.ondisconnect(); break; case parser.ERROR: this.emit('error', packet.data); break; } }; /** * Called upon a server event. * * @param {Object} packet * @api private */ Socket.prototype.onevent = function(packet){ var args = packet.data || []; debug('emitting event %j', args); if (packet.id) { debug('attaching ack callback to event'); args.push(this.ack(packet.id)); } if (this.connected) { emit.apply(this, args); } else { this.buffer.push(args); } }; /** * Produces an ack callback to emit with an event. * * @api private */ Socket.prototype.ack = function(){ var self = this; var sent = false; return function(){ // prevent double callbacks if (sent) return; var args = toArray(arguments); debug('sending ack %j', args); self.packet({ type: parser.ACK, data: args }); }; }; /** * Called upon a server acknowlegement. * * @param {Object} packet * @api private */ Socket.prototype.onack = function(packet){ debug('calling ack %s with %j', packet.id, packet.data); var fn = this.acks[packet.id]; fn.apply(this, packet.data); delete this.acks[packet.id]; }; /** * Called upon server connect. * * @api private */ Socket.prototype.onconnect = function(){ this.emit('connect'); this.connected = true; this.emitBuffered(); }; /** * Emit buffered events. * * @api private */ Socket.prototype.emitBuffered = function(){ for (var i = 0; i < this.buffer.length; i++) { emit.apply(this, this.buffer[i]); } this.buffer = []; }; /** * Called upon server disconnect. * * @api private */ Socket.prototype.ondisconnect = function(){ debug('server disconnect (%s)', this.nsp); this.destroy(); }; /** * Cleans up. * * @api private */ Socket.prototype.destroy = function(){ debug('destroying socket (%s)', this.nsp); // manual close means no reconnect for (var i = 0; i < this.subs.length; i++) { this.subs[i].destroy(); } // notify manager this.io.destroy(this); }; /** * Disconnects the socket manually. * * @return {Socket} self * @api public */ Socket.prototype.close = Socket.prototype.disconnect = function(){ debug('performing disconnect (%s)', this.nsp); this.packet(parser.PACKET_DISCONNECT); // manual close means no reconnect for (var i = 0; i < this.subs.length; i++) { this.subs[i].destroy(); } // notify manager this.io.destroy(this); // fire events this.onclose('io client disconnect'); return this; }; /** * Load `bind`. */ try { bind = require('bind'); } catch(e){ bind = require('bind-component'); }
JavaScript
0.000001
@@ -3968,32 +3968,34 @@ .ack = function( +id )%7B%0A var self = @@ -4207,16 +4207,30 @@ er.ACK,%0A + id: id,%0A da
7eedb451f01e6d73871fa85134bead4bfdcd8a99
add test for map
test/require.js
test/require.js
'use strict' var test = require('tape') var isNode = require('../is/node') test('require', function (t) { t.plan(8) var enhanceRequire = require('../require') var count = 0 try { require('./_files/styles.less') } catch (e) { count += 1 } t.equals(count, isNode ? 1 : 0, "`require('vigour-util/require')` shouldn't have any effect") enhanceRequire() count = 0 try { require('./_files/styles.less') require('./_files/styles.css') } catch (e) { count += 1 } t.equals(count, 0, 'makes `require` ignore styles') enhanceRequire({ package: true, exclude: '/scratch/' }) count = 0 try { require('./_files/scratch/this-should-be-ignored') } catch (e) { count += 1 } t.equals(count, 0, 'makes `require` ignore excluded string') enhanceRequire({ exclude: /\/scratch\// }) count = 0 try { require('./_files/scratch/this-should-be-ignored') } catch (e) { count += 1 } t.equals(count, 0, 'makes `require` ignore excluded regexp') enhanceRequire({ exclude: function exclude (item) { return item.indexOf('/scratch/') !== -1 } }) count = 0 try { require('./_files/scratch/this-should-be-ignored') } catch (e) { count += 1 } t.equals(count, 0, 'makes `require` ignore excluded paths') enhanceRequire.restore() count = 0 try { require('./_files/styles.less') } catch (e) { count += 1 } t.equals(count, isNode ? 1 : 0, "`require('vigour-util/require').restore()` should restore the original `require`") enhanceRequire({ exclude: [ 'scratch', /nooo/, function (item) { return item.indexOf('naaay') !== -1 } ] }) count = 0 try { require('./_files/scratch/this-should-be-ignored') require('./_files/nooo/this-should-be-ignored') require('./_files/naaay/this-should-be-ignored') } catch (e) { count += 1 } t.equals(count, 0, 'should accept an array of ignores') enhanceRequire.restore() count = 0 try { require('path') } catch (e) { console.log('e', e.stack) count += 1 } t.equals(count, 0, "`require('vigour-util/require').restore()` should restore `require`s default behaviour") })
JavaScript
0
@@ -114,9 +114,9 @@ lan( -8 +9 )%0A @@ -573,27 +573,8 @@ e(%7B%0A - package: true,%0A @@ -1282,24 +1282,274 @@ ed paths')%0A%0A + enhanceRequire(%7B%0A map: %7B'package.json': %7B isPackage: true %7D%7D%0A %7D)%0A%0A try %7B%0A var pkg = require('package.json')%0A t.ok(pkg.isPackage, 'should require the mapped object')%0A %7D catch (e) %7B%0A t.fail('crashed when requiring mapped object')%0A %7D%0A%0A enhanceReq
3636f5d3c112f1a23669909815e606939098e4b9
Add test for untrusted thenable attempting to fulfill a promise with another promise
test/resolve.js
test/resolve.js
(function(buster, when) { var assert, refute, fail, sentinel, other; assert = buster.assert; refute = buster.refute; fail = buster.assertions.fail; sentinel = {}; other = {}; buster.testCase('when.resolve', { 'should resolve an immediate value': function(done) { var expected = 123; when.resolve(expected).then( function(value) { assert.equals(value, expected); }, fail ).always(done); }, 'should resolve a resolved promise': function(done) { var expected, d; expected = 123; d = when.defer(); d.resolve(expected); when.resolve(d.promise).then( function(value) { assert.equals(value, expected); }, fail ).always(done); }, 'should reject a rejected promise': function(done) { var expected, d; expected = 123; d = when.defer(); d.reject(expected); when.resolve(d.promise).then( fail, function(value) { assert.equals(value, expected); } ).always(done); }, 'when assimilating untrusted thenables': { 'should trap exceptions during assimilation': function(done) { when.resolve({ then: function() { throw sentinel; } }).then( fail, function(val) { assert.same(val, sentinel); } ).always(done); }, 'should ignore exceptions after fulfillment': function(done) { when.resolve({ then: function(onFulfilled) { onFulfilled(sentinel); throw other; } }).then( function(val) { assert.same(val, sentinel); }, fail ).always(done); }, 'should ignore exceptions after rejection': function(done) { when.resolve({ then: function(_, onRejected) { onRejected(sentinel); throw other; } }).then( fail, function(val) { assert.same(val, sentinel); } ).always(done); } } }); })( this.buster || require('buster'), this.when || require('../when') );
JavaScript
0.000001
@@ -1761,16 +1761,375 @@ (done);%0A +%09%09%7D,%0A%0A%09%09'should assimilate thenable used as fulfillment value': function(done) %7B%0A%09%09%09when.resolve(%7B%0A%09%09%09%09then: function(onFulfilled) %7B%0A%09%09%09%09%09onFulfilled(%7B%0A%09%09%09%09%09%09then: function(onFulfilled) %7B%0A%09%09%09%09%09%09%09onFulfilled(sentinel);%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%7D);%0A%09%09%09%09%09throw other;%0A%09%09%09%09%7D%0A%09%09%09%7D).then(%0A%09%09%09%09function(val) %7B%0A%09%09%09%09%09assert.same(val, sentinel);%0A%09%09%09%09%7D,%0A%09%09%09%09fail%0A%09%09%09).always(done);%0A %09%09%7D%0A%09%7D%0A%0A
062e6d5a2354b1b71b9885f6113171c4d1ce42b8
Make async glob failure calls the supplied callback with the error.
lib/sokkit.js
lib/sokkit.js
(function() { var glob = require('glob'), path = require('path'), dirname = path.dirname, basename = path.basename, sep = path.sep; function Sokkit(options) { this.failed = []; this.modules = {}; this.disabled = {}; this.configure(options); } Sokkit.prototype = []; Sokkit.prototype = { configure: function(options) { options = options || {}; var path = dirname(dirname(require.main.filename)), modules = dirname(path); this.module = options.module || basename(path); this.pattern = options.pattern || (this.module + '-*'); this.path = options.path || (modules + sep + this.pattern); }, load: function(callback) { var sokkit = this; function process(files) { for(var index = 0, length = files.length; index < length; index++) { var module = basename(files[index]); try{ var result = require(module); sokkit.push(result); sokkit.modules[module] = result; }catch(error) { sokkit.failed.push({ module: module, error: error }); } } if (callback) { callback(null, sokkit); } } if (callback) { glob(this.path, function(error, files) { if (error) { console.warn('Plugin loading failed: ' + error); return; } process(files); }); }else{ process(glob.sync(this.path)); } return this; }, subset: function(filter) { var clone = new Sokkit({ module: this.module, pattern: this.pattern, path: this.path }); var modules = this.modules; for(var module in modules) { if (!modules.hasOwnProperty(module)) { continue; } var plugin = modules[module]; if (filter && filter(module, plugin)) { clone.push(plugin); clone.modules[module] = plugin; } } }, instantiate: function() { var args = Array.prototype.slice.call(arguments, 1), errors = [], modules = this.modules; var index = 0; for(var module in modules) { if (!modules.hasOwnProperty(module)) { continue; } try{ var plugin = require(module), instance = Object.create(plugin); plugin.apply(instance, args); this[index++] = instance; modules[module] = instance; }catch(error) { errors.push({ module: module, error: error }); index++ } } return errors; }, call: function(method) { return this.apply(method, Array.prototype.slice.call(arguments, 1)); }, apply: function(method, args) { var result = [], errors = [], modules = this.modules; result.errors = errors; for(var module in modules) { if (!modules.hasOwnProperty(module)) { continue; } var plugin = modules[module]; try{ result.push(plugin[method].apply(plugin, args)); }catch(error) { errors.push({ module: module, error: error }); } } return result; }, disable: function(module) { var plugin = this.modules[module]; if (!plugin) { throw new Error('Unknown plugin: ' + module); } var index = this.indexOf(plugin); this.splice(index, 1); delete this.modules[module]; this.disabled[module] = plugin; }, enable: function(module) { var plugin = this.disabled[module]; if (!plugin) { throw new Error('Unknown plugin: ' + module); } this.push(plugin); this.modules[module] = plugin; delete this.disabled[module]; } }; module.exports = Sokkit; })();
JavaScript
0
@@ -1216,48 +1216,16 @@ %09%09%09c -onsole.warn('Plugin loading failed: ' + +allback( erro
e6c2ca33a39592ed7d6fd51850b2cc184f053bec
Change generated value classes to use class syntax
types-lib.js
types-lib.js
/** * @flow */ import * as Immutable from 'immutable' export type Updater<T> = (t: T) => T; const registeredConstructors = {}; /** * Construct a class with properly-named fields. */ export const buildValueClass = ( className: string, fieldNames: Array<string>): any => { const defaults: any = {}; for (const name of fieldNames) { defaults[name] = undefined; } const resultConstructor = Immutable.Record(defaults); const resultClass = resultConstructor.prototype; for (const name of fieldNames) { const upperName = name[0].toUpperCase() + name.slice(1); resultClass['with' + upperName] = function(newVal) { return this.set(name, newVal); }; resultClass['update' + upperName] = function(updater) { return this.set(name, updater(this[name])); }; } resultClass.serialize = function() { const result = {}; result.__SERIALIZED_CLASS = className; for (const name of fieldNames) { result[name] = serialize(this[name]); } return result; }; registeredConstructors[className] = resultConstructor; return resultConstructor; }; export const buildUnionCaseClass = ( caseName: string, fieldNames: Array<string>): any => { const defaults: any = {}; for (const name of fieldNames) { defaults[name] = undefined; } defaults.type = undefined; const resultConstructor = Immutable.Record(defaults); const resultClass = resultConstructor.prototype; for (const name of fieldNames) { const upperName = name[0].toUpperCase() + name.slice(1); resultClass['with' + upperName] = function(newVal) { return this.set(name, newVal); }; resultClass['update' + upperName] = function(updater) { return this.set(name, updater(this[name])); }; } resultClass.match = function(visitor) { return visitor[caseName](this); }; resultClass.serialize = function() { const result = {}; result.__SERIALIZED_CLASS = caseName; for (const name of fieldNames) { result[name] = serialize(this[name]); } result.type = this.type; return result; }; registeredConstructors[caseName] = resultConstructor; return resultConstructor; }; const serialize = (obj: any): any => { if (obj == null || typeof obj !== 'object') { return obj; } if (typeof obj.serialize === 'function') { return obj.serialize(); } return obj; }; // TODO: Handle immutable maps. Currently it just doesn't serialize them. export const deserialize = (obj: any): any => { if (obj == null || typeof obj !== 'object') { return obj; } const className = obj.__SERIALIZED_CLASS; if (className == null) { return obj; } const constructorArg = {}; for (const name of Object.keys(obj)) { if (name !== '__SERIALIZED_CLASS') { constructorArg[name] = deserialize(obj[name]); } } const constructor = registeredConstructors[className]; return new constructor(constructorArg); }; export const serializeActionsMiddleware = (store: any) => (next: any) => (action: any) => { if (action != null && typeof action === 'object' && typeof action.serialize === 'function') { action = action.serialize(); } return next(action); };
JavaScript
0
@@ -398,32 +398,31 @@ c -onst resultConstructor = +lass ValueClass extends Imm @@ -448,62 +448,270 @@ lts) -;%0A const resultClass = resultConstructor.prototype; + %7B%0A serialize() %7B%0A const result = %7B%7D;%0A result.__SERIALIZED_CLASS = className;%0A for (const name of fieldNames) %7B%0A result%5Bname%5D = serialize(this%5Bname%5D);%0A %7D%0A return result;%0A %7D%0A %7D %0A @@ -813,35 +813,44 @@ 1);%0A -resultClass +ValueClass.prototype %5B'with' + up @@ -937,35 +937,44 @@ %7D;%0A -resultClass +ValueClass.prototype %5B'update' + @@ -1089,691 +1089,757 @@ re -sultClass.serialize = function() %7B%0A const result = %7B%7D;%0A result.__SERIALIZED_CLASS = className;%0A for (const name of fieldNames) %7B%0A result%5Bname%5D = serialize(this%5Bname%5D);%0A %7D%0A return result;%0A %7D;%0A registeredConstructors%5BclassName%5D = resultConstructor;%0A return resultConstructor;%0A%7D;%0A%0Aexport const buildUnionCaseClass = (%0A caseName: string, fieldNames: Array%3Cstring%3E): any =%3E %7B%0A const defaults: any = %7B%7D;%0A for (const name of fieldNames) %7B%0A defaults%5Bname%5D = undefined;%0A %7D%0A defaults.type = undefined;%0A const resultConstructor = Immutable.Record(defaults);%0A const resultClass = resultConstructor.prototype; +gisteredConstructors%5BclassName%5D = ValueClass;%0A return ValueClass;%0A%7D;%0A%0Aexport const buildUnionCaseClass = (%0A caseName: string, fieldNames: Array%3Cstring%3E): any =%3E %7B%0A const defaults: any = %7B%7D;%0A for (const name of fieldNames) %7B%0A defaults%5Bname%5D = undefined;%0A %7D%0A defaults.type = undefined;%0A class UnionCaseClass extends Immutable.Record(defaults) %7B%0A match(visitor) %7B%0A return visitor%5BcaseName%5D(this);%0A %7D%0A serialize() %7B%0A const result = %7B%7D;%0A result.__SERIALIZED_CLASS = caseName;%0A for (const name of fieldNames) %7B%0A result%5Bname%5D = serialize(this%5Bname%5D);%0A %7D%0A result.type = this.type;%0A return result;%0A %7D%0A %7D %0A @@ -1945,27 +1945,40 @@ -resultClass +UnionCaseClass.prototype %5B'with' @@ -2073,27 +2073,40 @@ -resultClass +UnionCaseClass.prototype %5B'update @@ -2225,68 +2225,28 @@ re -sultClass.match = function(visitor) %7B%0A return visi +gisteredConstruc tor +s %5Bcas @@ -2255,387 +2255,52 @@ ame%5D -(this);%0A %7D;%0A resultClass.serialize = function() %7B%0A const result = %7B%7D;%0A result.__SERIALIZED_CLASS = caseName;%0A for (const name of fieldNames) %7B%0A result%5Bname%5D = serialize(this%5Bname%5D);%0A %7D%0A result.type = this.type;%0A return result;%0A %7D;%0A registeredConstructors%5BcaseName%5D = resultConstructor;%0A return resultConstructor + = UnionCaseClass;%0A return UnionCaseClass ;%0A%7D;
a4a64461af70eec1aa59a781eff01c52497892fd
use the new DELETE endpoint to reset git repositories
commands/reset.js
commands/reset.js
'use strict' const cli = require('heroku-cli-util') const co = require('co') const {Dyno} = require('heroku-run') function * run (context) { const repo = require('../lib/repo') const app = context.app let dyno = new Dyno({ heroku: cli.heroku, app, attach: true, command: `set -e mkdir -p tmp/repo_tmp/unpack cd tmp/repo_tmp/unpack git init --bare . tar -zcf ../repack.tgz . curl -o /dev/null --upload-file ../repack.tgz '${yield repo.putURL(app)}' exit` }) yield dyno.start() } module.exports = { topic: 'repo', command: 'reset', description: 'reset the repo', needsAuth: true, needsApp: true, run: cli.command(co.wrap(run)) }
JavaScript
0
@@ -75,433 +75,249 @@ o')%0A -const %7BDyno%7D = require('heroku-run')%0A%0Afunction * run (context) %7B%0A const repo = require('../lib/repo')%0A const app = context.app%0A%0A let dyno = new Dyno(%7B%0A heroku: cli.heroku,%0A app,%0A attach: true,%0A command: %60set -e%0Amkdir -p tmp/repo_tmp/unpack%0Acd tmp/repo_tmp/unpack%0Agit init --bare .%0Atar -zcf ../repack.tgz .%0Acurl -o /dev/null --upload-file ../repack.tgz '$%7Byield repo.putURL(app)%7D'%0Aexit%60%0A %7D)%0A yield dyno.start( +%0Afunction * run (context, heroku) %7B%0A let r = heroku.request(%7B%0A method: 'DELETE',%0A path: %60/$%7Bcontext.app%7D.git%60,%0A host: %60git.$%7Bcontext.gitHost%7D%60%0A %7D)%0A%0A yield cli.action(%60Resetting Git repository for $%7Bcli.color.app(context.app)%7D%60, r )%0A%7D%0A
5049b6e3447af47416d7d30f16f6a7d47f507b1a
Fix toc to exit multiple nested lists
content/content.js
content/content.js
var $ = document.querySelector.bind(document) var state = { theme, raw, content, compiler, html: '', markdown: '', toc: '' } chrome.runtime.onMessage.addListener((req, sender, sendResponse) => { if (req.message === 'reload') { location.reload(true) } else if (req.message === 'theme') { state.theme = req.theme m.redraw() } else if (req.message === 'raw') { state.raw = req.raw m.redraw() } }) var oncreate = { markdown: () => { scroll() }, html: () => { scroll() if (state.content.toc && !state.toc) { state.toc = toc() m.redraw() } setTimeout(() => Prism.highlightAll(), 20) } } function mount () { $('pre').style.display = 'none' var md = $('pre').innerText m.mount($('body'), { oninit: () => { ;((done) => { if (document.charset === 'UTF-8') { done() return } m.request({method: 'GET', url: location.href, deserialize: (body) => { done(body) return body } }) })((data) => { state.markdown = data || md chrome.runtime.sendMessage({ message: 'markdown', compiler: state.compiler, markdown: state.markdown }, (res) => { state.html = res.html m.redraw() }) }) }, view: () => { var dom = [] if (state.raw) { dom.push(m('pre#markdown', {oncreate: oncreate.markdown}, state.markdown)) $('body').classList.remove('_toc-left', '_toc-right') } else { if (state.theme) { dom.push(m('link#theme [rel="stylesheet"] [type="text/css"]', { href: chrome.runtime.getURL('/themes/' + state.theme + '.css') })) } if (state.html) { dom.push(m('#html', {oncreate: oncreate.html, class: /github(-dark)?/.test(state.theme) ? 'markdown-body' : 'markdown-theme'}, m.trust(state.html) )) if (state.content.toc && state.toc) { dom.push(m.trust(state.toc)) $('body').classList.add('_toc-left') } } } return (dom.length ? dom : m('div')) } }) } function scroll () { if (state.content.scroll) { $('body').scrollTop = parseInt(localStorage.getItem('md-' + location.href)) } else if (location.hash) { $('body').scrollTop = $(location.hash) && $(location.hash).offsetTop setTimeout(() => { $('body').scrollTop = $(location.hash) && $(location.hash).offsetTop }, 100) } } scroll.init = () => { if (state.content.scroll) { var timeout = null window.addEventListener('scroll', () => { clearTimeout(timeout) timeout = setTimeout(() => { localStorage.setItem('md-' + location.href, $('body').scrollTop) }, 100) }) } setTimeout(scroll, 100) } if (document.readyState === 'complete') { mount() scroll.init() } else { window.addEventListener('DOMContentLoaded', mount) window.addEventListener('load', scroll.init) } var toc = ( link = (header) => '<a href="#' + header.id + '">' + header.title + '</a>') => Array.from($('#html').childNodes) .filter((node) => /h[1-6]/i.test(node.tagName)) .map((node) => ({ id: node.getAttribute('id'), level: parseInt(node.tagName.replace('H', '')), title: node.innerText })) .reduce((html, header, index, headers) => { if (index) { var prev = headers[index - 1] } if (!index || prev.level === header.level) { html += link(header) } else if (prev.level > header.level) { html += '</div>' + link(header) } else if (prev.level < header.level) { html += '<div id="_ul">' + link(header) } return html }, '<div id="_toc"><div id="_ul">') + '</div></div>'
JavaScript
0.000001
@@ -3630,26 +3630,92 @@ -html += '%3C/div%3E' +while (prev.level-- %3E header.level) %7B%0A html += '%3C/div%3E'%0A %7D%0A html + += lin
ef151929ee08df613b5547dfd411efa46fd9951a
Update node.js example
contrib/example.js
contrib/example.js
const net = require('net') const enableWatchMode = (process.argv[2] === 'w') const UInt16 = (value) => { const buf = Buffer.alloc(2) buf.writeUInt16BE(value, 0) return buf } const UInt8 = (value) => { const buf = Buffer.alloc(1) buf.writeUInt8(value, 0) return buf } const UInt64 = (value) => { const buf = Buffer.alloc(8) buf.fill(0) buf.writeUInt32BE(value, 4) console.log(buf) return buf } const WatchMode = Object.freeze({ None: 0, All: 1, Tagged: 2 }) class Ping { write (socket) { socket.write(UInt8(0)) } } class SetWatchMode { constructor (mode, tag) { this._mode = mode this._tag = tag } write (socket) { socket.write(UInt8(7)) socket.write(UInt8(this._mode)) if (this._tag !== null && this._mode === WatchMode.Tagged) { socket.write(UInt64(this._tag)) } } } class Radium { constructor (host = '127.0.0.1', port = 3126) { this._client = new net.Socket() this._onConnected = new Promise((resolve, reject) => { this._client.connect(port, host, resolve) }) } close () { this._client.end() } onConnected () { return this._onConnected } send (action) { action.write(this._client) } action (action) { return new Promise((resolve) => { // todo: parse response types and parse response this._client.once('data', (data) => { resolve(data.readUInt8(0)) }) this.send(action) }) } } const radium = new Radium() radium._client.on('data', (data) => { console.info('received data chunk', data) }) radium.onConnected() .then(() => { return Promise.all([ radium.action(new Ping()), radium.action(new Ping()) ]) }) .then((resp) => { console.log('Received', resp) if (enableWatchMode) { return radium.action(new SetWatchMode(WatchMode.Tagged, Number.parseInt(process.argv[3]))) } }) .then(() => { if (!enableWatchMode) { radium.close() } })
JavaScript
0.000001
@@ -751,17 +751,8 @@ tag -!== null && t @@ -1776,24 +1776,75 @@ atchMode) %7B%0A + const tag = Number.parseInt(process.argv%5B3%5D)%0A return @@ -1875,16 +1875,22 @@ tchMode( +tag ? WatchMod @@ -1901,42 +1901,29 @@ gged -, Number.parseInt(process.argv%5B3%5D) + : WatchMode.All, tag ))%0A
c843ee12ad501d7759baa8f3abbef65464852b61
Add auto-sidebar generating code
docs/_static/js/main.js
docs/_static/js/main.js
JavaScript
0.000001
@@ -1 +1,2259 @@ +var renderSidebarNav = function(type, headers) %7B%0A var $sidebar = $(%22.sidebar .accordion%22),%0A sidebarContents = '';%0A%0A $.each(headers, function (index, header) %7B%0A console.log('header: ' + header);%0A var $typeEl = $(%22.%22 + type + %22s-%22 + header),%0A typeTitle = $typeEl.find('h2').text(),%0A typeLink = %22#%22+$typeEl.find('h2').attr('id');%0A%0A sidebarContents += %22%3Cdiv class='accordion-group'%3E%22 +%0A %22%3Cdiv class='accordion-heading'%3E%22 +%0A %22%3Ca href='#' data-target='.%22 + type + %22-%22 + header + %22-accordion' data-parent='.sidebar-accordion' data-toggle='collapse'%3E%22 +%0A %22%3Cb%3E%22 + typeTitle + %22%3C/b%3E%22 +%0A %22%3C/a%3E%22 +%0A %22%3C/div%3E%22 +%0A %22%3Cdiv class='%22 + type + %22-%22 + header + %22-accordion accordion-body collapse in'%3E%22 +%0A %22%3Cdiv class='accordion-inner'%3E%22 +%0A %22%3Cul class='nav nav-list'%3E%22;%0A $typeEl.children('.' + type).each(function (idx, sub_type) %7B%0A var el = %22h4%22,%0A $type = $(sub_type).find(el);%0A title = $type.attr('id');%0A link = '#'+title;%0A%0A sidebarContents += %22%3Cli%3E%3Ca href='%22 + link + %22'%3E%22 + title + %22%3C/a%3E%3C/li%3E%22;%0A %7D);%0A%0A $typeEl.children('.' + type + '-parent').each(function (idx, sub_type) %7B%0A var el = %22h3%22,%0A $type = $(sub_type).find(el);%0A title = $type.attr('id');%0A link = '#'+title;%0A%0A sidebarContents += %22%3Cli%3E%3Ca href='%22 + link + %22'%3E%22 + title + %22%3C/a%3E%3C/li%3E%22;%0A %7D);%0A%0A sidebarContents += %22%3C/ul%3E%22 +%0A %22%3C/div%3E%22 +%0A %22%3C/div%3E%22 +%0A %22%3C/div%3E%22;%0A %7D);%0A $sidebar.append(sidebarContents);%0A%7D%0A%0Avar renderOptionsSidebarNav = function(option_types) %7B%0A renderSidebarNav('option', option_types);%0A%7D%0A%0Avar renderMethodsSidebarNav = function(method_types) %7B%0A renderSidebarNav('method', method_types);%0A%7D%0A%0Avar renderEventsSidebarNav = function(event_types) %7B%0A renderSidebarNav('event', event_types);%0A%7D %0A
f7818bc46d3b3966cd3a57422ca896f27b962be6
add module.exports
control/control.js
control/control.js
require("can-control");
JavaScript
0.000002
@@ -1,8 +1,25 @@ +module.exports = require(
60ec4def1e3627f9691c2d7544971358cf0f81aa
Add NODE_PATH support for resolveLoaders as well. (#778)
server/build/webpack.js
server/build/webpack.js
import { resolve, join } from 'path' import { createHash } from 'crypto' import { existsSync } from 'fs' import webpack from 'webpack' import glob from 'glob-promise' import WriteFilePlugin from 'write-file-webpack-plugin' import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin' import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin' import UnlinkFilePlugin from './plugins/unlink-file-plugin' import WatchPagesPlugin from './plugins/watch-pages-plugin' import JsonPagesPlugin from './plugins/json-pages-plugin' import getConfig from '../config' const documentPage = join('pages', '_document.js') const defaultPages = [ '_error.js', '_document.js' ] const nextPagesDir = join(__dirname, '..', '..', 'pages') const nextNodeModulesDir = join(__dirname, '..', '..', '..', 'node_modules') const interpolateNames = new Map(defaultPages.map((p) => { return [join(nextPagesDir, p), `dist/pages/${p}`] })) export default async function createCompiler (dir, { dev = false, quiet = false } = {}) { dir = resolve(dir) const config = getConfig(dir) const defaultEntries = dev ? [join(__dirname, '..', '..', 'client/webpack-hot-middleware-client')] : [] const mainJS = dev ? require.resolve('../../client/next-dev') : require.resolve('../../client/next') let minChunks const entry = async () => { const entries = { 'main.js': mainJS } const pages = await glob('pages/**/*.js', { cwd: dir }) for (const p of pages) { entries[join('bundles', p)] = [...defaultEntries, `./${p}?entry`] } for (const p of defaultPages) { const entryName = join('bundles', 'pages', p) if (!entries[entryName]) { entries[entryName] = [...defaultEntries, join(nextPagesDir, p) + '?entry'] } } // calculate minChunks of CommonsChunkPlugin for later use minChunks = Math.max(2, pages.filter((p) => p !== documentPage).length) return entries } const plugins = [ new webpack.LoaderOptionsPlugin({ options: { context: dir, customInterpolateName (url, name, opts) { return interpolateNames.get(this.resourcePath) || url } } }), new WriteFilePlugin({ exitOnErrors: false, log: false, // required not to cache removed files useHashIndex: false }), new webpack.optimize.CommonsChunkPlugin({ name: 'commons', filename: 'commons.js', minChunks (module, count) { // NOTE: it depends on the fact that the entry funtion is always called // before applying CommonsChunkPlugin return count >= minChunks } }), new JsonPagesPlugin(), new CaseSensitivePathPlugin() ] if (dev) { plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new UnlinkFilePlugin(), new WatchPagesPlugin(dir) ) if (!quiet) { plugins.push(new FriendlyErrorsWebpackPlugin()) } } else { plugins.push( new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: false }) ) } const mainBabelOptions = { babelrc: true, cacheDirectory: true, sourceMaps: dev ? 'both' : false, presets: [] } const hasBabelRc = existsSync(join(dir, '.babelrc')) if (hasBabelRc) { console.log('> Using .babelrc defined in your app root') } else { mainBabelOptions.presets.push(require.resolve('./babel/preset')) } const rules = (dev ? [{ test: /\.js(\?[^?]*)?$/, loader: 'hot-self-accept-loader', include: [ join(dir, 'pages'), nextPagesDir ] }, { test: /\.js(\?[^?]*)?$/, loader: 'react-hot-loader/webpack', exclude: /node_modules/ }] : []) .concat([{ test: /\.json$/, loader: 'json-loader' }, { test: /\.(js|json)(\?[^?]*)?$/, loader: 'emit-file-loader', include: [dir, nextPagesDir], exclude (str) { return /node_modules/.test(str) && str.indexOf(nextPagesDir) !== 0 }, options: { name: 'dist/[path][name].[ext]' } }, { loader: 'babel-loader', include: nextPagesDir, exclude (str) { return /node_modules/.test(str) && str.indexOf(nextPagesDir) !== 0 }, options: { babelrc: false, cacheDirectory: true, sourceMaps: dev ? 'both' : false, presets: [require.resolve('./babel/preset')] } }, { test: /\.js(\?[^?]*)?$/, loader: 'babel-loader', include: [dir], exclude (str) { return /node_modules/.test(str) }, options: mainBabelOptions }]) let webpackConfig = { context: dir, entry, output: { path: join(dir, '.next'), filename: '[name]', libraryTarget: 'commonjs2', publicPath: '/_webpack/', strictModuleExceptionHandling: true, devtoolModuleFilenameTemplate ({ resourcePath }) { const hash = createHash('sha1') hash.update(Date.now() + '') const id = hash.digest('hex').slice(0, 7) // append hash id for cache busting return `webpack:///${resourcePath}?${id}` } }, resolve: { modules: [ nextNodeModulesDir, 'node_modules' ].concat( (process.env.NODE_PATH || '') .split(process.platform === 'win32' ? ';' : ':') .filter((p) => !!p) ) }, resolveLoader: { modules: [ nextNodeModulesDir, 'node_modules', join(__dirname, 'loaders') ] }, plugins, module: { rules }, devtool: dev ? 'inline-source-map' : false, performance: { hints: false } } if (config.webpack) { console.log('> Using "webpack" config function defined in next.config.js.') webpackConfig = await config.webpack(webpackConfig, { dev }) } return webpack(webpackConfig) }
JavaScript
0
@@ -3223,24 +3223,155 @@ %0A )%0A %7D%0A%0A + const nodePathList = (process.env.NODE_PATH %7C%7C '')%0A .split(process.platform === 'win32' ? ';' : ':')%0A .filter((p) =%3E !!p)%0A%0A const main @@ -5438,155 +5438,41 @@ les' -%0A %5D.concat(%0A (process.env.NODE_PATH %7C%7C '')%0A .split(process.platform === 'win32' ? ';' : ':')%0A .filter((p) =%3E !!p) +,%0A ...nodePathList %0A -) +%5D %0A @@ -5557,32 +5557,32 @@ 'node_modules',%0A - join(__d @@ -5599,16 +5599,41 @@ oaders') +,%0A ...nodePathList %0A %5D
78361a3d2ae8da781a8470db779a68e2e5857231
append 'config' to configuration object names
server/config/config.js
server/config/config.js
'use strict'; var path = require('path'), _ = require('lodash'); /** * Environment variables and application configuration. */ var base = { app: { root: path.normalize(__dirname + '/../..'), port: process.env.PORT || 3000, env: process.env.NODE_ENV || 'development', secret: 'secret key' }, mongo: { url: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost:27017/koan' } }; var platforms = { development: { mongo: { url: 'mongodb://localhost:27017/koan-dev' } }, test: { app: { port: 3001 }, mongo: { url: 'mongodb://localhost:27017/koan-test' } }, production: { passport: { facebook: { clientID: 'APP_ID', clientSecret: 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, twitter: { clientID: 'CONSUMER_KEY', clientSecret: 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, google: { clientID: 'APP_ID', clientSecret: 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback' } } } }; // override the base configuration with the platform specific values _.merge(base, platforms[base.app.env]); module.exports = base;
JavaScript
0.999036
@@ -144,16 +144,22 @@ var base +Config = %7B%0D%0A @@ -466,17 +466,22 @@ platform -s +Config = %7B%0D%0A @@ -1332,16 +1332,22 @@ rge(base +Config , platfo @@ -1352,14 +1352,25 @@ form -s%5Bbase +Config%5BbaseConfig .app @@ -1399,9 +1399,15 @@ s = base +Config ;
c15e8ebb32faedfa49994a9a1c253f3137e10991
Fix environment for cloud
server/config/config.js
server/config/config.js
let path = require('path'); let rootPath = path.normalize(__dirname + '/../../'); const connectionStrings = { production: 'mongodb://ilian82:[email protected]:13958/proba-db', development: 'mongodb://localhost:27017/animalshotel' }; module.exports = { development: { environment: process.env.NODE_ENV || 'development', rootPath: rootPath, db: connectionStrings[process.env.NODE_ENV || 'development'], port: process.env.PORT || 3000 } };
JavaScript
0.000025
@@ -293,59 +293,114 @@ -environment +rootPath : -p ro -cess.env.NODE_ENV %7C%7C 'development', +otPath,%0A db: connectionStrings.development,%0A port: 3000%0A %7D,%0A production: %7B %0A @@ -457,47 +457,19 @@ ings -%5Bprocess.env.NODE_ENV %7C%7C 'development'%5D +.production ,%0A @@ -500,16 +500,8 @@ PORT - %7C%7C 3000 %0A
d3a376db189b2caf0129d798dac5233b04441214
Return page size to 50
controllers/pwa.js
controllers/pwa.js
/** * Copyright 2015-2016, Google, Inc. * 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. */ 'use strict'; const express = require('express'); const pwaLib = require('../lib/pwa'); const Pwa = require('../models/pwa'); const router = express.Router(); // eslint-disable-line new-cap const config = require('../config/config'); const CLIENT_ID = config.get('CLIENT_ID'); const CLIENT_SECRET = config.get('CLIENT_SECRET'); const LIST_PAGE_SIZE = 1; const DEFAULT_PAGE_NUMBER = 1; const DEFAULT_SORT_ORDER = 'newest'; /** * GET /pwas/add * * Display a page of PWAs (up to ten at a time). */ router.get('/', (req, res, next) => { const pageNumber = parseInt(req.query.page, 10) || DEFAULT_PAGE_NUMBER; const sortOrder = req.query.sort | DEFAULT_SORT_ORDER; const start = (pageNumber - 1) * LIST_PAGE_SIZE; pwaLib.list(start, LIST_PAGE_SIZE, sortOrder) .then(result => { res.render('pwas/list.hbs', { pwas: result.pwas, hasNextPage: result.hasMore, hasPreviousPage: pageNumber > 1, nextPageNumber: pageNumber + 1, previousPageNumber: pageNumber - 1, currentPageNumber: pageNumber }); }) .catch(err => { next(err); }); }); /** * GET /pwas/add * * Display a form for creating a PWA. */ router.get('/add', (req, res) => { res.render('pwas/form.hbs', { pwa: {}, action: 'Add' }); }); /** * POST /pwas/add * * Create a PWA. */ router.post('/add', (req, res, next) => { const manifestUrl = req.body.manifestUrl; const idToken = req.body.idToken; var pwa = new Pwa(manifestUrl); if (!manifestUrl) { res.render('pwas/form.hbs', { pwa, error: 'no manifest provided' }); return; } if (!idToken) { res.render('pwas/form.hbs', { pwa, error: 'user not logged in' }); return; } verifyIdToken(CLIENT_ID, CLIENT_SECRET, idToken) .then(user => { pwa.setUserId(user); return pwaLib.save(pwa); }) .then(savedData => { res.redirect(req.baseUrl + '/' + savedData.id); return; }) .catch(err => { if (typeof err === 'number') { switch (err) { case pwaLib.E_MANIFEST_ERROR: res.render('pwas/form.hbs', { pwa, error: 'error loading manifest' // could be 404, not JSON, domain does not exist }); return; default: return next(err); } } res.render('pwas/form.hbs', { pwa, error: err }); return; }); }); /** * GET /pwas/:id * * Display a PWA. */ router.get('/:pwa', (req, res, next) => { pwaLib.find(req.params.pwa) .then(entity => { res.render('pwas/view.hbs', { pwa: entity }); }) .catch(() => { return next(); }); }); /** * Errors on "/pwas/*" routes. */ router.use((err, req, res, next) => { // Format error and forward to generic error handler for logging and // responding to the request err.response = err.message; next(err); }); /** * @param {string} clientId * @param {string} clientSecret * @param {string} idToken * @return {Promise<GoogleLogin>} */ function verifyIdToken(clientId, clientSecret, idToken) { const authFactory = new (require('google-auth-library'))(); const client = new authFactory.OAuth2(clientId, clientSecret); return new Promise((resolve, reject) => { client.verifyIdToken(idToken, clientId, (err, user) => { if (err) { reject(err); } resolve(user); }); }); } module.exports = router;
JavaScript
0.000001
@@ -945,17 +945,18 @@ _SIZE = -1 +50 ;%0Aconst
6babf86a8d09c66190aad8512ea17f38681de11a
Remove catch-all route temporarily
server/config/routes.js
server/config/routes.js
import uc from '../APIv1/users/userController.js'; import rc from '../APIv1/recipes/recipeController.js'; import sc from '../APIv1/search/searchController.js'; module.exports = (app, express) => { /** * Users */ app.post('/api/v1/users/', /* auth, */ uc.createUser); app.get('/api/v1/users/:user_id', uc.getOneUser); // TODO: getAllUsers should be protected for only admins, eventually. app.get('/api/v1/users/', /* auth, */ uc.getAllUsers); // app.get('/api/v1/users/me', /* auth, */ getCurrentUser); // app.put('/api/v1/users/:user_id', /* auth, */ updateUser); // app.get('/api/v1/users/followers/:user_id', findFollowers); /** * Recipes */ // app.post('/api/v1/recipes/:recipe', /* auth, */ createRecipe); // app.get('/api/v1/recipes/:recipe', getOneRecipe); // app.put('/api/v1/recipes/:recipe', /* auth, */ updateRecipe); // app.get('/api/v1/recipes/:user', /* auth, */ getUsersRecipes); // app.get('/api/v1/recipes/me', /* auth, */ namedFn); // app.get('/api/v1/recipes/me', /* auth, */ namedFn); /** * Favorites */ // app.get('/api/v1/favorites/:user', /* auth, */ getUserFavorites); // app.get('/api/v1/favorites/:user/count', /* auth, */ getUserFavoritesCount); /** * Search */ app.get('/api/v1/recipes/search/:q', sc.searchRecipes); /** * Catch unspecified routes */ app.get('*', (request, response) => { // NOTE: this seems to conflict with /api/v1/users/ get response.redirect('/'); }); };
JavaScript
0.000012
@@ -1453,16 +1453,19 @@ get%0A + // respons
c3f76dabc13f8ecdae96027ef01b5d45256a3893
Remove DAOProperty from FOAMmodels.
core/FOAMmodels.js
core/FOAMmodels.js
/** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * 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. */ function IN_BROWSER() { return typeof vm == "undefined" || ! vm.runInThisContext; } function IN_NODEJS() { return ! IN_BROWSER(); } function IN_CHROME_APP() { return window.chrome && window.chrome.runtime && (!! window.chrome.runtime.id) }; function IN_BROWSER_NOT_APP() { return IN_BROWSER() && ! IN_CHROME_APP(); } var files = [ // ['ServiceWorker', function() { return window.navigator && navigator.serviceWorker; }], [ 'firefox', function() { return window.navigator && navigator.userAgent.indexOf('Firefox') != -1; }], [ 'funcName', function() { return ! Number.name; }], [ 'safari', function() { return window.navigator && navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1; }], [ 'node', IN_NODEJS ], [ 'i18n', IN_BROWSER ], 'stdlib', ['WeakMap', function() { return ! this['WeakMap']; }], 'async', 'parse', 'event', 'JSONUtil', 'XMLUtil', 'context', 'JSONParser', 'TemplateUtil', [ 'ChromeEval', IN_CHROME_APP ], 'FOAM', // To use FO, uncomment the next line // and comment out all lines from FObject to mm6Misc // inclusively // 'experimental/fo', // 'experimental/protobuffeatures', 'FObject', 'BootstrapModel', 'mm1Model', 'mm2Property', 'mm3Types', 'mm4Method', 'mm5Debug', 'mm6Misc', '../js/foam/core/bootstrap/OrDAO', [ '../js/foam/core/bootstrap/BrowserFileDAO', IN_BROWSER_NOT_APP ], [ '../js/node/dao/ModelFileDAO', IN_NODEJS ], '../js/foam/ui/Window', 'value', 'view', '../js/foam/ui/FoamTagView', 'cview', '../js/foam/grammars/CSS3', 'HTMLParser', 'mlang', 'mlang1', 'mlang2', 'glang', 'QueryParser', 'oam', 'visitor', 'messaging', // '../js/foam/dao/ProxyDAO', 'dao', 'arrayDAO', 'index', 'models', 'oauth', '../js/foam/core/types/DAOProperty', // TODO: remove when Adam fixes what he broke [ 'ModelDAO', IN_BROWSER_NOT_APP ], [ '../js/foam/core/bootstrap/ChromeAppFileDAO', IN_CHROME_APP ], [ 'ChromeAppModelDAO', IN_CHROME_APP ], [ 'NodeModelDAO', IN_NODEJS ] ];
JavaScript
0
@@ -2414,93 +2414,8 @@ h',%0A - '../js/foam/core/types/DAOProperty', // TODO: remove when Adam fixes what he broke%0A %5B
ad202d16a525dc4b6f603e080222d46a5d2e4052
Update TensorPlaceholder.js
CNN/Conv/TensorPlaceholder.js
CNN/Conv/TensorPlaceholder.js
export { Base }; import * as Pool from "../util/Pool.js"; import * as Recyclable from "../util/Recyclable.js"; import * as ActivationEscaping from "./ActivationEscaping.js"; /** * A placeholder for tensor. * * - In Operation.TwinArray.operation_append_Xxx(), it is used for tracking a tensor's final operation which should be responsible * for destroying the tensor. * * - In operation's .apply(), it is used for transferring tensor to the next sub operation. * * * * @member {Operation.Base} finalOperation * The operation uses this tensor at final. It should be responsible for destroying this tensor. If null, this tensor is * not used by any operation. * * @member {tf.tensor} realTensor * The real tensor represented by this placeholder. It is filled dynamically in an operation's apply() method. * * @member {ActivationEscaping.ScaleBoundsArray} scaleBoundsArray * The element value bounds (per channel) of the tensor. Usually, it is from the output of the previous operation's value bounds * set. It will be kept (not cloned) directly. So caller should use them carefully. * */ class Base extends Recyclable.Root { /** * Used as default TensorPlaceholder.Base provider for conforming to Recyclable interface. */ static Pool = new Pool.Root( "TensorPlaceholder.Base.Pool", Base, Base.setAsConstructor ); /** * */ constructor() { super(); Base.setAsConstructor_self.call( this ); } /** @override */ static setAsConstructor() { super.setAsConstructor(); Base.setAsConstructor_self.call( this ); return this; } /** @override */ static setAsConstructor_self() { this.finalOperation = null; this.realTensor = null; this.set_height_width_channelCount_scaleBoundsArray_byTensorPlaceholder( null ); } /** * Release the .scaleBoundsArray * * Usually, this method is not responsible for releasing .finalOperation and .realTensor. They should be handled * by the caller of apply(). * * @override */ disposeResources() { this.ScaleBoundsArray_dispose(); this.finalOperation = null; this.realTensor = null; this.set_height_width_channelCount_scaleBoundsArray_byTensorPlaceholder( null ); super.disposeResources(); } /** * Release (and recycle) .scaleBoundsArray (if exists). */ ScaleBoundsArray_dispose() { if ( this.scaleBoundsArray ) { this.scaleBoundsArray.disposeResources_and_recycleToPool(); this.scaleBoundsArray = null; } } /** * * @param {ActivationEscaping.ScaleBoundsArray} scaleBoundsArray * The tensor placeholder's ScaleBoundsArray. It will be owned by this TensorPlaceholder. (i.e. This TensorPlaceholder will be * responsible for releasing it.) */ set_height_width_channelCount_scaleBoundsArray( height, width, channelCount, channelCount_lowerHalf, channelCount_higherHalf, scaleBoundsArray ) { this.height = height; this.width = width; this.channelCount = channelCount; this.channelCount_lowerHalf = channelCount_lowerHalf; this.channelCount_higherHalf = channelCount_higherHalf; this.ScaleBoundsArray_dispose(); // Release old ScaleBoundsArray. this.scaleBoundsArray = scaleBoundsArray; } /** * Note: The .finalOperation and .realTensor are not modified by this method. * * @param {TensorPlaceholder} aTensorPlaceholder * The tensor placeholder's height, width, channelCount, scaleBoundsArray will be used directly (i.e. not cloned) by this * tensor placeholder. If null, these properties will be set to undefined. */ set_height_width_channelCount_scaleBoundsArray_byTensorPlaceholder( aTensorPlaceholder ) { if ( aTensorPlaceholder ) { this.set_height_width_channelCount_scaleBoundsArray( aTensorPlaceholder.height, aTensorPlaceholder.width, aTensorPlaceholder.channelCount, aTensorPlaceholder.channelCount_lowerHalf, aTensorPlaceholder.channelCount_higherHalf, aTensorPlaceholder.scaleBoundsArray.clone() // Note: Because TensorPlaceholder owns the ScaleBoundsArray, it should be cloned. ); } else { this.set_height_width_channelCount_scaleBoundsArray( undefined, undefined, undefined, undefined, undefined, undefined ); } } /** * * @param {TensorPlaceholder} aTensorPlaceholder The tensor placeholder to be comapred. * * @return {boolean} * Return true, if this tensor placeholder's height, width, channelCount are the same as aTensorPlaceholder. Note: the * .channelCount_lowerHalf and .channelCount_higherHalf are not compared. */ is_height_width_channelCount_same_byTensorPlaceholder( aTensorPlaceholder ) { if ( ( this.height != aTensorPlaceholder.height ) || ( this.width != aTensorPlaceholder.width ) || ( this.channelCount != aTensorPlaceholder.channelCount ) //|| ( this.channelCount_lowerHalf != aTensorPlaceholder.channelCount_lowerHalf ) //|| ( this.channelCount_higherHalf != aTensorPlaceholder.channelCount_higherHalf ) ) return false; return true; } }
JavaScript
0.000001
@@ -4010,16 +4010,17 @@ ndsArray +? .clone()
15fb7872743a26742a0b9db1f7c67425c0ef91a1
change if else to else
generators/gulp/templates/gulpfile.js
generators/gulp/templates/gulpfile.js
var path = require('path'); var gulp = require('gulp'); var nsp = require('gulp-nsp'); var gulpRequireTasks = require('gulp-require-tasks'); var watch = require('gulp-watch'); var taskListing = require('gulp-task-listing'); <% if(type === 'dynamic') { -%> var exec = require('gulp-exec'); <% } -%> <% if(type === 'static') { -%> var staticRender = require('./gulp-tasks/static'); <% } -%> gulpRequireTasks({ path: path.resolve(process.cwd(), './gulp-tasks') }); gulp.task('help', taskListing); gulp.task('nsp', function(cb) { nsp({package: path.resolve('package.json')}, cb); }); gulp.task('prepublish', ['nsp']); <% if(type === 'static') { -%> gulp.task('build', [ 'babel:build' ], staticRender); gulp.task('watch', ['babel:build'], function() { gulp.watch('./src/**', [ 'babel:render', 'lint' ]); }); <% else if(type === 'dynamic') { -%> gulp.task('server', [ 'babel:build' ], function() { gulp.src('./') .pipe(exec('NODE_ENV=1 node ./lib/server')) .pipe(exec.reporter(reportOptions)); }); gulp.task('server:dev', [ 'babel:render' ], function() { gulp.src('./') .pipe(exec('node ./lib/server')) .pipe(exec.reporter(reportOptions)); }); gulp.task('watch', ['babel:build'], function() { gulp.watch('./src/**', [ 'server:dev', 'lint' ]); }); <% } -%> gulp.task('default', [ <% if(eslint) { -%> 'lint', <% } -%> 'test' ]);
JavaScript
0.000456
@@ -827,12 +827,16 @@ %0A%3C%25 -else +%7D -%25%3E%0A%3C%25 if(
7088b4d6a0b93d5b5619e7eb164e01d2e2843373
add discussLinker to sub-dir label
src/containers/Sidebar/Footer.js
src/containers/Sidebar/Footer.js
import React from 'react' // eslint-disable-next-line import/named import { ICON_CMD } from '@config' import { Wrapper, InnerWrapper, SettingIcon, OptionWrapper, OptionItem, OptionDivider, } from './styles/footer' import { sortBtnOnClick } from './logic' const Footer = ({ pin, showFooterShadow, sortOptActive }) => ( <Wrapper pin={pin} dropShadow={showFooterShadow}> <InnerWrapper pin={pin}> <SettingIcon src={`${ICON_CMD}/setting.svg`} /> <OptionWrapper pin={pin}> <OptionItem active={sortOptActive} onClick={() => sortBtnOnClick()}> 排序 </OptionItem> <OptionDivider /> <OptionItem>分组</OptionItem> </OptionWrapper> </InnerWrapper> </Wrapper> ) export default Footer
JavaScript
0.000001
@@ -77,16 +77,28 @@ ICON_CMD +, ISSUE_ADDR %7D from @@ -108,16 +108,113 @@ onfig'%0A%0A +import Popover from '@components/Popover'%0Aimport DiscussLinker from '@components/DiscussLinker'%0A%0A import %7B @@ -736,24 +736,181 @@ nDivider /%3E%0A + %3CPopover%0A placement=%22top%22%0A trigger=%22hover%22%0A content=%7B%3CDiscussLinker title=%22%E5%88%86%E7%BB%84%22 addr=%7B%60$%7BISSUE_ADDR%7D/597%60%7D /%3E%7D%0A %3E%0A %3COpt @@ -929,24 +929,43 @@ OptionItem%3E%0A + %3C/Popover%3E%0A %3C/Opti
08a8709ea43c471009a2f1afefd1193cdfc5b371
Fix bug in Sec2Heading.
src/converter/r2t/Sec2Heading.js
src/converter/r2t/Sec2Heading.js
import { last } from 'substance' import { replaceWith, findChild } from '../util/domHelpers' export default class Sec2Heading { import(dom) { // find all top-level sections let topLevelSecs = dom.findAll('sec').filter(sec => sec.parentNode.tagName !== 'sec') topLevelSecs.forEach((sec) => { replaceWith(sec, _flattenSec(sec, 1)) }) } export(dom) { let allHeadings = dom.findAll('heading') let containers = [] allHeadings.forEach((heading)=> { let container = heading.parentNode if (!container._sec2heading) { containers.push(container) container._sec2heading = true } }) containers.forEach((container) => { _createSections(container) }) } } function _flattenSec(sec, level) { let result = [] let h = sec.createElement('heading') h.attr(sec.getAttributes()) h.attr('level', level) // move the section front matter if(sec.find('sec-meta')) { console.error('<sec-meta> is not supported by <heading> right now.') } let label = sec.find('label') if (label) { h.attr('label', label.textContent) label.remove() } let title = findChild(sec, 'title') if (title) { h.append(title.childNodes) title.remove() } result.push(h) // process the remaining content recursively let children = sec.children let L = children.length for (let i = 0; i < L; i++) { const child = children[i] if (child.tagName === 'sec') { result = result.concat(_flattenSec(child, level+1)) } else { result.push(child) } } return result } function _createSections(container) { const doc = container.getOwnerDocument() const children = container.children // clear the container first container.empty() let stack = [{ el: container }] for (let i=0; i < children.length; i++) { let child = children[i] if (child.tagName === 'heading') { let heading = child let level = child.attr('level') || 1 while (stack.length >= level+1) { stack.pop() } let sec = doc.createElement('sec') // copy all attributes from the heading to the section element let attributes = {} child.getAttributes().forEach((val, key) => { if (key !== 'level') { attributes[key] = val } }) sec.attr(attributes) let title = doc.createElement('title') title.innerHTML = heading.innerHTML sec.appendChild(title) last(stack).el.appendChild(sec) stack.push({ el: sec }) } else { last(stack).el.appendChild(child) } } }
JavaScript
0
@@ -1949,16 +1949,25 @@ level = +parseInt( child.at @@ -1981,17 +1981,20 @@ el') %7C%7C -1 +%221%22) %0A w
b814aecb67c42ef68109e5304343c6a743f31200
Fix setting default location, #55
src/cred/phone-number/actions.js
src/cred/phone-number/actions.js
import { getEntity, read, swap, updateEntity } from '../../store/index'; import * as c from '../index'; import * as cc from '../country_codes'; import { closeLocationSelect, openLocationSelect } from './index'; export function changePhoneNumber(id, phoneNumber) { swap(updateEntity, "lock", id, c.setPhoneNumber, phoneNumber); } export function changePhoneLocation(id, location) { swap(updateEntity, "lock", id, lock => { lock = closeLocationSelect(lock); lock = c.setPhoneLocation(lock, location); return lock; }); } // TODO: move this to another place since is not really an action. export function setInitialPhoneLocation(m, options) { const { defaultLocation } = options; if (defaultLocation && typeof defaultLocation === "string") { if (!cc.findByIsoCode(defaultLocation)) { throw new Error(`Unable to set the default location, can't find any country with the code "${defaultLocation}".`); } return c.setPhoneLocation(m, defaultLocation); } else { const user = read(getEntity, "user"); const userLocation = user && user.get("location"); return cc.findByIsoCode(userLocation) ? c.setPhoneLocation(m, userLocation) : m; } } export function selectPhoneLocation(id, searchStr) { swap(updateEntity, "lock", id, openLocationSelect, searchStr); } export function cancelSelectPhoneLocation(id) { swap(updateEntity, "lock", id, closeLocationSelect); }
JavaScript
0
@@ -769,13 +769,25 @@ -if (! +const location = cc.f @@ -815,16 +815,35 @@ ocation) +;%0A if (!location ) %7B%0A @@ -998,24 +998,17 @@ tion(m, -defaultL +l ocation) @@ -1072,21 +1072,17 @@ const -userL +l ocation @@ -1083,16 +1083,33 @@ ation = +cc.findByIsoCode( user && @@ -1128,16 +1128,17 @@ cation%22) +) ;%0A re @@ -1146,44 +1146,16 @@ urn -cc.findByIsoCode(userLocation)%0A +location ? c @@ -1179,21 +1179,17 @@ (m, -userL +l ocation) %0A @@ -1184,22 +1184,16 @@ ocation) -%0A : m;%0A
e1a2964d467b52a620ce0db2bd167fbdb3dab519
Add data for checkboxes
src/data/serviceRequestFields.js
src/data/serviceRequestFields.js
export const singleLineFields = [ { name: 'Name', required: true, type: 'isAlpha', error: 'Not a valid name' }, { name: 'Email', required: true, type: 'isEmail', error: 'Not a valid email' }, { name: 'Phone', required: false, type: 'isNumeric', error: 'Not a valid phone number' }, { name: 'Department', required: false, type: 'isAlphanumeric', error: 'Text is not valid' } ] export const multiLineFields = [ { name: 'Project Description', required: true, type: 'isAlphanumeric', error: 'Not a valid project description' }, { name: 'Project Goal', required: false, type: 'isAlphanumeric', error: 'Not a valid goal' }, { name: 'Project Budget', required: false, type: 'isNumeric', error: 'Not a valid number' }, { name: 'Key Messages', required: false, type: 'isAlphanumeric', error: 'Not a valid key message' }, { name: 'Primary Target Audience', required: false, type: 'isAlphanumeric', error: 'Not a valid target' }, { name: 'Secondary Target Audience', required: false, type: 'isAlphanumeric', error: 'Not a valid target' }, { name: 'Project Contact (if other than yourself)', required: false, type: null, error: null }, { name: 'Comments', required: false, type: 'isAlphanumeric', error: 'Not a valid comment' } ] export const leftCheckboxes = [ { name: 'Photography', icon: true, dialogTitle: 'Photography', dialogText: `<p>Photography in addition to events listed below is dependent upon student photographer availability.</p><h3>Events covered:</h3> <ul> <li>Graduation </li> <li>Nursing Graduation</li> <li>Alumni Awards</li> <li>Faculty Awards</li> <li>Employee Breakfast</li> <li>Move-In Day</li> <li>Poverello Award</li> <li>Founders Association Awards</li> <li>March for Life</li> <li>Rehearsal for Anathan Theatre</li> <li>Bishop's Requests</li> <li>Homecoming Events</li> <li>Festival of Praise (1)</li> <li>High Profile Talks</li> <li>Feast of St. Francis Mass</li> <li>Resurrection Party</li> <li>Holy Thursday Mass</li> <li>Baccalaureate Mass</li> <li>Opening of Orientation</li> <li>Opening Convocation and Mass</li> <li>Oath of Fidelity</li> <li>Vocations Fair</li> </ul>` }, { name: 'Simple2' }, { name: 'Simple3' }, { name: 'Simple4' }, { name: 'Simple5' }, { name: 'Simple6' } ] export const rightCheckboxes = [ { name: 'Simple7' }, { name: 'Simple8' }, { name: 'Simple9' }, { name: 'Simple10' }, { name: 'Simple11' }, { name: 'Simple12' } ]
JavaScript
0.000002
@@ -1480,24 +1480,208 @@ ckboxes = %5B%0A + %7B name: 'Citation Writing' %7D,%0A %7B name: 'Direct Mail Piece' %7D,%0A %7B name: 'Editing/Proofreading' %7D,%0A %7B name: 'Email Blast' %7D,%0A %7B name: 'Event Program' %7D,%0A %7B name: 'Invitations' %7D,%0A %7B%0A name @@ -2688,15 +2688,16 @@ e: ' -Simple2 +Print Ad ' %7D, @@ -2712,38 +2712,46 @@ e: ' -Simple3' %7D,%0A %7B name: 'Simple4 +Printed Literature (Brochure,Viewbook) ' %7D, @@ -2766,15 +2766,16 @@ e: ' -Simple5 +Radio Ad ' %7D, @@ -2790,15 +2790,37 @@ e: ' -Simple6 +Reprint/Update Existing Piece ' %7D%0A @@ -2871,14 +2871,39 @@ : 'S -imple7 +ocial Media (New Platform/Feed) ' %7D, @@ -2919,14 +2919,22 @@ : 'S -imple8 +ocial Media Ad ' %7D, @@ -2950,86 +2950,275 @@ : 'S -imple9' %7D,%0A %7B name: 'Simple10' %7D,%0A %7B name: 'Simple11' %7D,%0A %7B name: 'Simple12 +ocial Media Post' %7D,%0A %7B name: 'Television Ad' %7D,%0A %7B name: 'Video' %7D,%0A %7B name: 'Website (Content Update)' %7D,%0A %7B name: 'Website (Event Posting)' %7D,%0A %7B name: 'Website (New Page/Section)' %7D,%0A %7B name: 'Writing' %7D,%0A %7B name: 'Other' %7D,%0A %7B name: 'Not sure what I need ' %7D%0A
3d0d2f07b4df0f704895749b6b39dec12464973c
add divider tests
src/divider/__tests__/Divider.js
src/divider/__tests__/Divider.js
import React from 'react'; import {shallow} from 'enzyme'; import Divider from '../Divider'; describe('Divider Component', () => { it('should render without issues', () => { const component = shallow(<Divider />); expect(component.length).toBe(1); expect(component).toMatchSnapshot(); }); it('should render with style', () => { const component = shallow(<Divider style={{ backgroundColor: 'blue' }} />); expect(component.length).toBe(1); expect(component).toMatchSnapshot(); expect(component.props().style.length).toBe(2); expect(component.props().style[1].backgroundColor).toBe('blue'); }); });
JavaScript
0.000001
@@ -300,16 +300,19 @@ ;%0A %7D);%0A + %0A it('sh
bc2f3991e050f25038f302f7f488bd407f8ad033
Make those nameToEmojiMap tests more explicit in source.
src/emoji/__tests__/data-test.js
src/emoji/__tests__/data-test.js
import { getFilteredEmojiNames, nameToEmojiMap } from '../data'; // Prettier disabled in .prettierignore ; it misparses this file, apparently // because of the emoji. (Even if they're tucked away in comments, it still // gets it wrong.) /* eslint-disable dot-notation, spellcheck/spell-checker */ describe('nameToEmojiMap', () => { test('works for some single-codepoint emoji', () => { expect(nameToEmojiMap['thumbs_up']).toEqual('👍').toEqual(''); expect(nameToEmojiMap['pride']).toEqual('🌈'); expect(nameToEmojiMap['rainbow']).toEqual('🌈'); }); // Skipped because of (part of?) #3129. test.skip('works for some multi-codepoint emoji', () => { expect(nameToEmojiMap['0']).toEqual('0⃣'); expect(nameToEmojiMap['asterisk']).toEqual('*⃣'); expect(nameToEmojiMap['hash']).toEqual('#⃣'); }); }); describe('getFilteredEmojiNames', () => { test('empty query returns all emojis', () => { const list = getFilteredEmojiNames('', {}); expect(list).toHaveLength(1560); }); test('non existing query returns empty list', () => { const list = getFilteredEmojiNames('qwerty', {}); expect(list).toHaveLength(0); }); test('returns a sorted list of emojis starting with query', () => { const list = getFilteredEmojiNames('go', {}); expect(list).toEqual([ 'go', 'goal', 'goat', 'goblin', 'gold', 'gold_record', 'golf', 'gondola', 'goodnight', 'gooooooooal', 'gorilla', 'got_it', ]); }); test('search in realm emojis as well', () => { expect(getFilteredEmojiNames('qwerty', { qwerty: {} })).toEqual(['qwerty']); }); test('remove duplicates', () => { expect(getFilteredEmojiNames('dog', {})).toEqual(['dog', 'dogi']); expect(getFilteredEmojiNames('dog', { dog: {} })).toEqual(['dog', 'dogi']); }); });
JavaScript
0
@@ -255,20 +255,23 @@ ble -dot-notation +no-multi-spaces , sp @@ -337,486 +337,560 @@ %7B%0A -test('works for some single-codepoint emoji', () =%3E %7B%0A expect(nameToEmojiMap%5B'thumbs_up'%5D).toEqual('%F0%9F%91%8D').toEqual('');%0A expect(nameToEmojiMap%5B'pride'%5D).toEqual('%F0%9F%8C%88');%0A expect(nameToEmojiMap%5B'rainbow'%5D).toEqual('%F0%9F%8C%88');%0A %7D);%0A%0A // Skipped because of (part of?) #3129.%0A test.skip('works for some multi-codepoint emoji', () =%3E %7B%0A expect(nameToEmojiMap%5B'0'%5D).toEqual('0%E2%83%A3');%0A expect(nameToEmojiMap%5B'asterisk'%5D).toEqual('*%E2%83%A3');%0A expect(nameToEmojiMap%5B'hash'%5D).toEqual('#%E2%83%A3 +const check = (name, string1, string2) =%3E %7B%0A expect(string1).toEqual(string2);%0A expect(nameToEmojiMap%5Bname%5D).toEqual(string1);%0A %7D;%0A%0A test('works for some single-codepoint emoji', () =%3E %7B%0A check('thumbs_up', '%F0%9F%91%8D', '%5Cu%7B1f44d%7D');%0A check('pride', '%F0%9F%8C%88', '%5Cu%7B1f308%7D');%0A check('rainbow', '%F0%9F%8C%88', '%5Cu%7B1f308%7D');%0A %7D);%0A%0A // Skipped because of (part of?) #3129.%0A test.skip('works for some multi-codepoint emoji', () =%3E %7B%0A check('0', '0%E2%83%A3', '0%5Cu%7B20e3%7D');%0A check('asterisk', '*%E2%83%A3', '*%5Cu%7B20e3%7D');%0A check('hash', '#%E2%83%A3', '#%5Cu%7B20e3%7D ');%0A
b500a42c4a8cecc3b95966b39b5b3d57847e6a9f
Update foam.comics.DAOController to use new TableView
src/foam/comics/DAOController.js
src/foam/comics/DAOController.js
/** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * 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. */ foam.CLASS({ package: 'foam.comics', name: 'DAOController', imports: [ 'stack' ], properties: [ { name: 'data', hidden: true, factory: function() { return this.__context__[foam.String.daoize(this.of.name)]; } }, { name: 'predicate', view: 'foam.u2.view.RecipricalSearch' }, { name: 'filteredDAO', view: 'foam.u2.TableView', expression: function(data, predicate) { return predicate ? data.where(predicate) : data; } }, { class: 'Class', name: 'of', hidden: true } ], actions: [ { name: 'create', code: function() { this.stack.push({ class: 'foam.comics.DAOCreateController', of: this.of }); } } ] });
JavaScript
0
@@ -1025,16 +1025,21 @@ foam.u2. +view. TableVie
c9a85c59f821841872daf13f5e1fc7111d11bc2c
Remove return statement from .update()
src/helpers/FaceNormalsHelper.js
src/helpers/FaceNormalsHelper.js
import { Matrix3 } from '../math/Matrix3'; import { Vector3 } from '../math/Vector3'; import { LineSegments } from '../objects/LineSegments'; import { LineBasicMaterial } from '../materials/LineBasicMaterial'; import { Float32BufferAttribute } from '../core/BufferAttribute'; import { BufferGeometry } from '../core/BufferGeometry'; /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */ function FaceNormalsHelper( object, size, hex, linewidth ) { // FaceNormalsHelper only supports THREE.Geometry this.object = object; this.size = ( size !== undefined ) ? size : 1; var color = ( hex !== undefined ) ? hex : 0xffff00; var width = ( linewidth !== undefined ) ? linewidth : 1; // var nNormals = 0; var objGeometry = this.object.geometry; if ( objGeometry && objGeometry.isGeometry ) { nNormals = objGeometry.faces.length; } else { console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' ); } // var geometry = new BufferGeometry(); var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 ); geometry.addAttribute( 'position', positions ); LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) ); // this.matrixAutoUpdate = false; this.update(); } FaceNormalsHelper.prototype = Object.create( LineSegments.prototype ); FaceNormalsHelper.prototype.constructor = FaceNormalsHelper; FaceNormalsHelper.prototype.update = ( function () { var v1 = new Vector3(); var v2 = new Vector3(); var normalMatrix = new Matrix3(); return function update() { this.object.updateMatrixWorld( true ); normalMatrix.getNormalMatrix( this.object.matrixWorld ); var matrixWorld = this.object.matrixWorld; var position = this.geometry.attributes.position; // var objGeometry = this.object.geometry; var vertices = objGeometry.vertices; var faces = objGeometry.faces; var idx = 0; for ( var i = 0, l = faces.length; i < l; i ++ ) { var face = faces[ i ]; var normal = face.normal; v1.copy( vertices[ face.a ] ) .add( vertices[ face.b ] ) .add( vertices[ face.c ] ) .divideScalar( 3 ) .applyMatrix4( matrixWorld ); v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 ); position.setXYZ( idx, v1.x, v1.y, v1.z ); idx = idx + 1; position.setXYZ( idx, v2.x, v2.y, v2.z ); idx = idx + 1; } position.needsUpdate = true; return this; }; }() ); export { FaceNormalsHelper };
JavaScript
0.000063
@@ -2520,24 +2520,8 @@ e;%0A%0A -%09%09return this;%0A%0A %09%7D;%0A
79c66c31e367c571c9698dcc12b80cc5e3ec7082
fix navbar: avoid unnecesary call to onLoad
src/js/controllers/navbar_top.js
src/js/controllers/navbar_top.js
'use strict'; /** * @ngdoc function * @name Pear2Pear.controller:NavbarTopCtrl * @description * # NavbarTop Ctrl */ angular.module('Pear2Pear') .controller( 'NavbarTopCtrl', [ 'SwellRTSession', '$scope', '$route', 'ProjectsSvc', function(SwellRTSession, $scope, $route, ProjectsSvc){ var getSharedMode = function(){ if ($scope.project){ return $scope.project.shareMode; } return null; }; $scope.$on('$locationChangeStart', function(event) { SwellRTSession.onLoad(function(){ if ($route.current.params.id){ ProjectsSvc.find($route.current.params.id) .then(function(proxy) { $scope.project = proxy; }); } }); }); $scope.shareIcon = function shareIcon() { switch (getSharedMode()) { case 'link': return 'fa-link'; case 'public': return 'fa-globe'; default: return ''; } }; $scope.isShared = function(mode) { if ($scope.project){ return getSharedMode() === mode; } return false; }; $scope.setShared = function setShared(mode){ $scope.project.setShareMode(mode); }; $scope.timestampProjectAccess = function(){ $scope.project.timestampProjectAccess(); }; }]);
JavaScript
0.000001
@@ -541,58 +541,30 @@ -SwellRTSession.onLoad(function()%7B%0A if ( +if ($route.current && $rou @@ -586,18 +586,16 @@ ms.id)%7B%0A - @@ -641,18 +641,16 @@ ams.id)%0A - @@ -687,34 +687,32 @@ - $scope.project = @@ -725,34 +725,32 @@ ;%0A - %7D);%0A @@ -751,25 +751,9 @@ - %7D%0A %7D); +%7D %0A
573233ed1d75aaa5d4837703be3427b84a6a8865
Update Renderer.js
src/js/core/Renderer/Renderer.js
src/js/core/Renderer/Renderer.js
// -------------------------------------------------------------------------------- // Copyright (c) 2015 Ruggero Enrico Visintin // // 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. // -------------------------------------------------------------------------------- function Renderer(glContext) { } Renderer.prototype.clear = function() { glContext.clear(glContext.COLOR_BUFFER_BIT | glContext.DEPTH_BUFFER_BIT); } Renderer.prototype.clearColor = function(red, green, blue, alpha) { glContext.clearColor(red, green, blue, alpha); } Renderer.prototype.enableDepthTest = function() { glContext.enable(glContext.DEPTH_TEST); } Renderer.prototype.disableDepthTest = function() { glContext.disable(glContext.DEPTH_TEST); } Renderer.prototype.setShaderProgram = function(shaderProgram) { glContext.useProgram(shaderProgram); } Renderer.prototype.drawTriangles = function(vertexBuffer, start, count) { glContext.bindBuffer(glContext.ARRAY_BUFFER, vertexBuffer); glContext.drawArrays(glContext.TRIANGLES, start, count); glContext.bindBuffer(glContext.ARRAY_BUFFER, null); }
JavaScript
0
@@ -1317,16 +1317,65 @@ t) %0A%7B%0A +// not implemented yet%0A throw %22Not implemented%22; %0A%7D%0A%0ARend
6d7578843ffa5daac35bf63f4c2b55dd4129653f
fix bug,close #10
src/listeners/request/request.js
src/listeners/request/request.js
/** * @file 代理请求转发到其他服务器 * @author zdying */ 'use strict'; var http = require('http'); var https = require('https'); var zlib = require('zlib'); var execResponseCommand = require('../../commands/execCommand'); module.exports = { response: function (rewriteRule, request, response) { var proxyOption = request.proxy_options; var isHTTPS = proxyOption.protocol === 'https:'; var self = this; proxyOption.headers['accept-encoding'] = 'gzip,deflate'; if (isHTTPS) { proxyOption.rejectUnauthorized = false; } var proxy = (isHTTPS ? https : http).request(proxyOption, function (res) { response.headers = res.headers; // response.removeHeader('Content-Encoding') // delete response.headers['content-encoding'] execResponseCommand(rewriteRule, { response: response }, 'response'); /** * Emitted each time the server set response info (eg: headers). * @event ProxyServer#setResponse * @property {http.ServerResponse} response request object */ self.emit('setResponse', response); // response.pipe(res) response.writeHead(res.statusCode, res.headers); /* res.pause() log.warn('request was paused:'.red, _url.bold.red) setTimeout(function(){ res.resume() log.warn('request was resumed:'.red, _url.bold.red) }, 5000) */ var contentType = res.headers['content-type']; var encoding = response.headers['content-encoding']; var canUnZip = encoding === 'gzip' || encoding === 'deflate'; var isTextFile = /(text|xml|html|plain|json|javascript|css)/.test(contentType); if (canUnZip && isTextFile) { var unzipStream = encoding === 'gzip' ? zlib.createUnzip() : zlib.createInflate(); unzipStream.on('data', function (chunk) { // console.log('ondata =>', chunk.toString()) /** * Emitted whenever the response stream received some chunk of data. * @event ProxyServer#data * @property {Buffer} data response data */ self.emit('data', chunk); }); /* istanbul ignore next */ unzipStream.on('error', function (err) { log.error('error ==>', err); response.end(err.stack); }); res.pipe(unzipStream).pipe(response); } else { res.on('data', function (chunk) { /** * Emitted whenever the response stream received some chunk of data. * @event ProxyServer#data * @property {Buffer} data response data */ self.emit('data', chunk); // console.log('ondata =>', chunk.toString()) }); res.pipe(response); } res.on('end', function () { request.res = res; /** * Emitted when a response is end. This event is emitted only once. * @event ProxyServer#response * @property {http.ServerResponse} response response object */ self.emit('response', response); if (request.PROXY) { log.access(request, (proxyOption.protocol || 'http:') + '//' + proxyOption.hostname + (proxyOption.port ? ':' + proxyOption.port : '') + proxyOption.path); } else { log.access(request); // log.info('direc -', request.url.bold, Date.now() - start, 'ms') } }); }); proxy.on('error', function (e) { /* istanbul ignore next */ if (e.code === 'ENOTFOUND') { response.statusCode = 404; response.end(); } else { response.statusCode = 500; response.end(e.stack); } log.error('proxy error:', request.url); log.detail(e.stack); request.res = response; log.access(request); }); request.pipe(proxy); } };
JavaScript
0
@@ -2281,91 +2281,9 @@ - response.end(err.stack);%0A %7D);%0A%0A res.pipe(unzipStream).pipe(response +%7D );%0A @@ -2635,24 +2635,31 @@ %7D);%0A + %7D%0A%0A res.pi @@ -2671,24 +2671,16 @@ sponse); -%0A %7D %0A%0A
f0378bb40f8bc7733bce77636f9bf7bafd4dbba5
Stop then disconnect
server/discord/music.js
server/discord/music.js
const r = require('./../db'); const client = require('./'); const bot = require('./'); const getPlayer = (message) => { if (!message.member) { return Promise.reject(new Error('Not a guild')); } const player = client.voiceConnections.get(message.channel.guild.id); if (player) { return Promise.resolve(player); } const options = {}; return client.voiceConnections.join(message.channel.guild.id, message.member.voiceState.channelID, options); }; const stop = async (message) => { const player = bot.voiceConnections.get(message.channel.guild.id); if (player) { player.disconnect(); await r.table('playlist') .get(message.channel.guild.id) .replace({ id: message.channel.guild.id, playlist: [] }); } }; const list = async (message, callback) => { const playlist = (await r.table('playlist') .get(message.channel.guild.id)) || []; callback(playlist); }; const current = (message, callback) => { list(message, (playlist) => { callback((playlist.playlist && playlist.playlist[0]) || null); }); }; const play = (message) => { current(message, (media) => { getPlayer(message).then((player) => { if (media) { console.log(media); player.play(media.track); player.on('disconnect', (err) => { if (err) console.log(err); console.log('Disconnected'); }); player.on('error', (err) => { if (err.type === 'TrackExceptionEvent') { message.channel.createMessage('Something went wrong while decoding the track'); } else { message.channel.createMessage('Generic music error message here'); } }); player.on('stuck', (err) => { console.log('Stuck!'); console.log(err); }); player.once('end', async (data) => { if (!(data.reason && data.reason === 'REPLACED')) { await r.table('playlist') .get(message.channel.guild.id) .update({ playlist: r.row('playlist').deleteAt(0) }); play(message); } }); } else { setTimeout(async () => { await r.table('playlist') .get(message.channel.guild.id) .replace({ id: message.channel.guild.id, playlist: [] }); player.disconnect(); }, 2000); } }); }); }; const connect = (message) => { getPlayer(message) .then(() => { play(message); }); }; const add = async (message, details) => { if (!message.member) { if (!details.silent) { message.channel.createMessage('You need to be in a Guild!'); } } else if (!message.member.voiceState || !message.member.voiceState.channelID) { if (!details.silent) { message.channel.createMessage('You need to be in a Voice Channel!'); } } else { if (Array.isArray(details)) { await r.table('playlist') .get(message.channel.guild.id) .replace({ id: message.channel.guild.id, playlist: r.row('playlist').default([]).union(details) }); } else { await r.table('playlist') .get(message.channel.guild.id) .replace({ id: message.channel.guild.id, playlist: r.row('playlist').default([]).append(details) }); } if (!bot.voiceConnections.get(message.channel.guild.id)) connect(message); } }; const skip = (message) => { const player = bot.voiceConnections.get(message.channel.guild.id); if (player) { player.stop(); } }; exports.connect = connect; exports.add = add; exports.stop = stop; exports.skip = skip; exports.list = list; /* { media: Object or string, type: string, name: string } */
JavaScript
0.000002
@@ -559,32 +559,49 @@ %0A%09if (player) %7B%0A +%09%09player.stop();%0A %09%09player.disconn @@ -2023,152 +2023,20 @@ %09%09%09%09 -await r.table('playlist')%0A%09%09%09%09%09%09.get(message.channel.guild.id)%0A%09%09%09%09%09%09.replace(%7B%0A%09%09%09%09%09%09%09id: message.channel.guild.id,%0A%09%09%09%09%09%09%09playlist: %5B%5D%0A%09%09%09%09%09%09%7D +player.stop( );%0A%09
8de63ccdbf11cf1d3b970a729d983247433fbc71
Fix bad func sig.
server/export-worker.js
server/export-worker.js
// A single worker for processing an export (e.g. rendering a map into an // MBTiles sqlite database). Workers run in a *different process* from the // main TileMill node process because: // // - export tasks can be long-running (minutes, sometimes hours) // - export tasks can be CPU intensive, to the point of compromising the // responsiveness of the main TileMill process // // See the `export.js` for how workers are created. require.paths.splice(0, require.paths.length); require.paths.unshift( __dirname + '/../lib/node', __dirname + '/../server', __dirname + '/../shared', __dirname + '/../' ); var _ = require('underscore')._, worker = require('worker').worker, path = require('path'), fs = require('fs'), sys = require('sys'), settings = require('settings'), Step = require('step'), Tile = require('tilelive').Tile, TileBatch = require('tilelive').TileBatch; worker.onmessage = function (data) { var Format = { 'png': FormatPNG, 'pdf': FormatPDF, 'mbtiles': FormatMBTiles }[data.format]; new Format(this, data); }; // Generic export format class. var Format = function(worker, data) { _.bindAll(this, 'update', 'complete', 'setup', 'render'); var that = this; this.worker = worker; this.data = data; Step( function() { that.setup(this); }, function() { that.render(this); }, function() { that.complete(this); } ); } // Tell the parent process to update the provided `attributes` of Export model. Format.prototype.update = function(attributes) { this.worker.postMessage({ event: 'update', attributes: attributes }); } // Tell the parent process that the export task is complete. Format.prototype.complete = function() { this.worker.postMessage({ event: 'complete' }); } // Setup tasks before processing begins. Ensures that the target export // filename does not conflict with an existing file by appending a short hash // if necessary. Format.prototype.setup = function(callback) { var that = this; Step( function() { path.exists(path.join(settings.export_dir, that.data.filename), this); }, function(exists) { if (exists) { var extension = path.extname(that.data.filename); var hash = require('crypto') .createHash('md5') .update(+new Date) .digest('hex') .substring(0,6); that.data.filename = that.data.filename.replace(extension, '') + '_' + hash + extension; } that.update({ status: 'processing', updated: +new Date, filename: that.data.filename }); callback(); } ); } // MBTiles format // -------------- // Exports a map into an MBTiles sqlite database. Renders and inserts tiles in // batches of 100 images and updates the parent process on its progress after // each batch. var FormatMBTiles = function(worker, data) { Format.call(this, worker, data); } sys.inherits(FormatMBTiles, Format); FormatMBTiles.prototype.render = function(callback) { var that = this; var batch = new TileBatch({ filepath: path.join(settings.export_dir, that.data.filename), batchsize: 100, bbox: that.data.bbox.split(','), format: that.data.tile_format, interactivity: that.data.interactivity, minzoom: that.data.minzoom, maxzoom: that.data.maxzoom, mapfile: that.data.mapfile, mapfile_dir: path.join(settings.mapfile_dir), metadata: { name: that.data.metadata_name, type: that.data.metadata_type, description: that.data.metadata_description, version: that.data.metadata_version, formatter: that.data.metadata_formatter } }); Step( function() { batch.setup(this); }, function(err) { var next = this; var RenderTask = function(end) { process.nextTick(function() { batch.renderChunk(function(err, rendered) { if (!rendered) return next(); that.update({ progress: batch.tiles_current / batch.tiles_total, updated: +new Date() }); RenderTask(); }); }); }; that.update({ status: 'processing', updated: +new Date }); RenderTask(); }, function() { batch.fillGridData(this); }, function() { that.update({ status: 'complete', progress: 1, updated: +new Date() }); batch.finish(this); }, function() { callback(); } ); } // Image format // ------------ // Abstract image class. Exports a map into a single image file. Extenders of // this class should set: // // - `this.format` String image format, e.g. `png`. var FormatImage = function(worker, data) { Format.call(this, worker, data); } sys.inherits(FormatImage, Format); FormatImage.prototype.render = function(callback) { var that = this; Step( function() { var options = _.extend({}, that.data, { scheme: 'tile', format: that.format, mapfile_dir: path.join(settings.mapfile_dir), bbox: that.data.bbox.split(',') }); try { var tile = new Tile(options); tile.render(this); } catch (err) { that.update({ status: 'error', error: 'Tile invalid: ' + err.message, updated: +new Date }); this(); } }, function(err, data) { if (!err) { fs.writeFile( path.join(settings.export_dir, that.data.filename), data[0], 'binary', function(err) { that.update({ status: err ? 'error' : 'complete', error: err ? 'Error saving image: ' + err.message : '', progress: err ? 0 : 1, updated: +new Date }); callback(); }); } else { that.update({ status: 'error', error: 'Error rendering image: ' + err.message, updated: +new Date }); callback(); } } ); } // PDF export format class. var FormatPDF = function(worker, data) { this.format = 'pdf'; FormatImage.call(this, worker, data); } sys.inherits(FormatPDF, FormatImage); // PNG export format class. var FormatPNG = function(worker, data) { this.format = 'png'; FormatImage.call(this, worker, data); } sys.inherits(FormatPNG, FormatImage);
JavaScript
0.000113
@@ -4145,19 +4145,16 @@ unction( -end ) %7B%0A
afeac49bcfb72c661607cd956a15f043a8d78d5d
Add form errors
lib/browser/tag/update.js
lib/browser/tag/update.js
import { tmpl } from 'riot-tmpl' import { startsWith, each, extend } from './../common/util/misc' import { isFunction, isUndefined } from './../common/util/check' import { remAttr, setAttr } from './../common/util/dom' import setEventHandler from './setEventHandler' import { initChildTag, makeVirtual, arrayishRemove } from './../common/util/tags' import { RIOT_PREFIX, T_OBJECT, RIOT_TAG_IS, __TAG_IMPL, IE_VERSION, CASE_SENSITIVE_ATTRIBUTES } from './../common/global-variables' /** * Update dynamically created data-is tags with changing expressions * @param { Object } expr - expression tag and expression info * @param { Tag } parent - parent for tag creation */ export function updateDataIs(expr, parent) { var tagName = tmpl(expr.value, parent), conf if (expr.tag && expr.tagName === tagName) { expr.tag.update() return } // sync _parent to accommodate changing tagnames if (expr.tag) { var delName = expr.value, tags = expr.tag._parent.tags setAttr(expr.tag.root, RIOT_TAG_IS, tagName) // update for css arrayishRemove(tags, delName, expr.tag) } expr.impl = __TAG_IMPL[tagName] conf = {root: expr.dom, parent: parent, hasImpl: true, tagName: tagName} expr.tag = initChildTag(expr.impl, conf, expr.dom.innerHTML, parent) expr.tagName = tagName expr.tag.mount() expr.tag.update() // parent is the placeholder tag, not the dynamic tag so clean up parent.on('unmount', () => { var delName = expr.tag.opts.dataIs, tags = expr.tag.parent.tags, _tags = expr.tag._parent.tags arrayishRemove(tags, delName, expr.tag) arrayishRemove(_tags, delName, expr.tag) expr.tag.unmount() }) } /** * Update on single tag expression * @this Tag * @param { Object } expr - expression logic * @returns { undefined } */ export function updateExpression(expr) { var dom = expr.dom, attrName = expr.attr, isToggle = /^(show|hide)$/.test(attrName), value = isToggle || tmpl(expr.expr, this), isValueAttr = attrName === 'riot-value', isVirtual = expr.root && expr.root.tagName === 'VIRTUAL', parent = dom && (expr.parent || dom.parentNode), old if (expr.bool) value = value ? attrName : false else if (isUndefined(value) || value === null) value = '' if (expr._riot_id) { // if it's a tag if (expr.isMounted) { expr.update() // if it hasn't been mounted yet, do that now. } else { expr.mount() if (isVirtual) { var frag = document.createDocumentFragment() makeVirtual.call(expr, frag) expr.root.parentElement.replaceChild(frag, expr.root) } } return } old = expr.value expr.value = value if (expr.update) { expr.update() return } if (expr.isRtag && value) return updateDataIs(expr, this) if (old === value && !isToggle) return // no change, so nothing more to do if (isValueAttr && dom.value === value) return // textarea and text nodes have no attribute name if (!attrName) { // about #815 w/o replace: the browser converts the value to a string, // the comparison by "==" does too, but not in the server value += '' // test for parent avoids error with invalid assignment to nodeValue if (parent) { // cache the parent node because somehow it will become null on IE // on the next iteration expr.parent = parent if (parent.tagName === 'TEXTAREA') { parent.value = value // #1113 if (!IE_VERSION) dom.nodeValue = value // #1625 IE throws here, nodeValue } // will be available on 'updated' else dom.nodeValue = value } return } // remove original attribute if (!expr.isAttrRemoved || !value) { remAttr(dom, attrName) expr.isAttrRemoved = true } // event handler if (isFunction(value)) { setEventHandler(attrName, value, dom, this) // show / hide } else if (isToggle) { value = tmpl(expr.expr, extend({}, this, this.parent)) if (attrName === 'hide') value = !value dom.style.display = value ? '' : 'none' // field value } else if (isValueAttr) { dom.value = value // <img src="{ expr }"> } else if (startsWith(attrName, RIOT_PREFIX) && attrName !== RIOT_TAG_IS) { attrName = attrName.slice(RIOT_PREFIX.length) if (CASE_SENSITIVE_ATTRIBUTES[attrName]) attrName = CASE_SENSITIVE_ATTRIBUTES[attrName] if (value != null) setAttr(dom, attrName, value) } else { // <select> <option selected={true}> </select> if (attrName === 'selected' && parent && /^(SELECT|OPTGROUP)$/.test(parent.tagName) && value != null) { parent.value = dom.value } if (expr.bool) { dom[attrName] = value if (!value) return } if (value === 0 || value && typeof value !== T_OBJECT) { setAttr(dom, attrName, value) } } } /** * Update all the expressions in a Tag instance * @this Tag * @param { Array } expressions - expression that must be re evaluated */ export default function update(expressions) { each(expressions, updateExpression.bind(this)) }
JavaScript
0.000001
@@ -2824,16 +2824,70 @@ , this)%0A + // TODO: the toggle value should be cached as well!%0A if (ol