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
5dc3bb05cf343c783cb77780b4aa40f5039c8cfe
Fix Spinner
src/components/Spinner.js
src/components/Spinner.js
var React = require('react/addons'); var classNames = require('classnames'); module.exports = React.createClass({ displayName: 'Spinner', propTypes: { size: React.PropTypes.oneOf(['sm', 'md', 'lg']), type: React.PropTypes.oneOf(['default', 'primary', 'inverted']) }, getDefaultProps() { return { type: 'default' }; }, render() { var componentClass = classNames( 'Spinner', 'Spinner--' + this.props.type, 'Spinner--' + this.props.size, this.props.className ); return ( <div className={componentClass}> <span className="Spinner_dot Spinner_dot--first" /> <span className="Spinner_dot Spinner_dot--second" /> <span className="Spinner_dot Spinner_dot--third" /> </div> ); } });
JavaScript
0.000002
@@ -147,16 +147,53 @@ ypes: %7B%0A +%09%09className: React.PropTypes.string,%0A %09%09size:
ce39de9bd764b7be4fcca73ba6f22e791e7490b8
Fix platypus-generated script lossage in GM 0.4
src/content/dochandler.js
src/content/dochandler.js
/* === START LICENSE === Copyright 2004-2005 Aaron Boodman Contributors: Jeremy Dunck, Nikolas Coukouma, Matthew Gray. 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: Note that this license applies only to the Greasemonkey extension source files, not to the user scripts which it runs. User scripts are licensed separately by their authors. 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. === END LICENSE === The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ // GM_DocHandlers are created by GM_BrowserUI to process individual documents // loaded into the content area. function GM_DocHandler(contentWindow, chromeWindow) { GM_log("> GM_DocHandler") this.contentWindow = contentWindow; this.chromeWindow = chromeWindow; this.initScripts(); this.injectScripts(); GM_log("< GM_DocHandler") } GM_DocHandler.prototype.initScripts = function() { GM_log("> GM_DocHandler.initScripts"); var config = new Config(); config.load(); this.scripts = []; outer: for (var i = 0; i < config.scripts.length; i++) { var script = config.scripts[i]; if (script.enabled) { for (var j = 0; j < script.includes.length; j++) { var pattern = convert2RegExp(script.includes[j]); if (pattern.test(this.contentWindow.location.href)) { for (var k = 0; k < script.excludes.length; k++) { pattern = convert2RegExp(script.excludes[k]); if (pattern.test(this.contentWindow.location.href)) { continue outer; } } this.scripts.push(script); continue outer; } } } } GM_log("* number of matching scripts: " + this.scripts.length); GM_log("< GM_DocHandler.initScripts"); } GM_DocHandler.prototype.injectScripts = function() { GM_log("> GM_DocHandler.injectScripts") // trying not to keep to much huge state hanging around, just to avoid // stupid mistakes that would leak memory. So not making any of the API // objects instance data until it is necessary to do so. // GM_registerMenuCommand and GM_xmlhttpRequest are the same for every // script so we instance them here, before the loop. var xmlhttpRequester = new GM_xmlhttpRequester(this.contentWindow, this.chromeWindow); this.menuCommander = new GM_MenuCommander(this.contentWindow); var xmlhttpRequest = GM_hitch(xmlhttpRequester, "contentStartRequest"); var registerMenuCommand = GM_hitch(this.menuCommander, "registerMenuCommand"); for (var i = 0; i < this.scripts.length; i++) { var script = this.scripts[i]; var scriptElm = this.contentWindow.document.createElement("script"); // GM_setValue, GM_getValue, and GM_log differ for every script, so they // need to be instanced for each script. var storage = new GM_ScriptStorage(script); var logger = new GM_ScriptLogger(script); var setValue = GM_hitch(storage, "setValue"); var getValue = GM_hitch(storage, "getValue"); var log = GM_hitch(logger, "log"); // TODO: investigate invoking user scripts with the least possible // opportunity for page scripts to interfere -- either by calling GM apis, // or by removing or changing user scripts. // I imagine that right now, a page script could catch DOMSubtreeModified // and remove window.GM_apis. // TODO: invoke user scripts by embedding a link to a javascript file. // This has debugging benefits; when the script errors it shows the right // line number. //TODO: Add in GM_registerMenuCommand var toInject = ["(function(", "GM_xmlhttpRequest, GM_registerMenuCommand, GM_setValue, ", "GM_getValue, GM_log, GM_openInTab) { delete window.GM_apis; ", getContents(getScriptChrome(script.filename)), "}).apply(this, window.GM_apis);" ].join(""); this.contentWindow.GM_apis = [xmlhttpRequest, registerMenuCommand, setValue, getValue, log, GM_openInTab]; GM_log('injecting: ' + toInject); scriptElm.appendChild(this.contentWindow.document. createTextNode(toInject)); this.contentWindow.document.body.appendChild(scriptElm); this.contentWindow.document.body.removeChild(scriptElm); GM_log("* injected '" + script.name + "'"); } GM_log("< GM_DocHandler.injectScripts") }
JavaScript
0.000004
@@ -4740,16 +4740,18 @@ %22 +%5Cn %7D).apply
d3f2e6b533fd1cc767b49da4ae4a77fdcc8aec7a
use correct role for worker
src/controller/clients.js
src/controller/clients.js
var when = require('when'), bcrypt = require('bcrypt'), clientDao = require('../dao/client'), firewall = require('../util/firewall'); module.exports = function (app) { function createClient(params, id) { var client = {}; params = params || {}; client.id = id || undefined; client.username = params.username || ''; client.password = params.password || undefined; client.name = params.name || ''; client.phone = params.phone || ''; return client; } function validateClient(client, passwordRequired) { return when.promise(function (resolve, reject) { var errors = []; if (0 === client.username.length) { errors.push('Username is mandatory'); } if (passwordRequired && (!client.password || 0 === client.password.length)) { errors.push('Password is mandatory'); } if (0 === client.name.length) { errors.push('Name is mandatory'); } if (0 === client.phone.length) { errors.push('Phone is mandatory'); } resolve(errors); }); } function handleError(res) { return function (err) { console.error(err); res.send(500, 'Internal Server Error'); }; } app.get('/clients', firewall(['admin', 'worker'], function (req, res) { clientDao.findAll().then(function (clients) { res.render('clients/index', { clients: clients, user: req.user }); }); })); app.get('/clients/new', firewall(['admin', 'worker'], function (req, res) { res.render('clients/new', { client: createClient(), user: req.user }); })); app.post('/clients', firewall(['admin', 'worker'], function (req, res) { var client = createClient(req.body); validateClient(client, true).then(function (errors) { if (errors.length) { res.render('clients/new', { errors: errors, client: client, user: req.user }); } else { return when.promise(function (resolve, reject) { bcrypt.hash(client.password, 8, function (err, hash) { if (err) return reject(err); resolve(hash); }); }).then(function (hash) { client.password = hash; return clientDao.insert(client); }).then(function () { res.redirect('/clients'); }); } }).catch(handleError(res)); })); app.del('/clients/:id', firewall(['admin', 'worker'], function (req, res) { clientDao.delete(req.params.id).then(function () { res.redirect('/clients'); }).catch(handleError(res)); })); app.get('/clients/:id/edit', firewall(['admin', 'worker'], function (req, res) { clientDao.find(req.params.id).then(function (client) { if (!client) { res.send(404, 'Client not found'); } else { client.password = ''; res.render('clients/edit', { client: client, user: req.user }); } }).catch(handleError(this)); })); app.put('/clients/:id', firewall(['admin', 'worker'], function (req, res) { var client = createClient(req.body, req.params.id); validateClient(client).then(function (errors) { if (errors.length) { res.render('clients/edit', { errors: errors, client: client, user: req.user }); } else { return when.promise(function (resolve, reject) { if (!client.password) return resolve(); bcrypt.hash(client.password, 8, function (err, hash) { if (err) return reject(err); resolve(hash); }); }).then(function (hash) { client.password = hash; return clientDao.update(client); }).then(function () { res.redirect('/clients'); }); } }); })); app.get('/join', function (req, res) { res.render('auth/join', { client: createClient() }); }); app.post('/join', function (req, res) { var client = createClient(req.body); validateClient(client, true).then(function (errors) { if (errors.length) { res.render('auth/join', { errors: errors, client: client }); } else { return when.promise(function (resolve, reject) { bcrypt.hash(client.password, 8, function (err, hash) { if (err) return reject(err); resolve(hash); }); }).then(function (hash) { client.password = hash; return clientDao.insert(client); }).then(function () { req.session.username = client.username; res.redirect('/'); }); } }).catch(handleError(res)); }); };
JavaScript
0.008858
@@ -1415,38 +1415,37 @@ wall(%5B'admin', ' -worker +basic '%5D, function (re @@ -1693,38 +1693,37 @@ wall(%5B'admin', ' -worker +basic '%5D, function (re @@ -1890,38 +1890,37 @@ wall(%5B'admin', ' -worker +basic '%5D, function (re @@ -2861,38 +2861,37 @@ wall(%5B'admin', ' -worker +basic '%5D, function (re @@ -3088,38 +3088,37 @@ wall(%5B'admin', ' -worker +basic '%5D, function (re @@ -3577,14 +3577,13 @@ ', ' -worker +basic '%5D,
ff91c34c9e7dba8b7457248694722d6fe615e6aa
Fix typo
src/core/PriorityQueue.js
src/core/PriorityQueue.js
// Priority Queue based on python heapq module // http://svn.python.org/view/python/branches/release27-maint/Lib/heapq.py var PriorityQueue = new Class({ initialize: function(array, compare) { if (compare) { this.compare = compare; } if (array) { this.heap = array; for (var i = 0; i < Math.floor(this.heap.length / 2); i++) { this.siftUp(i); } } else { this.heap = []; } }, push: function(item) { this.heap.push(item); this.siftDown(0, this.heap.length - 1); }, pop: function() { var lastElement, returnItem; lastElement = this.heap.pop(); if (this.heap.length) { var returnItem = this.heap[0]; this.heap[0] = lastElement; this.siftUp(0); } else { returnItem = lastElement; } return (returnItem); }, peek: function() { return (this.heap[0]); }, isEmpty: function() { return (this.heap.length == 0); }, siftDown: function(startPosition, position) { var newItem = this.heap[position]; while (position > startPosition) { var parentPosition = (position - 1) >> 1; var parent = this.heap[parentPosition]; if (this.compare(newItem, parent)) { this.heap[position] = parent; position = parentPosition; continue; } break; } this.heap[position] = newItem; }, siftUp: function(position) { var endPosition = this.heap.length; var startPosition = position; var newItem = this.heap[position]; var childPosition = 2 * position + 1; while (childPosition < endPosition) { var rightPosition = childPosition + 1; if (rightPosition < endPosition && !this.compare(this.heap[childPosition], this.heap[rightPosition])) { childPosition = rightPosition; } this.heap[position] = this.heap[childposition]; position = childPosition; childPosition = 2 * position + 1; } this.heap[position] = newItem; this.siftDown(startPosition, position); }, compare: function(a, b) { return (a < b); } });
JavaScript
0.999999
@@ -2172,17 +2172,17 @@ ap%5Bchild -p +P osition%5D
09c15119eecdd92aeb725add2bdd4dd81f2e7246
Fix redirects
src/context.js
src/context.js
var URL = require("url"); var Cookies = require("@rill/cookies"); var HttpError = require("@rill/error"); var Request = require("./request"); var Response = require("./response"); module.exports = Context; function Context (app, req, res) { this.app = app; this.req = req; this.res = res; this.request = new Request(this); this.response = new Response(this); this.cookies = this.request.cookies = this.response.cookies = new Cookies(req.headers.cookie); this.request.redirect = this.response.redirect = this.redirect.bind(this); } var context = Context.prototype; context.throw = function throwHttp (code, message, meta) { error = new HttpError(code, message, meta); this.response.status = error.code; throw error; }; context.assert = function assertHttp (val, code, message, meta) { if (!val) this.throw(code, message, meta); }; context.redirect = function redirect (url, alt) { alt = URL.resolve(this.request.href, alt || "/"); url = URL.resolve(this.request.href, url); this.response.headers["location"] = (url === "back") ? this.response.headers["referrer"] || alt : url; } context.refresh = function refresh (url, delay) { delay = delay || 0; url = URL.resolve(this.request.href, url || this.request.href); this.response.headers["refresh"] = delay + "; url=" + url; };
JavaScript
0.000003
@@ -941,100 +941,83 @@ %7B%0A%09 -alt = URL.resolve(this.request.href, alt %7C%7C %22/ +url = (url === %22back %22) -; %0A%09 -url = URL.resolve(this.request.href, +%09? this.response.headers%5B%22referrer%22%5D %7C%7C alt%0A%09%09: url -) ;%0A%0A%09 @@ -1056,77 +1056,43 @@ %5D = -(url === %22back%22)%0A%09%09? this.response.headers%5B%22referrer%22%5D %7C%7C alt%0A%09%09: +URL.resolve(this.request.href, url +) ;%0A%7D%0A
eedfda514428bb442c86a57f771383f6052a9536
Fix executeAction when throttling is disabled
src/core/throttle-core.js
src/core/throttle-core.js
'use strict'; import * as actionTypeCore from './action-type-core'; var BPromise = require('bluebird'); let redisClient; function getKey(uuid) { return `throttle--${ uuid }`; } // Cache of action types // Key: action type code // Value: throttle time let actionTypeCache; /** * Initializes throttle core, by loading cache */ function initialize() { if (process.env.DISABLE_THROTTLE === 'true') { return; } redisClient = require('../util/redis').connect().client; return actionTypeCore.getActionTypes() .then(types => { actionTypeCache = {}; types.forEach(type => { actionTypeCache[type.code] = type.cooldown; }); }); } function _hasCooldownPassed(cooldownTime, lastExecuted) { const timeNow = Date.now(); const executeAllowed = lastExecuted + cooldownTime; return timeNow >= executeAllowed; } /** * Checks if throttle time has passed for given users * given action type. */ function canDoAction(uuid, actionType) { if (process.env.DISABLE_THROTTLE === 'true') { return BPromise.resolve(true); } const cooldownTime = actionTypeCache[actionType]; if (cooldownTime === undefined || cooldownTime === null) { return BPromise.resolve(false); } return redisClient.hgetallAsync(getKey(uuid)) .then(lastThrottlesByActionType => { if (!lastThrottlesByActionType) { return true; } const lastExecutedTime = lastThrottlesByActionType[actionType]; if (!lastExecutedTime) { return true; } const lastExecuted = Number(lastExecutedTime); return _hasCooldownPassed(cooldownTime, lastExecuted); }); } /** * Marks given user's given action as executed as this moment. */ function executeAction(uuid, actionType) { const timeNow = Date.now().toString(); return redisClient.hmsetAsync(getKey(uuid), actionType, timeNow); } export { initialize, canDoAction, executeAction };
JavaScript
0.000001
@@ -1745,24 +1745,109 @@ tionType) %7B%0A + if (process.env.DISABLE_THROTTLE === 'true') %7B%0A return BPromise.resolve();%0A %7D%0A%0A const time
4907a688cc6999dfad86ab34539bf34047e69d4e
Use ES6 getters in App
src/tabris/App.js
src/tabris/App.js
import NativeObject from './NativeObject'; const CERTIFICATE_ALGORITHMS = ['RSA2048', 'RSA4096', 'ECDSA256']; const EVENT_TYPES = ['foreground', 'background', 'pause', 'resume', 'terminate', 'backnavigation', 'certificatesReceived']; export default class App extends NativeObject { constructor() { super('tabris.App'); if (arguments[0] !== true) { throw new Error('App can not be created'); } } getResourceLocation(path) { if (!this._resourceBaseUrl) { this._resourceBaseUrl = this._nativeGet('resourceBaseUrl'); } let subPath = path != null ? '/' + normalizePath('' + path) : ''; return this._resourceBaseUrl + subPath; } dispose() { throw new Error('tabris.app can not be disposed'); } reload() { this._nativeCall('reload', {}); } installPatch(url, callback) { if (typeof url !== 'string') { throw new Error('parameter url is not a string'); } if (!this._pendingPatchCallback) { this._pendingPatchCallback = callback || true; this._nativeListen('patchInstall', true); this._nativeCall('installPatch', {url}); } else if (typeof callback === 'function') { callback(new Error('Another installPatch operation is already pending.')); } } _listen(name, listening) { if (EVENT_TYPES.includes(name)) { this._nativeListen(name, listening); } else { super._listen(name, listening); } } _trigger(name, event = {}) { if (name === 'patchInstall') { this._nativeListen('patchInstall', false); let callback = this._pendingPatchCallback; delete this._pendingPatchCallback; if (typeof callback === 'function') { if (event.error) { callback(new Error(event.error)); } else { try { let patch = event.success ? JSON.parse(event.success) : null; callback(null, patch); } catch (error) { callback(new Error('Failed to parse patch.json')); } } } } else { return super._trigger(name, event); } } _validateCertificate(event) { let hashes = this.$pinnedCerts[event.host]; if (hashes && !hashes.some(hash => event.hashes.includes(hash))) { event.preventDefault(); } } } NativeObject.defineProperties(App.prototype, { pinnedCertificates: { type: 'array', default() { return []; }, set(name, value) { this.$pinnedCerts = checkCertificates(value); this.on('certificatesReceived', this._validateCertificate, this); this._storeProperty(name, value); this._nativeSet(name, value); } } }); function checkCertificates(certificates) { let hashes = {}; for (let cert of certificates) { if (typeof cert.host !== 'string') { throw new Error('Invalid host for pinned certificate: ' + cert.host); } if (typeof cert.hash !== 'string' || !cert.hash.startsWith('sha256/')) { throw new Error('Invalid hash for pinned certificate: ' + cert.hash); } if (tabris.device.platform === 'iOS') { if (!('algorithm' in cert)) { throw new Error('Missing algorithm for pinned certificate: ' + cert.host); } if (typeof cert.algorithm !== 'string' || CERTIFICATE_ALGORITHMS.indexOf(cert.algorithm) === -1) { throw new Error('Invalid algorithm for pinned certificate: ' + cert.algorithm); } } hashes[cert.host] = hashes[cert.host] || []; hashes[cert.host].push(cert.hash); } return hashes; } export function create() { let app = new App(true); Object.defineProperty(app, 'id', {get: () => app._nativeGet('appId')}); Object.defineProperty(app, 'version', {get: () => app._nativeGet('version')}); Object.defineProperty(app, 'versionCode', {get: () => app._nativeGet('versionId')}); return app; } function normalizePath(path) { return path.split(/\/+/).map((segment) => { if (segment === '..') { throw new Error("Path must not contain '..'"); } if (segment === '.') { return ''; } return segment; }).filter(string => !!string).join('/'); }
JavaScript
0.000083
@@ -416,16 +416,194 @@ %7D%0A %7D%0A%0A + get id() %7B%0A return this._nativeGet('appId');%0A %7D%0A%0A get version() %7B%0A return this._nativeGet('version');%0A %7D%0A%0A get versionCode() %7B%0A this._nativeGet('versionId');%0A %7D%0A%0A getRes @@ -3720,17 +3720,14 @@ %7B%0A -let app = +return new @@ -3742,264 +3742,8 @@ e);%0A - Object.defineProperty(app, 'id', %7Bget: () =%3E app._nativeGet('appId')%7D);%0A Object.defineProperty(app, 'version', %7Bget: () =%3E app._nativeGet('version')%7D);%0A Object.defineProperty(app, 'versionCode', %7Bget: () =%3E app._nativeGet('versionId')%7D);%0A return app;%0A %7D%0A%0Af
a4f3a5fc0f60d15537f74abae185782b1a5410ee
Fix some jslint errors.
src/customMenus.jquery.js
src/customMenus.jquery.js
/*jslint devel: true, browser: true, indent: 2, nomen: true */ /*global define, $ */ (function ($) { 'use strict'; var oldVal; /** * m class * @author Brian McAllister - http://brianmcallister.com * @version 0.0.1 */ $.m = function (element, options) { var plugin = this, privateApi = {}; // Reference to main element. this.$select = $(element).addClass('m-select'); // Set up options this.originalOptions = options || {}; this.defaults = { clickToOpen: true, // Click the title to open the dropdown list. unicodeArrow: false // Add a little unicode arrow to the title. Pass true, or your own arrow unicode. }; this.options = $.extend(this.defaults, this.originalOptions); /** * Initialize. */ this.initialize = function () { privateApi.setElementReferences() .buildCustomHtml() .setPlaceholderText() .bindCustomEvents(); }; // Private methods. privateApi = { setElementReferences: function () { var arrow, icon; plugin.$wrapper = $('<div class="m-select-box-wrapper"></div>'); plugin.$title = $('<span class="m-title"></span>'); plugin.$titleTarget = plugin.$title; plugin.$list = $('<ul class="m-list"></ul>'); if (plugin.options.unicodeArrow) { icon = '&#x25BE;'; // Use a string if it's passed. if (typeof plugin.options.unicodeArrow === 'string') { icon = plugin.options.unicodeArrow; } // Update the title to accomodate the text and the icon. plugin.$title.attr('class', 'm-title-wrap') .append('<span class="m-title-target"></span><span class="m-arrow-icon">' + icon + '</span>'); // Update the new target. plugin.$titleTarget = plugin.$title.find('.m-title-target'); } return this; }, buildCustomHtml: function () { var $options = plugin.$select.find('option'), hasPlaceholder = false; // Wrap the select and update the $wrapper element. plugin.$select.wrap(plugin.$wrapper); plugin.$wrapper = plugin.$select.parent(); // Create the list. $options.each(function (index, option) { var $option = $(option), val = $option.val(), text = $option.text(), li = '<li data-value="' + val + '">' + text + '</li>' // Add a classname for the placeholder (only one!) if (val === '' && !hasPlaceholder) { li = li.substring(0, 4) + 'class="m-placeholder" ' + li.substring(4); hasPlaceholder = true; } plugin.$list.append(li); }); // Append the title and the list. plugin.$wrapper.append(plugin.$title, plugin.$list); return this; }, setPlaceholderText: function () { this.updateTitle(this.getOptionData(this.getSelected())); return this; }, bindCustomEvents: function () { var privateApi = this; // Update m by clicking dropdown list items. plugin.$list.on('click', 'li', function (event) { var $target = $(event.target), data = privateApi.getOptionData($target); privateApi.updateSelect(data); $target.addClass('selected').siblings().removeClass('selected'); }); // Update m by changing the select box. plugin.$select.on('change', function () { var data = privateApi.getOptionData(privateApi.getSelected()); privateApi.updateTitle(data); }); if (plugin.options.clickToOpen) { this.clickToOpen(); } return this; }, showList: function () { plugin.$list.css('display', 'block'); return this; }, hideList: function () { plugin.$list.css('display', 'none'); return this; }, clickToOpen: function () { var $win = $(window), privateApi = this; plugin.$list.css('display', 'none') // You probably want this. // Clicking an li always closes the list. .on('click.m', 'li', function () { privateApi.hideList(); $win.off('click.m'); // Remove this handler if it exists. }); plugin.$title.on('click.m', function () { // Either show or hide the list. if (plugin.$list.css('display') !== 'block') { privateApi.showList(); setTimeout(function () { $win.on('click.m', function (event) { event.preventDefault(); // This is not working? privateApi.hideList(); $win.off('click.m'); }); }, 15); } else { privateApi.hideList(); $win.off('click.m'); } }); }, getOptionData: function ($el) { return {text: $el.text(), value: $el.val() || $el.data('value')}; }, getSelected: function () { return plugin.$select.find(':selected'); }, updateTitle: function (data) { plugin.$titleTarget.text(data.text); return this; }, updateSelect: function (data) { plugin.$select.val(data.value); return this; } }; this.initialize(); }; // Monkeypatch jQuery#val to fire an event on our select. oldVal = $.fn.val; $.fn.val = function (value) { var $this = $(this), newVal; // Call the old val() function... newVal = oldVal.apply(this, arguments); // ...fire our custom event... if ($this.data('m') && value) { $this.trigger('change'); } // ...return the value as the old val() does. return newVal; }; // Add the function to jQuery. $.fn.m = function (options) { return this.each(function () { var $this = $(this), menu; if ($this.data('m') === undefined) { menu = new $.m(this, options); $this.data('m', menu); } }); }; }($)); // define([ // 'jquery' // ], function ($) { // 'use strict'; // // // });
JavaScript
0.00002
@@ -555,25 +555,60 @@ opdown list. + Behaves like a regular select box. %0A - unicod @@ -776,21 +776,17 @@ tions);%0A - %0A + /**%0A @@ -1083,29 +1083,14 @@ var -arrow, icon;%0A +icon;%0A %0A @@ -1318,25 +1318,17 @@ /ul%3E');%0A - %0A + @@ -1391,27 +1391,17 @@ 25BE;';%0A - %0A + @@ -1559,27 +1559,17 @@ %7D%0A - %0A + @@ -1788,27 +1788,17 @@ pan%3E');%0A - %0A + @@ -2467,27 +2467,18 @@ '%3C/li%3E' +; %0A - %0A @@ -2707,29 +2707,17 @@ %7D%0A - %0A + @@ -3308,21 +3308,9 @@ t);%0A - %0A + @@ -4077,24 +4077,16 @@ = this;%0A - %0A
e4902efdf0b1596a54b354248dfb236e92a191a5
test fix
src/test/test.es6
src/test/test.es6
import 'core-js/shim'; import assert from 'assert'; import fs from 'fs'; import path from 'path'; import http from 'http'; import {emoji} from 'node-emoji'; import Proposal from '../index'; const fileReadAssertions = (fileReadPromise, cont) => { fileReadPromise.then((json) => { const data = JSON.parse(json), isFarley = data.success && data.number === 42 && data.name === 'Chris Farley'; assert.ok(isFarley, errify('Expected file data not found!')); cont(); }) .catch(cont); }; const emojify = (emo, pre='') => (str) => `${pre}${emoji[emo]} ${str}`, errify = emojify('poop'), h1 = emojify('pineapple'), cool = emojify('cool'), fw = emojify('fireworks', '\t\t'); describe(h1('Proposal tests'), () => { const read = fs.readFile, sampleFile = path.resolve(__dirname, 'fixtures/sample.json'); it(cool('Should return a Promise when a Proposal has arguments'), function (done) { const readPromise = Proposal(read, sampleFile), isAPromise = (readPromise instanceof Promise); assert.ok(isAPromise, errify('Proposal broke its Promise!')); fileReadAssertions(readPromise, done); }); it(cool('Returns a function that waits for more input if Proposal has only one arguments'), function (done) { const chickenCurry = Proposal(read), curryIsntPromise = !(chickenCurry instanceof Promise), curryIsFunction = (typeof chickenCurry === 'function'); assert.ok(curryIsntPromise, errify('You made an empty Promise! You know you won\'t keep it!')); assert.ok(curryIsFunction, errify('chickenCurry is not a function!')); const curryRead = chickenCurry(sampleFile), curryReadIsPromise = (curryRead instanceof Promise); assert.ok(curryReadIsPromise, errify('Promise not generated properly when curried function executed!')); fileReadAssertions(curryRead, done); }); it(cool('Tests a Proposal against a nodeback with no args'), function (done) { const handler = (req, res) => { console.log('hey'); res.writeHead(200); res.end('hello world\n'); }, serv = http.createServer(handler), closeProposal = Proposal(serv.close.bind(serv)), isntAPromise = !(closeProposal instanceof Promise); assert.ok(isntAPromise, errify('You made an empty Promise with server.close!')); serv.on('listening', () => { console.log(fw('server listening')); const closePromise = closeProposal(), isAPromise = (closePromise instanceof Promise); assert.ok(isAPromise, errify('closePromise is not a Promise!')); closePromise.then(() => { console.log(fw('closing server')); done(); }).catch(done); }); it(cool('A-weits'), async function (done) { const farley = await Proposal(read, sampleFile); console.log(farley); assert.ok(farley.name.includes('Farley'), 'Not Chris Farley!'); done(); }); serv.listen(10000); }); });
JavaScript
0.000001
@@ -2710,19 +2710,48 @@ %7D);%0A -%0A + serv.listen(10000);%0A%0A %7D);%0A%0A it(coo @@ -2967,39 +2967,8 @@ );%0A%0A - serv.listen(10000);%0A%0A %7D);%0A %0A%7D);
a7546c6662937341e01abd3d102e1bef632fdf08
resolve #13 Ignore empty lines
src/crontab.js
src/crontab.js
$(function () { 'use strict'; var crontabInputId = 'crontab'; var resultId = 'result'; var submitButtonId = 'check'; var daysOfWeek = 'ๆ—ฅๆœˆ็ซๆฐดๆœจ้‡‘ๅœŸๆ—ฅ'; var rangeOfUnits = { 'ๅˆ†': [0, 59], 'ๆ™‚': [0, 23], 'ๆ—ฅ': [1, 31], 'ๆœˆ': [1, 12], 'ๆ›œ': [0, 7] }; var errors = { 'error': 'error', 'insufficient': '่ฆ็ด ใŒไธ่ถณใ—ใฆใ„ใพใ™', 'outOfRange': 'out of range', 'unexpectedValue': 'unexpected value' }; $('#' + submitButtonId).on('click', function () { var crontab = $('#' + crontabInputId).val(); var resultBox = $('#' + resultId); var lines = crontab.split(/\n/); // Initialize the result table var table = $('<table></table>'); table.append('<thead><tr><th>ๆœˆ</th><th>ๆ—ฅ</th><th>ๆ›œๆ—ฅ</th><th>ๆ™‚</th><th>ๅˆ†</th></tr></thead>'); for (var i = 0; i < lines.length; i++) { var line = lines[i]; // Split params with whitespace var params = line.split(/ +/); // Check if this line has at least 5 params if (params.length < 5) { resultBox.html(getErrorMessage(null, 'insufficient')); return; } var minute, hour , day, month, dow, command; // Extract cron timing params var timings = params.splice(0, 5); minute = timings.shift(); hour = timings.shift(); day = timings.shift(); month = timings.shift(); dow = timings.shift(); // Join params left as a line of a command if (params.length > 0) { command = params.join(' '); } else { command = ''; } // Prepare a table body for the result var result = '<tbody>'; // Add timings to the result result += '<tr>'; result += describe(month, 'ๆœˆ', false, 'ใƒถๆœˆ'); result += describe(day, 'ๆ—ฅ'); result += describe(dow, 'ๆ›œ', daysOfWeek, 'ๆ—ฅ'); result += describe(hour, 'ๆ™‚', false, 'ๆ™‚้–“'); result += describe(minute, 'ๅˆ†'); result += '</tr>'; // Add command to the result result += '<tr>'; result += '<td class="left" colspan="5">' + htmlEscape(command) + '</td>'; result += '</tr>'; result += '</tbody>'; table.append(result); } resultBox.html(table); }); function describe(param, unit, convert, unitForInterval) { return '<td>' + parse(param, unit, convert, unitForInterval) + '</td>'; } function parse(param, unit, convert, unitForInterval) { // Split the elements with `,` for multiple params var elements = param.split(','); // Initialize the result var result = ''; // Get allowed ranges for this unit var rangeOfUnit = rangeOfUnits[unit]; var element, interval, intervalElements, rangeElements; for (var i = 0; i < elements.length; i++) { intervalElements = elements[i].split('/'); element = intervalElements[0]; if (intervalElements.length === 2) { interval = intervalElements[1]; } else { interval = undefined; } // Can not have more than 2 elements; if (intervalElements.length > 2) { return getErrorMessage(element); } if (element === '*') { if (interval && interval > 1) { result += '<em>' + interval + (unitForInterval || unit) + 'ใŠใ</em>'; } else { result += '<span class="gray">ใ™ในใฆ</span>'; } } else { if (i >= 1) { result += ', <br>'; } // Split the element with `-` for range rangeElements = element.split('-'); // Range can not have more than 2 elements if (rangeElements.length > 2) { return getErrorMessage(element); } // Check if each element is within allowed range for (var j = 0; j < rangeElements.length; j++) { if (rangeElements[j] < rangeOfUnit[0] || rangeElements[j] > rangeOfUnit[1]) { return getErrorMessage(element, 'outOfRange'); } } // Check if each element has expected values only if (!expectedValuesOnly(rangeElements)) { return getErrorMessage(element, 'unexpectedValue'); } // Convert values if specified if (convert) { rangeElements[0] = convert.charAt(rangeElements[0]); } rangeElements[0] = '<em>' + htmlEscape(rangeElements[0]) + unit + '</em>'; // Apply the above to the second element, if any if (rangeElements[1]) { if (convert) { rangeElements[1] = convert.charAt(rangeElements[1]); } rangeElements[1] = '<em>' + htmlEscape(rangeElements[1]) + unit + '</em>'; } // Join the minimum and the maximum; // do nothing is the element is not a range element = rangeElements.join('ใ‹ใ‚‰'); result += element; if (interval && interval > 1) { result += 'ใฎ<em>' + interval + (unitForInterval || unit) + 'ใŠใ</em>'; } } } return result; } function getErrorMessage(data, type) { // Set type 'error' if type is omitted or error message is not assigned if (typeof type === 'undefined' || !errors[type]) { type = 'error'; } // Get an error indicator var error = errors[type]; // If data is given, add separator if (data) { error += ': '; } else { // Set void string in case data is null data = ''; } return '<span class="error">' + error + data + '</span>'; } function expectedValuesOnly(values) { var result = true; $(values).each(function () { if (!this.match(/^[0-9\*\/]+$/)) { result = false; } }); return result; } function htmlEscape(str) { return $('<div>').text(str).html(); } });
JavaScript
0.000048
@@ -930,24 +930,136 @@ lines%5Bi%5D;%0A%0A + // Skip empty lines%0A if (line.match(/%5E%5Cs*$/)) %7B%0A continue;%0A %7D%0A%0A @@ -1243,31 +1243,61 @@ -resultBox.html( +table.append('%3Ctbody%3E%3Ctr%3E%3Ctd colspan=%225%22%3E' + getError @@ -1304,20 +1304,20 @@ Message( -null +line , 'insuf @@ -1325,16 +1325,39 @@ icient') + + '%3C/td%3E%3C/tr%3E%3C/tbody%3E' );%0A @@ -1367,22 +1367,24 @@ -return +continue ;%0A
637f9a2960615bf722b41ec22cad44a7b504ecbd
fix typo in example output
src/toKatakana.js
src/toKatakana.js
import { DEFAULT_OPTIONS } from './constants'; import isRomaji from './isRomaji'; import isMixed from './isMixed'; import hiraganaToKatakana from './utils/hiraganaToKatakana'; import romajiToHiragana from './utils/romajiToHiragana'; /** * Convert input to [Katakana](https://en.wikipedia.org/wiki/Katakana) * @param {String} [input=''] text * @param {DefaultOptions} [options=defaultOptions] * @return {String} converted text * @example * toKatakana('toukyou, ใŠใŠใ•ใ‹') * // => 'ใƒˆใ‚ฆใ‚ญใƒงใ‚ฆใ€ใ€€ใ‚ชใ‚ชใ‚ตใ‚ซ' * toKatakana('only ใ‹ใช', { passRomaji: true }) * // => 'only ใ‚ซใƒŠ' * toKatakana('wi') * // => 'ใ†ใƒ' * toKatakana('wi', { useObsoleteKana: true }) * // => 'ใƒฐ' */ function toKatakana(input = '', options = {}) { const config = Object.assign({}, DEFAULT_OPTIONS, options); if (config.passRomaji) return hiraganaToKatakana(input); if (isRomaji(input) || isMixed(input)) { const romaji = romajiToHiragana(input, config); return hiraganaToKatakana(romaji); } return hiraganaToKatakana(input); } export default toKatakana;
JavaScript
0.000131
@@ -592,10 +592,10 @@ =%3E ' -%E3%81%86%E3%81%83 +%E3%82%A6%E3%82%A3 '%0A *
0fcdcb036e99de2858dbb0717c45a0c0c951947d
Fix brokenness
Commando.js
Commando.js
global.Promise = require('bluebird'); const commando = require('discord.js-commando'); const Currency = require('./currency/Currency'); const Experience = require('./currency/Experience'); const oneLine = require('common-tags').oneLine; const path = require('path'); const Raven = require('raven'); const winston = require('winston'); const Database = require('./postgreSQL/PostgreSQL'); const Redis = require('./redis/Redis'); const SequelizeProvider = require('./postgreSQL/SequelizeProvider'); const config = require('./settings'); const database = new Database(); const redis = new Redis(); const client = new commando.Client({ owner: config.owner, commandPrefix: '?', unknownCommandResponse: false, disableEveryone: true }); let earnedRecently = []; let gainedXPRecently = []; Raven.config(config.ravenKey); Raven.install(); database.start(); redis.start(); client.setProvider(new SequelizeProvider(database.db)); client.on('error', winston.error) .on('warn', winston.warn) .on('ready', () => { winston.info(oneLine` Client ready... Logged in as ${client.user.username}#${client.user.discriminator} (${client.user.id}) `); Currency.leaderboard(); }) .on('disconnect', () => { winston.warn('Disconnected!'); }) .on('reconnect', () => { winston.warn('Reconnecting...'); }) .on('commandRun', (cmd, promise, msg, args) => { winston.info(oneLine`${msg.author.username}#${msg.author.discriminator} (${msg.author.id}) > ${msg.guild ? `${msg.guild.name} (${msg.guild.id})` : 'DM'} >> ${cmd.groupID}:${cmd.memberName} ${Object.values(args)[0] !== '' ? `>>> ${Object.values(args)}` : ''} `); }) .on('message', async (message) => { if (message.author.bot) return; const hasImageAttachment = message.attachments.some(attachment => { return attachment.url.match(/\.(png|jpg|jpeg|gif|webp)$/); }); const moneyEarned = hasImageAttachment ? Math.ceil(Math.random() * 7) + 1 : Math.ceil(Math.random() * 7) + 5; Currency.addBalance(message.author.id, moneyEarned); earnedRecently.push(message.author.id); setTimeout(() => { const index = earnedRecently.indexOf(message.author.id); earnedRecently.splice(index, 1); }, 8000); if (!gainedXPRecently.includes(message.author.id)) { const xpEarned = Math.ceil(Math.random() * 9) + 3; const oldLevel = await Experience.getLevel(message.author.id); Experience.addExperience(message.author.id, xpEarned).then(async () => { const newLevel = await Experience.getLevel(message.author.id); if (newLevel > oldLevel) { Currency.addBalance(message.author.id, 100 * newLevel); message.channel.sendMessage(`You leveled up to level ${newLevel}! Wooooooooo`); } }).catch(winston.error); gainedXPRecently.push(message.author.id); setTimeout(() => { const index = gainedXPRecently.indexOf(message.author.id); gainedXPRecently.splice(index, 1); }, 60 * 1000); } }) .on('commandError', (cmd, err) => { if (err instanceof commando.FriendlyError) return; winston.error(`Error in command ${cmd.groupID}:${cmd.memberName}`, err); }) .on('commandBlocked', (msg, reason) => { winston.info(oneLine` Command ${msg.command ? `${msg.command.groupID}:${msg.command.memberName}` : ''} blocked; ${reason} `); }) .on('commandPrefixChange', (guild, prefix) => { winston.info(oneLine` Prefix changed to ${prefix || 'the default'} ${guild ? `in guild ${guild.name} (${guild.id})` : 'globally'}. `); }) .on('commandStatusChange', (guild, command, enabled) => { winston.info(oneLine` Command ${command.groupID}:${command.memberName} ${enabled ? 'enabled' : 'disabled'} ${guild ? `in guild ${guild.name} (${guild.id})` : 'globally'}. `); }) .on('groupStatusChange', (guild, group, enabled) => { winston.info(oneLine` Group ${group.id} ${enabled ? 'enabled' : 'disabled'} ${guild ? `in guild ${guild.name} (${guild.id})` : 'globally'}. `); }); client.registry .registerGroups([ ['info', 'Info'], ['currency', 'Currency'], ['games', 'Games'], ['item', 'Item'], ['weather', 'Weather'], ['music', 'Music'], ['tags', 'Tags'] ]) .registerDefaults() .registerCommandsIn(path.join(__dirname, 'commands')); client.login(config.token);
JavaScript
0.000002
@@ -1696,16 +1696,70 @@ eturn;%0A%0A +%09%09if (!earnedRecently.includes(message.author.id)) %7B%0A%09 %09%09const @@ -1823,16 +1823,17 @@ =%3E %7B%0A%09%09%09 +%09 return a @@ -1885,20 +1885,22 @@ )$/);%0A%09%09 +%09 %7D);%0A +%09 %09%09const @@ -1932,16 +1932,18 @@ achment%0A +%09%09 %09%09? Math @@ -1971,16 +1971,18 @@ 7) + 1%0A +%09%09 %09%09: Math @@ -2012,16 +2012,17 @@ ) + 5;%0A%0A +%09 %09%09Curren @@ -2069,16 +2069,17 @@ rned);%0A%0A +%09 %09%09earned @@ -2114,16 +2114,17 @@ .id);%0A%09%09 +%09 setTimeo @@ -2134,16 +2134,17 @@ () =%3E %7B%0A +%09 %09%09%09const @@ -2194,24 +2194,25 @@ hor.id);%0A%09%09%09 +%09 earnedRecent @@ -2232,16 +2232,17 @@ ex, 1);%0A +%09 %09%09%7D, 800 @@ -2244,16 +2244,20 @@ , 8000); +%0A%09%09%7D %0A%0A%09%09if (
5cd1c38dbf434d2d77b750f7ee7c025bac1fe2c5
Update loadTexture
nin/dasBoot/Loader.js
nin/dasBoot/Loader.js
var Loader = (function(){ var eventNames = { AUDIO: 'canplaythrough', IMG: 'load' }; var itemsToAjax = []; var itemsToLoad = []; var rootPath = ''; return { setRootPath: function(path){ rootPath = path; }, loadAjax: function(filepath, callback) { itemsToAjax.push({ filepath: filepath, callback: callback }); }, loadTexture: function(filepath, callback) { var image = new Image(); image.crossOrigin = "Anonymous"; var texture = new THREE.Texture(); texture.image = image; texture.sourceFile = filepath; Loader.load(filepath, image, function() { texture.needsUpdate = true; if (typeof callback === 'function') { callback(); } }); return texture; }, load: function(filepath, element, callback) { console.log('starting to load', filepath); itemsToLoad.push({ filepath: filepath, element: element, callback: callback }); }, start: function(onprogress, oncomplete) { var maxWaitingCount = itemsToAjax.length + itemsToLoad.length; var waitingCount = maxWaitingCount; function registerAsLoaded(item)ย { onprogress(100 - waitingCount / maxWaitingCount * 100); console.log('finished loading', item.filepath); if(!--waitingCount) { oncomplete(); } } itemsToLoad.forEach(function(item) { var eventName = eventNames[item.element.tagName]; item.element.addEventListener(eventName, listener); function listener() { item.element.removeEventListener(eventName, listener); item.callback && item.callback(); registerAsLoaded(item); }; if(window.FILES) { item.element.src = 'data:audio/mp3;base64,' + FILES[item.filepath]; } else { item.element.src = rootPath + item.filepath; } }); itemsToAjax.forEach(function(item) { var response = null; var request = new XMLHttpRequest(); request.open('GET', rootPath + item.filepath, 1); request.onload = function() { item.callback(request.responseText); registerAsLoaded(item); } request.send(); }); } }; })();
JavaScript
0
@@ -610,35 +610,37 @@ -Loader.load(filepath, image +image.addEventListener('load' , fu @@ -639,33 +639,32 @@ oad', function() - %7B%0A textur @@ -769,24 +769,63 @@ %7D%0A %7D);%0A + image.src = rootPath + filepath;%0A return
0dd3bb30fddb4bc1a8d08eee1d02a6c6126f0dcf
Put more border on the top
wm.js
wm.js
(function(exports) { // Don't extend Window as this needs to be in the // WM client, not its own client. var WindowFrame = new Class({ Extends: Window, initialize: function(wm, server, windowId) { this._wm = wm; this._server = server; this.clientWindowId = windowId; }, _syncGeometry: function(geom, forceClientConfigure) { // A real WM would cache this, as it would cause a round-trip. var clientGeom = this._server.getGeometry(this._wm, this.clientWindowId); // Hardcoded 10px border for now. // The top-left of the frame is the top-left of the window, and we'll // put the client 10px in. That means we should only touch the width // and height. this._server.configureWindow(this._wm, this.frameWindowId, { x: geom.x, y: geom.y, width: geom.width + 20, height: geom.height + 20 }); if (forceClientConfigure || clientGeom.width != geom.width || clientGeom.height != geom.height) { this._server.configureWindow(this._wm, this.clientWindowId, { x: 10, y: 10, width: geom.width, height: geom.height }); } }, construct: function() { var geom = this._server.getGeometry(this._wm, this.clientWindowId); this.frameWindowId = this._server.createWindow(this._wm); this._server.selectInput(this._wm, this.frameWindowId, ["Expose"]); this._server.changeAttributes(this._wm, this.frameWindowId, { backgroundColor: 'red' }); // for now this._server.reparentWindow(this._wm, this.clientWindowId, this.frameWindowId); // Map the frame window. this._server.mapWindow(this._wm, this.frameWindowId); this._syncGeometry(geom, true); }, _configureRequestStack: function(event) { this._server.configureWindow(this._wm, this.frameWindowId, { stackMode: event.detail }); }, configureRequest: function(event) { // ICCCM 4.1.5 // The coordinate system of the ConfigureRequest is that of the root; // that is, the X/Y in the ConfigureNotify are of the top-left of the // outer frame window. Note that the width/height are of the client // window. // We don't generate synthetic events quite yet. this._syncGeometry(event, false); if (event.hasStack) this._configureRequestStack(event); }, expose: function(wrapper) { // background color takes care of it for now wrapper.clearDamage(); }, }); var WindowManager = new Class({ connect: function(server) { this._server = server; this._server.clientConnected(this); this._server.selectInput(this, this._server.rootWindowId, ["SubstructureRedirect", "UnmapNotify"]); // client window => window frame this._windowFrames = {}; // frame window => window frame this._windowFramesById = {}; }, handleEvent: function(event) { switch (event.type) { case "MapRequest": return this.mapRequest(event); case "ConfigureRequest": return this.configureRequest(event); case "Expose": // This should only happen for frame windows. return this.exposeFrame(event); } }, exposeFrame: function(event) { var frame = this._windowFramesById[event.windowId]; frame.expose(event.ctx); }, configureRequest: function(event) { var frame = this._windowFrames[event.windowId]; // If we don't have a frame for a window, it was never // mapped, simply re-configure the window with whatever // it requested. if (!frame) { this._server.configureWindow(this, event.windowId, { x: event.x, y: event.y, width: event.width, height: event.height }); } else { // The frame will move/resize the window to its // client coordinates. frame.configureRequest(event); } }, mapRequest: function(event) { var frame = new WindowFrame(this, this._server, event.windowId); this._windowFrames[event.windowId] = frame; // Reparent the original window and map the frame. frame.construct(); this._windowFramesById[frame.frameWindowId] = frame; // Map the original window, now that we've reparented it // back into the frame. this._server.mapWindow(this, event.windowId); }, unmapNotify: function(event) { var frame = this._windowFrames[event.windowId]; frame.destroy(); delete this._windowFrames[event.windowId]; }, }); exports.WindowManager = WindowManager; })(window);
JavaScript
0
@@ -577,41 +577,63 @@ -// Hardcoded 10px border for now. +var border = %7B top: 30, left: 5, right: 5, bottom: 5 %7D; %0A%0A @@ -918,57 +918,251 @@ m.y, - width: geom.width + 20, height: geom.height + 20 +%0A width: geom.width + border.left + border.right,%0A height: geom.height + border.top + border.bottom %7D); @@ -1358,17 +1358,34 @@ x: -10, y: 10 +border.left, y: border.top , wi
166d76d0174df434187323d8a4073f8241039975
remove unused dependency
Gulpfile.js
Gulpfile.js
var gulp = require('gulp'); gulp.task('default', ['build', 'documentation']); gulp.task('build', function () { var autoprefixer = require('gulp-autoprefixer'); var sass = require('gulp-sass'); var sourcemaps = require('gulp-sourcemaps'); return gulp.src('sass/canon-bootstrap.scss') .pipe(sourcemaps.init()) .pipe(autoprefixer({ browsers: ['last 2 versions'] })) .pipe(sass({ includePaths: ['node_modules/bootstrap-sass/assets/stylesheets'] })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('build')); }); gulp.task('documentation', ['build'], function (done) { var join = require('path').join; var async = require('async'); var metalsmith = require('metalsmith'); var copy = require('metalsmith-copy'); var markdown = require('metalsmith-markdown'); var templates = require('metalsmith-templates'); async.series({ metalsmith: function (done) { metalsmith(join(__dirname, 'docs')) .use(markdown()) .use(templates('handlebars')) .build(done); }, canon: function (done) { gulp.src('build/**/*') .pipe(gulp.dest('docs/build/canon')) .on('end', done); } }, done); }); gulp.task('server', ['documentation'], function () { var webserver = require('gulp-webserver'); gulp.watch(['sass/**/*.scss', 'docs/{src,templates}/**/*.{html,md}'], ['documentation']); return gulp.src('docs/build') .pipe(webserver({ livereload: true })); });
JavaScript
0.000002
@@ -703,49 +703,8 @@ ');%0A - var copy = require('metalsmith-copy');%0A va
6b90035b8c92c95407a36e3e34aaf9296fc2815e
Remove watch task.
Gulpfile.js
Gulpfile.js
/** * Created by xubt on 4/30/16. */ var gulp = require('gulp'); var jshint = require('gulp-jshint'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var ngmin = require('gulp-ngmin'); var ngAnnotate = require('gulp-ng-annotate'); var less = require('gulp-less'); var gulpSequence = require('gulp-sequence'); var lib = require('bower-files')({ overrides: { 'x-editable': { main: './dist/bootstrap3-editable/js/bootstrap-editable.js', dependencies: { "jquery": ">=1.6" } } } }); var cleanCSS = require('gulp-clean-css'); // ่ฏญๆณ•ๆฃ€ๆŸฅ gulp.task('jshint', function () { return gulp.src(['kanban/**/*.js', '!kanban/static/**/*.js', '!kanban/**/util/*.js']) .pipe(jshint()) .pipe(jshint.reporter('default')); }); // ๅˆๅนถๅŽ‹็ผฉ็ฌฌไธ‰ๆ–น็ฑปๅบ“ gulp.task('minify-bower-components', function () { gulp.src(lib.ext('js').files) .pipe(concat('lib.min.js')) .pipe(gulp.dest('kanban/static/js/')); }); // ๅˆๅนถCSS gulp.task('minify-css', function () { return gulp.src(['kanban/**/*.css', '!kanban/static/css/*.css']) .pipe(concat('thiki-kanban.min.css')) .pipe(cleanCSS({compatibility: 'ie8'})) .pipe(gulp.dest('kanban/static/css')); }); // ๅˆๅนถLESS gulp.task('minify-less', function () { return gulp.src(['kanban/**/*.less', '!kanban/static/**/*.less']) .pipe(concat('thiki-kanban.min.less')) .pipe(cleanCSS({compatibility: 'ie8'})) .pipe(gulp.dest('kanban/static/less')); }); //Less่ฝฌcss gulp.task('build-less-to-css', function () { return gulp.src('kanban/static/less/thiki-kanban.min.less') .pipe(concat('thiki-kanban.min.less-css.css')) .pipe(less()) .pipe(gulp.dest('kanban/static/less')); }); // ๅˆๅนถๆ–‡ไปถไน‹ๅŽๅŽ‹็ผฉไปฃ็  gulp.task('minify-js', function () { return gulp.src([ 'kanban/*.js', 'kanban/**/*.js', '!kanban/static/**/*.js']) .pipe(ngAnnotate()) .pipe(ngmin({dynamic: false})) .pipe(concat('thiki-kanban.js')) .pipe(gulp.dest('kanban/static/js')) .pipe(uglify()) .pipe(rename('thiki-kanban.min.js')) .pipe(gulp.dest('kanban/static/js')); }); // ็›‘่ง†ๆ–‡ไปถ็š„ๅ˜ๅŒ– gulp.task('watch', function () { gulp.watch(['kanban/*.js', 'kanban/**/*.js', 'kanban/styles/*.css', 'kanban/**/*.less', 'kanban/**/*.css', 'gulpfile.js', '!kanban/static/**/*.js', '!kanban/static/**/*.css'], ['jshint', 'minify-bower-components', 'minify-js', 'minify-less', 'build-less-to-css', 'minify-css']); }); // ๆณจๅ†Œ็ผบ็œไปปๅŠก gulp.task('default', gulpSequence('jshint', 'minify-bower-components', 'minify-js', 'minify-less', 'build-less-to-css', 'minify-css', 'watch'));
JavaScript
0.000006
@@ -2715,17 +2715,8 @@ css' -, 'watch' ));%0A
6530cde02408d4b4176364019af2a55d1babce56
Update urlStatistics.js
ClientAngular/js/controllers/urlStatistics.js
ClientAngular/js/controllers/urlStatistics.js
app.controller('urlStatistics', function($scope, $rootScope, $http) { $rootScope.notStatisticsView = true; $rootScope.textUrlStatistics = "Inspect a Shortify URL"; //x $rootScope.labels = []; //Casistiche $rootScope.series = []; //y $rootScope.data = []; /**Funzione per la richiesta delle informazioni riguardanti uno specifico shorturl e la visualizzazione del grafuico associato*/ $rootScope.showStatistics = function(urlforstat) { if (urlforstat == "" || urlforstat == null) { return; //Campo non avvalorato } else { if($rootScope.notStatisticsView) { //Richiesta delle informazioni associate ad uno specifico shorturl $http.post("http://localhost:4567/api/v1/stats", {shorturl: urlforstat}) .success(function(response) { $rootScope.error = false; //Ottengo dati per statistiche dalla response var hourCounters = response.hourCounters; $scope.uniqueCounter = response.uniqueCounter; var countryCounters = response.countryCounters; dayCounters = response.dayCounters; $scope.longUrl = response.longUrl; $scope.shortUrl = response.shortUrl; //BAR CHART statistiche intervalli orari var labels = Object.keys(hourCounters).sort(); var perHour = []; //Visite per ora //Riepimento delle liste di valori per la rappresentazione grafica for (var i = 0; i < labels.length; i++) { perHour.push(hourCounters[labels[i]]); } //Dati utili per il grafico canvas $rootScope.labels = labels; $rootScope.series = ['Visits per hour']; $rootScope.data = [perHour]; //TABELLA VISITE GIORNALIERE var days = Object.keys(dayCounters).reverse(); for (var i = 0; i < days.length; i++) { var count = dayCounters[days[i]]; var table = document.getElementById("days-table-rows"); var row = table.insertRow(i); row.setAttribute("class", "success"); var d = row.insertCell(0); var v = row.insertCell(1); d.innerHTML = days[i]; v.innerHTML = count; } //TABELLA VISITE PER NAZIONE var countries = Object.keys(countryCounters); for (var i = 0; i < countries.length; i++) { var count = countryCounters[countries[i]]; var table = document.getElementById("country-table-rows"); var row = table.insertRow(i); row.setAttribute("class", "success"); var c = row.insertCell(0); var v = row.insertCell(1); if (countries[i] != "NULL") { c.innerHTML = '<span class="flag-icon flag-icon-' + countries[i].toLowerCase() + '"></span>'; v.innerHTML = count; } else { c.innerHTML = "UNDEFINED"; v.innerHTML = count; } } //visualizza le statistiche $rootScope.notStatisticsView = false; //sposta la vista verso il div $('html, body').animate({scrollTop:$('#statisticsDiv').position().top}, 'slow'); }) .error(function(response) { $rootScope.done = false; $rootScope.textError = response.error; document.getElementById("errorDiv").setAttribute("class", "alert alert-danger centeredText animated fadeIn"); $rootScope.error = true; }); //visualizza le statistiche $rootScope.notStatisticsView = false; } } } $scope.hideStatistics = function() { //PULIZIA ELIMINANDO RIGHE AGGIUNTE ALLE TABELLE var countryTableRows = document.getElementById("country-table-rows"); while (countryTableRows.firstChild) { countryTableRows.removeChild(countryTableRows.firstChild); } var daysTableRows = document.getElementById("days-table-rows"); while (daysTableRows.firstChild) { daysTableRows.removeChild(daysTableRows.firstChild); } $rootScope.notStatisticsView = true; } });
JavaScript
0.000001
@@ -4592,111 +4592,8 @@ %0A - //visualizza le statistiche%0A $rootScope.notStatisticsView = false;%0A @@ -5228,8 +5228,9 @@ %0A%7D); +%0A
fbf49a32a77cf2da079303afc049867a388133db
Fix Region spec
spec/specs/region.js
spec/specs/region.js
define(function() { describe('Minionette.Region', function() { var RegionView = Minionette.View.extend({ template: _.template('<p>test</p><%= view("region") %><p>test</p>') }); function addInnerView(name, parentView) { var v = new Minionette.View({tagName: 'p'}); v.template = _.template("test"); v.render(); parentView.addRegion(name, v); parentView.render(); return v; } beforeEach(function() { this.view = new RegionView(); this.region = new Minionette.Region({view: this.view}); }); afterEach(function() { delete this.view; delete this.region; }); describe("#_configure()", function() { it("picks view out of initialization options", function() { expect(this.region.view).to.equal(this.view); }); }); describe("#_ensureView()", function() { it("sets #view to a #_view if one is not passed in", function() { var region = new Minionette.Region(); expect(region.view).to.equal(region._view); }); it("sets #view to #_view if passed in view isn't an instanceof Backbone.View", function() { var region = new Minionette.Region({view: 'view?'}); expect(region.view).to.equal(region._view); }); }); describe("#render()", function() { it("calls #view#render()", function() { var stub = this.sinon.stub(this.view, 'render'); this.region.render(); expect(stub).to.have.been.called; }); it("returns #view#render()", function() { var expected = _.uniqueId(); this.view.render = function() { return expected; }; var ret = this.region.render(); expect(ret).to.equal(expected); }); }); describe("#attach()", function() { beforeEach(function() { this.newView = new Minionette.View(); }); afterEach(function() { delete this.newView; }); it("replaces current view#el with newView#el (the same index in parent)", function() { var v = addInnerView('region', this.view), expectedIndex = v.$el.index(); this.view.region.attach(this.newView); expect(this.newView.$el.index()).to.equal(expectedIndex); }); it("doesn't call #view#remove()", function() { var stub = this.sinon.stub(this.view, 'remove'); this.region.attach(this.newView); expect(stub).to.not.have.been.called; }); it("sets #view to newView", function() { this.region.attach(this.newView); expect(this.region.view).to.equal(this.newView); }); it("returns newView", function() { var ret = this.region.attach(this.newView); expect(ret).to.equal(this.newView); }); }); describe("#detach()", function() { it("sets #_detachedView to the old #view", function() { var oldView = this.region.view; this.region.detach(); expect(this.region._detachedView).to.equal(oldView); }); it("sets #view to #_view", function() { this.region.detach(); expect(this.region.view).to.equal(this.region._view); }); it("replaces current view#el with _view#el (the same index in parent)", function() { var v = addInnerView('region', this.view), expectedIndex = v.$el.index(); this.view.region.detach(); expect(this.view.region._view.$el.index()).to.equal(expectedIndex); }); it("calls #view#$el#detach()", function() { var spy = this.sinon.spy(); this.view.on('click', spy); this.region.detach(); this.view.trigger('click'); expect(spy).to.have.been.called; }); it("returns this for chaining", function() { var ret = this.region.detach(); expect(ret).to.equal(this.region); }); }); describe("#reattach()", function() { beforeEach(function() { this.region.detach(); }); it("scopes #reattach() to _parent", function() { this.view.remove(); // Make sure view isn't in the document.body var v = addInnerView('region', this.view); this.view.region.detach(); var expectedIndex = this.view.region.view.$el.index(); this.view.region.reattach(); expect(v.$el.index()).to.equal(expectedIndex); }); it("replaces view#el with _detachedView#el", function() { var v = addInnerView('region', this.view); this.view.region.detach(); var expectedIndex = this.view.region.view.$el.index(); this.view.region.reattach(); expect(v.$el.index()).to.equal(expectedIndex); }); it("deletes #_detachedView so it can't be re#attach()ed", function() { this.region.reattach(); expect(this.region._detachedView).to.not.exist; }); }); describe("#remove()", function() { it("calls #view#remove()", function() { var stub = this.sinon.stub(this.view, 'remove'); this.region.remove(); expect(stub).to.have.been.called; }); it("replaces view#el with _view#el", function() { var v = addInnerView('region', this.view), expectedIndex = v.$el.index(); this.view.region.remove(); expect(this.view.region._view.$el.index()).to.equal(expectedIndex); }); it("returns removedView", function() { var removedView = this.region.remove(); expect(removedView).to.equal(this.view); }); }); describe("#reset()", function() { it("replaces view#el with _view#el", function() { var v = addInnerView('region', this.view), expectedIndex = v.$el.index(); this.view.region.reset(); expect(this.view.region._view.$el.index()).to.equal(expectedIndex); }); it("doesn't call #remove on old #view", function() { var stub = this.sinon.stub(this.view, 'remove'); this.region.reset(); expect(stub).to.not.have.been.called; }); }); describe("#_removeView()", function() { it("sets #view to #_view", function() { this.region._removeView(this.view); expect(this.region.view).to.equal(this.region._view); }); it("replaces view#el with _view#el", function() { var v = addInnerView('region', this.view), expectedIndex = v.$el.index(); this.view.region.reset(); expect(this.view.region._view.$el.index()).to.equal(expectedIndex); }); it("doesn't call #remove on old #view", function() { var stub = this.sinon.stub(this.view, 'remove'); this.region._removeView(this.view); expect(stub).to.not.have.been.called; }); it("only resets if #view equals passed in view", function() { var v = new Minionette.View(); this.region._removeView(v); expect(this.region.view).to.equal(this.view); }); }); }); });
JavaScript
0
@@ -4810,22 +4810,26 @@ is.view. -remove +$el.detach (); // M
8c8b177f4dc9845e84131e5777f9911851f20a59
Add metadata passing to rethrowFx
src/helpers.js
src/helpers.js
export function actionIs(actionName) { return function () { return this.filter(({action}) => action === actionName); }; } export function parentIs(parentName) { return function () { return this.filter(({parent}) => parent === parentName); }; } export function filter(cond) { return function () { return this.filter(cond); }; } export function debounce(time) { return function () { return this.debounce(time); }; } export function throttle(time) { return function () { return this.throttle(time); }; } export function rethrowFx(action, payload) { return function (stream) { stream.send(action, payload) } } export function subcomponentFx(subParent, dispatchSub) { return function (stream) { stream.subStream(subParent, dispatchSub) } }
JavaScript
0
@@ -580,16 +580,26 @@ payload +, metadata ) %7B%0A re @@ -654,16 +654,26 @@ payload +, metadata )%0A %7D%0A%7D%0A
f392e0ba6078628f6575898f063070f18b03a04f
Normalize path
src/i-route.js
src/i-route.js
"use strict"; /** * Class for use route * @author Ivanildo de Castro * @license MIT */ function IRoute(options){ this.options = options; this.routes = []; } IRoute.prototype.routes = []; IRoute.prototype.add = function(path){ var i; for(i = 1 ; i < arguments.length ; i++){ this.routes.push({ path: path, callback: arguments[i] }); } return this; }; IRoute.prototype.execute = function(path){ var routes = this.get(path); var total = routes.length; var request = this.getRequest(path); var options = {}; if(total){ this.executeNext(request, routes, 0, total, options); } }; IRoute.prototype.executeNext = function(request, routes, index, total, options){ if(options.redirect){ } if(index < total){ var route = routes[index]; request.params = this.getParams(request.path, route); route.callback( request, this.executeNext.bind( this, request, routes, index + 1, total ) ); } }; IRoute.prototype.get = function(path){ return this.routes.filter( this.comparePaths.bind(this, path) ); }; IRoute.prototype.comparePaths = function(path, route){ var regexp = this.getRegExpPath(route.path); return regexp.test(path); }; IRoute.prototype.getRegExpPath = function(path){ var regexp = path; if(typeof regexp === 'string'){ regexp = regexp.replace(/(\/\:\w+)\?/g, '($1)?'); regexp = regexp.replace(/\:\w+/g, '(\\w+)'); regexp = new RegExp('^[\/]?'+regexp+'$', 'gi'); } return regexp; }; IRoute.prototype.getRequest = function(path){ return { path: path, params: this.getParams() }; }; IRoute.prototype.getParams = function(path, route){ if(!path || !route || typeof route.path !== 'string'){ return {}; } var regexp = this.getRegExpPath(route.path); var params = route.path.match(/\:\w+/g); var values = regexp.exec(path); var i; var result = {}; var name; for(i = 0 ; i < params.length ; i++){ name = params[i].replace(/^:/, ''); result[name] = values[i + 1]; } return result; }; if(module && module.exports){ module.exports = IRoute; }else{ window.IRoute = IRoute; }
JavaScript
0.002268
@@ -452,32 +452,71 @@ function(path)%7B%0A +%0A path = this.normalizePath(path);%0A%0A var routes = @@ -710,24 +710,239 @@ ;%0A %7D%0A%7D;%0A%0A +IRoute.prototype.normalizePath = function(path)%7B%0A if(!/%5E%5C//.test(path))%7B%0A path = '/' + path;%0A %7D%0A%0A if(/%5C/$/.test(path))%7B%0A path = path.substring(0, path.length - 1);%0A %7D%0A%0A return path;%0A%7D;%0A%0A IRoute.proto @@ -1007,24 +1007,24 @@ options)%7B%0A%0A - if(optio @@ -1025,16 +1025,27 @@ (options + && options .redirec @@ -2418,16 +2418,53 @@ name;%0A%0A + if(params && params.length)%7B%0A for( @@ -2489,32 +2489,36 @@ .length ; i++)%7B%0A + name = @@ -2554,16 +2554,20 @@ + + result%5Bn @@ -2588,16 +2588,26 @@ i + 1%5D;%0A + %7D%0A %7D%0A%0A
3b81ee4b99453f275435633364186ffec1febb21
Fix whitespace
IPython/html/static/widgets/js/widget_link.js
IPython/html/static/widgets/js/widget_link.js
// Copyright (c) IPython Development Team. // Distributed under the terms of the Modified BSD License. define([ "widgets/js/widget", "jquery", ], function(widget, $){ var LinkModel = widget.WidgetModel.extend({ initialize: function() { this.on("change:widgets", function(model, value, options) { this.update_bindings(model.previous("widgets") || [], value); this.update_value(this.get("widgets")[0]); }, this); this.on("destroy", function(model, collection, options) { this.update_bindings(this.get("widgets"), []); }, this); }, update_bindings: function(oldlist, newlist) { var that = this; _.each(oldlist, function(elt) {elt[0].off("change:" + elt[1], null, that);}); _.each(newlist, function(elt) {elt[0].on("change:" + elt[1], function(model, value, options) { that.update_value(elt); }, that); // TODO: register for any destruction handlers // to take an item out of the list }); }, update_value: function(elt) { if (this.updating) {return;} var model = elt[0]; var attr = elt[1]; var new_value = model.get(attr); this.updating = true; _.each(_.without(this.get("widgets"), elt), function(element, index, list) { if (element[0]) { element[0].set(element[1], new_value); element[0].save_changes(); } }, this); this.updating = false; }, }); var DirectionalLinkModel = widget.WidgetModel.extend({ initialize: function() { this.on("change", this.update_bindings, this); this.on("destroy", function() { if (this.source) { this.source[0].off("change:" + this.source[1], null, this); } }, this); }, update_bindings: function() { if (this.source) { this.source[0].off("change:" + this.source[1], null, this); } this.source = this.get("source"); if (this.source) { this.source[0].on("change:" + this.source[1], function() { this.update_value(this.source); }, this); this.update_value(this.source); } }, update_value: function(elt) { if (this.updating) {return;} var model = elt[0]; var attr = elt[1]; var new_value = model.get(attr); this.updating = true; _.each(this.get("targets"), function(element, index, list) { if (element[0]) { element[0].set(element[1], new_value); element[0].save_changes(); } }, this); this.updating = false; }, }); return { "LinkModel": LinkModel, "DirectionalLinkModel": DirectionalLinkModel, } });
JavaScript
0.999999
@@ -400,20 +400,32 @@ value);%0A -%09%09%09%09 + this.upd @@ -481,17 +481,20 @@ this);%0A -%09 + @@ -897,213 +897,447 @@ 1%5D,%0A -%09%09%09%09%09%09 function(model, value, options) %7B%0A%09%09%09%09%09%09%09 that.update_value(elt);%0A%09%09%09%09%09%09 %7D, that);%0A%09%09%09%09%09 // TODO: register for any destruction handlers%0A%09%09%09%09%09 // to take an item out of the list%0A%09%09%09%09%09 + function(model, value, options) %7B%0A that.update_value(elt);%0A %7D, that);%0A // TODO: register for any destruction handlers%0A // to take an item out of the list%0A %7D) @@ -1682,39 +1682,76 @@ ) %7B%0A -%09%09%09%09%09%09if (element%5B0%5D) %7B%0A%09%09%09%09%09%09%09 + if (element%5B0%5D) %7B%0A elem @@ -1777,39 +1777,59 @@ 1%5D, new_value);%0A -%09%09%09%09%09%09%09 + element%5B0%5D.save_ @@ -1839,22 +1839,39 @@ nges();%0A -%09%09%09%09%09%09 + %7D%0A @@ -2514,19 +2514,28 @@ urce%22);%0A -%09%09%09 + if (this @@ -3052,39 +3052,76 @@ ) %7B%0A -%09%09%09%09%09%09if (element%5B0%5D) %7B%0A%09%09%09%09%09%09%09 + if (element%5B0%5D) %7B%0A elem @@ -3159,15 +3159,35 @@ e);%0A -%09%09%09%09%09%09%09 + elem @@ -3201,33 +3201,32 @@ save_changes();%0A - @@ -3318,17 +3318,16 @@ %7D);%0A%0A -%0A retu
e7638806fa27f9a51f703eb9799beb1c1591b747
Update sk.js
src/i18n/sk.js
src/i18n/sk.js
// Validation errors messages for Parsley import Parsley from '../parsley'; Parsley.addMessages('sk', { defaultMessage: "Prosรญm zadajte sprรกvnu hodnotu.", type: { email: "Prosรญm zadajte sprรกvnu emailovรบ adresu.", url: "Prosรญm zadajte platnรบ URL adresu.", number: "Toto pole mรดลพe obsahovaลฅ len ฤรญsla", integer: "Toto pole mรดลพe obsahovaลฅ len celรฉ ฤรญsla", digits: "Toto pole mรดลพe obsahovaลฅ len kladnรฉ celรฉ ฤรญsla.", alphanum: "Toto pole mรดลพe obsahovaลฅ len alfanumerickรฉ znaky." }, notblank: "Toto pole nesmie byลฅ prรกzdne.", required: "Toto pole je povinnรฉ.", pattern: "Toto pole je je neplatnรฉ.", min: "Prosรญm zadajte hodnotu vรคฤลกiu alebo rovnรบ %s.", max: "Prosรญm zadajte hodnotu menลกiu alebo rovnรบ %s.", range: "Prosรญm zadajte hodnotu v rozmedzรญ %s a %s", minlength: "Prosรญm zadajte hodnotu dlhรบ %s znakov a viacej.", maxlength: "Prosรญm zadajte hodnotu kratลกiu ako %s znakov.", length: "Prosรญm zadajte hodnotu medzi %s a %s znakov.", mincheck: "Je nutnรฉ vybraลฅ minimรกlne %s z moลพnostรญ.", maxcheck: "Je nutnรฉ vybraลฅ maximรกlne %s z moลพnostรญ.", check: "Je nutnรฉ vybraลฅ od %s do %s z moลพnostรญ.", equalto: "Prosรญm zadajte rovnakรบ hodnotu." }); Parsley.setLocale('sk');
JavaScript
0.000001
@@ -326,24 +326,25 @@ a%C5%A5 len %C4%8D%C3%ADsla +. %22,%0A integ @@ -392,16 +392,17 @@ l%C3%A9 %C4%8D%C3%ADsla +. %22,%0A d @@ -666,19 +666,16 @@ pole je -je neplatn%C3%A9 @@ -920,17 +920,23 @@ notu dlh -%C3%BA +%C5%A1iu ako %25s znak @@ -941,17 +941,8 @@ akov - a viacej .%22,%0A @@ -1114,34 +1114,32 @@ a%C5%A5 minim%C3%A1lne %25s -z mo%C5%BEnost%C3%AD.%22,%0A ma @@ -1178,26 +1178,24 @@ axim%C3%A1lne %25s -z mo%C5%BEnost%C3%AD.%22,%0A @@ -1245,10 +1245,8 @@ %25s -z mo%C5%BEn
66d93ce701187ed0d2b7d9edee92f773fba22159
Fix adding classes to DOMTokenList (#213)
src/iconlib.js
src/iconlib.js
JSONEditor.AbstractIconLib = Class.extend({ mapping: { collapse: '', expand: '', "delete": '', edit: '', add: '', cancel: '', save: '', moveup: '', movedown: '' }, icon_prefix: '', getIconClass: function(key) { if(this.mapping[key]) return this.icon_prefix+this.mapping[key]; else return null; }, getIcon: function(key) { var iconclass = this.getIconClass(key); if(!iconclass) return null; var i = document.createElement('i'); i.classList.add(iconclass); return i; } });
JavaScript
0
@@ -521,20 +521,55 @@ .add -(iconclass); +.apply(i.classList, iconclass.split(' '));%0A %0A
5e64a02319e93e1dc2b0dbb7808eede88e929aaf
add interesting welcome message
api.js
api.js
/** * Module dependencies. */ var express = require('express') , http = require('http') , path = require('path') , cors = require('cors') , async = require('async') , redis = require('redis'); if (process.env.REDIS_URL) { var redisURL = require('url').parse(process.env.REDIS_URL); var client = redis.createClient(redisURL.port, redisURL.hostname); client.auth(redisURL.auth.split(":")[1]); } else { var client = redis.createClient(); } var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(cors()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/api/statuses', function (req, res) { client.keys("aerobot:status:*", function (err, reply) { async.reduce(reply, {}, function(memo, item, callback) { client.hgetall(item, function(err, reply) { memo[item] = reply; callback(null, memo); }); }, function(err, result){ console.log(result); res.json(result); }); }); }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
JavaScript
0
@@ -953,22 +953,65 @@ /', -routes.index); +function (req, res) %7B%0A res.end(%22get outta here%22);%0A%7D);%0A %0Aapp
152f0b23a6e733d9e5ae841c74d298406e226ed3
create server for test
src/1request.spec.js
src/1request.spec.js
import "babel-polyfill"; import expect from 'expect.js'; import http from 'http'; import _1request from './1request'; function expectToBePromise (obj) { expect(obj).to.be.an('object'); expect(obj).to.have.property('then'); expect(obj.then).to.be.a('function'); }; describe('_1request', () => { it('shoud return promise', () => { expectToBePromise(_1request({})); }); });
JavaScript
0.000001
@@ -269,37 +269,655 @@ %0A%7D;%0A -describe('_1request', () =%3E %7B +%0Aconst%0Ahost = '127.0.0.1',%0Aport = 3010,%0AserverUrl = %60http://$%7Bhost%7D:$%7Bport%7D/%60%0A;%0A%0Avar server = http.createServer((req, resp) =%3E %7B%0A try %7B%0A if (req.url === '/') %7B%0A resp.writeHead(200, %7B'Content-Type': 'text/plain'%7D);%0A resp.end('okay');%0A %7D%0A else %7B%0A resp.writeHead(200, %7B'Content-Type': 'text/plain'%7D);%0A resp.end(req.url.substr(1));%0A %7D%0A %7D%0A catch (err) %7B%0A console.error(err);%0A %7D%0A%7D);%0A%0Adescribe('_1request', () =%3E %7B%0A before ((done) =%3E %7B%0A console.log(%60server listen on $%7Bport%7D%60);%0A server.listen(port, host, null, done);%0A %7D);%0A%0A after ((done) =%3E %7B%0A console.log('server close');%0A server.close(done);%0A %7D)%0A %0A i
ab5961ee278e01d8342e50805dd8ca7334bac089
fix bug
src/js/core.js
src/js/core.js
/* * @name Core * @description This is used as a main entry point for the code and also * to prevent a cluttered index file because of many script includes * @author Riko Ophorst */ (function (window, document) { window.addEventListener('load', function () { var tags = [], /* * Note: Order of scripts array DOES matter; * First entry gets loaded first, second gets * loaded second, etc. */ scripts = [ './src/js/game.js', './src/js/stats.js', './src/js/utils.js', './src/js/assets.js', './src/js/statemanager.js', './src/js/input.js', './src/js/gameobject.js' './src/js/main.js' ], loadScript = function (i) { var scriptTag = document.createElement('script'); scriptTag.src = scripts[i] ? scripts[i] : undefined; scriptTag.addEventListener('load', function () { if (scripts[++i] !== undefined) { loadScript(i); } else { Game.initialise(); } }); document.head.appendChild(scriptTag); tags.push(scriptTag); }; loadScript(0); }); })(window, document); /// Requires a given JavaScript file function require(paths, cb) { var loaded = 0; for (var i = 0; i < paths.length; i++) { var scriptTag = document.createElement('script'); scriptTag.src = './src/js/' + paths[i]; scriptTag.addEventListener('load', function () { if(cb && ++loaded >= paths.length) { cb(); } }); document.head.appendChild(scriptTag); } } function extend (obj, obj2, bool) { for (var prop in obj2) { if (obj[prop] !== undefined || !bool) { obj[prop] = obj2[prop]; } else { if (obj['base'] === undefined) { obj['base'] = {}; } if (obj['base'][prop] === undefined) { obj['base'][prop] = []; } obj['base'][prop].push(obj[prop]); } } }
JavaScript
0.000001
@@ -608,24 +608,25 @@ meobject.js' +, %0A%09%09%09%09'./src/
40b368e9b845e5751ece15f53de345b02966defe
update console message
src/js/main.js
src/js/main.js
console.log('hello world');
JavaScript
0
@@ -10,19 +10,53 @@ og(' +T he -llo world +se Are Not the Droids You Are Looking For. ');%0A
4b1a3bd428dbc0b8c8e744be3f500887de2fcc1e
Comment nav toogle
src/js/main.js
src/js/main.js
// SVG for Everybody svg4everybody(); // Toggle on/off nav on click var nav = document.getElementById('nav'); var navToggle = document.getElementById('navToggle'); function toggleNav() { nav.classList.toggle('is-open'); } if (nav && navToggle) { navToggle.addEventListener('click', toggleNav); }
JavaScript
0
@@ -63,16 +63,19 @@ n click%0A +/*%0A var nav @@ -296,12 +296,15 @@ ggleNav);%0A%7D%0A +*/%0A
19ffba0f907516af810a8f77476c2990fb9365ba
add notes to the example file
auth.js
auth.js
// authorization to my prerelease box. // please don't steal my client secret. // it's only good for another month anyway. // note my password is not here, but my // most recent security token is. var sfdc = require('./lib/force.js'); var c = new sfdc.Connection('prerellogin.pre.salesforce.com','prerelna1.pre.salesforce.com','3MVG9lKcPoNINVBIuX965tJtsFOmtFJxx0sE0Z2_dBo1kuM7D2DvM51RWN8neZ7Bpckw7V2aVq74sKSjnluir','4377211423215529444'); c.authorize('couchand+spring13@gmail.com','','La8Mu2IqdEuQpqrjggHuIvd9v').then(function(){console.log('in');});
JavaScript
0
@@ -546,8 +546,1077 @@ );%7D);%0A%0A%0A +var mystuff = %7B%7D%0Ac.tooling.insert('metadatacontainer',%7B'name':'fod'%7D).then(function(id)%7Bmystuff.container = id;%7D);%0A%0Ac.tooling.query('select id, body from apexclass where name = %5C'foobar%5C'').then(function(res)%7Bmystuff.body = res%5B0%5D.Body;mystuff.cls = res%5B0%5D.Id;%7D);%0A%0Amystuff.body2 = mystuff.body.substr(0,mystuff.body.length-1)+%22%5Cn%5Ctpublic void doNothing()%5Cn%5Ct%7B%5Cn%5Ct%7D%5Cn%7D%22%0A%0Ac.tooling.insert('apexclassmember',%7B'metadatacontainerid':mystuff.container,'contententityid':mystuff.cls,'body':mystuff.body2%7D).then(function(id)%7Bmystuff.acm = id;console.log(id);%7D);%0A%0Ac.tooling.getSObject('apexclassmember',mystuff.acm).then(console.log)%0A%0Ac.tooling.deploy(mystuff.container,true).then(console.log)%0A%0Ac.tooling.getSObject('apexclassmember',mystuff.acm).then(console.log)%0A%0Ac.tooling.getSObject('apexclassmember',mystuff.acm).then(function(res)%7Bmystuff.st = res.SymbolTable;%7D);%0A%0A%0A//now try a failed deployment!%0A// watch node.js crash!%0A//then try again!%0A%0Ac.tooling.deploy('1dcx000000000BKAAY',true).then(console.log,function(err)%7Bconsole.log('err!',err.ErrorMsg,err.CompilerErrors);%7D);%0A%0A
62e3f7f53e979a7fbeb3e92c2de765b8a14465be
Fix issue with trackLinks event.target
boba.js
boba.js
window.Boba = (function() { var defaults = { pageName: "page", siteName: "site", defaultCategory: null, defaultAction: null, defaultLabel: null }; function Boba(opts) { this.ga = Boba.getGA(); if (typeof this.ga !== "undefined") { // Extend defaults with options. this.opts = $.extend(defaults, opts); // Watch anything defined in the options. if (typeof this.opts.watch !== "undefined") { for (var i = this.opts.watch.length - 1; i >= 0; i--) { this.watch.apply(this, this.opts.watch[i]); }; } this.setPageName(this.opts.pageName); this.setSiteName(this.opts.siteName); this.trackLinks = $.proxy(this.trackLinks, this); this.push = $.proxy(this.push, this); this.watch = $.proxy(this.watch, this); this._onTrackedClick = $.proxy(this._onTrackedClick, this); } else { console.warn("Google Analytics not found. Boba could not initialize."); } return this; } // // Instance methods. // Boba.prototype = { watch: function watch(eventType, selector, func) { var trackingFunction = function(event) { this.push(func(event)); }; $("body").on( eventType + ".tracker", selector, $.proxy(trackingFunction, this) ); return this; }, trackLinks: function trackLinks() { this.watch('click', '.js-track', this._onTrackedClick); return this; }, push: function bobaInstancePush(data) { data = [ data.gaCategory || data.category || this.opts.defaultCategory, data.gaAction || data.action || this.opts.defaultAction, data.gaLabel || data.label || this.opts.defaultLabel ] this.ga.apply(null, data); return this; }, // Get and set page name. setPageName: function setPageName(name) { this._pageName = name; return this; }, getPageName: function getPageName() { return this._pageName; }, // Get and set site name. setSiteName: function setSiteName(name) { this._siteName = name; return this; }, getSiteName: function getSiteName() { return this._siteName; }, _onTrackedClick: function trackClick(event) { if (this.ga) { return $(event.target).data(); } } }; // // Class methods. // // Replaces non-word characters and spaces with underscores. Boba.cleanValue = function cleanValue(value) { return value .replace(/\W+/g, "_") .replace(/_+/g, "_") .toLowerCase(); }; // Constructs a Google Analytics function. Boba.getGA = function getGA() { var ga; if (typeof window.ga !== "undefined" && window.ga !== null) { ga = $.proxy(window.ga, window, "send", "event"); } else if (typeof window._gaq !== "undefined" && window._gaq !== null) { ga = function gaqpush() { // Prepend "_trackEvent" to the array and push it. Array.prototype.unshift.call(arguments, "_trackEvent"); window._gaq.push(arguments); }; } return ga; }; return Boba; }());
JavaScript
0.012453
@@ -2326,17 +2326,24 @@ $(event. -t +currentT arget).d
acf919f810ba721857d9f65c32928dad6e4bd8b5
Update module with multiple export setup
src/keypath.js
src/keypath.js
/* * gkeypath * https://github.com/goliatone/gkeypath * Created with gbase. * Copyright (c) 2014 goliatone * Licensed under the MIT license. */ /* jshint strict: false, plusplus: true */ /*global define: false, require: false, module: false, exports: false */ /*(function(root, name, deps, factory) { "use strict"; // Node if (typeof deps === 'function') { factory = deps; deps = []; } if (typeof exports === 'object') { module.exports = factory.apply(root, deps.map(require)); } else if (typeof define === 'function' && 'amd' in define) { //require js, here we assume the file is named as the lower //case module name. define(name.toLowerCase(), deps, factory); } else { // Browser var d, i = 0, global = root, old = global[name], mod; while ((d = deps[i]) !== undefined) deps[i++] = root[d]; global[name] = mod = factory.apply(global, deps); //Export no 'conflict module', aliases the module. mod.noConflict = function() { global[name] = old; return mod; }; } }(this, "keypath", function() {*/ define("keypath", function() { var Keypath = {}; var DEFAULTS = { assertionMessage: 'Assertion failed' }; Keypath.VERSION = '0.1.8'; Keypath.set = function(target, path, value) { if (!target) return undefined; var keys = path.split('.'); path = keys.pop(); keys.forEach(function(prop) { if (!target[prop]) target[prop] = {}; target = target[prop]; }); Keypath._set(target, path, value); //target[path] = value; return target; }; Keypath.get = function(target, path, defaultValue) { if (!target || !path) return false; path = path.split('.'); var l = path.length, i = 0, p = ''; for (; i < l; ++i) { p = path[i]; if (target.hasOwnProperty(p)) target = target[p]; else return Keypath._get(defaultValue); } return Keypath._get(target); }; Keypath.has = function(target, path) { return this.get(target, path, '#$#NFV#$#') !== '#$#NFV#$#'; }; Keypath.assert = function(target, path, message) { message = message || Keypath.DEFAULTS.assertionMessage; var value = this.get(target, path, message); if (value !== message) return value; this.onError(message, path); return undefined; }; Keypath.wrap = function(target, inject) { var wrapper = new Wrapper(target); if (!inject) return wrapper; if (typeof inject === 'function') inject(target, wrapper); if (typeof inject === 'string') Keypath.set(target, inject, wrapper); return wrapper; }; Keypath.onError = console.error.bind(console); /////////////////////////////////////////////////// // PRIVATE METHODS /////////////////////////////////////////////////// Keypath._get = function(value) { return typeof value === 'function' ? value() : value; }; Keypath._set = function(src, method, val) { if (typeof src[method] === 'function') return src[method].call(src, val); return src[method] = val; }; /////////////////////////////////////////////////// // WRAPPER Internal Class /////////////////////////////////////////////////// /** * Wrapper Constructor * @param {Object} target Object to be wrapped */ function Wrapper(target) { this.target = target; } Wrapper.prototype.set = function(path, value) { return Keypath.set(this.target, path, value); }; Wrapper.prototype.get = function(path, defaultValue) { return Keypath.get(this.target, path, defaultValue); }; Wrapper.prototype.has = function(path) { return Keypath.has(this.target, path); }; Keypath.Wrapper = Wrapper; return Keypath; }) // );
JavaScript
0
@@ -259,18 +259,16 @@ alse */%0A -/* (functio @@ -1191,41 +1191,9 @@ () %7B -*/%0Adefine(%22keypath%22, function() %7B +%0A %0A%0A @@ -4016,11 +4016,7 @@ ;%0A%7D) -%0A// );%0A
54652ae8ca0b093f028fb84e5ba2963d61803079
include trigger and add update to loop
lib/engine/main.js
lib/engine/main.js
define([ 'require', 'num', "engine/game", "engine/scene/scenestack", "engine/loop", "engine/time/time", "engine/time/timer", "engine/input/input", "engine/view/canvas", "engine/view/camera", "engine/view/viewport", "engine/input/tool", "messaging/eventmanager", "engine/rendering/renderer/combinedrenderer", "engine/map/map", "engine/core/environment", "assets/loader", "engine/domready" ], function( require, num, Game, SceneStack, Loop, Time, Timer, Input, Canvas, Camera, Viewport, Tool, EventManager, CombinedRenderer, Map, Environment, Loader, domReady ) { var Vector2 = require('num').Vector2; var main = function(game, canvas) { domReady(function() { env = {}; // Setup SceneStack. env.sceneStack = new SceneStack(); // Setup EventManager. env.eventManager = new EventManager(); // Configure and start the game loop. env.loop = new Loop().clear().start(); // Add global time listener. env.time = new Time(); env.loop.add(env.time, env.time.update); // Single point to update all Timers. env.loop.add(Timer, Timer.update); // Single point to update all Tweens. env.loop.add(createjs.Tween, createjs.Tween.tick); env.canvas = canvas; env.input = new Input(env.canvas.canvasId); env.input.tool = new Tool(); env.loop.add(env.input, env.input.updateTool); // choose, which subset of the world should be displayed var viewport = new Viewport( Vector2.Zero.copy(), new Vector2(100, 40) ); env.camera = new Camera(viewport); env.renderer = new CombinedRenderer(); // TODO: preload title and transition maps new Map("title"); new Map("transition"); /* var queue = new createjs.LoadQueue(true); queue.on("fileload", handleFileLoad, this); queue.on("complete", handleComplete, this); queue.loadFile("filePath/file.jpg"); queue.loadFile({id:"image", src:"filePath/file.jpg"}); queue.loadManifest(["filePath/file.jpg", {id:"image", src:"filePath/file.jpg"}]); queue.load(); */ Loader.load(function() { new (game)(); }); }); }; return main; });
JavaScript
0
@@ -398,16 +398,35 @@ omready%22 +,%0A%09%22engine/trigger%22 %0A%5D, func @@ -611,16 +611,33 @@ domReady +,%0A%09TriggerUpdater %0A) %7B%0A @@ -1747,19 +1747,73 @@ tion%22);%0A +%0A %09%09%09 +env.loop.add(TriggerUpdater, TriggerUpdater.update);%0A %0A%09%09%09/*%0A%09 @@ -2156,19 +2156,16 @@ ;%0A%09%09%09*/%0A -%09%09%09 %0A%09%09%09Load
ecc7785849d7c5a3f26d35b904f3515a72dc53b2
fix style import
src/landing.js
src/landing.js
/** * Created by Christian on 11.12.2014. */ import 'file-loader?name=index.html!extract-loader!html-loader!./index.html'; import 'file-loader?name=landingcontent.html!extract-loader!html-loader!./landingcontent.html'; import 'phovea_ui/src/_bootstrap'; import './style.scss'; import * as $ from 'jquery'; $(document).ready(function () { navigator.sayswho = (function () { var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if (/trident/i.test(M[1])) { tem = /\brv[ :]+(\d+)/g.exec(ua) || []; return 'IE ' + (tem[1] || ''); } if (M[1] === 'Chrome') { tem = ua.match(/\b(OPR|Edge)\/(\d+)/); if (tem != null) return tem.slice(1).join(' ').replace('OPR', 'Opera'); } M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?']; if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]); return M.join(' '); })(); $('body').load('landingcontent.html', function () { if (navigator.sayswho.toLowerCase().indexOf("chrome") == -1) { $("#whoami").text("You are currently using " + navigator.sayswho + "!"); $("#chromeWarning").css({ display: "block" }); } }); });
JavaScript
0
@@ -250,16 +250,54 @@ strap';%0A +import 'phovea_ui/src/_font-awesome';%0A import '
b9d7c24ab15412a8de14a148090ebe55845bd5b9
fix start position when inode changed
lib/fileManager.js
lib/fileManager.js
'use strict' var path = require('path') var fs = require('fs') var os = require('fs') var Tail = require('tail-forever') function log(text) { if (process.env.LOG_TAIL_FILE_INFO) { console.log(text) } } function FileManager (options) { this.filePointers = this.readFilePointers() this.filesToWatch = [] this.options = options } function getFilesizeInBytes (filename) { var stats = fs.statSync(filename) var fileSizeInBytes = stats['size'] return fileSizeInBytes } FileManager.prototype.tailFiles = function (fileList) { fileList.forEach(this.tailFile.bind(this)) } FileManager.prototype.getTempDir = function () { return process.env.LOGSENE_TMP_DIR || os.getTempDir() } FileManager.prototype.getTailPosition = function (file) { var storedPos = this.filePointers[file] if (!storedPos) { log('no position stored for ' + file) return {start: getFilesizeInBytes(file)} } else { var fd = fs.openSync(file, 'r') var stat = fs.fstatSync(fd) if (stat.ino === storedPos.inode) { return {start: storedPos.pos, inode: storedPos.inode} } else { log('Watching file ' + file + ' inode changed, set tail position = 0') return {start: 0, inode: storedPos.inode} } } } FileManager.prototype.tailFile = function (file) { var tail = null try { var pos = this.getTailPosition(file) tail = new Tail(file, pos) this.filesToWatch.push(tail) tail.on('line', function (line) { this.options.parseLine(line, file, this.options.log) }.bind(this)) tail.on('error', function (error) { log('ERROR tailing file '+file+': ' + error) }) console.log('Watching file:' + file +' from position: ' + pos.start) return tail } catch (error) { console.log('ERROR tailing file '+file+': ', error) return null } } FileManager.prototype.terminate = function () { var filePositions = this.filesToWatch.map(function (tailObj) { var position = tailObj.unwatch() position.fileName = tailObj.filename console.log('unwatch ' + tailObj.filename + ' inode: ' + position.inode + ' pos:' +position.pos) return position }) try { var fileName = path.join(this.getTempDir(), 'logagentTailPointers.json') fs.writeFileSync(fileName,JSON.stringify(filePositions)) log("File positions stored in: " + fileName) } catch (err) { log('error writing file pointers:' + err) } } FileManager.prototype.readFilePointers = function () { var filePointers = {} try { var fp = fs.readFileSync(path.join(this.getTempDir(), 'logagentTailPointers.json')) var filePointerArr = JSON.parse(fp) filePointerArr.forEach(function (f) { filePointers[f.fileName]={pos: f.pos, inode: f.inode} }) log(filePointers) } catch (err) { log('Error reading file pointers: ' + err) } return filePointers } module.exports = FileManager
JavaScript
0
@@ -976,17 +976,16 @@ ync(fd)%0A -%0A if ( @@ -1195,32 +1195,8 @@ t: 0 -, inode: storedPos.inode %7D %0A
f4753f66c1ef4b37728064640ca09bff5619cd17
add workaround for node regression
lib/http-agents.js
lib/http-agents.js
'use strict'; const { Agent: HttpAgent } = require('http'); const { Agent: HttpsAgent } = require('https'); const { connect: tlsConnect } = require('tls'); let Client; for (const ctor of [HttpAgent, HttpsAgent]) { class SSHAgent extends ctor { constructor(connectCfg, agentOptions) { super(agentOptions); this._connectCfg = connectCfg; this._defaultSrcIP = (agentOptions && agentOptions.srcIP) || 'localhost'; } createConnection(options, cb) { const srcIP = (options && options.localAddress) || this._defaultSrcIP; const srcPort = (options && options.localPort) || 0; const dstIP = options.host; const dstPort = options.port; if (Client === undefined) Client = require('./client.js'); const client = new Client(); let triedForward = false; client.on('ready', () => { client.forwardOut(srcIP, srcPort, dstIP, dstPort, (err, stream) => { triedForward = true; if (err) { client.end(); return cb(err); } stream.once('close', () => client.end()); cb(null, decorateStream(stream, ctor, options)); }); }).on('error', cb).on('close', () => { if (!triedForward) cb(new Error('Unexpected connection close')); }).connect(this._connectCfg); } } exports[ctor === HttpAgent ? 'SSHTTPAgent' : 'SSHTTPSAgent'] = SSHAgent; } function noop() {} function decorateStream(stream, ctor, options) { if (ctor === HttpAgent) { // HTTP stream.setKeepAlive = noop; stream.setNoDelay = noop; stream.setTimeout = noop; stream.ref = noop; stream.unref = noop; stream.destroySoon = stream.destroy; return stream; } // HTTPS options.socket = stream; return tlsConnect(options); }
JavaScript
0
@@ -1780,22 +1780,31 @@ ream;%0A -return +const wrapped = tlsConn @@ -1816,11 +1816,227 @@ ptions); +%0A%0A // This is a workaround for a regression in node v12.16.3+%0A // https://github.com/nodejs/node/issues/35904%0A wrapped.on('close', () =%3E %7B%0A if (stream.isPaused())%0A stream.resume();%0A %7D);%0A%0A return wrapped; %0A%7D%0A
6f0a269fd8aceeeb00bd992fe12c5e4392a5d70e
Extend on capabilities
src/mage/on.js
src/mage/on.js
ZCJ.mage.on = function(evt, fn) { return this.forEach( function() { this.addEventListener(evt, fn, false); }); };
JavaScript
0.000001
@@ -1,50 +1,611 @@ -ZCJ.mage.on = function( +//Support multiple events in one %22on%22 function%0Afunction on( elem, evnts, input, fn ) %7B%0A%09var evnt;%0A%0A%09// Check if the evnts is an object%0A%09if ( typeof evnts === %22object%22 ) %7B%0A%0A%09%09for ( evnt in evnts ) %7B%0A%09%09%09//Execurte each object event as a non object%0A%09%09%09on( elem, ev +n t, -fn) %7B%0A%09return this +input, evnts%5B evnt %5D );%0A%09%09%7D%0A%09%09return elem;%0A%09%7D%0A%0A%09//on(div, click, function)%0A%09if ( fn === null ) %7B%0A %0A%09%09// If no function is specified then input is the function%0A%09%09fn = input;%0A%09%09input = undefined;%0A%0A%09%7D%0A%0A%09//Handle a flase statement%0A%09if ( fn === false ) %7B%0A%09%09return false;%0A%09%7D else if ( !fn ) %7B%0A%09%09return elem;%0A%09%7D%0A%0A%09//Add event listeners%0A%09return elem .for @@ -653,26 +653,138 @@ r(ev -t +nts , fn, -false);%0A%09%7D); +input);%0A%09%7D );%0A%7D%0A%0AZCJ.mage.on = function(evnt, input, fn) %7B%0A%09//Send to the on handler%0A%09return on( this, evnt, input, fn );%0A %0A%7D;
75c2c40708818fa74e431a4656768b9c21b8348d
Update sharp.js
dev/sharp.js
dev/sharp.js
;(sharp = function(){ var microtime = function(getFloat){ var now = new Date().getTime() / 1000; var s = parseInt(now, 10); return (getFloat) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s; } var today = function(glue){ glue = glue || "-" var date = new Date() return (date.getDate() < 10 ? '0' : '') + date.getDate() + glue + (date.getMonth() < 10 ? '0' : '') + (date.getMonth()+1) + glue + date.getFullYear() } var random = function(min, max){ return Math.floor(Math.random() * (max - min + 1) + min) } var trim = function(str){ return str.replace(/^\s+|\s+$/g, '') } var inArray = function(needle, haystack){ return haystack.indexOf(needle) !== -1 ? true : false } var isBoolean = function(_var){ return (_var === true || _var === false) } var isString = function(_var){ return (typeof _var === 'string') } var isObject = function(_var){ if (Object.prototype.toString.call(_var) === '[object Array]') return false return (_var !== null && typeof _var === 'object') } var isNull = function(_var){ return (_var === null) } var escape = function(_var){ return (_var + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0') } var stripTags = function(_var, _allowed){ allowed = (((allowed || '') + '') .toLowerCase() .match(/<[a-z][a-z0-9]*>/g) || []) .join('') var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi return _var .replace(commentsAndPhpTags, '') .replace(tags, function($0, $1) { return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '' }) } return { microtime: microtime, today: today, random: random, trim: trim, inArray: inArray, isBoolean: isBoolean, isString: isString, isObject: isObject, isNull: isNull, escape: escape, stripTags: stripTags } }());
JavaScript
0.000001
@@ -1410,16 +1410,17 @@ +_ allowed @@ -1424,16 +1424,17 @@ ed = ((( +_ allowed @@ -1720,16 +1720,17 @@ %09return +_ allowed.
7b80d3789933295bd8cbcf8a8b28e8808301e7b6
Set default dev host to 0.0.0.0 and allow to redefine NODE_HOST and NODE_PORT
devServer.js
devServer.js
import express from 'express'; import webpack from 'webpack'; import config from './webpack.config.dev'; import mainRoute from 'server/routes/main'; const app = express(); const compiler = webpack(config); app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(require('webpack-hot-middleware')(compiler)); app.get('/', mainRoute); app.listen(3000, 'localhost', (err) => { if (err) { console.log(err); return; } console.log('Listening at http://localhost:3000'); });
JavaScript
0
@@ -200,16 +200,119 @@ config); +%0Aconst NODE_PORT = process.env.NODE_PORT %7C%7C 3000;%0Aconst NODE_HOST = process.env.NODE_HOST %7C%7C '0.0.0.0'; %0A%0Aapp.us @@ -516,89 +516,67 @@ ten( -3000, 'localhost', (err) =%3E %7B%0A if (err) %7B%0A console.log(err);%0A return;%0A %7D%0A +NODE_PORT, NODE_HOST, (err) =%3E err ?%0A console.error(err) : %0A c @@ -586,17 +586,17 @@ ole.log( -' +%60 Listenin @@ -611,26 +611,34 @@ p:// -localhost:3000');%0A%7D +$%7BNODE_HOST%7D:$%7BNODE_PORT%7D%60) );%0A
45fd5c40b7b4943b9e6109c60b4d6fa16346883e
Add triangle check logic
homework/w5-graph-draw/src/asset/js/bundle.js
homework/w5-graph-draw/src/asset/js/bundle.js
$(window).ready(function(){ $('#triangle-calculator').submit(function(e){ e.preventDefault(); // // Code start here // var isTriangle = false; var triangleType = 'Not a triangle'; var a = $('#a_number').val(); var b = $('#b_number').val(); var c = $('#c_number').val(); if ( a <= b + c && b <= a + c && c <= a + b ) { isTriagle = true; if ( a == b && a == c ) { triangleType = 'Equilateral'; } else if ( a != b && b != c && c != a ) { triangleType = 'Scalene'; } else { triangleType = 'Isoscalene'; } } $('#log-msg').append('Triangle type: ' + triangleType + "\n"); // // Code end here // }); });
JavaScript
0.000001
@@ -152,40 +152,8 @@ //%0A - var isTriangle = false;%0A @@ -189,24 +189,25 @@ triangle';%0A +%0A var @@ -209,16 +209,26 @@ var a = + parseInt( $('#a_n @@ -232,32 +232,34 @@ a_number').val() + ) ;%0A var b @@ -259,16 +259,26 @@ var b = + parseInt( $('#b_n @@ -290,16 +290,18 @@ ').val() + ) ;%0A @@ -309,16 +309,26 @@ var c = + parseInt( $('#c_n @@ -340,16 +340,18 @@ ').val() + ) ;%0A%0A @@ -404,38 +404,8 @@ ) %7B -%0A isTriagle = true; %0A%0A @@ -575,32 +575,66 @@ pe = 'Scalene';%0A + console.log('b');%0A %7D el @@ -675,32 +675,32 @@ = 'Isoscalene';%0A - %7D%0A @@ -696,16 +696,47 @@ %7D +%0A%0A console.log('a'); %0A
b4278d4dd74d8fb71255ef65dd7d4ae46033673c
Update decrypting copy text (#4127)
shared/util/kbfs-notifications.js
shared/util/kbfs-notifications.js
/* @flow */ import _ from 'lodash' import {KbfsCommonFSErrorType, KbfsCommonFSNotificationType, KbfsCommonFSStatusCode} from '../constants/types/flow-types' import {getTLF} from '../util/kbfs' import path from 'path' import type {FSNotification} from '../constants/types/flow-types' type DecodedKBFSError = { 'title': string, 'body': string, } export function decodeKBFSError (user: string, notification: FSNotification): DecodedKBFSError { const basedir = notification.filename.split(path.sep)[0] const tlf = `/keybase${getTLF(notification.publicTopLevelFolder, basedir)}` switch (notification.errorType) { case KbfsCommonFSErrorType.accessDenied: return { title: 'Keybase: Access denied', body: `${user} does not have ${notification.params.mode} access to ${tlf}`, } case KbfsCommonFSErrorType.userNotFound: return { title: 'Keybase: User not found', body: `${notification.params.username} is not a Keybase user`, } case KbfsCommonFSErrorType.revokedDataDetected: return { title: 'Keybase: Possibly revoked data detected', body: `${tlf} was modified by a revoked or bad device. Use 'keybase log send' to file an issue with the Keybase admins.`, } case KbfsCommonFSErrorType.notLoggedIn: return { title: `Keybase: Permission denied in ${tlf}`, body: "You are not logged into Keybase. Try 'keybase login'.", } case KbfsCommonFSErrorType.timeout: return { title: `Keybase: ${_.capitalize(notification.params.mode)} timeout in ${tlf}`, body: `The ${notification.params.mode} operation took too long and failed. Please run 'keybase log send' so our admins can review.`, } case KbfsCommonFSErrorType.rekeyNeeded: return notification.params.rekeyself ? { title: 'Keybase: Files need to be rekeyed', body: `Please open one of your other computers to unlock ${tlf}`, } : { title: 'Keybase: Friends needed', body: `Please ask another member of ${tlf} to open Keybase on one of their computers to unlock it for you.`, } case KbfsCommonFSErrorType.badFolder: return { title: 'Keybase: Bad folder', body: `${notification.params.tlf} is not a Keybase folder. All folders begin with /keybase/private or /keybase/public.`, } case KbfsCommonFSErrorType.overQuota: const usageBytes = parseInt(notification.params.usageBytes, 10) const limitBytes = parseInt(notification.params.limitBytes, 10) const usedGB = (usageBytes / 1e9).toFixed(1) const usedPercent = Math.round(100 * usageBytes / limitBytes) return { title: 'Keybase: Out of space', body: `Action needed! You are using ${usedGB}GB (${usedPercent}%) of your quota. Please delete some data.`, } default: return { title: 'Keybase: KBFS error', body: `${notification.status}`, } } // This code came from the kbfs team but this isn't plumbed through the protocol. Leaving this for now // if (notification.errorType === KbfsCommonFSErrorType.notImplemented) { // if (notification.feature === '2gbFileLimit') { // return ({ // title: 'Keybase: Not yet implemented', // body: `You just tried to write a file larger than 2GB in ${tlf}. This limitation will be removed soon.` // }) // } else if (notification.feature === '512kbDirLimit') { // return ({ // title: 'Keybase: Not yet implemented', // body: `You just tried to write too many files into ${tlf}. This limitation will be removed soon.` // }) // } else { // return ({ // title: 'Keybase: Not yet implemented', // body: `You just hit a ${notification.feature} limitation in KBFS. It will be fixed soon.` // }) // } // } else { // return ({ // title: 'Keybase: KBFS error', // body: `${notification.status}` // }) // } } // TODO: Once we have access to the Redux store from the thread running // notification listeners, store the sentNotifications map in it. let sentNotifications = {} let sentError = null function rateLimitAllowsNotify (action, state, tlf, isError) { if (!(action in sentNotifications)) { sentNotifications[action] = {} } if (!(state in sentNotifications[action])) { sentNotifications[action][state] = {} } const now = new Date() // If we haven't notified for {action,state,tlf} or it was >20s ago, do it. const MSG_DELAY = 20 * 1000 if (tlf in sentNotifications[action][state] && now - sentNotifications[action][state][tlf] <= MSG_DELAY) { return false } // If we last displayed an error, don't replace it with another notification for 5s. const ERROR_DELAY = 5 * 1000 if (sentError !== null && now - sentError <= ERROR_DELAY) { return false } sentNotifications[action][state][tlf] = now if (isError) { sentError = now } return true } export function kbfsNotification (notification: FSNotification, notify: any, getState: any) { const action = { [KbfsCommonFSNotificationType.encrypting]: 'Encrypting and uploading', [KbfsCommonFSNotificationType.decrypting]: 'Decrypting, verifying, and downloading', [KbfsCommonFSNotificationType.signing]: 'Signing and uploading', [KbfsCommonFSNotificationType.verifying]: 'Verifying and downloading', [KbfsCommonFSNotificationType.rekeying]: 'Rekeying', }[notification.notificationType] if (action === undefined) { // Ignore notification types we don't care about. return } const state = { [KbfsCommonFSStatusCode.start]: 'starting', [KbfsCommonFSStatusCode.finish]: 'finished', [KbfsCommonFSStatusCode.error]: 'errored', }[notification.statusCode] // KBFS fires a notification when it changes state between connected // and disconnected (to the mdserver). For now we just log it. if (notification.notificationType === KbfsCommonFSNotificationType.connection) { const state = (notification.statusCode === KbfsCommonFSStatusCode.start) ? 'connected' : 'disconnected' console.log(`KBFS is ${state}`) return } if (notification.statusCode === KbfsCommonFSStatusCode.finish) { // Since we're aggregating dir operations and not showing state, // let's ignore file-finished notifications. return } const basedir = notification.filename.split(path.sep)[0] const tlf = getTLF(notification.publicTopLevelFolder, basedir) let title = `KBFS: ${action}` let body = `Files in ${tlf} ${notification.status}` let user = 'You' || getState().config.username const isError = notification.statusCode === KbfsCommonFSStatusCode.error // Don't show starting or finished, but do show error. if (isError) { ({title, body} = decodeKBFSError(user, notification)) } if (rateLimitAllowsNotify(action, state, tlf, isError)) { notify(title, {body}) } }
JavaScript
0
@@ -5234,36 +5234,8 @@ ting -, verifying, and downloading ',%0A
8fc1dfded60d0702b9c5fcbffa950fd0a6b839e7
Add code to focus to richtext field back in (when toolbar button is pressed).
resources/assets/js/plugins/scribe/toolbar.js
resources/assets/js/plugins/scribe/toolbar.js
/** * Loosely based on guardian/scribe-plugin-toolbar. */ import { selectClosestWord } from 'plugins/scribe/ux/select-closest-word'; /* global setTimeout */ export default (toolbarNode) => { return (scribe) => { const updateToolbar = button => { const command = scribe.getCommand(button.dataset.commandName), selection = new scribe.api.Selection(); if(selection.range && command.queryState(button.dataset.commandValue)) { button.classList.add('active'); } else { button.classList.remove('active'); } if(!selection.range || command.queryEnabled()) { button.removeAttribute('disabled'); } else { button.setAttribute('disabled', 'disabled'); } }, buttons = toolbarNode.querySelectorAll('[data-command-name]'); [...buttons].forEach(button => { if(!button.dataset.commandIgnore) { button.addEventListener('mousedown', (e) => { selectClosestWord(scribe, button.dataset.commandName); scribe .getCommand(button.dataset.commandName) .execute(button.dataset.commandValue); e.preventDefault(); }); } const update = () => updateToolbar(button); button.addEventListener('blur', () => setTimeout(update, 0)); scribe.el.addEventListener('keyup', update); scribe.el.addEventListener('mouseup', () => setTimeout(update, 0)); scribe.el.addEventListener('focus', update); scribe.el.addEventListener('blur', () => setTimeout(update, 0)); scribe.on('scribe:content-changed', update); }); }; };
JavaScript
0
@@ -907,24 +907,48 @@ n', (e) =%3E %7B +%0A%09%09%09%09%09scribe.el.focus(); %0A%0A%09%09%09%09%09selec
52d6a1b35c6a9591aebbc67ae0e69c45e0afc528
Update ConcatAlongAxisId2.js
CNN/Conv/ConcatAlongAxisId2.js
CNN/Conv/ConcatAlongAxisId2.js
export { Base }; import * as BoundsArraySet from "../BoundsArraySet.js"; /** * Concatenate two tensor3d ( height x width x channel ) always along the last axis (i.e. axisId = 2, along the channel axis). It could * destroy one or two of the input tensors. * * @member {boolean} bKeepInputTensor0 * If false, the first input tensor will be disposed after concatenating. If true, the first input tensor will be kept after concatenating. * * @member {boolean} bKeepInputTensor1 * If false, the second input tensor will be disposed after concatenating. If true, the second input tensor will be kept after concatenating. * * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray0 * The element value bounds (per channel) of this concatenation operation's input0. It will be kept (not cloned) directly. So caller * should not modify them. * * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray1 * The element value bounds (per channel) of this concatenation operation's input1. It will be kept (not cloned) directly. So caller * should not modify them. * * @member {BoundsArraySet.InputsOutputs} boundsArraySet * The element value bounds (per channel) of this concatenation operation. * * @member {function} pfnConcat * This is a method. It has one parameter inputTensorsArray and return a outputTensor. The inputTensorsArray (tf.tensor3d[]) * represents all the images ( height x width x channel ) which will be concatenated. They should have the same ( height x width ) * but could have different channel count. The outputTensor (tf.tensor3d) represents the result of concatenating the inputs along * the last axis (i.e. the channel axis ( axisId = 2 ) ). The inputTensor may or may not be disposed. In fact, this method calls * one of Concat_and_keep0_keep1(), Concat_and_keep0_destroy1(), Concat_and_destroy0_keep1(), Concat_and_destroy0_destroy1() * according to the parameters. * */ class Base { constructor( bKeepInputTensor0, bKeepInputTensor1, inputScaleBoundsArray0, inputScaleBoundsArray1 ) { this.bKeepInputTensor0 = bKeepInputTensor0; this.bKeepInputTensor1 = bKeepInputTensor1; Base.adjust_pfnConcat.call( this ); { this.boundsArraySet = new BoundsArraySet.InputsOutputs( inputScaleBoundsArray0, inputScaleBoundsArray1, 1 // Arbitrarily set a legal (but temporary) outputChannelCount0. It will be adjusted later. ); this.boundsArraySet.set_outputs_all_by_concat_input0_input1(); // The outputChannelCount0 will be adjusted. } } /** * Adjust this.pfnConcat so that this.pfnConcat() will or will not dispose its inputTensors. */ setKeepInputTensor0( bKeepInputTensor0 ) { this.bKeepInputTensor0 = bKeepInputTensor0; Base.adjust_pfnConcat.call( this ); } /** * Adjust this.pfnConcat so that this.pfnConcat() will or will not dispose its inputTensors. */ setKeepInputTensor1( bKeepInputTensor1 ) { this.bKeepInputTensor1 = bKeepInputTensor1; Base.adjust_pfnConcat.call( this ); } /** * Adjust this.pfnConcat so that this.pfnConcat() will or will not dispose its inputTensors. */ setKeepInputTensor( bKeepInputTensor0, bKeepInputTensor1 ) { this.bKeepInputTensor0 = bKeepInputTensor0; this.bKeepInputTensor1 = bKeepInputTensor1; Base.adjust_pfnConcat.call( this ); } /** Set this.pfnConcat according to this.bKeepInputTensor0 and this.bKeepInputTensor1. */ static adjust_pfnConcat() { if ( this.bKeepInputTensor0 ) { if ( this.bKeepInputTensor1 ) { this.pfnConcat = Base.Concat_and_keep0_keep1; } else { this.pfnConcat = Base.Concat_and_keep0_destroy1; } } else { if ( this.bKeepInputTensor1 ) { this.pfnConcat = Base.Concat_and_destroy0_keep1; } else { this.pfnConcat = Base.Concat_and_destroy0_destroy1; } } } /** Concatenate along axis id 2. (Both the inputTensorsArray[ 0 ] and inputTensorsArray[ 1 ] will not be disposed. */ static Concat_and_keep0_keep1( inputTensorsArray ) { return tf.concat( inputTensorsArray, 2 ); // AxisId = 2 } /** Concatenate along axis id 2. (The inputTensorsArray[ 0 ] will not be disposed. The inputTensorsArray[ 1 ] will be disposed. */ static Concat_and_keep0_destroy1( inputTensorsArray ) { let t = tf.concat( inputTensorsArray, 2 ); // AxisId = 2 inputTensorsArray[ 1 ].dispose(); return t; } /** Concatenate along axis id 2. (The inputTensorsArray[ 0 ] will be disposed. The inputTensorsArray[ 1 ] will not be disposed. */ static Concat_and_destroy0_keep1( inputTensorsArray ) { let t = tf.concat( inputTensorsArray, 2 ); // AxisId = 2 inputTensorsArray[ 0 ].dispose(); return t; } /** Concatenate along axis id 2. (Both the inputTensorsArray[ 0 ] and inputTensorsArray[ 1 ] will be disposed. */ static Concat_and_destroy0_destroy1( inputTensorsArray ) { let t = tf.concat( inputTensorsArray, 2 ); // AxisId = 2 inputTensorsArray[ 0 ].dispose(); inputTensorsArray[ 1 ].dispose(); return t; } }
JavaScript
0
@@ -1233,17 +1233,16 @@ tion.%0A * - %0A * @mem
22d8709b4a82b47dadcdc6031ecc8177a154bb25
Fix file name
public/finalapp.js
public/finalapp.js
var finalApp = angular.module('finalApp', ['ngRoute']); finalApp.controller('finalController', function($scope, $http) { // Init $scope.db = {}; $scope.db.clubs = []; $scope.db.courses = []; $scope.db.holes = []; $scope.db.matchups = []; $scope.db.players = []; $scope.db.rounds = []; $scope.db.scores = []; $scope.db.seasons = []; $scope.db.teams = []; $scope.db.weeks = []; $scope.db.edit = {}; $scope.db.edit.clubs = {}; $scope.db.edit.courses = {}; $scope.db.edit.holes = {}; $scope.db.edit.matchups = {}; $scope.db.edit.players = {}; $scope.db.edit.rounds = {}; $scope.db.edit.scores = {}; $scope.db.edit.seasons = {}; $scope.db.edit.teams = {}; $scope.db.edit.weeks = {}; $scope.db.edit.clubs.index = {}; $scope.db.edit.courses.index = {}; $scope.db.edit.holes.index = {}; $scope.db.edit.matchups.index = {}; $scope.db.edit.players.index = {}; $scope.db.edit.rounds.index = {}; $scope.db.edit.scores.index = {}; $scope.db.edit.seasons.index = {}; $scope.db.edit.teams.index = {}; $scope.db.edit.weeks.index = {}; // Clubs $scope.Clubs = function() { $http.get('/api/clubs') .success(function(data) { $scope.db.clubs = data; //console.log('Clubs: ' + data); }) .error(function(data) { console.log('Error: ' + data); $scope.db.clubs = []; }); }; $scope.clubEdit = function($index, confirm) { if (!$scope.db.edit.clubs.index[$index]) { $scope.db.edit.clubs.index[$index] = $scope.db.clubs[$index]; } else if (confirm) { $http.post('/api/club/' + $scope.db.edit.clubs.index[$index].CLUB_ID, $scope.db.clubs[$index]) .success(function(data) { delete $scope.db.edit.clubs.index[$index]; $scope.Clubs(); }) .error(function(data) { console.log('Error: ' + data); delete $scope.db.edit.clubs.index[$index]; $scope.Clubs(); }); } else { delete $scope.db.edit.clubs.index[$index]; $scope.Clubs(); } }; // Courses $scope.Courses = function() { $http.get('/api/courses') .success(function(data) { $scope.db.courses = data; //console.log('Courses: ' + data); }) .error(function(data) { console.log('Error: ' + data); $scope.db.courses = []; }); }; // Holes $scope.Holes = function() { $http.get('/api/holes') .success(function(data) { $scope.db.holes = data; //console.log('Holes: ' + data); }) .error(function(data) { console.log('Error: ' + data); $scope.db.holes = []; }); }; // Matchups $scope.Matchups = function() { $http.get('/api/matchups') .success(function(data) { $scope.db.matchups = data; //console.log('Matchups: ' + data); }) .error(function(data) { console.log('Error: ' + data); $scope.db.matchups = []; }); }; // Players $scope.Players = function() { $http.get('/api/players') .success(function(data) { $scope.db.players = data; //console.log('Players: ' + data); }) .error(function(data) { console.log('Error: ' + data); $scope.db.players = []; }); }; // Rounds $scope.Rounds = function() { $http.get('/api/rounds') .success(function(data) { $scope.db.rounds = data; //console.log('Rounds: ' + data); }) .error(function(data) { console.log('Error: ' + data); $scope.db.rounds = []; }); }; // Scores $scope.Scores = function() { $http.get('/api/scores') .success(function(data) { $scope.db.scores = data; //console.log('Scores: ' + data); }) .error(function(data) { console.log('Error: ' + data); $scope.db.scores = []; }); }; // Seasons $scope.Seasons = function() { $http.get('/api/seasons') .success(function(data) { $scope.db.seasons = data; //console.log('Seasons: ' + data); }) .error(function(data) { console.log('Error: ' + data); $scope.db.seasons = []; }); }; // Teams $scope.Teams = function() { $http.get('/api/teams') .success(function(data) { $scope.db.seasons = data; //console.log('Teams: ' + data); }) .error(function(data) { console.log('Error: ' + data); $scope.db.seasons = []; }); }; // Weeks $scope.Weeks = function() { $http.get('/api/weeks') .success(function(data) { $scope.db.weeks = data; //console.log('Weeks: ' + data); }) .error(function(data) { console.log('Error: ' + data); $scope.db.weeks = []; }); }; // $scope.init = function () { // console.log("Calling functions."); // $scope.Clubs(); // $scope.Courses(); // $scope.Holes(); // $scope.Matchups(); // $scope.Players(); // $scope.Rounds(); // $scope.Scores(); // $scope.Seasons(); // $scope.Teams(); // $scope.Weeks(); // // }; }); finalApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider .when('/', { templateUrl: 'views/main.ejs' }) .when('/clubs', { templateUrl: 'views/clubs.ejs' }) .when('/courses', {templateUrl: 'views/courses.ejs' }) .when('/holes', { templateUrl: 'views/holes.ejs' }) .when('/matchups', { templateUrl: 'views/matchups.ejs' }) .when('/players', { templateUrl: 'views/players.ejs' }) .when('/rounds', { templateUrl: 'views/rounds.ejs' }) .when('/scores', { templateUrl: 'views/scores.ejs' }) .when('/seasons', { templateUrl: 'views/seasons.ejs' }) .when('/teams', { templateUrl: 'views/teams.ejs' }) .when('/weeks', { templateUrl: 'views/weeks.ejs' }) .otherwise({redirectTo: '/'}); $locationProvider.html5Mode({ enabled: true, requireBase: false }); }]); finalApp.directive('navbar', function() { return { restrict: 'E', replace: true, scope: false, templateUrl: 'views/navbar.ejs' }; });
JavaScript
0.000034
@@ -1207,32 +1207,33 @@ s = data;%0A + //console.log('C
d053540fdcc1b0c182b2effca2ab339cd5e3e960
Support objects with promise values.
lib/makePromise.js
lib/makePromise.js
/*global Promise:true*/ var Promise = require('bluebird'); var oathbreaker = require('./oathbreaker'); function makePromise(body) { return new Promise(function (resolve, reject) { var runningTasks = 0; var errors = []; function finishWhenDone () { if (runningTasks === 0) { if (errors.length > 0) { reject(errors[0]); } else { resolve(); } } } var runner = function (cb) { runningTasks += 1; return function () { runningTasks -= 1; try { var result = cb.apply(null, arguments); var promise = oathbreaker(result); if (promise) { runningTasks += 1; result.then(function () { runningTasks -= 1; finishWhenDone(); }).caught(function (e) { errors.push(e); runningTasks -= 1; finishWhenDone(); }); } } catch (e) { errors.push(e); } finally { finishWhenDone(); } }; }; try { var promise = oathbreaker(body(runner)); if (promise) { runningTasks += 1; promise.then(function () { runningTasks -= 1; finishWhenDone(); }).caught(function (e) { errors.push(e); runningTasks -= 1; finishWhenDone(); }); } } catch (e) { errors.push(e); } finishWhenDone(); }); } makePromise.all = Promise.all; makePromise.settle = Promise.settle; makePromise.any = Promise.any; module.exports = makePromise;
JavaScript
0
@@ -1933,105 +1933,747 @@ %0A%7D%0A%0A -makePromise.all = Promise.all;%0AmakePromise.settle = Promise.settle;%0AmakePromise.any = Promise.any +function isPromise(obj) %7B%0A return obj && typeof obj === 'object' && typeof obj.then === 'function';%0A%7D%0A%0Afunction isNonPromiseNonArrayObject(obj) %7B%0A return obj && typeof obj === 'object' && typeof obj.then !== 'function' && !Array.isArray(obj);%0A%7D%0A%0Afunction extractPromisesFromObject(obj) %7B%0A var promises = Object.keys(obj)%0A .filter(function (key) %7B%0A return isPromise(obj%5Bkey%5D);%0A %7D).map(function (key) %7B%0A return obj%5Bkey%5D;%0A %7D);%0A return promises;%0A%7D%0A%0A%5B'all', 'any', 'settle'%5D.forEach(function (staticMethodName) %7B%0A makePromise%5BstaticMethodName%5D = function (obj) %7B%0A return Promise%5BstaticMethodName%5D(isNonPromiseNonArrayObject(obj) ? extractPromisesFromObject(obj) : obj);%0A %7D;%0A%7D) ;%0A%0Am
e60b4814fbd325dd2819f08d26cc001ea721de4f
Make label click work
src/ui/options.js
src/ui/options.js
(function () { document.getElementById('seasonList').onchange = function () { document.getElementById('episodeList').innerHTML = ''; buildEpisodeList(document.getElementById('seasonList').value); }; document.getElementById('historyLimit').addEventListener('blur', save); function init() { buildSeasonList(); document.getElementById('historyLimit').value = get('historyLimit') || 30; } function buildSeasonList(season) { var div = document.getElementById('seasonList'); for (i = 0; i < get('totalSeasons'); i++) { var optionValue = document.createElement('option'); optionValue.text = 'Season ' + (i + 1).toString(); optionValue.value = (i + 1).toString(); div.appendChild(optionValue); } buildEpisodeList(1); } function buildEpisodeList(season) { var div = document.getElementById('episodeList'); var currentSeason = get('unwatchedEpisodes')[season - 1]; var episodeNames = get('episodeNames')[season - 1]; for (i = 0; i < get('seasonLengths')[season - 1]; i++) { var checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.value = 'Episode' + (i + 1).toString(); checkbox.onclick = function () { save() }; checkbox.id = i + 1; if (currentSeason.indexOf(i + 1) === -1) { checkbox.checked = true; } else { checkbox.checked = false; } div.appendChild(checkbox); var label = document.createElement('label'); label.htmlFor = 'Episode' + (i + 1).toString(); label.appendChild(document.createTextNode(i + 1 + '. ' + episodeNames[i].replace(/['"]+/g, ''))); div.appendChild(label); div.appendChild(document.createElement('br')); } } function save() { var selectedSeason = document.getElementById('seasonList').value; var newEpisodes = []; for (i = 0; i < get('seasonLengths')[selectedSeason - 1]; i++) if (!document.getElementById((i + 1).toString()).checked) newEpisodes.push(i + 1); var unwatchedEpisodes = get('unwatchedEpisodes'); unwatchedEpisodes[selectedSeason - 1] = newEpisodes; set('historyLimit', document.getElementById('historyLimit').value || 30); set('unwatchedEpisodes', unwatchedEpisodes); } function set(key, data) { localStorage.setItem('randomSpEpisodeExt.' + key, JSON.stringify(data)); } function get(key) { return JSON.parse(localStorage.getItem('randomSpEpisodeExt.' + key)); } init(); })();
JavaScript
0.000001
@@ -1721,38 +1721,13 @@ r = -'Episode' + (i + 1).toString() +i + 1 ;%0A
4ecf4e4659f2984c9900031295f340568912be37
add solution
Algorithms/JS/arrays/singleNumber.js
Algorithms/JS/arrays/singleNumber.js
// Given an array of integers, every element appears twice except for one. Find that single one.
JavaScript
0.000003
@@ -90,8 +90,395 @@ le one.%0A +%0A%0Avar singleNumber = function(nums) %7B%0A if(nums.length%3C1)%7B%0A return nums;%0A %7D%0A var map = %7B%7D;%0A for(var i=0;i%3Cnums.length;i++)%7B%0A if(map%5Bnums%5Bi%5D%5D === undefined)%7B%0A map%5Bnums%5Bi%5D%5D = 1;%0A %7D%0A else%7B%0A map%5Bnums%5Bi%5D%5D += 1;%0A %7D%0A %7D%0A for(var key in map)%7B%0A if(map%5Bkey%5D === 1)%7B%0A return Number(key);%0A %7D%0A %7D%0A%7D;%0A
0366c9bfbaad56ed1e1e8b7cd638d9b94d126b0f
add solution
Algorithms/JS/arrays/spiralMatrix.js
Algorithms/JS/arrays/spiralMatrix.js
spiralMatrix.js
JavaScript
0.000003
@@ -1,16 +1,1302 @@ -spiralMatrix.js +// Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.%0A%0A// For example,%0A// Given the following matrix:%0A%0A// %5B%0A// %5B 1, 2, 3 %5D,%0A// %5B 4, 5, 6 %5D,%0A// %5B 7, 8, 9 %5D%0A// %5D%0A// You should return %5B1,2,3,6,9,8,7,4,5%5D.%0A%0A%0Avar spiralOrder = function(matrix, shrink, arr) %7B // 132ms runtime%0A if(!arr) arr = %5B%5D;%0A if(!matrix %7C%7C !matrix%5B0%5D) return arr; // if matrix doesnt exist or is empty return arr%0A if(!shrink) shrink = 0;%0A%0A var height = matrix.length - 2 * shrink, // -2 because of matrix arr and length%0A width = matrix%5B0%5D.length - 2 * shrink;%0A%0A if( height === 0 %7C%7C width === 0 ) return arr;%0A%0A if( width === 1) %7B%0A for( var i = shrink; i %3C shrink + height; i++ ) arr.push(matrix%5Bi%5D%5Bshrink + width - 1%5D);%0A return arr;%0A %7D%0A%0A if(height === 1)%7B%0A for(var i = shrink; i %3C shrink + width; i++) arr.push(matrix%5Bshrink%5D%5Bi%5D);%0A return arr;%0A %7D%0A%0A for(var i = shrink; i %3C shrink + width - 1; i++) arr.push( matrix%5Bshrink%5D%5Bi%5D );%0A for(var i = shrink; i %3C shrink + height - 1; i++) arr.push( matrix%5Bi%5D%5Bshrink + width - 1%5D );%0A for(var i = shrink + width - 1; i %3E shrink; i--) arr.push( matrix%5Bshrink + height - 1%5D%5Bi%5D );%0A for(var i = shrink + height - 1; i %3E shrink; i--) arr.push( matrix%5Bi%5D%5Bshrink%5D );%0A%0A return spiralOrder( matrix,shrink + 1,arr );%0A%7D; %0A
6a3497422a08923b6e06a0ed455e109358aa23e4
Add update notifier for using npm
lib/modules/npm.js
lib/modules/npm.js
var fs = require("fs") var path = require("path") var spawn = require("child_process").spawn var dirname = require("../config").dirname module.exports = function (argv, cb) { cb = typeof cb === "function" ? cb : false argv = typeof argv === "object" ? argv : [] var exists = fs.existsSync(dirname.current) if (!exists) { console.log("npmbrew use <version>") return } var pkg = require(path.join(dirname.current, "package.json")) var bin = typeof pkg.bin === "string" ? pkg.bin : typeof pkg.bin === "object" ? pkg.bin.npm : false if (!bin) { console.log("There isn't bin prop in package.json for npmbrew") return } bin = path.join(dirname.current, pkg.bin) var cmd = spawn(bin, argv) cmd.stdout.on("data", function (stdout) { process.stdout.write(stdout) }) cmd.on("exit", function (code) { if (cb) cb(code) }) }
JavaScript
0
@@ -128,16 +128,64 @@ .dirname +%0Avar updateNotifier = require(%22update-notifier%22) %0A%0Amodule @@ -893,24 +893,127 @@ on (code) %7B%0A + updateNotifier(%7B%0A packageName : pkg.name,%0A packageVersion : pkg.version,%0A %7D).notify()%0A if (cb)
e3b3231a546066b22f308f14ed8abb8736092493
Update Bindings formatting, fix #79
src/commands/rover/BindingsCommand.js
src/commands/rover/BindingsCommand.js
const Command = require('../Command') const DiscordServer = require('../../DiscordServer') const Util = require('../../Util') module.exports = class BindingsCommand extends Command { constructor (client) { super(client, { name: 'bindings', aliases: ['listbindings', 'roverbindings'], description: 'Displays a list of bound roles' }) } /** * Checks if a role exists and return its name, or a default * value if it doesn't. * @param {Snowflake} id The Role id * @returns {string} The processed role name */ getRoleName (id) { let role = this.server.server.roles.get(id) if (role) return role.name return '<Deleted role, delete this binding.>' } async fn (msg) { if (this.server.getSetting('verifiedRole')) { let id = this.server.getSetting('verifiedRole') msg.reply({ embed: { color: 0x2ecc71, title: 'Verified role', fields: [ { name: 'Role name', value: this.getRoleName(id), inline: true }, { name: 'Role id', value: id, inline: true } ] }}) } if (this.server.getSetting('verifiedRemovedRole')) { let id = this.server.getSetting('verifiedRemovedRole') msg.reply({ embed: { color: 0xe74c3c, title: 'Not Verified role', fields: [ { name: 'Role name', value: this.getRoleName(id), inline: true }, { name: 'Role id', value: id, inline: true } ] }}) } this.server.cleanupRankBindings() let groupBindingsText = '' for (let binding of this.server.getSetting('groupRankBindings')) { if (binding.groups == null) { binding = DiscordServer.convertOldBinding(binding) } if (groupBindingsText === '') { groupBindingsText = '**Group Bindings**\n\n' } let id = binding.role groupBindingsText += `${this.getRoleName(id)} <${id}>\n\`\`\`markdown\n` for (let group of binding.groups) { if (group.id.match(/[a-z]/i)) { groupBindingsText += `# VirtualGroup ${group.id}\n` groupBindingsText += `Argument ${group.ranks.length > 0 ? group.ranks[0] : 'none'}` } else { groupBindingsText += `# Group ${group.id}\n` groupBindingsText += `Rank${group.ranks.length === 1 ? '' : 's'} ` + Util.simplifyNumbers(group.ranks) } groupBindingsText += '\n\n' } groupBindingsText += '```\n' } if (groupBindingsText.length > 0) msg.reply(groupBindingsText, { split: true }) } }
JavaScript
0
@@ -717,24 +717,50 @@ fn (msg) %7B%0A + let bindingText = ''%0A%0A if (this @@ -861,254 +861,87 @@ -msg.reply(%7B embed: %7B%0A color: 0x2ecc71,%0A title: 'Verified role',%0A fields: %5B%0A %7B name: 'Role name', value: this.getRoleName(id), inline: true %7D,%0A %7B name: 'Role id', value: id, inline: true %7D%0A %5D%0A %7D%7D) +bindingText += %60$%7Bthis.getRoleName(id)%7D %3C$%7Bid%7D%3E%5Cn%5C%60%5C%60%5C%60fix%5CnVerified%5Cn%5C%60%5C%60%5C%60%5Cn%60 %0A @@ -1072,257 +1072,358 @@ -msg.reply(%7B embed: %7B%0A color: 0xe74c3c,%0A title: ' +bindingText += %60**Unverified Role**%5Cn$%7Bthis.getRoleName(id)%7D %3C$%7Bid%7D%3E%5Cn%5C%60%5C%60%5C%60css%5Cn Not -V +v erified - role', +%5Cn%5C%60%5C%60%5C%60%5Cn%60 %0A +%7D%0A%0A -fields: %5B%0A %7B name: 'Role name', value: this.getRoleName(id), inline: true %7D,%0A %7B name: 'Role id', value: id, inline: true %7D%0A %5D%0A %7D%7D +if (bindingText.length %3E 0) %7B%0A msg.reply('**__Role Bindings__**%5Cn%5Cn' + bindingText)%0A %7D else %7B%0A msg.reply('No verified or unverified roles are configured. Run %60!verifiedrole %3Crole%3E%60 or %60unverifiedrole %3Crole%3E%60 to set them.' )%0A @@ -1741,16 +1741,18 @@ xt = '** +__ Group Bi @@ -1757,16 +1757,18 @@ Bindings +__ **%5Cn%5Cn'%0A @@ -1899,22 +1899,31 @@ for (let + %5Bindex, group +%5D of bind @@ -1932,19 +1932,84 @@ g.groups -) %7B +.entries()) %7B%0A if (index %3E 0) groupBindingsText += '...or%5Cn'%0A %0A @@ -2471,16 +2471,138 @@ '%60%60%60%5Cn' +%0A%0A if (groupBindingsText.length %3E 1500) %7B%0A msg.reply(groupBindingsText)%0A groupBindingsText = ''%0A %7D %0A %7D%0A%0A @@ -2670,25 +2670,8 @@ Text -, %7B split: true %7D )%0A
f446f9627400b7b93b6a30fec8d932cf080dc6c8
Drop unused code
lib/permissions.js
lib/permissions.js
'use strict'; /*global nodeca*/ /** * nodeca.permissions **/ nodeca.permissions = module.exports = {}; /** * nodeca.permissions.fetch(keys, params, callback) -> Void **/ module.exports.fetch = function fetch(keys, params, callback) { var data = {}; keys.forEach(function (key) { data[key] = false; }); callback(null, data); }; /** * nodeca.permissions.fetchSync(keys, params) -> Object **/ module.exports.fetchSync = function fetchSync(keys, params) { // returns calculated object of permissions of keys }; var requiredKeys = {}; /** * nodeca.permissions.shouldFetch(apiPath, keys) -> Void **/ module.exports.shouldFetch = function shouldFetch(apiPath, keys) { requiredKeys[apiPath] = (requiredKeys[apiPath] || []).concat(keys); }; module.exports.getRequiredKeys = function getRequiredKeys(apiPath) { return requiredKeys[apiPath] || []; }; /** * nodeca.permissions.cache(env, storeName, params, settings) -> Void **/ module.exports.cache = function cache(env, storeName, params, settings) { };
JavaScript
0.000001
@@ -344,693 +344,4 @@ %0A%7D;%0A -%0A%0A/**%0A * nodeca.permissions.fetchSync(keys, params) -%3E Object%0A **/%0Amodule.exports.fetchSync = function fetchSync(keys, params) %7B%0A // returns calculated object of permissions of keys%0A%7D;%0A%0A%0Avar requiredKeys = %7B%7D;%0A%0A%0A/**%0A * nodeca.permissions.shouldFetch(apiPath, keys) -%3E Void%0A **/%0Amodule.exports.shouldFetch = function shouldFetch(apiPath, keys) %7B%0A requiredKeys%5BapiPath%5D = (requiredKeys%5BapiPath%5D %7C%7C %5B%5D).concat(keys);%0A%7D;%0A%0A%0Amodule.exports.getRequiredKeys = function getRequiredKeys(apiPath) %7B%0A return requiredKeys%5BapiPath%5D %7C%7C %5B%5D;%0A%7D;%0A%0A%0A/**%0A* nodeca.permissions.cache(env, storeName, params, settings) -%3E Void%0A**/%0Amodule.exports.cache = function cache(env, storeName, params, settings) %7B%0A%7D;%0A
b2033fdad2e6312f17e5e1220d578c857f9e5f2f
Update character
output.js
output.js
var fs = require('fs'); var child_process = require('child_process') var max_sleep = 300 //Added a comment that achieves no r
JavaScript
0
@@ -118,8 +118,9 @@ ves no r +e
566edf584874b70a97b2231507df9e1686de6949
Update character
output.js
output.js
var fs = require('fs'); var child_process = require('child_process') var max_sleep = 30
JavaScript
0
@@ -80,8 +80,9 @@ eep = 30 +0
e97dc0006bb621d2ca7929ac0e47c7914d3241b1
update Crumbs
src/Crumbs/Crumbs.js
src/Crumbs/Crumbs.js
/** * @file Crumbs component * @author liangxiaojun(liangxiaojun@derbysoft.com) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import Crumb from '../_Crumb'; import Tip from '../Tip'; import Theme from '../Theme'; import Util from '../_vendors/Util'; class Crumbs extends Component { static Theme = Theme; constructor(props, ...restArgs) { super(props, ...restArgs); this.itemRender = ::this.itemRender; } itemRender(item, index) { if (item.renderer) { return item.renderer(item, index); } const {itemRenderer, onItemTouchTap} = this.props; if (itemRenderer) { return itemRenderer(item, index); } return <Crumb {...item} onTouchTap={e => { item.onTouchTap && item.onTouchTap(e); onItemTouchTap && onItemTouchTap(e, item, index); }}/>; } render() { const {className, style, data, separator, showLastSeparator} = this.props, crumbsClassName = (className ? ' ' + className : ''); return ( <div className={'crumbs' + crumbsClassName} style={style}> { data && data.map((item, index) => ( <div key={index} className="crumbs-item-wrapper"> {this.itemRender(item, index)} { !showLastSeparator && index === data.length - 1 ? null : <div className="crumbs-separator"> {separator} </div> } </div> )) } </div> ); } }; Crumbs.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * The theme of the Crumbs. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * Crumbs data config. */ data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({ /** * The CSS class name of the list button. */ className: PropTypes.string, /** * Override the styles of the list button. */ style: PropTypes.object, /** * The theme of the list button. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * The url of crumb. */ href: PropTypes.string, /** * The text value of the list button.Type can be string or number. */ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The list item's display text. Type can be string, number or bool. */ text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The desc value of the list button. Type can be string or number. */ desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * If true,the list item will be disabled. */ disabled: PropTypes.bool, /** * If true,the button will be have loading effect. */ isLoading: PropTypes.bool, /** * If true,the element's ripple effect will be disabled. */ disableTouchRipple: PropTypes.bool, /** * Use this property to display an icon. It will display on the left. */ iconCls: PropTypes.string, /** * Use this property to display an icon. It will display on the right. */ rightIconCls: PropTypes.string, /** * The message of tip. */ tip: PropTypes.string, /** * The position of tip. */ tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)), /** * If true,the item will have center displayed ripple effect. */ rippleDisplayCenter: PropTypes.bool, /** * You can create a complicated renderer callback instead of value and desc prop. */ renderer: PropTypes.func, /** * Callback function fired when a list item touch-tapped. */ onTouchTap: PropTypes.func }), PropTypes.string, PropTypes.number])).isRequired, separator: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), showLastSeparator: PropTypes.bool, /** * Crumbs data renderer callback. */ itemRenderer: PropTypes.func, onItemTouchTap: PropTypes.func }; Crumbs.defaultProps = { className: null, style: null, theme: Theme.DEFAULT, data: null, separator: '>', showLastSeparator: false }; export default Crumbs;
JavaScript
0
@@ -155,16 +155,53 @@ -types'; +%0Aimport classNames from 'classnames'; %0A%0Aimport @@ -1151,17 +1151,16 @@ sName = -( classNam @@ -1164,31 +1164,74 @@ Name - ? ' ' + className : '' +s('crumbs', %7B%0A %5BclassName%5D: className%0A %7D );%0A%0A @@ -1279,19 +1279,8 @@ me=%7B -'crumbs' + crum
b868dab0e449de4f6f2ce878a8cbf91b762ad430
correct a spelling mistake
src/util-fetch.js
src/util-fetch.js
/** * @fileoverview Utilities for fetching js ans css files. */ (function(util, data, global) { var config = data.config; var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement; var baseElement = head.getElementsByTagName('base')[0]; var UA = navigator.userAgent; var isWebKit = UA.indexOf('AppleWebKit') > 0; var IS_CSS_RE = /\.css(?:\?|$)/i; var READY_STATE_RE = /loaded|complete|undefined/; util.getAsset = function(url, callback, charset) { var isCSS = IS_CSS_RE.test(url); var node = document.createElement(isCSS ? 'link' : 'script'); if (charset) { var cs = util.isFunction(charset) ? charset(url) : charset; if (cs) { node.charset = cs; } } assetOnload(node, callback); if (isCSS) { node.rel = 'stylesheet'; node.href = url; } else { node.async = 'async'; node.src = url; } // For some cache cases in IE 6-9, the script executes IMMEDIATELY after // the end of the insertBefore execution, so use `currentlyAddingScript` // to hold current node, for deriving url in `define`. currentlyAddingScript = node; // ref: #185 & http://dev.jquery.com/ticket/2709 baseElement ? head.insertBefore(node, baseElement) : head.appendChild(node); currentlyAddingScript = null; }; function assetOnload(node, callback) { if (node.nodeName === 'SCRIPT') { scriptOnload(node, cb); } else { styleOnload(node, cb); } var timer = setTimeout(function() { util.log('Time is out:', node.src); cb(); }, config.timeout); function cb() { if (!cb.isCalled) { cb.isCalled = true; clearTimeout(timer); callback(); } } } function scriptOnload(node, callback) { node.onload = node.onerror = node.onreadystatechange = function() { if (READY_STATE_RE.test(node.readyState)) { // Ensure only run once node.onload = node.onerror = node.onreadystatechange = null; // Reduce memory leak if (node.parentNode) { try { if (node.clearAttributes) { node.clearAttributes(); } else { for (var p in node) delete node[p]; } } catch (x) { } // Remove the script if (!config.debug) { head.removeChild(node); } } // Dereference the node node = undefined; callback(); } }; // NOTICE: // Nothing will happen in Opera when the file status is 404. In this case, // the callback will be called when time is out. } function styleOnload(node, callback) { // for IE6-9 and Opera if (global.hasOwnProperty('attachEvent')) { // see #208 node.attachEvent('onload', callback); // NOTICE: // 1. "onload" will be fired in IE6-9 when the file is 404, but in // this situation, Opera does nothing, so fallback to timeout. // 2. "onerror" doesn't fire in any browsers! } // Polling for Firefox, Chrome, Safari else { setTimeout(function() { poll(node, callback); }, 0); // Begin after node insertion } } function poll(node, callback) { if (callback.isCalled) { return; } var isLoaded; if (isWebKit) { if (node['sheet']) { isLoaded = true; } } // for Firefox else if (node['sheet']) { try { if (node['sheet'].cssRules) { isLoaded = true; } } catch (ex) { if (ex.name === 'SecurityError' || // firefox >= 13.0 ex.name === 'NS_ERROR_DOM_SECURITY_ERR') { // old firefox isLoaded = true; } } } setTimeout(function() { if (isLoaded) { // Place callback in here due to giving time for style rendering. callback(); } else { poll(node, callback); } }, 1); } var currentlyAddingScript; var interactiveScript; util.getCurrentScript = function() { if (currentlyAddingScript) { return currentlyAddingScript; } // For IE6-9 browsers, the script onload event may not fire right // after the the script is evaluated. Kris Zyp found that it // could query the script nodes and the one that is in "interactive" // mode indicates the current script. // Ref: http://goo.gl/JHfFW if (interactiveScript && interactiveScript.readyState === 'interactive') { return interactiveScript; } var scripts = head.getElementsByTagName('script'); for (var i = 0; i < scripts.length; i++) { var script = scripts[i]; if (script.readyState === 'interactive') { interactiveScript = script; return script; } } }; util.getScriptAbsoluteSrc = function(node) { return node.hasAttribute ? // non-IE6/7 node.src : // see http://msdn.microsoft.com/en-us/library/ms536429(VS.85).aspx node.getAttribute('src', 4); }; })(seajs._util, seajs._data, this); /** * References: * - http://unixpapa.com/js/dyna.html * - ../test/research/load-js-css/test.html * - ../test/issues/load-css/test.html * - http://www.blaze.io/technical/ies-premature-execution-problem/ */
JavaScript
0.999999
@@ -1,13 +1,12 @@ -%0A /**%0A * @file @@ -42,17 +42,17 @@ ng js an -s +d css fil
3fe32c9040c5e888f3f672351774d1f739fc11c6
Update character
output.js
output.js
var fs = require('fs'); var child_process = require('child_process') var max_sleep = 300 //Added a comment that achieves no real goal. if ( process.argv[ 2 ] && process.argv[ 3 ] ) { var inFile =
JavaScript
0
@@ -191,8 +191,9 @@ nFile = +p
1bef5c8589f54c2294794bc7e6f8d722e42fbf3d
update files
lib/plugins/css.js
lib/plugins/css.js
/*! * plugins/css * Version: 0.0.1 * Date: 2017/05/19 * https://github.com/nuintun/gulp-css * * This is licensed under the MIT License (MIT). * For details, see: https://github.com/nuintun/gulp-css/blob/master/LICENSE */ 'use strict'; var path = require('path'); var util = require('../util'); var through = require('@nuintun/through'); /** * loader * * @param options * @returns {Stream} */ module.exports = function(options) { return through(function(vinyl, next) { util.transportId(vinyl, options); util.transportCssDeps(vinyl, options); next(null, vinyl); }); };
JavaScript
0.000001
@@ -470,16 +470,26 @@ n(vinyl, + encoding, next) %7B
3a6e97ec3574ed3a0fd9e9cd6617c1ca63ab7f35
Fix cell title to longer format
src/util/index.js
src/util/index.js
import moment from 'moment'; const defaultDisabledTime = { disabledHours() { return []; }, disabledMinutes() { return []; }, disabledSeconds() { return []; }, }; export function getTodayTime(value) { const today = moment(); today.locale(value.locale()).utcOffset(value.utcOffset()); return today; } export function getTitleString(value) { return value.format('L'); } export function getTodayTimeStr(value) { const today = getTodayTime(value); return getTitleString(today); } export function getMonthName(month) { const locale = month.locale(); const localeData = month.localeData(); return localeData[locale === 'zh-cn' ? 'months' : 'monthsShort'](month); } export function syncTime(from, to) { if (!moment.isMoment(from) || !moment.isMoment(to)) return; to.hour(from.hour()); to.minute(from.minute()); to.second(from.second()); } export function getTimeConfig(value, disabledTime) { let disabledTimeConfig = disabledTime ? disabledTime(value) : {}; disabledTimeConfig = { ...defaultDisabledTime, ...disabledTimeConfig, }; return disabledTimeConfig; } export function isTimeValidByConfig(value, disabledTimeConfig) { let invalidTime = false; if (value) { const hour = value.hour(); const minutes = value.minute(); const seconds = value.second(); const disabledHours = disabledTimeConfig.disabledHours(); if (disabledHours.indexOf(hour) === -1) { const disabledMinutes = disabledTimeConfig.disabledMinutes(hour); if (disabledMinutes.indexOf(minutes) === -1) { const disabledSeconds = disabledTimeConfig.disabledSeconds(hour, minutes); invalidTime = disabledSeconds.indexOf(seconds) !== -1; } else { invalidTime = true; } } else { invalidTime = true; } } return !invalidTime; } export function isTimeValid(value, disabledTime) { const disabledTimeConfig = getTimeConfig(value, disabledTime); return isTimeValidByConfig(value, disabledTimeConfig); } export function isAllowedDate(value, disabledDate, disabledTime) { if (disabledDate) { if (disabledDate(value)) { return false; } } if (disabledTime) { if (!isTimeValid(value, disabledTime)) { return false; } } return true; }
JavaScript
0.007609
@@ -389,16 +389,17 @@ ormat('L +L ');%0A%7D%0A%0Ae
096f6b52fa89e8c0fdce9bfade82bd43ed9921e7
reorder trace attributes
shelly/plotlyjs/static/plotlyjs/src/graph_reference.js
shelly/plotlyjs/static/plotlyjs/src/graph_reference.js
'use strict'; var Plotly = require('./plotly'), objectAssign = require('object-assign'); var NESTEDMODULEID = '_nestedModules', COMPOSEDMODULEID = '_composedModules', ANYTYPE = '*', ISLINKEDTOARRAY = '_isLinkedToArray', ISSUBPLOTOBJ = '_isSubplotObj'; var graphReference = { traces: {}, layout: {} }; module.exports = function getGraphReference() { Plotly.Plots.allTypes.forEach(getTraceAttributes); getLayoutAttributes(); return graphReference; }; function getTraceAttributes(type) { var globalAttributes = Plotly.Plots.attributes, _module = getModule({type: type}), attributes = {}, layoutAttributes = {}; // global attributes (same for all trace types) attributes = objectAssign(attributes, globalAttributes); // module attributes (+ nested + composed) attributes = coupleAttrs( _module.attributes, attributes, 'attributes', type ); attributes.type = type; attributes = removeUnderscoreAttrs(attributes); graphReference.traces[type] = { attributes: attributes }; // trace-specific layout attributes if(_module.layoutAttributes !== undefined) { layoutAttributes = coupleAttrs( _module.layoutAttributes, layoutAttributes, 'layoutAttributes', type ); graphReference.traces[type].layoutAttributes = layoutAttributes; } } function getLayoutAttributes() { var globalLayoutAttributes = Plotly.Plots.layoutAttributes, subplotsRegistry = Plotly.Plots.subplotsRegistry, layoutAttributes = {}; // global attributes (same for all trace types) layoutAttributes = objectAssign(layoutAttributes, globalLayoutAttributes); // layout module attributes (+ nested + composed) layoutAttributes = coupleAttrs( globalLayoutAttributes, layoutAttributes, 'layoutAttributes', ANYTYPE ); layoutAttributes = removeUnderscoreAttrs(layoutAttributes); // add ISSUBPLOTOBJ key Object.keys(layoutAttributes).forEach(function(k) { if(subplotsRegistry.gl3d.idRegex.test(k) || subplotsRegistry.geo.idRegex.test(k) || /^xaxis[0-9]*$/.test(k) || /^yaxis[0-9]*$/.test(k) ) layoutAttributes[k][ISSUBPLOTOBJ] = true; }); graphReference.layout = { layoutAttributes: layoutAttributes }; } function coupleAttrs(attrsIn, attrsOut, whichAttrs, type) { var nestedModule, nestedAttrs, nestedReference, composedModule, composedAttrs; Object.keys(attrsIn).forEach(function(k) { if(k === NESTEDMODULEID) { Object.keys(attrsIn[k]).forEach(function(kk) { nestedModule = getModule({module: attrsIn[k][kk]}); if(nestedModule === undefined) return; nestedAttrs = nestedModule[whichAttrs]; nestedReference = coupleAttrs( nestedAttrs, {}, whichAttrs, type ); Plotly.Lib.nestedProperty(attrsOut, kk) .set(nestedReference); }); return; } if(k === COMPOSEDMODULEID) { Object.keys(attrsIn[k]).forEach(function(kk) { if(kk !== type) return; composedModule = getModule({module: attrsIn[k][kk]}); if(composedModule === undefined) return; composedAttrs = composedModule[whichAttrs]; composedAttrs = coupleAttrs( composedAttrs, {}, whichAttrs, type ); attrsOut = objectAssign(attrsOut, composedAttrs); }); return; } attrsOut[k] = attrsIn[k]; }); return attrsOut; } // helper methods function getModule(arg) { if('type' in arg) return Plotly.Plots.getModule({type: arg.type}); else if('module' in arg) return Plotly[arg.module]; } function removeUnderscoreAttrs(attributes) { Object.keys(attributes).forEach(function(k){ if(k.charAt(0) === '_' && k !== ISLINKEDTOARRAY) delete attributes[k]; }); return attributes; }
JavaScript
0.000001
@@ -687,112 +687,80 @@ // -global attributes (same for all trac +mak e +' type -s)%0A attributes = objectAssign(attributes, globalAttributes) +' the first attribute in the object%0A attributes.type = type ;%0A%0A @@ -898,24 +898,204 @@ ype%0A );%0A%0A + // global attributes (same for all trace types)%0A attributes = objectAssign(attributes, globalAttributes);%0A%0A // 'type' gets overwritten by globalAttributes; reset it here%0A attribut @@ -1110,16 +1110,17 @@ = type;%0A +%0A attr
1a57cadf91ad3f344d834ecb6616f29baf226adf
add moogoose connect
sistema-mongoose-atomico-promises-events/server/app.js
sistema-mongoose-atomico-promises-events/server/app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var users = require('./routes/users'); // Modules var UsersAPI = require('./modules/users/routes_express'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/users', users); // API JSON app.use('/api/users', UsersAPI); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
JavaScript
0
@@ -212,16 +212,78 @@ arser'); +%0Arequire(%22mongoose%22).connect('mongodb://localhost/instagram'); %0A%0Avar ro
6062443c7be4e820df59b58516cc07aa88dbb141
Update eval.js
commands/eval.js
commands/eval.js
const Discord = require('discord.js'); const config = require("./config.json"); exports.run = async (bot, message) => { var embed = new Discord.RichEmbed() .setTitle("Restricted") .setColor("#f45f42") .addField("You are restricted from this command", "Its for the bot owner only!") const randomColor = "#000000".replace(/0/g, function () { return (~~(Math.random() * 16)).toString(16); }); const clean = text => { if (typeof(text) === "string") return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/@/g, "@" + String.fromCharCode(8203)); else return text; } const args = message.content.split(" ").slice(1); if (!args) return message.reply("Put what args you want") try { if(message.author.id !== config.ownerID) return message.channel.send({ embed: embed }); const code = args.join(" "); let evaled = eval(code); if (typeof evaled !== "string") evaled = require("util").inspect(evaled); var embed2 = new Discord.RichEmbed() .setTitle("Evaled:", false) .setColor(randomColor) .addField("Evaled: :inbox_tray:", `\`\`\`js\n${args}\n\`\`\``, false) .addField("Output: :outbox_tray:", clean(evaled), false) message.channel.send({ embed: embed2 }); } catch (err) { var embed3 = new Discord.RichEmbed() .setTitle("ERROR:") .setColor("#f44242") .addField("Evaled: :inbox_tray:", `\`\`\`js\n${args}\n\`\`\``) .addField("Output: :outbox_tray:", `\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``) message.channel.send({ embed: embed3 }); }};
JavaScript
0.000001
@@ -1152,23 +1152,16 @@ n%5C%60%5C%60%5C%60%60 -, false )%0A @@ -1210,23 +1210,16 @@ (evaled) -, false )%0A
c9689d4dadba79cf1f57f248daffd351dce86d7b
fix the build
test/javascripts/acceptance/groups-test.js.es6
test/javascripts/acceptance/groups-test.js.es6
import { acceptance } from "helpers/qunit-helpers"; acceptance("Groups"); test("Browsing Groups", () => { visit("/groups/discourse"); andThen(() => { ok(count('.user-stream .item') > 0, "it has stream items"); }); visit("/groups/discourse/members"); andThen(() => { ok(count('.group-members tr') > 0, "it lists group members"); }); visit("/groups/discourse/topics"); andThen(() => { ok(count('.user-stream .item') > 0, "it lists stream items"); }); visit("/groups/discourse/mentions"); andThen(() => { ok(count('.user-stream .item') > 0, "it lists stream items"); }); visit("/groups/discourse/messages"); andThen(() => { ok(count('.user-stream .item') > 0, "it lists stream items"); }); });
JavaScript
0.000016
@@ -167,52 +167,54 @@ t('. -user-stream .item') %3E 0, %22it has stream item +group-members tr') %3E 0, %22it lists group member s%22); @@ -248,22 +248,20 @@ scourse/ -member +post s%22);%0A a @@ -290,32 +290,33 @@ count('. -group-members tr +user-stream .item ') %3E 0, @@ -321,36 +321,35 @@ , %22it lists -group member +stream item s%22);%0A %7D);%0A%0A
245af689a1d9344b312f22fda022845b874018e4
Make 'help topics' show a list of all topics.
commands/help.js
commands/help.js
'use strict'; const l10nFile = __dirname + '/../l10n/commands/help.yml'; const l10n = require('../src/l10n')(l10nFile); const util = require('util'); const HelpFiles = require('../src/help_files').HelpFiles; const wrap = require('wrap-ansi'); const _ = require('../src/helpers'); /* NEW: { title: 'Welcome to Ranvier', body: 'Important topics include:', related: 'levels','attributes','mutants','mental','physical','energy','combat','social', }, */ exports.command = (rooms, items, players, npcs, Commands) => { return (args, player) => { const print = txt => player.say(wrap(txt, 80)); if (!args) { displayHelpFile('HELP'); return displayHelpFile('NEW'); } args = args.toUpperCase().trim(); const errMsg = "" + player.getName() + " attempted to get a helpfile for " + args + "."; try { displayHelpFile(args); } catch(e) { util.log(e); } finally { util.log(errMsg); } function displayHelpFile(topic) { const file = HelpFiles[topic]; if ( !file) { return args in Commands.player_commands ? player.writeL10n(l10n, 'NO_HELP_FILE') : player.writeL10n(l10n, 'NOT_FOUND'); } // --- Helpers for printing out the help files. Help helpers. const hr = () => print('<green>---------------------------------' + '---------------------------------</green>'); const title = txt => print('<bold>' + txt + '</bold>'); const usage = usage => print('<cyan> USAGE: </cyan>' + usage); const options = option => print('<red> - </red>' + option); const related = topic => print('<magenta> * </magenta>' + topic); const maybeForEach = (txt, fn) => _.toArray(txt).forEach(fn); hr(); if (file.title) { title(file.title); } if (file.body) { print(file.body); } if (file.usage) { maybeForEach(file.usage, usage); } hr(); if (file.options) { player.say('<green>OPTIONS:</green>'); maybeForEach(file.options, options); hr(); } if (file.related) { const defaultTopicsHeader = '<blue>RELATED TOPICS:</blue>'; player.say(file.topicsHeader || defaultTopicsHeader); maybeForEach(file.related, related); hr(); } } }; };
JavaScript
0.001088
@@ -891,16 +891,225 @@ + %22.%22;%0A%0A + if (args === 'TOPICS') %7B%0A for (topic in HelpFiles) %7B%0A if (topic === 'NOT_FOUND' %7C%7C topic === 'NO_HELP_FILE') %7B continue; %7D%0A player.say(topic.toLowerCase());%0A %7D%0A return;%0A %7D%0A%0A try
3987ae62b77e321171fd8862d1d838d85b71dc93
Remove missing RGBFormat
src/util/three.js
src/util/three.js
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as CONST from "three/src/constants.js"; import { Euler } from "three/src/math/Euler.js"; import { Matrix4 } from "three/src/math/Matrix4.js"; import { Quaternion } from "three/src/math/Quaternion.js"; import { Vector3 } from "three/src/math/Vector3.js"; export const paramToGL = function (gl, p) { if (p === CONST.RepeatWrapping) { return gl.REPEAT; } if (p === CONST.ClampToEdgeWrapping) { return gl.CLAMP_TO_EDGE; } if (p === CONST.MirroredRepeatWrapping) { return gl.MIRRORED_REPEAT; } if (p === CONST.NearestFilter) { return gl.NEAREST; } if (p === CONST.NearestMipMapNearestFilter) { return gl.NEAREST_MIPMAP_NEAREST; } if (p === CONST.NearestMipMapLinearFilter) { return gl.NEAREST_MIPMAP_LINEAR; } if (p === CONST.LinearFilter) { return gl.LINEAR; } if (p === CONST.LinearMipMapNearestFilter) { return gl.LINEAR_MIPMAP_NEAREST; } if (p === CONST.LinearMipMapLinearFilter) { return gl.LINEAR_MIPMAP_LINEAR; } if (p === CONST.UnsignedByteType) { return gl.UNSIGNED_BYTE; } if (p === CONST.UnsignedShort4444Type) { return gl.UNSIGNED_SHORT_4_4_4_4; } if (p === CONST.UnsignedShort5551Type) { return gl.UNSIGNED_SHORT_5_5_5_1; } if (p === CONST.ByteType) { return gl.BYTE; } if (p === CONST.ShortType) { return gl.SHORT; } if (p === CONST.UnsignedShortType) { return gl.UNSIGNED_SHORT; } if (p === CONST.IntType) { return gl.INT; } if (p === CONST.UnsignedIntType) { return gl.UNSIGNED_INT; } if (p === CONST.FloatType) { return gl.FLOAT; } if (p === CONST.AlphaFormat) { return gl.ALPHA; } if (p === CONST.RGBFormat) { return gl.RGB; } if (p === CONST.RGBAFormat) { return gl.RGBA; } if (p === CONST.LuminanceFormat) { return gl.LUMINANCE; } if (p === CONST.LuminanceAlphaFormat) { return gl.LUMINANCE_ALPHA; } if (p === CONST.AddEquation) { return gl.FUNC_ADD; } if (p === CONST.SubtractEquation) { return gl.FUNC_SUBTRACT; } if (p === CONST.ReverseSubtractEquation) { return gl.FUNC_REVERSE_SUBTRACT; } if (p === CONST.ZeroFactor) { return gl.ZERO; } if (p === CONST.OneFactor) { return gl.ONE; } if (p === CONST.SrcColorFactor) { return gl.SRC_COLOR; } if (p === CONST.OneMinusSrcColorFactor) { return gl.ONE_MINUS_SRC_COLOR; } if (p === CONST.SrcAlphaFactor) { return gl.SRC_ALPHA; } if (p === CONST.OneMinusSrcAlphaFactor) { return gl.ONE_MINUS_SRC_ALPHA; } if (p === CONST.DstAlphaFactor) { return gl.DST_ALPHA; } if (p === CONST.OneMinusDstAlphaFactor) { return gl.ONE_MINUS_DST_ALPHA; } if (p === CONST.DstColorFactor) { return gl.DST_COLOR; } if (p === CONST.OneMinusDstColorFactor) { return gl.ONE_MINUS_DST_COLOR; } if (p === CONST.SrcAlphaSaturateFactor) { return gl.SRC_ALPHA_SATURATE; } return 0; }; export const paramToArrayStorage = function (type) { switch (type) { case CONST.UnsignedByteType: return Uint8Array; case CONST.ByteType: return Int8Array; case CONST.ShortType: return Int16Array; case CONST.UnsignedShortType: return Uint16Array; case CONST.IntType: return Int32Array; case CONST.UnsignedIntType: return Uint32Array; case CONST.FloatType: return Float32Array; } }; export const swizzleToEulerOrder = (swizzle) => swizzle.map((i) => ["", "X", "Y", "Z"][i]).join(""); export const transformComposer = function () { const euler = new Euler(); const quat = new Quaternion(); const pos = new Vector3(); const scl = new Vector3(); const transform = new Matrix4(); return function (position, rotation, quaternion, scale, matrix, eulerOrder) { if (eulerOrder == null) { eulerOrder = "XYZ"; } if (rotation != null) { if (eulerOrder instanceof Array) { eulerOrder = swizzleToEulerOrder(eulerOrder); } euler.setFromVector3(rotation, eulerOrder); quat.setFromEuler(euler); } else { quat.set(0, 0, 0, 1); } if (quaternion != null) { quat.multiply(quaternion); } if (position != null) { pos.copy(position); } else { pos.set(0, 0, 0); } if (scale != null) { scl.copy(scale); } else { scl.set(1, 1, 1); } transform.compose(pos, quat, scl); if (matrix != null) { transform.multiplyMatrices(transform, matrix); } return transform; }; };
JavaScript
0.000951
@@ -2017,62 +2017,8 @@ %7D%0A - if (p === CONST.RGBFormat) %7B%0A return gl.RGB;%0A %7D%0A if
c54cf5923ae736bd6cf57c146cb4a7913b71021f
Update roll.js
commands/roll.js
commands/roll.js
exports.run = function(client, message, args){ var x = args; if (args == '' || args == null) { return message.channel.send(`I am sorry. Please specify the amount of sides on the die to roll from.`); } min = Math.ceil(1); max = Math.floor(x) y = Math.floor(Math.random() * (max - min + 1)) + min; message.channel.send(y); } exports.conf = { enabled: true, guildOnly: false, aliases: ['roll'], permLevel: 2 }; exports.help = { name: 'Roll', description: 'Roll command.', usage: 'roll' };
JavaScript
0
@@ -78,11 +78,12 @@ s == - '' += %22%22 %7C%7C @@ -135,17 +135,17 @@ el.send( -%60 +%22 I am sor @@ -211,9 +211,9 @@ rom. -%60 +%22 ); %0D @@ -217,16 +217,17 @@ ; %0D%0A %7D +; %0D%0A%0D%0A m @@ -268,16 +268,17 @@ floor(x) +; %0D%0A y = @@ -362,16 +362,17 @@ d(y);%0D%0A%7D +; %0D%0A%0D%0Aexpo @@ -436,22 +436,22 @@ iases: %5B -' +%22 roll -' +%22 %5D,%0D%0A pe @@ -498,14 +498,14 @@ me: -' +%22 Roll -' +%22 ,%0D%0A @@ -518,17 +518,17 @@ iption: -' +%22 Roll com @@ -532,17 +532,17 @@ command. -' +%22 ,%0D%0A usa @@ -549,14 +549,16 @@ ge: -' +%22 roll -' +%22 %0D%0A%7D; +%0D%0A
9fd9039e53c4dc6916fbeffcff011ddce871004b
Fix event emitting
parser.js
parser.js
var spawn = require('child_process').spawn; var events = require('events'); var util = require('util'); var SAR = function(interval, options) { events.EventEmitter.call(this); options = options || {}; this.interval = interval || 5; this.parameters = options.parameters || ['-A']; this._buffer = ''; } var mapping = { 'rtps': 'io', //-b 'pgpgin/s': 'page', //-B 'DEV': 'block', //-d 'kbhubfree': 'hugepage', //-H 'INTR': 'int', //-I 'MHz': 'power:cpu', //-m CPU 'rpm': 'power:fan', //-m FAN 'wghMHz': 'power:freq', //-m FREQ 'inV': 'power:voltage', //-m IN 'degC': 'power:temp', //-m TEMP 'BUS': 'power:usb', //-m USB 'rxpck/s': 'net:dev', //-n DEV 'rxerr/s': 'net:edev', //-n EDEV 'call/s': 'net:nfs', //-n NFS 'scall/s': 'net:nfsd', //-n NFSD 'totsck': 'net:sock', //-n SOCK 'irec/s': 'net:ip', //-n IP 'ihdrerr/s': 'net:eip', //-n EIP 'imsg/s': 'net:icmp', //-n ICMP 'ierr/s': 'net:eicmp', //-n EICMP 'active/s': 'net:tcp', //-n TCP 'atmptf/s': 'net:etcp', //-n ETCP 'idgm/s': 'net:udp', //-n UDP 'tcp6sck': 'net:sock6', //-n SOCK6 'irec6/s': 'net:ip6', //-n IP6 'ihdrer6/s': 'net:eip6', //-n EIP6 'imsg6/s': 'net:icmp6', //-n ICMP6 'ierr6/s': 'net:eicmp6', //-n EICMP6 'idgm6/s': 'net:udp6', //-n UDP6 'CPU': 'cpu', //-P or -u 'runq-sz': 'load', //-q 'kbmemfree': 'memory', //-r 'frmpg/s': 'memoryPages', //-R 'kbswpfree': 'swap', //-S 'dentunusd': 'kernel', //-v 'proc/s': 'task', //-w 'pswpin/s': 'swapPages', //-W 'rcvin/s': 'tty', //-y }; util.inherits(SAR, events.EventEmitter); SAR.prototype.start = function() { var self = this; this._child = spawn('sar', this.parameters.concat([this.interval])); this._child.stdout.on('data', function(buf) { try { self._buffer += buf.toString(); while(self._buffer.indexOf('\n\n') !== -1) { var raw = self._buffer.substr(0, self._buffer.indexOf('\n\n')); self._buffer = self._buffer.substr(self._buffer.indexOf('\n\n')+2); var data = raw.split('\n').map(function(line) { //transform line to array of fields return line.split(/\s+/).filter(function(_,index) { // filter timestamps (first field) return index; }); }).reduce(function(columns, line, index) { //change row-major order to column-major order return line.forEach(function(field, index) { (columns[index] || (columns[index] = [])) && columns[index].push(field); }), columns; }, []).reduce(function(result, column) { //the first value in the array is the column header return (result[column[0]] = column.filter(function(_,index) { return index; })), result; }, {}); var found = false; for(var prop in mapping) { if(prop in data) { found = true; this.emit(mapping[prop], data); break; } } found || this.emit('UNKNOWN', data); } } catch(ex) { this.emit('error', ex); } }); } module.exports = SAR;
JavaScript
0.000023
@@ -2885,28 +2885,28 @@ -this +self .emit(mappin @@ -2979,20 +2979,20 @@ ound %7C%7C -this +self .emit('U @@ -3039,20 +3039,20 @@ %7B%0A -this +self .emit('e
e52d239a0f24ea4a2a498b3c50b6ef965d8a269a
fix background color
client/app.js
client/app.js
function App() { // default settings this.cellSize = 16; this.canvasWidth = 256; this.canvasHeight = 256; this.color = '#789'; this.gameRun = false; this.gamePause = false; this.apple = {x: -1, y: -1}; // centring document.getElementById('main').style.textAlign = 'center'; // configuring canvas this.canvas = document.getElementById('canvas'); this.canvas.width = this.canvasWidth; this.canvas.height = this.canvasHeight; this.canvas.style.border = '1px solid #444'; // context this.context = canvas.getContext('2d'); // scene this.sceneWidth = Math.ceil(this.canvasWidth / this.cellSize); this.sceneHeight = Math.ceil(this.canvasHeight / this.cellSize); // load snake this.snake = new Snake(this); // show this.updateScene(); this.showMsg('Znake!', 'Press space to play'); } App.prototype.updateScene = function() { // clear scene this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight); // snake for (var i = this.snake.getSize() - 1; i != -1; i--) { if (i == 0) { this.context.fillStyle = '#aa0000'; } else { this.context.fillStyle = this.color; } this.context.fillRect(this.snake.body[i].x * this.cellSize + 1, this.snake.body[i].y * this.cellSize + 1, this.cellSize - 2, this.cellSize - 2); } // apple if (this.snake.apple.x != -1 && this.snake.apple.y != -1) { this.context.beginPath(); this.context.fillStyle = '#00aa00'; this.context.arc(this.snake.apple.x * this.cellSize + this.cellSize / 2, this.snake.apple.y * this.cellSize + this.cellSize / 2, this.cellSize / 2 - 2, 0, Math.PI * 2); this.context.fill(); this.context.closePath(); } } /* Game message */ App.prototype.showMsg = function(header, action) { this.context.beginPath(); this.context.fillStyle = 'rgba(0, 0, 0, 0.7)'; this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight); this.context.closePath(); this.context.beginPath(); this.context.font = "normal normal 32px monospace"; this.context.fillStyle = '#aa0000'; this.context.textAlign = "center"; this.context.fillText(header, this.canvasWidth / 2, this.canvasHeight / 2); this.context.closePath(); this.context.beginPath(); this.context.font = "normal normal 14px monospace"; this.context.fillStyle = '#aa0000'; this.context.textAlign = "center"; this.context.fillText(action, this.canvasWidth / 2, this.canvasHeight / 2 + 32); this.context.closePath(); } /* Game status */ App.prototype.isStatusOn = function() { return this.gameRun; } App.prototype.setGameOn = function() { this.gameRun = true; this.snake.createApple(); } App.prototype.setGameOff = function(status) { this.gameRun = false; this.snake = new Snake(this); this.apple = {x: -1, y: -1}; switch (status) { // game over case 1: this.showMsg('Game Over', 'Press space to play'); break; // game win case 2: this.showMsg('You Win!', 'Press space to play'); break; } } /* Pause status */ App.prototype.isStatusPause = function() { return this.gamePause; } App.prototype.setPauseOn = function() { this.gamePause = true; this.showMsg('Pause', 'Press space to continue'); } App.prototype.setPauseOff = function() { this.gamePause = false; } /* Key's */ App.prototype.isKeyPause = function(event) { if (this.isKeySpace(event) || event.keyCode == 80) { return true; } return false; } App.prototype.isKeyUp = function(event) { if (event.keyCode == 87 || event.keyCode == 38) { return true; } return false; } App.prototype.isKeyDown = function(event) { if (event.keyCode == 83 || event.keyCode == 40) { return true; } return false; } App.prototype.isKeyLeft = function(event) { if (event.keyCode == 65 || event.keyCode == 37) { return true; } return false; } App.prototype.isKeyRight = function(event) { if (event.keyCode == 68 || event.keyCode == 39) { return true; } return false; } App.prototype.isKeySpace = function(event) { if (event.keyCode == 32) { return true; } return false; }
JavaScript
0.000016
@@ -99,24 +99,56 @@ ight = 256;%0A +%09this.backgroundColor = '#000';%0A %09this.color @@ -910,21 +910,68 @@ context. -clear +fillStyle = this.backgroundColor;%0A%09this.context.fill Rect(0,
9c4d8a0916e57998387e350692888d282165184a
Update warn.js
commands/warn.js
commands/warn.js
const Discord = require('discord.js') const config = require("./config.json"); exports.run = (bot, message, args, channel) => { if (!args) return message.reply("What was the user doing that needed to be warned?") let user = message.mentions.users.first() if (!user) return message.reply("Mention someone to warn them!") message.channel.send(`***${user}*** has been warned!`) user.send(`You have been warned in ***${message.guild.name}*** for ***${args}***`) var embed = new Discord.RichEmbed() .setTitle("Warn") .setColor("#80d4ff") .setThumbnail(`${user.displayAvatarURL}`) .addField(`${user.tag} has been warned`, `Has been warned by ${message.author.tag}`) .addField("User's ID", `${user.id}`) channel.send({ embed: embed }); };
JavaScript
0.000001
@@ -122,16 +122,79 @@ l) =%3E %7B%0A + var args2 = message.content.split(' ').slice(2).join(' ');%0A if (!a @@ -196,16 +196,17 @@ f (!args +2 ) return @@ -511,16 +511,17 @@ **$%7Bargs +2 %7D***%60)%0Av @@ -672,27 +672,8 @@ een -warned%60, %60Has been warn @@ -700,16 +700,44 @@ or.tag%7D%60 +, %60Reason being is $%7Bargs2%7D%60 )%0A.addFi
84b6d5cafd9f795524f92c913f8ec96f4a5e164f
trim extra newline
packages/heroku-run/commands/run.js
packages/heroku-run/commands/run.js
'use strict'; let tls = require('tls'); let url = require('url'); let tty = require('tty'); let h = require('heroku-cli-util'); function buildCommand(args) { let cmd = ''; for (let arg of args) { if (arg.indexOf(' ') !== -1) { arg = `"${arg}"`; } cmd = cmd + " " + arg; } return cmd.trim(); } function env () { let c = {}; if (tty.isatty(1)) { c.COLUMNS = process.stdout.columns; c.LINES = process.stdout.rows; } return c; } function startDyno(heroku, app, size, command) { return heroku.apps(app).dynos().create({ command: command, attach: true, size: size, env: env(), }); } function attachToRendezvous(uri) { let c = tls.connect(uri.port, uri.hostname); c.setEncoding('utf8'); process.stdin.setEncoding('utf8'); c.on('connect', function () { c.write(uri.path.substr(1) + '\r\n'); }); let firstLine = true; c.on('data', function (data) { // discard first line if (firstLine) { firstLine = false; if (tty.isatty(0)) { process.stdin.setRawMode(true); process.stdin.pipe(c); } return; } data = data.replace('\r\n', '\n'); let exitCode = data.match(/^heroku-command-exit-status (\d+)$/m); if (exitCode) { process.stdout.write(data.replace(/^heroku-command-exit-status \d+$/m, '')); process.exit(exitCode[1]); } process.stdout.write(data); }); c.on('timeout', function () { console.error('timed out'); }); c.on('end', function () { process.exit(0); }); c.on('error', h.errorHandler()); process.on('SIGINT', function () { c.end(); }); } module.exports = { topic: 'run', help: `run a one-off process inside a Heroku dyno`, variableArgs: true, needsAuth: true, needsApp: true, hidden: true, flags: [ {name: 'size', char: 's', description: 'dyno size', hasValue: true}, {name: 'exit-code', description: 'placeholder'}, ], run: h.command(function* (context, heroku) { let command = buildCommand(context.args); if (!command) { h.error('Usage: heroku run COMMAND\n\nExample: heroku run bash'); process.exit(1); } let p = startDyno(heroku, context.app, context.flags.size, `${command}; echo heroku-command-exit-status $?`); let dyno = yield h.action(`Running ${h.color.cyan.bold(command)} attached to terminal`, p, {success: false}); console.error(`up, ${dyno.name}`); attachToRendezvous(url.parse(dyno.attach_url)); }), };
JavaScript
0
@@ -1341,16 +1341,18 @@ tus %5Cd+$ +%5Cn /m, ''))
798fb0b7270dc27c1c7ddb4952a1abe1c575748d
Fix race condition in event test (#11310)
tests/fast-integration/test/2-commerce-mock.js
tests/fast-integration/test/2-commerce-mock.js
const axios = require("axios"); const https = require("https"); const { expect } = require("chai"); const httpsAgent = new https.Agent({ rejectUnauthorized: false, // curl -k }); axios.defaults.httpsAgent = httpsAgent; const { ensureCommerceMockLocalTestFixture, checkAppGatewayResponse, sendEventAndCheckResponse, cleanMockTestFixture, } = require("./fixtures/commerce-mock"); const { printRestartReport, getContainerRestartsForAllNamespaces, eventingSubscription, waitForFunction, waitForSubscription, k8sApply, genRandom, retryPromise, } = require("../utils"); describe("CommerceMock tests", function () { this.timeout(10 * 60 * 1000); this.slow(5000); const testNamespace = "test"; let initialRestarts = null; it("Listing all pods in cluster", async function () { initialRestarts = await getContainerRestartsForAllNamespaces(); }); it("CommerceMock test fixture should be ready", async function () { await ensureCommerceMockLocalTestFixture("mocks", testNamespace).catch((err) => { console.dir(err); // first error is logged return ensureCommerceMockLocalTestFixture("mocks", testNamespace); }); }); it("lastorder function should be ready", async function () { await waitForFunction("lastorder", testNamespace); }); it("In-cluster event subscription should be ready", async function () { await k8sApply([eventingSubscription( `sap.kyma.custom.inapp.order.received.v1`, `http://lastorder.${testNamespace}.svc.cluster.local`, "order-received", testNamespace)]); await waitForSubscription("order-received", testNamespace); await waitForSubscription("order-created", testNamespace); }); it("in-cluster event should be delivered", async function () { const eventId = "event-"+genRandom(5); // send event using function query parameter send=true await retryPromise(() => axios.post("https://lastorder.local.kyma.dev", { id: eventId }, {params:{send:true}}), 10, 1) // verify if event was received using function query parameter inappevent=eventId let response = await retryPromise(() => axios.get("https://lastorder.local.kyma.dev", { params: { inappevent: eventId } })); expect(response).to.have.nested.property("data.id", eventId, "The same event id expected in the result"); expect(response).to.have.nested.property("data.shipped", true, "Order should have property shipped"); }); it("function should reach Commerce mock API through app gateway", async function () { await checkAppGatewayResponse(); }); it("order.created.v1 event should trigger the lastorder function", async function () { await sendEventAndCheckResponse(); }); it("Should print report of restarted containers, skipped if no crashes happened", async function () { const afterTestRestarts = await getContainerRestartsForAllNamespaces(); printRestartReport(initialRestarts, afterTestRestarts); }); it("Test namespaces should be deleted", async function () { await cleanMockTestFixture("mocks", testNamespace, true); }); });
JavaScript
0.000002
@@ -559,16 +559,25 @@ romise,%0A + debug,%0A %7D = requ @@ -2013,10 +2013,13 @@ 0, 1 +000 )%0A - @@ -2107,23 +2107,8 @@ %0A - let response = awa @@ -2119,29 +2119,108 @@ etryPromise( -() =%3E +async () =%3E %7B%0A debug(%22Waiting for event: %22,eventId);%0A let response = await axios.get(%22 @@ -2290,26 +2290,21 @@ tId %7D %7D) -); %0A -%0A expect @@ -2403,16 +2403,18 @@ sult%22);%0A + expe @@ -2511,16 +2511,38 @@ pped%22);%0A + %7D, 10, 1000);%0A %0A %7D);%0A%0A
2dfdfb3307950e7be6b9848e46ebea5b3c510aec
Fix kint issues.
network/error-parsing.js
network/error-parsing.js
let message = require('../message'); let dispatcher = require('../dispatcher'); let {isObject, isArray} = require('lodash/lang'); /** * Define all the error types of the exceptions which are defined. * @type {object} */ let errorTypes = { entity: "entity", collection: "collection", composite: "composite" }; /** * List of all the global messages to look after. * @type {Array} */ let globalMessages = [{ name: "globalErrors", type: "error" }, { name: "globalSuccess", type: "success" }, { name: "globalWarnings", type: "warning" }, { name: "globalInfos", type: "error" }, { name: "globalErrorMessages", type: "error" }, { name: "globalSuccessMessages", type: "success" }, { name: "globalWarningMessages", type: "warning" }, { name: "globalInfoMessages", type: "error" }, { name: "errors", type: "error" }]; function configure(options) { options = options || {}; if (isArray(options.globalMessages)) { globalMessages = options.globalMessages; } if (isObject(options.errorTypes)) { errorTypes = options.errorTypes; } } /** * Template an error message with parameters. * @param {object} parameters - The parameters to format. * @return {object} - The formated parameters. */ function _formatParameters(parameters) { var options = {}, formatter, value; for (var prop in parameters) { if (parameters.hasOwnProperty(prop)) { if (parameters[prop].domain) { var domain = metadataBuilder.getDomains()[parameters[prop].domain]; formatter = domain ? domain.format : undefined; } else { formatter = undefined; } value = formatter && formatter.value ? formatter.value(parameters[prop].value) : parameters[prop].value; options[prop] = value; } } return options; } function _treatGlobalMessagesPerType(messages, type) { messages.forEach(function convertErrorsIntoNotification(element) { var options = {}; if (isObject(element)) { options = _formatParameters(element.parameters); element = element.message; } message.addMessage({ type: type, content: require('i18n').t(element, options), creationDate: Date.now() }); }); } /** * Treat the global errors. * @param {object} responseJSON - Treat the global errors. * @param {object} options - Options for error handling.{isDisplay:[true/false], globalMessages: [{type: "error", name: "propertyName"}]} * @return {} */ function _treatGlobalErrors(responseJSON, options) { options = options || {}; var allMessagesTypes = options.globalMessages || globalMessages; if (responseJSON !== undefined) { var messages = responseJSON; //Looping through all messages types. allMessagesTypes.forEach(function treatAllTypes(globalMessageConf) { //Treat all the gloabe var msgs = messages[globalMessageConf.name]; if (msgs !== undefined) { _treatGlobalMessagesPerType(msgs, globalMessageConf.type); } }); } } /** * Treat the response json of an error. * @param {object} responseJSON The json response from the server. * @param {object} options The options containing the model. {model: Backbone.Model} * @return {object} The constructed object from the error response. */ function _treatEntityExceptions(responseJSON, options) { dispatcher.handleServerAction({ data: {[options.node]: err}, //maybe err[options.node] type: 'updateError', status: {[options.node]: {name:config.status}, isLoading: false} }); } /** * Treat the collection exceptions. * @param {object} responseJSON The JSON response from the server. * @param {object} options Options for error handling. {isDisplay: boolean, model: Backbone.Model} * @return {object} The constructed object from the error response. */ function _treatCollectionExceptions(responseJSON, options) { console.warn('Not yet implemented as collection are not savable.') } /** * Treat with all the custom exception * @param {object} responseJSON - Response from the server. * @param {object} options - Options for the exceptions teratement such as the {model: modelVar}. * @return {object} - The parsed error response. */ function _treatBadRequestExceptions(responseJSON, options) { if (responseJSON.type !== undefined) { switch (responseJSON.type) { case errorTypes.entity: return _treatEntityExceptions(responseJSON, options); case errorTypes.collection: return _treatCollectionExceptions(responseJSON, options); default: break; } } } /** * Transform errors send by API to application errors. Dispatch depending on the response http code. * @param {object} response - Object whic * @param {object} options - Options for the exceptions teratement such as the model, {model: modelVar}. * @return {object} - The parsed error response. */ function manageResponseErrors(response, options) { if (!response) { console.warn('You are not dealing with any response'); return false; } //Rethrow the error if it is one. if (isObject(response) && response instanceof Error) { throw response; } //Parse the response. options = options || {}; response = response || {}; let responseErrors = response.responseJSON || response; if (responseErrors === undefined) { if (response.responseText !== undefined) { try { //The first try is to parse the response in JSON. Maybe the return mime type is not correct. responseErrors = JSON.parse(response.responseText); } catch (e) { //Construt an error with the text. responseErrors = { status: response.status, globalErrorMessages: [response.responseText] }; } }else { responseErrors = {}; } } responseErrors.status = responseErrors.status ||response.status; if (responseErrors.status) { _treatGlobalErrors(responseErrors); /*Deal with all the specific exceptions*/ switch (responseErrors.status) { case 400: return _treatBadRequestExceptions(responseErrors, options); break; case 401: return _treatBadRequestExceptions(responseErrors, options); break; case 422: return _treatBadRequestExceptions(responseErrors, options); break; default: break; } return; } } module.exports = { configure: configure, manageResponseErrors: manageResponseErrors };
JavaScript
0
@@ -251,16 +251,16 @@ ty: -%22 +' entity -%22 +' ,%0A @@ -273,17 +273,17 @@ ection: -%22 +' collecti @@ -284,17 +284,17 @@ llection -%22 +' ,%0A co @@ -302,17 +302,17 @@ posite: -%22 +' composit @@ -312,17 +312,17 @@ omposite -%22 +' %0A%7D;%0A%0A/** @@ -3627,19 +3627,28 @@ .node%5D: -err +responseJSON %7D, //may @@ -3728,22 +3728,24 @@ : %7Bname: -config + options .status%7D
e57792bc8e5f3ec31716d3f24e90015631861078
Add redis as a session store.
backend/index.js
backend/index.js
"use strict"; var debug = require('debug')('server'); var express = require('express'); var io = require('socket.io')(); var path = require('path'); var routes = require('./routes/index'); var app = express(); app.use('/', routes); app.set('view engine', 'jade'); app.set('views', path.join(__dirname, 'views')); var server = app.listen(process.env.PORT || 3000, function () { var host = server.address().address; var port = server.address().port; debug('listening at http://%s:%s', host, port); }); io.attach(server); // TODO: move these lines to separated file. io.on('connection', function (socket) { debug('+1 socket connection'); io.emit('test', { message: 'Hey, everyone! +1 connection' }); socket.on('test', function (data) { debug('received: %s', data); }); socket.on('disconnect', function () { debug('-1 socket connection'); }); });
JavaScript
0
@@ -147,68 +147,506 @@ ');%0A -%0Avar routes = require('./routes/index');%0A%0Avar app = express( +var redis = require('redis');%0Avar session = require('express-session');%0Avar sessionStore = require('connect-redis')(session);%0A%0Avar routes = require('./routes/index');%0A%0Avar app = express();%0Avar redisClient = redis.createClient();%0A%0Aapp.use(session(%7B%0A secret: 'kashikoi kawaii erichika',%0A resave: false, // don't save session if unmodified%0A saveUninitialized: false, // don't create session until something stored%0A store: new sessionStore(%7B host: 'localhost', port: 6379, client: redisClient %7D)%0A%7D) );%0A%0A
8eecb9a979e4962454b036f0d1c1905a928acd54
edit link service
src/domain/linkService.js
src/domain/linkService.js
import api from '../service/apiClient'; import { fbTemplate } from 'claudia-bot-builder'; const ACTION_LINK = 'link'; const NOUN_ACCOUNT = 'account'; const FRONTEND_URL = 'https://jenius-hackathon-bot-login.herokuapp.com'; const REDIRECT_URI = 'https://b4vritvu47.execute-api.ap-southeast-1.amazonaws.com/latest/facebook?access_token=UrhwukcTj0s'; class LinkService { _getAccountLink() { const message = { attachment: { type: 'template', payload: { template_type: 'generic', elements: [{ title: 'Link to your Jenius account', image_url: FRONTEND_URL + '/linking.png', buttons: [{ type: 'account_link', url: FRONTEND_URL + '?redirect_uri=' + encodeURIComponent(REDIRECT_URI) }] }] } } }; // console.log('Message =', JSON.stringify(message)); return message; } runCommand(command) { return this._getAccountLink(); } } export default LinkService;
JavaScript
0
@@ -219,133 +219,19 @@ .com -';%0Aconst REDIRECT_URI = 'https://b4vritvu47.execute-api.ap-southeast-1.amazonaws.com/latest/facebook?access_token=UrhwukcTj0s +/index.html ';%0A%0A @@ -617,62 +617,8 @@ _URL - + '?redirect_uri=' + encodeURIComponent(REDIRECT_URI) %0A
61461db913546d140bba3b082c78dc553d852401
fix jasmine spec for correct reshare behavior
spec/javascripts/app/models/post/interacations_spec.js
spec/javascripts/app/models/post/interacations_spec.js
describe("app.models.Post.Interactions", function(){ beforeEach(function(){ this.interactions = factory.post().interactions; this.author = factory.author({guid: "loggedInAsARockstar"}); loginAs({guid: "loggedInAsARockstar"}); this.userLike = new app.models.Like({author : this.author}); }); describe("toggleLike", function(){ it("calls unliked when the user_like exists", function(){ spyOn(this.interactions, "unlike").and.returnValue(true); this.interactions.likes.add(this.userLike); this.interactions.toggleLike(); expect(this.interactions.unlike).toHaveBeenCalled(); }); it("calls liked when the user_like does not exist", function(){ spyOn(this.interactions, "like").and.returnValue(true); this.interactions.likes.reset([]); this.interactions.toggleLike(); expect(this.interactions.like).toHaveBeenCalled(); }); }); describe("like", function(){ it("calls create on the likes collection", function(){ this.interactions.like(); expect(this.interactions.likes.length).toEqual(1); }); }); describe("unlike", function(){ it("calls destroy on the likes collection", function(){ this.interactions.likes.add(this.userLike); this.interactions.unlike(); expect(this.interactions.likes.length).toEqual(0); }); }); describe("reshare", function() { var ajax_success = { status: 200, responseText: [] }; beforeEach(function(){ this.reshare = this.interactions.post.reshare(); }); it("triggers a change on the model", function() { spyOn(this.interactions, "trigger"); this.interactions.reshare(); jasmine.Ajax.requests.mostRecent().respondWith(ajax_success); expect(this.interactions.trigger).toHaveBeenCalledWith("change"); }); it("adds the reshare to the stream", function() { app.stream = { addNow: $.noop }; spyOn(app.stream, "addNow"); this.interactions.reshare(); jasmine.Ajax.requests.mostRecent().respondWith(ajax_success); expect(app.stream.addNow).toHaveBeenCalledWith(this.reshare); }); }); });
JavaScript
0
@@ -1439,18 +1439,27 @@ seText: -%5B%5D +'%7B%22id%22: 1%7D' %7D;%0A%0A @@ -2114,28 +2114,23 @@ ledWith( -this.reshare +%7Bid: 1%7D );%0A %7D
199124b49ee84a904f84311c9e88092e5d13caaf
Fix AbstractTraitTest
tests/library/CM/Frontend/AbstractTraitTest.js
tests/library/CM/Frontend/AbstractTraitTest.js
define(["CM/Frontend/AbstractTrait"], function() { QUnit.module('CM/Frontend/AbstractTrait', { beforeEach: function() { var FooTrait = _.clone(CM_Frontend_AbstractTrait); FooTrait.traitProperties = { foo: function() { return true; }, bar: CM_Frontend_AbstractTrait.abstractMethod }; this.FooTrait = FooTrait; }, afterEach: function() { this.FooTrait = null; } }); QUnit.test("isImplementedBy", function(assert) { var FooTrait = this.FooTrait; assert.notOk(FooTrait.isImplementedBy()); assert.notOk(FooTrait.isImplementedBy(null)); assert.notOk(FooTrait.isImplementedBy(1)); assert.notOk(FooTrait.isImplementedBy('')); assert.notOk(FooTrait.isImplementedBy('foo')); assert.notOk(FooTrait.isImplementedBy(/foo/)); assert.notOk(FooTrait.isImplementedBy([])); assert.notOk(FooTrait.isImplementedBy({})); var Foo = function() { }; Foo.prototype = {}; Foo.prototype.constructor = Foo; assert.notOk(FooTrait.isImplementedBy(new Foo())); }); QUnit.test("applyImplementation", function(assert) { var FooTrait = this.FooTrait; var Foo = function() { }; Foo.prototype = {}; Foo.prototype.constructor = Foo; assert.notOk(FooTrait.isImplementedBy(new Foo())); assert.throws(function() { FooTrait.applyImplementation(Foo.prototype); }, /bar not implemented./); Foo.prototype.bar = function() { return true; }; FooTrait.applyImplementation(Foo.prototype); var foo = new Foo(); assert.ok(FooTrait.isImplementedBy(foo)); assert.ok(foo.bar()); assert.ok(foo.bar()); var Bar = function() { }; Bar.prototype = Object.create(Foo.prototype); Bar.prototype.constructor = Bar; var bar = new Bar(); assert.ok(FooTrait.isImplementedBy(bar)); assert.ok(bar.foo()); assert.ok(bar.bar()); }); });
JavaScript
0.000001
@@ -1630,27 +1630,27 @@ sert.ok(foo. -bar +foo ());%0A ass
88773292fe20e358f19634e9d4ebd70270fbe485
Fix providing an invalid source
src/newsapi.js
src/newsapi.js
import axios from 'axios'; const BASE_URL = 'https://newsapi.org/v2'; // 100 is the maximum allowed const PAGE_SIZE = 100; const SOURCES = [ 'abc-news', 'ars-technica', 'associated-press', 'bbc-news', 'bloomberg', 'business-insider', 'buzzfeed', 'cbs-news', 'cnbc', 'cnn', 'engadget', 'entertainment-weekly', 'espn', 'financial-times', 'fortune', 'fox-sports', 'google-news', 'ign', 'mashable', 'msnbc', 'mtv-news', 'national-geographic', 'nbc-news', 'new-scientist', 'newsweek', 'new-york-magazine', 'nfl-news', 'politico', 'polygon', 'recode', 'reuters', 'techcrunch', 'techradar', 'the-economist', 'the-huffington-post', 'the-new-york-times', 'the-next-web', 'the-telegraph', 'the-verge', 'the-wall-street-journal', 'the-washington-post', 'time', 'usa-today' ]; function requestHeadlines(page, apiKey) { const options = { headers: {'X-Api-Key': apiKey} }; return axios.get( `${BASE_URL}/top-headlines?page=${page}&pageSize=${PAGE_SIZE}&sources=${SOURCES.join( ',' )}`, options ); } function requestSources(apiKey) { const options = { headers: {'X-Api-Key': apiKey} }; return axios.get(`${BASE_URL}/sources`, options); } function storeArticles(store, articles) { for (const article of articles) { if (!article.title || !article.url) { continue; } const source = article.source; const trimmedArticle = { title: article.title, url: article.url }; if (store.hasOwnProperty(source.id)) { if (store[source.id].articles.length < 3) { store[source.id].articles.push(trimmedArticle); } } else { store[source.id] = { name: source.name, articles: [trimmedArticle] }; } } } export function getSourcesWithArticles(apiKey) { const sources = {}; const sourceUrls = {}; return requestSources(apiKey) .then(response => { const data = response.data; if (data.status !== 'ok') { throw new Error(data.message); } for (let {id, url} of data.sources) { sourceUrls[id] = url; } return requestHeadlines(1, apiKey); }) .then(response => { const data = response.data; if (data.status !== 'ok') { throw new Error(data.message); } // const totalResults = data.totalResults; // const numPages = Math.ceil(totalResults / PAGE_SIZE); storeArticles(sources, data.articles); const getRemainingPages = []; // for (let page = 2; page <= numPages; page++) { // getRemainingPages.push(requestHeadlines(page, apiKey)); // } return axios.all(getRemainingPages); }) .then(responses => { for (let response of responses) { const data = response.data; if (data.status === 'ok') { storeArticles(sources, data.articles); } } return Object.entries(sources).map(([id, source]) => { source.url = sourceUrls[id]; return source; }); }); }
JavaScript
0.011284
@@ -119,20 +119,18 @@ = 100;%0A%0A -cons +le t SOURCE @@ -714,29 +714,8 @@ r',%0A - 'the-economist',%0A @@ -2403,32 +2403,337 @@ %0A %7D%0A%0A + /* Providing an invalid source to the top-headlines endpoint will%0A result in a 400 error. */%0A SOURCES = SOURCES.filter(source =%3E%0A Boolean(%0A data.sources.find(validSource =%3E validSource.id === source)%0A )%0A );%0A%0A retu
d162d347f1e94525a3824b1e4c65cd2aa9f24281
Rewrite Lock to remove the need of EventEmitter
src/utils/lock.js
src/utils/lock.js
const EventEmitter = require('events') const { KafkaJSLockTimeout } = require('../errors') module.exports = class Lock { constructor({ timeout = 1000 } = {}) { this.locked = false this.timeout = timeout this.emitter = new EventEmitter() } async acquire() { return new Promise((resolve, reject) => { if (!this.locked) { this.locked = true return resolve() } let timeoutId const tryToAcquire = () => { if (!this.locked) { this.locked = true clearTimeout(timeoutId) this.emitter.removeListener('releaseLock', tryToAcquire) return resolve() } } this.emitter.on('releaseLock', tryToAcquire) timeoutId = setTimeout( () => reject(new KafkaJSLockTimeout('Timeout while acquiring lock')), this.timeout ) }) } async release() { this.locked = false setImmediate(() => this.emitter.emit('releaseLock')) } }
JavaScript
0
@@ -1,26 +1,36 @@ const -EventEmitter +%7B KafkaJSLockTimeout %7D = requi @@ -37,68 +37,167 @@ re(' -event +../error s')%0A +%0A const -%7B KafkaJS +PRIVATE = %7B%0A LOCKED: Symbol('private:Lock:locked'),%0A TIMEOUT: Symbol('private: Lock -T +:t imeout - %7D = require('../errors') +'),%0A WAITING: Symbol('private:Lock:waiting'),%0A%7D %0A%0Amo @@ -265,39 +265,48 @@ = %7B%7D) %7B%0A this -.locked +%5BPRIVATE.LOCKED%5D = false%0A thi @@ -306,24 +306,33 @@ this -.timeout +%5BPRIVATE.TIMEOUT%5D = timeo @@ -346,35 +346,35 @@ this -.emitter = new EventEmitter +%5BPRIVATE.WAITING%5D = new Set ()%0A @@ -462,38 +462,56 @@ this -.locked) %7B%0A this.locked +%5BPRIVATE.LOCKED%5D) %7B%0A this%5BPRIVATE.LOCKED%5D = t @@ -594,16 +594,22 @@ cquire = + async () =%3E %7B @@ -626,23 +626,32 @@ f (!this -.locked +%5BPRIVATE.LOCKED%5D ) %7B%0A @@ -660,23 +660,32 @@ this -.locked +%5BPRIVATE.LOCKED%5D = true%0A @@ -736,47 +736,33 @@ this -.emitter.removeListener('releaseLock', +%5BPRIVATE.WAITING%5D.delete( tryT @@ -831,35 +831,30 @@ this -.emitter.on('releaseLock', +%5BPRIVATE.WAITING%5D.add( tryT @@ -987,16 +987,25 @@ this -.timeout +%5BPRIVATE.TIMEOUT%5D %0A @@ -1053,78 +1053,164 @@ this -.locked = false%0A setImmediate(() =%3E this.emitter.emit('releas +%5BPRIVATE.LOCKED%5D = false%0A const waitingForLock = Array.from(this%5BPRIVATE.WAITING%5D)%0A return Promise.all(waitingForLock.map(acquireLock =%3E acquir eLock -' +() ))%0A
62c0cc335e26bb87ce21e93d18f70f02739f3bf2
Fix callerId for dial
lib/routes/call.js
lib/routes/call.js
var _ = require('lodash'); var config = require('../config'); var twilio = require('../twilio'); var team = require('../team'); var middlewares = require('../middlewares'); module.exports = function(app) { // Fallback for errors app.post('/twiml/call/fallback', twilio.twimlResponse(function(resp) { resp.say( resp._('callError') ); }, { valid: false })); // Entry point for call app.post('/twiml/call', twilio.twimlResponse(function(resp, body) { var from = body.From; var tocall = body.tocall; var member = team.get(from); if (tocall) { resp.dial(tocall, { action: twilio.actionUrl('dial/status') }); return; } if (member) { // Ask for a number to call resp.say( resp._('teamPrompNumber', { member: member }) ) .gather({ action: twilio.actionUrl('dial'), finishOnKey: '#' }); } else { // Dial first team member resp.say( resp._('callWelcome') ); resp.dial(_.first(team.humans()).phone, { action: twilio.actionUrl('call/0/status'), timeout: config.call.timeout }); } })); // Status of dial app.post('/twiml/call/:number/status', twilio.twimlResponse(function(resp, body, req) { var status = body.DialCallStatus; var number = Number(req.params.number || 0); var nextCall = team.humans()[number+1]; var hasFailed = (status == "failed" || status == "busy" || status == "no-answer" || status == "canceled"); if (hasFailed) { if (nextCall) { // Dial number resp.say( resp._('callHold') ); resp.dial(toCall.phone, { action: twilio.actionUrl('call/external/'+(number+1)+'/status'), timeout: config.call.timeout }); } else { resp.say( resp._('callUnavailable') ); resp.record({ action: twilio.actionUrl('call/record') }); } } })); // After recording a message app.post('/twiml/call/record', twilio.twimlResponse(function(resp, body) { resp.say(resp._('callRecord')); resp.hangup(); })); // Team member entered a number to call app.post('/twiml/dial', middlewares.team, twilio.twimlResponse(function(resp, body, req) { // Dial number resp.dial(body.Digits, { action: twilio.actionUrl('dial/status') }); })); app.post('/twiml/dial/status', middlewares.team, twilio.twimlResponse(function(resp, body) { var status = body.CallStatus; var hasFailed = (status == "failed" || status == "busy" || status == "no-answer" || status == "canceled"); if (hasFailed) { resp.say( resp._('teamFailed') ); resp.hangup(); } })); };
JavaScript
0.000002
@@ -644,24 +644,74 @@ l(tocall, %7B%0A + callerId: _.first(config.phones),%0A @@ -2813,24 +2813,70 @@ y.Digits, %7B%0A + callerId: _.first(config.phones),%0A
cc984417a04cccd2e5ccef217172c731d39942d5
Update jsPerf_CNNHeightWidthResize.js
CNN/jsPerf/jsPerf_CNNHeightWidthResize.js
CNN/jsPerf/jsPerf_CNNHeightWidthResize.js
import * as HeightWidthDepth from "./HeightWidthDepth.js"; import * as PartTime from "../PartTime.js"; import * as ValueMax from "../ValueMax.js"; //import * as TensorTools from "../util/TensorTools.js"; /** * Test different resize implementation for CNN. * * @see {@link https://jsperf.com/colorfulcakechen-cnn-height-width-resize} * @see {@link https://colorfulcakechen.github.io/query-submit-canvas/CNN/jsPerf/TestFilters2D.html} */ let testCase_Height = 101; let testCase_Width = 101; let testCase_Depth = 24; //globalThis.testSet_101x101x24 = new HeightWidthDepth.Base( 101, 101, 24 ); // height, width, depth /** Aggregate all progress about WebGL an CPU. */ class Progress extends ValueMax.Percentage.Aggregate { constructor() { let children = [ new ValueMax.Percentage.Concrete(), // Increased when executing by WebGL. // new ValueMax.Percentage.Concrete(), // Increased when executing by WASM. new ValueMax.Percentage.Concrete(), // Increased when executing by CPU. ]; super(children); // [ this.WebGL, this.WASM, this.CPU ] = children; [ this.WebGL, this.CPU ] = children; } } /** Profile test case. */ globalThis.testCaseLoader = async function () { let progress = new Progress(); let progressReceiver = new ValueMax.Receiver.HTMLProgress.createByTitle_or_getDummy("TestProgressBar"); let resultProfilesWebGL; { await tf.setBackend("webgl"); // WebGL seems crashed jsPerf. console.log("library WebGL ready."); console.log("library WebGL compiling..."); // For pre-compile tensorflow.js GPU codes. (and Test correctness.) globalThis.testCase = new HeightWidthDepth.Base( testCase_Height, testCase_Width, testCase_Depth, progress, progress.WebGL, progressReceiver ); resultProfilesWebGL = await globalThis.testCase.generateProfiles(); globalThis.testCase.disposeTensors(); console.log("library WebGL compiling done."); } let resultProfilesWASM; //!!! ...unfinished... Wait until tensorflow WASM mature. // { // await tf.setBackend("wasm") // WASM seems no ResizeNearestNeighbor. // console.log("library WASM ready."); // // console.log("library WASM compiling..."); // For pre-compile tensorflow.js WASM codes. (and Test correctness.) // // globalThis.testCase = new HeightWidthDepth.Base( // testCase_Height, testCase_Width, testCase_Depth, progress, progress.WASM, progressReceiver ); // // resultProfilesWASM = await globalThis.testCase.generateProfiles(); // globalThis.testCase.disposeTensors(); // console.log("library WASM compiling done."); // } let resultProfilesCPU; { await tf.setBackend("cpu"); //await tf.ready(); console.log("library CPU ready."); console.log("library CPU compiling..."); // For pre-compile tensorflow.js CPU codes. (and Test correctness.) globalThis.testCase = new HeightWidthDepth.Base( testCase_Height, testCase_Width, testCase_Depth, progress, progress.CPU, progressReceiver ); resultProfilesCPU = await globalThis.testCase.generateProfiles(); // DO NOT dispose it so that jsPerf can use it. //globalThis.testCase.disposeTensors(); console.log("library CPU compiling done."); } // Display to web page. publishProfiles( "profilesHTMLTable", resultProfilesWebGL, resultProfilesWASM, resultProfilesCPU ); } /** * Publish the profiles to HTML table. * * @param {string} strResultHTMLTableName the HTML table name for display execution time. * @param {Object[]} profilesWebGL the array of profiles for execution time of WebGL. * @param {Object[]} profilesWASM the array of profiles for execution time of WASM. * @param {Object[]} profilesCPU the array of profiles for execution time of CPU. */ function publishProfiles( strResultHTMLTableName, profilesWebGL, profilesWASM, profilesCPU ) { if ( !document ) return; if ( !strResultHTMLTableName ) return; let htmlTable = document.getElementById( strResultHTMLTableName ); if ( !htmlTable ) return; /** * @param {HTMLTable} htmlTable The HTML table as display target. * @param {string} th_OR_td "th" for table header, "td" for table body. * @param {string[]|number[]} dataArray The data to be displaye */ function addOneLineCells( htmlTable, th_OR_td, dataArray ) { let cellElementName; let oneLine = document.createElement( "tr" ); let count = dataArray.length; for ( let i = 0; i < count; ++i ) { let data = dataArray[ i ]; if ( 0 == i ) cellElementName = "th"; // First column always use <th> else cellElementName = th_OR_td; let oneCell = document.createElement( cellElementName ); oneCell.appendChild( document.createTextNode( data ) ) oneLine.appendChild( oneCell ); } htmlTable.appendChild( oneLine ); } // Table header (top line). addOneLineCells( htmlTable, "th", [ "TestName", "backend", "kernelMs", "wallMs", // "backend", "kernelMs", "wallMs", "backend", "kernelMs", "wallMs", "newBytes", "newTensors", "peakBytes" ] ); let digitsCount = 6; let profileCount = profilesWebGL.length; for ( let i = 0; i < profileCount; ++i ) { let profileWebGL = profilesWebGL[ i ]; // let profileWASM = profilesWASM[ i ]; let profileCPU = profilesCPU[ i ]; addOneLineCells( htmlTable, "td", [ profileWebGL.title, profileWebGL.backendName, profileWebGL.kernelMs.toFixed( digitsCount ), profileWebGL.wallMs.toFixed( digitsCount ), // profileWASM.backendName, profileWASM.kernelMs.toFixed( digitsCount ), profileWASM.wallMs.toFixed( digitsCount ), profileCPU.backendName, profileCPU.kernelMs.toFixed( digitsCount ), profileCPU.wallMs.toFixed( digitsCount ), profileWebGL.newBytes, profileWebGL.newTensors, profileWebGL.peakBytes ] ); } }
JavaScript
0
@@ -4076,20 +4076,19 @@ am %7BHTML -Tabl +Nod e%7D @@ -4094,20 +4094,19 @@ html -Tabl +Nod e The HT @@ -4113,16 +4113,37 @@ ML table + (or thead, or tbody) as disp @@ -4345,20 +4345,19 @@ ls( html -Tabl +Nod e, th_OR @@ -4867,20 +4867,19 @@ html -Tabl +Nod e.append @@ -4897,24 +4897,192 @@ ine );%0A %7D%0A%0A + let thead = document.createElement( %22thead%22 );%0A let tbody = document.createElement( %22tbody%22 );%0A%0A htmlTable.appendChild( thead );%0A htmlTable.appendChild( tbody );%0A%0A // Table h @@ -5114,33 +5114,29 @@ eLineCells( -htmlTable +thead , %22th%22, %5B%0A @@ -5570,25 +5570,21 @@ eCells( -htmlTable +tbody , %22td%22,
88aead045e12cd6063fd621573c3883199f1ee16
Update exit url to yeoman.io
lib/routes/exit.js
lib/routes/exit.js
'use strict'; var yosay = require('yosay'); module.exports = function (app) { app.insight.track('yoyo', 'exit'); var url = 'https://github.com/yeoman/yeoman#team'; var maxLength = url.length; var newLine = new Array(maxLength).join(' '); console.log( '\n' + yosay( 'Bye from us! Chat soon.' + newLine + newLine + 'The Yeoman Team ' + url, { maxLength: maxLength } ) ); };
JavaScript
0
@@ -131,41 +131,20 @@ http -s :// -github.com/yeoman/yeoman#team +yeoman.io ';%0A
d036beedd1ddfde16a9837b53a48846d024bc97c
Update scatter
scatter.js
scatter.js
var margin = {top: 50, right:50, bottom: 50, left: 50}, w = 6*50 + margin.left - margin.right, h = 9*50 + margin.top - margin.bottom; var color = d3.scale.linear() .domain([0, 2000]) .range(["yellow", "darkred"]) .interpolate(d3.interpolateLab); var x = d3.scale.linear() .domain([0, 6]) .range([0, w + 50]); var y = d3.scale.linear() .domain([0, 10]) .range([h , -50]); var yinv = d3.scale.linear() .domain([0, 9]) .range([0, h]); var xAxis = d3.svg.axis() .scale(x) .tickValues([0,1,2,3,4,5]) .tickFormat(d3.format(",.0d")) //.tickPadding() .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left"); var side = 1; var bins = d3.bin() .size([w, h]) .side(side); var svg = d3.select("#area2").append("svg") .attr("width", w + margin.left + margin.right) .attr("height", h + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" +margin.left+ "," +margin.top+ ")"); var points = []; d3.csv("paired.csv", function(error, data) { data.forEach(function(d) { d.time = +d.f; d.intensity = +d.sz; points.push([d.time, d.intensity]); }); //console.log(points); //debugging // svg.append("g") // .attr("class", "x axis") // .attr("transform", "translate(0," + h + ")") // .call(xAxis); var selX = svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + h + ")") .call(xAxis); selX.selectAll("text").attr("transform", "translate(25, 0)"); var selY = svg.append("g") .attr("class", "y axis") .call(yAxis); selY.selectAll("text").attr("transform", "translate(0, -25)"); //svg.append("g") // .attr("class", "y axis") // .call(yAxis); svg.selectAll(".square") .data(bins(points)) .enter().append("rect") .attr("class", "square") .attr("x", function(d) { return x(d.x)+2; }) .attr("y", function(d) { return y(d.y)-yinv(side); }) .attr("width", x(side)-2) .attr("height", yinv(side)-2) .style("fill", function(d) { return color(d.length); }) // the function is called every time the event occurs .on("mouseover", function (d) { d3.select(this).classed("highlight", true) }) .on("mouseout", function (d) { d3.select(this).classed("highlight", false) }); });
JavaScript
0.000001
@@ -25,17 +25,18 @@ , right: -5 +10 0, botto @@ -38,17 +38,18 @@ bottom: -5 +10 0, left: @@ -64,17 +64,17 @@ w = 6* -5 +3 0 + marg @@ -107,17 +107,17 @@ h = 9* -5 +3 0 + marg @@ -333,17 +333,17 @@ %5B0, w + -5 +3 0%5D);%0A %0Av @@ -405,17 +405,17 @@ e(%5Bh , - -5 +3 0%5D);%0A %0Av @@ -2406,24 +2406,477 @@ %7D);%0A%09 +%0A%0A%09 svg.append(%22text%22)%0A .attr(%22transform%22, %22rotate(-90)%22)%0A .attr(%22y%22, 0-margin.left*0.8)%0A .attr(%22x%22,0-(h/2)+10 )%0A .attr(%22dy%22, %221em%22)%0A .style(%22text-anchor%22, %22middle%22)%0A .text(%22Hail Size (inch)%22);%0A %0Asvg.append(%22text%22) // text label for the x axis%0A .attr(%22x%22, 0 + (w/2)+15)%0A .attr(%22y%22, 0 + h + margin.bottom*0.35 )%0A .style(%22text-anchor%22, %22middle%22)%0A .text(%22Scale (F)%22);%0A%09 %0A%09 %0A%09 %0A%7D) @@ -2873,12 +2873,13 @@ %0A%09 %0A%7D);%0A +%0A
e30fc1ee81ef557b00eca6749446e42efebc51fa
Remove referenced talk from related talks
lib/routes/talk.js
lib/routes/talk.js
var util = require('util'); var slug = require('slug'); var uuid = require('uuid'); var request = require('request'); var async = require('async'); var config = require('../../config.json'); var talks = require('libtlks').talk; /** * Route /search * @param req HTTP Request object * @param req HTTP Response object */ exports.search = function(req, res) { "use strict"; var q = req.query.q; var user = req.session.user; var context = { title: "Tech talks by '" + q + "'" + " | tlks.io", description: "Tech talks by '" + q + "'" + " | tlks.io", user: user, q: q, talks: [] }; var url = config.elasticsearch + '/tlksio/talk/_search?q=' + q; request.get({ url: url, method: 'GET', json: true }, function(error, response, body) { if (error) { context.message = util.inspect(err); res.status(500).render("500", context); } var hits = body.hits.hits; async.map(hits, function(el, callback) { var obj = el._source; obj.tags = obj.tags.split(',').map(function(el) { return el.trim(); }); talks.getBySlug(config.mongodb, obj.slug, function(err, talks) { if (err) { context.message = util.inspect(err); res.status(500).render("500", context); } callback(null, talks[0]); }); }, function(err, results) { if (err) { context.message = util.inspect(err); res.status(500).render("500", context); } context.talks = results; res.render("search", context); }); }); }; /** * Route /talk/play/:id * @param req HTTP Request object * @param res HTTP Response object */ exports.play = function(req, res) { "use strict"; var slug = req.params.slug; talks.play(config.mongodb, slug, function(err, talk) { if (err) { var context = { message: util.inspect(err) }; res.status(500).render("500", context); } var url = 'https://www.youtube.com/watch?v=' + talk.code; res.redirect(url); }); }; /** * Route /talk/upvote/:id * @param req HTTP Request object * @param res HTTP Response object */ exports.upvote = function(req, res) { "user strict"; var id = req.params.id; var user = req.session.user; if (user === undefined) { res.status(401).send("401").end(); } else { var userid = user.id; talks.upvote(config.mongodb, id, userid, function(err, updated) { if (err) { var context = { message: util.inspect(err) }; res.status(500).render("500", context); } var result = { "result": updated ? true : false }; res.send(result); }); } }; /** * Route /talk/favorite/:id * @param req HTTP Request object * @param res HTTP Response object */ exports.favorite = function(req, res) { "user strict"; var id = req.params.id; var user = req.session.user; if (user === undefined) { res.status(401).send("401").end(); } else { var userid = user.id; talks.favorite(config.mongodb, id, userid, function(err, updated) { if (err) { var context = { message: util.inspect(err) }; res.status(500).render("500", context); } var result = { "result": updated ? true : false }; res.send(result); }); } }; /** * Route /talk/unfavorite/:id * @param req HTTP Request object * @param res HTTP Response object */ exports.unfavorite = function(req, res) { "user strict"; var id = req.params.id; var user = req.session.user; if (user === undefined) { res.status(401).send("401").end(); } else { var userid = user.id; talks.unfavorite(config.mongodb, id, userid, function(err, updated) { if (err) { var context = { message: util.inspect(err) }; res.status(500).render("500", context); } var result = { "result": updated ? true : false }; res.send(result); }); } }; /** * Route /talk/:slug * @param req HTTP Request object * @param res HTTP Response object */ exports.talk = function(req, res) { "use strict"; var slug = req.params.slug; var user = req.session.user; var context = { user: user }; talks.getBySlug(config.mongodb, slug, function(err, docs) { var talk = docs[0]; if (err) { context.message = util.inspect(err); res.status(500).render("500", context); } if (talk) { context.talk = talk; context.title = talk.title + " | tlks.io"; context.description = talk.description.substring(0,200); talks.related(config.mongodb, talk.tags, 5, function(err, docs) { if (err) { context.message = util.inspect(err); res.status(500).render("500", context); } context.related = docs; res.render("talk", context); }); } else { res.status(404).render("404", context); } }); }; /** * Route /add * @param req HTTP Request object * @param res HTTP Response object */ exports.add = function(req, res) { "use strict"; var user = req.session.user; if (user === undefined) { res.status(401).send("401").end(); } else { var context = { title: "tlks.io : Add a new talk", user: user }; res.render('add', context); } }; /** * Route /save * @param req HTTP Request object * @param res HTTP Response object */ exports.save = function(req, res) { "use strict"; // user var user = req.session.user; if (user === undefined) { res.status(401).send("401").end(); } else { // talk var talk = { id: uuid.v1(), code: req.body.code, title: req.body.title, slug: slug(req.body.title).toLowerCase(), description: req.body.description, author: { id: user.id, username: user.username, avatar: user.avatar }, "viewCount": 0, "voteCount": 0, "votes": [], "favoriteCount": 0, "favorites": [], "tags": req.body.tags.split(',').map(function(el) { return el.trim().toLowerCase(); }), "created": Date.now(), "updated": Date.now() }; // create talk talks.createTalk(config.mongodb, talk, function(err, talk) { if (err) { var context = { message: util.inspect(err) }; res.status(500).render("500", context); } // render res.redirect('/'); }); } };
JavaScript
0
@@ -5265,24 +5265,33 @@ fig.mongodb, + talk.id, talk.tags,
5d7ae30662f15195ea0831808a93eb4d3c90551b
Test if resp isPlainObject and replace this.model with ridge/model if it is default value of Backbone.Model.
collection.js
collection.js
module.exports = Backbone.Collection.extend({ constructor: function(attributes, options) { Backbone.Collection.apply(this, arguments); if(!this.model) this.model = require('ridge/model'); return this; }, parse: function(resp) { if(_.isObject(resp)) { _.extend(this, _.pick(resp, 'totalCount', 'perPage')); return _.find(resp, _.isArray); } return resp; } });
JavaScript
0
@@ -141,9 +141,8 @@ %09if( -! this @@ -147,17 +147,37 @@ is.model -) + === Backbone.Model) %0A%09%09%09this @@ -264,16 +264,21 @@ %09if(_.is +Plain Object(r
69b6f27adbbd2cbd57edf78bdbf6bcbdb3ae2508
Attach mousedown to holder div, not document
colorwheel.js
colorwheel.js
"use strict"; class ColorWheel { constructor(id, size) { this.radius = size / 2; this.ringsize = size / 10; this.color = 0; this.length = Math.sqrt(2 * Math.pow(this.radius - this.ringsize, 2)); this.half = this.length / 2; this.can = $('<canvas>').attr({ width: size, height: size }); this.ctx = this.can.get(0).getContext('2d'); this.outer = $('<div/>').addClass('colorwheel-outer').css({ width: this.ringsize, height: this.ringsize }); this.inner = $('<div/>').addClass('colorwheel-inner'); this.holder = $('<div/>').attr('id', id).append(this.outer).append(this.inner).append(this.can); this.x = this.y = this.radius; this.renderInner(); this.setColor(this.color * (Math.PI / 180)); this.inner.css({ left: this.can.position().left + this.x - 5, top: this.can.position().top + this.y - 5 }); this.focusOut = false, this.focusIn = false; this.renderOuter(); this.renderInner(); var _this = this; $(document).on('mousedown', function (evt) { evt.preventDefault(); var offset = _this.getRelativePos(_this.can, evt); var dist = Math.sqrt(Math.pow(_this.x - offset.x, 2) + Math.pow(_this.y - offset.y, 2)); if (dist < _this.radius && dist > _this.radius - _this.ringsize) { _this.focusOut = true; _this.updateOuter(evt); } else if (dist < _this.radius - _this.ringsize) { _this.focusIn = true; _this.updateInner(evt); } }); $(document).on('mouseup', function (evt) { _this.focusOut = _this.focusIn = false; }).on('mousemove', function (evt) { if (_this.focusOut) { _this.updateOuter(evt); } else if (_this.focusIn) { _this.updateInner(evt); } }); $('body').append(this.holder); } getColor() { var x = this.inner.offset().left - this.can.offset().left + 5; var y = this.inner.offset().top - this.can.offset().top + 5; var c = this.ctx.getImageData(x, y, 1, 1).data; return { 'r': c[0], 'g': c[1], 'b': c[2] }; } setColor(angle) { var middle = this.radius - ((this.ringsize) / 2); this.outer.css({ left: Math.cos(angle) * middle + this.can.position().left + this.x - (this.ringsize / 2) - 2, top: Math.sin(angle) * middle + this.can.position().top + this.y - (this.ringsize / 2) - 2 }); } renderOuter() { for (var i = 0; i < 360; i++) { this.ctx.beginPath(); this.ctx.fillStyle = 'hsl(' + i + ', 100%, 50%)'; this.ctx.moveTo(this.x, this.y); this.ctx.arc(this.x, this.y, this.radius, (i - 2) * (Math.PI / 180), (i * (Math.PI / 180)), false); this.ctx.lineTo(this.x, this.y); this.ctx.fill(); } //Draw white to hide the center area this.ctx.beginPath(); this.ctx.fillStyle = 'white'; this.ctx.moveTo(this.x, this.y); this.ctx.arc(this.x, this.y, this.radius - this.ringsize, 0, 2 * Math.PI, false); this.ctx.fill(); } renderInner() { this.ctx.lineWidth = 1; this.ctx.strokeRect(this.x - this.half + 2, this.y - this.half + 2, this.length - 2, this.length - 2); for (var j = 0; j < 5; j++) { for (var i = 0; i < 100; i++) { var line = this.ctx.createLinearGradient( this.x - this.half + 2, (this.y - this.half) + 2 + ((i * (this.length - 3)) / 100), (this.x + this.half), (this.y - this.half) + 2 + ((i * (this.length - 3)) / 100) + 3 ) var sat = 50 - (i / 2) line.addColorStop(0, 'hsl(' + this.color + ',' + 0 + '%,' + (100 - i) + '%)'); line.addColorStop(.5, 'hsl(' + this.color + ',' + 100 + '%,' + sat + '%)'); line.addColorStop(1, 'hsl(' + this.color + ',' + 100 + '%,' + sat + '%)'); this.ctx.fillStyle = line; this.ctx.fillRect( this.x - this.half + 2, (this.y - this.half) + 2 + ((i * (this.length - 3)) / 100), this.length - 2, (this.length - 2) / 100 ); } }; } updateInner(evt) { var offset = this.getRelativePos(this.can, evt); var xDiff = Math.abs(this.x - offset.x); var yDiff = Math.abs(this.y - offset.y); var dist = Math.sqrt(Math.pow(this.x - offset.x, 2) + Math.pow(this.y - offset.y, 2)); if (dist < this.radius - this.ringsize && xDiff < this.half && yDiff < this.half) { this.inner.css({ left: this.can.position().left + offset.x - 5, top: this.can.position().top + offset.y - 5 }); } } updateOuter(evt) { var offset = this.getRelativePos(this.can, evt); var rawAngle = Math.atan2(offset.y - this.y, offset.x - this.x), angle = rawAngle * 180 / Math.PI; if (rawAngle < 0) { angle = 360 - (angle * -1); } this.setColor(rawAngle); this.color = Math.round(angle); this.renderInner(); } getRelativePos(element, evt) { var parentOffset = $(element).offset(); var eX = evt.pageX - parentOffset.left; var eY = evt.pageY - parentOffset.top; return { x: eX, y: eY }; } }
JavaScript
0.000002
@@ -1158,32 +1158,35 @@ ;%0A $( -document +this.holder ).on('moused @@ -5745,9 +5745,8 @@ %0A %7D%0A%7D -%0A
18bf47de3a015360ca90bb2128aaab60ab1e1c10
refactor compat handling case
node/endpoint-handler.js
node/endpoint-handler.js
// Copyright (c) 2015 Uber Technologies, Inc. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var parallel = require('run-parallel'); var TypedError = require('error/typed'); var util = require('util'); var EndpointAlreadyDefinedError = TypedError({ type: 'endpoint-already-defined', message: 'endpoint {endpoint} already defined on service {service}', service: null, endpoint: null, oldHandler: null, newHandler: null }); var InvalidHandlerError = TypedError({ type: 'invalid-handler', message: 'invalid handler function' }); function TChannelEndpointHandler(serviceName) { if (!(this instanceof TChannelEndpointHandler)) { return new TChannelEndpointHandler(serviceName); } var self = this; self.serviceName = serviceName; self.endpoints = Object.create(null); self.type = null; } TChannelEndpointHandler.prototype.register = function register(name, handler) { var self = this; if (self.endpoints[name] !== undefined) { throw EndpointAlreadyDefinedError({ service: self.serviceName, endpoint: name, oldHandler: self.endpoints[name], newHandler: handler }); } if (typeof handler !== 'function') { throw InvalidHandlerError(); } self.endpoints[name] = handler; return handler; }; TChannelEndpointHandler.prototype.handleRequest = function handleRequest(req, res) { var self = this; // TODO: waterfall req.arg1.onValueReady(function arg1Ready(err, arg1) { if (err) throw err; // TODO: protocol error, respond with error frame handleArg1(arg1); }); function handleArg1(arg1) { var name = String(arg1); var handler = self.endpoints[name]; if (!handler) { res.sendError('BadRequest', util.format( 'no such endpoint service=%j endpoint=%j', req.service, name)); } else if (handler.canStream) { handler(req, res); } else { parallel({ arg2: req.arg2.onValueReady, arg3: req.arg3.onValueReady }, function argsDone(err, args) { if (err) throw err; // TODO: protocol error, respond with error frame else handler(req, res, args.arg2, args.arg3); }); } } }; module.exports = TChannelEndpointHandler;
JavaScript
0.000008
@@ -3180,16 +3180,46 @@ %7D, + argsDone);%0A %7D%0A%0A functio @@ -3250,36 +3250,32 @@ - if (err) throw err; @@ -3254,32 +3254,50 @@ if (err) + %7B%0A throw err; // T @@ -3358,16 +3358,145 @@ +%7D else %7B%0A compatHandle(handler, args);%0A %7D%0A %7D%0A%0A function compatHandle(handler, args) %7B%0A -else han @@ -3537,24 +3537,8 @@ 3);%0A - %7D);%0A
fde33beacc69febdcf3c531824ba9d59f21a4575
tidy up function
build/wrapper/wrapper.controller.js
build/wrapper/wrapper.controller.js
(function() { 'use strict'; angular .module('app.controllers') .controller('wrapper', wrapper); wrapper.$inject = ['fireBaseFactory', '$modal', '$state', 'SweetAlert']; function wrapper(fireBaseFactory, $modal, $state, SweetAlert) { /* jshint validthis: true */ var vm = this; /** * Bind the Menu to the wrapper controller */ vm.menu = fireBaseFactory.getMenu(); vm.status = fireBaseFactory.checkStatus(); vm.authModal = function() { var modalInstance = $modal.open({ templateUrl: 'wrapper/auth/auth.tpl.html', controller: 'authController', }); }; vm.logout = function() { fireBaseFactory.logout(); SweetAlert.swal("Logged Out", "You have now been logged out", "success"); $state.go('otherwise'); }; } })();
JavaScript
0.000017
@@ -413,42 +413,9 @@ %0A%0A%09%09 -vm.status = fireBaseFactory.checkS +s tatu @@ -586,16 +586,34 @@ %7D);%0A +%09%09 //status();%0A %09%09%7D;%0A%0A%09%09 @@ -745,16 +745,30 @@ cess%22);%0A +%09%09%09 status();%0A %09%09%09 $sta @@ -787,22 +787,95 @@ wise');%0A - %09%09%7D;%0A%0A +%09%09function status() %7B%0A%09%09%09vm.status = fireBaseFactory.checkStatus();%0A%09%09%7D%0A%0A %7D%0A%0A%7D
15c051b4032a3d13b08b4aaaad1b7b98d531a479
Allow partial collection name in white list
lib/storePlugin.js
lib/storePlugin.js
var QUERIES = {}, COLLECTIONS_WHITELIST = []; var errors = { 'access_denied': "403: access denied - only server-queries are allowed, collection: '{0}', query: '{2}'", 'unknown_name': "403: there is no such server-query, name: '{1}', collection: '{0}'", 'query_error': "403: there is an error inside server query, name: '{1}', collection: '{0}', params: '{3}', error: '{4}'" }; var once; module.exports = function (racer, whitelist){ if (whitelist && Array.isArray(whitelist)) { COLLECTIONS_WHITELIST = COLLECTIONS_WHITELIST.concat(whitelist); } if (once) return; racer.on('store', function(store){ store.shareClient.use('query', handleQuery); store.addServerQuery = function(collection, queryName, queryFunction){ QUERIES[collection + '.' + queryName] = queryFunction; }; racer.emit('serverQuery', store); }); once = true; }; function handleQuery(shareRequest, next) { var query, collection, session, queryName, queryParams, serverQuery; query = shareRequest.query; collection = shareRequest.collection; session = shareRequest.agent.connectSession; if (isIdsQuery(query)) return next(); if (COLLECTIONS_WHITELIST.indexOf(collection) >= 0) return next(); queryName = query['$queryName']; queryParams = query['$params'] || {}; if (!queryName) return next(err('access_denied')); var queryFunction = QUERIES[collection + '.' + queryName]; if (!queryFunction) return next(err('unknown_name')); try{ serverQuery = queryFunction(queryParams, session); } catch(e){ return next(err('query_error', e)); } if (isString(serverQuery)) return next(err('query_error', serverQuery)); shareRequest.query = serverQuery; return next(); function err(name, text){ return formatString( errors[name], collection, queryName, JSON.stringify(query), JSON.stringify(queryParams), String(text) ); } } function isIdsQuery(query){ var idQuery = query && query['_id']; var inQuery = query && query['_id'] && query['_id']['$in']; return oneField(query) && oneField(idQuery) && isArray(inQuery); } function isArray(obj){ return Array.isArray(obj); } function isString(obj){ return typeof obj === 'string' || obj instanceof String; } function oneField(obj){ if (!(obj instanceof Object)) return false; return Object.keys(obj).length === 1; } function formatString(str) { var args = arguments; return str.replace(/{(\d+)}/g, function(match, number) { return typeof args[+number+1] != 'undefined' ? args[+number+1]: match; }); }
JavaScript
0.004385
@@ -890,16 +890,261 @@ e;%0A%0A%7D;%0A%0A +function checkCollWhitelist(coll) %7B%0A var letPass = false;%0A %0A for (var i = 0; i %3C COLLECTIONS_WHITELIST.length; i++) %7B%0A if (coll.indexOf(COLLECTIONS_WHITELIST%5Bi%5D) %3E= 0) %7B%0A letPass = true;%0A break;%0A %7D%0A %7D%0A %0A return letPass;%0A%7D%0A%0A function @@ -1426,37 +1426,26 @@ if ( -COLLECTIONS_WHITELIST.indexOf +checkCollWhitelist (col @@ -1452,21 +1452,16 @@ lection) - %3E= 0 ) return
d61dd880bfe69ba987bc247f22b0d592743dce52
Load tasks from jStorage
scripts.js
scripts.js
$(document).ready(function() { var id = 0; if($.jStorage.get('tasks')) { console.log($.jStorage.get('tasks')); } $('.add').click(function() { add($('input').val()); $('input').val(''); save(); }); function add(value, _id) { if(!_id) _id = id; $('.main').append('<li class="' + _id + '">' + value + '</li>'); id++; } function save() { var tasks = {}; $('.main li').each(function(index, key) { tasks[$(key).attr('class')] = $(key).html(); }); $.jStorage.set('tasks', tasks); } }); function get() { server = new Object() comp1 = new Object() comp2 = new Object() $('#server ul').children().map(function() { server[$(this).attr('class')] = $(this).text() }); $('#comp1 ul').children().map(function() { comp1[$(this).attr('class')] = $(this).text() }); $('#comp2 ul').children().map(function() { comp2[$(this).attr('class')] = $(this).text() }); }
JavaScript
0.000001
@@ -75,19 +75,57 @@ %7B%0A%09%09 -console.log +for (var key in $.jStorage.get('tasks')) %7B%0A%09%09%09add ($.j @@ -144,18 +144,32 @@ 'tasks') -); +%5Bkey%5D, key);%0A%09%09%7D %0A%09%7D%0A%0A%09$(
0764ab4aebaa1c845afd8bdfbf88e55ad6afc3a3
Add `capturePayload` and `returnResults` helpers to the test-allows module (for capturing payload)
lib/test-allows.js
lib/test-allows.js
import { createAllowedTest } from './test-generators'; import { getList, createItem, fetchItem, updateItem } from './store-ops'; import { handleFailure } from './assert-promise'; function testUpdate(name, source, data, message) { return createAllowedTest( fetchItem.call(this, name, source) .then(function(item) { return updateItem(item, data); }, handleFailure("Failed to obtain model for updating")), name + " is updatable", name + " failed to be updated", message ); } function testDelete(name, source, message) { return createAllowedTest( fetchItem.call(this, name, source) .then(function(item) { if (item.get('currentState.stateName').match(/created/)) { item.transitionTo('saved'); } return item.destroyRecord(); }, handleFailure("Failed to obtain model for deleting")), name + " is deletable", name + " failed to be deleted", message ); } function testCreate(name, data, message) { return createAllowedTest( createItem.call(this, name, data), name + " is creatable", name + " failed to be created", message ); } function testList(name, message) { return createAllowedTest( getList.call(this, name), name + " is listable", name + " failed to be listed", message ); } function testGet(name, source, message) { return createAllowedTest( fetchItem.call(this, name, source), name + " is readable", name + " failed to be fetched", message ); } export { testList, testCreate, testGet, testUpdate, testDelete };
JavaScript
0
@@ -99,16 +99,26 @@ dateItem +, getStore %7D from @@ -183,16 +183,422 @@ mise';%0A%0A +function capturePayload(store, item, resultArray) %7B%0A var serializer = store.serializerFor(item);%0A serializer.reopen(%7B%0A extract: function(store, type, payload) %7B%0A resultArray.clear();%0A resultArray.unshift(payload);%0A return this._super.apply(this, arguments);%0A %7D%0A %7D);%0A%7D%0A%0Afunction returnResults(array) %7B%0A return function(result) %7B%0A array.unshift(result);%0A return array;%0A %7D;%0A%7D%0A%0A function @@ -632,32 +632,52 @@ ata, message) %7B%0A + var results = %5B%5D;%0A return createA @@ -748,32 +748,83 @@ unction(item) %7B%0A + capturePayload(item.store, item, results);%0A return u @@ -904,24 +904,61 @@ updating%22)) +%0A%0A .then(returnResults(results)) ,%0A name + @@ -1068,32 +1068,52 @@ rce, message) %7B%0A + var results = %5B%5D;%0A return createA @@ -1307,16 +1307,67 @@ %7D%0A + capturePayload(item.store, item, results);%0A @@ -1457,16 +1457,53 @@ eting%22)) +%0A%0A .then(returnResults(results)) ,%0A na @@ -1615,32 +1615,105 @@ ata, message) %7B%0A + var results = %5B%5D;%0A capturePayload(getStore(this.App), name, results);%0A return createA @@ -1761,16 +1761,52 @@ e, data) +%0A .then(returnResults(results)) ,%0A na @@ -1910,32 +1910,105 @@ ame, message) %7B%0A + var results = %5B%5D;%0A capturePayload(getStore(this.App), name, results);%0A return createA @@ -2047,16 +2047,52 @@ s, name) +%0A .then(returnResults(results)) ,%0A na @@ -2205,24 +2205,97 @@ message) %7B%0A + var results = %5B%5D;%0A capturePayload(getStore(this.App), name, results);%0A return cre @@ -2348,16 +2348,52 @@ source) +%0A .then(returnResults(results)) ,%0A na
18f6afe4458308dc4228e40428a60a452f08878d
fix some task copy issue
cabrini-server/controllers/tasks.js
cabrini-server/controllers/tasks.js
var express = require('express'); var router = express.Router(); var Task = require('../models/Task'); //Only get unassigned todo List of Org router.get('/organization/list/:id', function (req, res) { var orgID = req.param("id"); Task.find({ $and: [ { org_id: orgID }, { user_id: {$exists: false} } ] }, function (err, tasks) { if (err) throw err; res.send(JSON.stringify(tasks)); }); }); router.get('/user/list:id', function (req, res) { var userID = req.param("id"); Task.find({ user_id: userID }, function (err, tasks) { if (err) throw err; res.send(JSON.stringify(tasks)); }); }); router.post('/create', function (req, res) { var TaskData = req.body; var newTask = Task(TaskData); newTask.save(function (err) { if (err) throw err; res.send(JSON.stringify(newTask)); }); console.log(TaskData); }); router.post('/assign/:taskID/:userID', function (req, res) { var userID = req.param("userID"); var taskID = req.param("taskID"); Task.findOne({ _id: taskID }, function (err, taskTemplate) { if (taskTemplate) { objectIdDel(JSON.parse(JSON.stringify(taskTemplate))); taskTemplate.user_id = userID; taskTemplate.save(function (err) { if (err) throw err; res.send(JSON.stringify(taskTemplate)); }); } else { res.sendStatus(404); } }); }); var objectIdDel = function (copiedObjectWithId) { if (copiedObjectWithId != null && typeof (copiedObjectWithId) != 'string' && typeof (copiedObjectWithId) != 'number' && typeof (copiedObjectWithId) != 'boolean') { //for array length is defined however for objects length is undefined if (typeof (copiedObjectWithId.length) == 'undefined') { delete copiedObjectWithId._id; for (var key in copiedObjectWithId) { objectIdDel(copiedObjectWithId[key]); //recursive del calls on object elements } } else { for (var i = 0; i < copiedObjectWithId.length; i++) { objectIdDel(copiedObjectWithId[i]); //recursive del calls on array elements } } } } module.exports = router;
JavaScript
0.000075
@@ -1106,32 +1106,56 @@ late) %7B%0A +var copyTemplate = Task( objectIdDel(JSON @@ -1191,16 +1191,17 @@ plate))) +) ;%0A @@ -1194,36 +1194,36 @@ te))));%0A -task +copy Template.user_id @@ -1241,20 +1241,20 @@ -task +copy Template @@ -1332,36 +1332,36 @@ (JSON.stringify( -task +copy Template));%0A @@ -1744,24 +1744,17 @@ if ( -typeof ( +! copiedOb @@ -1775,24 +1775,8 @@ gth) - == 'undefined') %7B%0A @@ -2130,16 +2130,45 @@ %7D%0A %7D%0A + return copiedObjectWithId;%0A %7D%0Amodule
53bfc22123b860fdc530220cb9d00ab7909701d7
fix initial load of complaints
js/complaints/directives/Complaints.js
js/complaints/directives/Complaints.js
(function() { angular.module("mrgApp").directive('complaints', ['ComplaintsService', 'COMPLAINTS_SORTING_TYPES', function(ComplaintsService, COMPLAINTS_SORTING_TYPES) { return { restrict: 'E', replace: true, templateUrl: 'partials/complaints/directives/Complaints.html', link: function(scope) { scope.numPerPage = 10; scope.complaintsCurrentPage = 1; scope.complaintsSortingTypes = COMPLAINTS_SORTING_TYPES; scope.sortingType = COMPLAINTS_SORTING_TYPES.byGroundTime; scope.loadData = function() { ComplaintsService.getComplaintsByIndex((scope.complaintsCurrentPage - 1) * scope.numPerPage, scope.numPerPage).then(function(data) { scope.complaints = data.rows; scope.complaintsNoOfPages = Math.ceil(data.total_rows / scope.numPerPage); }, function(reason) { alert(reason); }); } scope.getComplaintsByFieldSorted = function (descendingSorting){ ComplaintsService.getComplaintsByFieldSorted(scope.sortingType, (scope.complaintsCurrentPage - 1) * scope.numPerPage, scope.numPerPage, descendingSorting).then(function(data) { scope.complaints = data.rows; scope.complaintsNoOfPages = Math.ceil(data.total_rows / scope.numPerPage); }, function(reason) { alert(reason); }); }; scope.deleteComplaint = function(complaint) { ComplaintsService.deleteComplaint(complaint) }; scope.$watch('complaintsCurrentPage', scope.loadData); } } }]); }());
JavaScript
0.000002
@@ -608,24 +608,27 @@ scope. -loadData +initialLoad = funct @@ -655,32 +655,20 @@ -ComplaintsServic +scop e.getCom @@ -680,363 +680,44 @@ tsBy -Index((scope.complaintsCurrentPage - 1) * scope.numPerPage, scope.numPerPage).then(function(data) %7B%0A scope.complaints = data.rows;%0A scope.complaintsNoOfPages = Math.ceil(data.total_rows / scope.numPerPage);%0A %7D, function(reason) %7B%0A alert(reason);%0A %7D +FieldSorted(scope.sortingType, false );%0A @@ -811,16 +811,29 @@ nction ( +sortingType, descendi @@ -901,38 +901,32 @@ tsByFieldSorted( -scope. sortingType, (sc @@ -1524,16 +1524,19 @@ ope. -loadData +initialLoad );%0A
2f8472b34f916696da8fa541b6e27437cd1d70d2
Extract passage proof reading errors
src/scripts/app/play/proofreadings/controller.js
src/scripts/app/play/proofreadings/controller.js
'use strict'; module.exports = /*@ngInject*/ function ProofreadingPlayCtrl( $scope, $state, ProofreadingService, RuleService, _ ) { $scope.id = $state.params.id; function error(e) { console.error(e); $state.go('index'); } function prepareProofreading(pf) { $scope.passageQuestions = {}; pf.replace(/{\+([^-]+)-([^|]+)\|([^}]+)}/g, function(key, plus, minus, ruleNumber) { $scope.passageQuestions[key] = { plus: plus, minus: minus, ruleNumber: ruleNumber }; pf = pf.replace(key, minus); }); var prepared = _.chain(pf.split(/\s/)) .filter(function removeNullWords(n) { return n !== ''; }) .map(function parseHangingPfQuestionsWithNoSpace(w) { _.each($scope.passageQuestions, function(v, key) { if (w !== key && w.indexOf(key) !== -1) { w = w.split(key).join(' ' + key).split(/\s/); } }); return w; }) .flatten() .map(function(w) { if ($scope.passageQuestions[w]) { var c = _.clone($scope.passageQuestions[w]); c.text = c.minus; c.responseText = c.text; return c; } else { return { text: w, responseText: w }; } }) .map(function trim(w) { w.text = w.text.trim(); w.responseText = w.responseText.trim(); return w; }) .value(); prepared = _.chain(prepared) .zip(_.map(_.range(prepared.length), function() { return { text: ' ', responseText: ' ' }; })) .flatten() .value(); return prepared; } $scope.obscure = function(key) { return btoa(key); }; $scope.ubObscure = function(o) { return atob(o); }; ProofreadingService.getProofreading($scope.id).then(function(pf) { pf.passage = prepareProofreading(pf.passage); console.log(pf.passage); $scope.pf = pf; }, error); };
JavaScript
0.999913
@@ -1014,38 +1014,107 @@ -if ($scope.passageQuestions%5Bw%5D +var passageQuestion = _.findWhere($scope.passageQuestions, %7Bminus: w%7D);%0A if (passageQuestion ) %7B%0A @@ -1139,23 +1139,16 @@ _.clone( -$scope. passageQ @@ -1158,12 +1158,8 @@ tion -s%5Bw%5D );%0A @@ -1220,16 +1220,42 @@ c.text;%0A + console.log(c);%0A @@ -2065,16 +2065,16 @@ f = pf;%0A - %7D, err @@ -2077,12 +2077,657 @@ error); +%0A%0A $scope.submitPassage = function(passage) %7B%0A function isValid(passageEntry) %7B%0A if (_.has(passageEntry, 'minus')) %7B%0A //A grammar entry%0A return passageEntry.responseText === passageEntry.plus;%0A %7D else %7B%0A //A regular word%0A return passageEntry.text === passageEntry.responseText;%0A %7D%0A %7D%0A var errors = %5B%5D;%0A _.each(passage, function(p) %7B%0A if (!isValid(p)) %7B%0A errors.push(p);%0A %7D%0A %7D);%0A if (errors.length %3E 1) %7B%0A showErrors(errors);%0A %7D else %7B%0A showNext();%0A %7D%0A %7D;%0A%0A function showErrors(errors) %7B%0A $scope.errors = errors;%0A %7D%0A%0A function showNext() %7B%0A%0A %7D %0A%7D;%0A
24c89a965d9954f9149300e4f8b9a18e24ab957a
debug button and text
lib/tools/Debug.js
lib/tools/Debug.js
/** * Created by apizzimenti on 5/19/16. */ "use strict"; /** * @author Anthony Pizzimenti * * @desc Provides an easy way to specify debugging within the Phaser game. * * @param game {object} Phaser game instance. * * @property game {game} Phaser game instance. * @property x {number} Middle of the Phaser game window. * @property y {number} Starting height to display debug information. * @property color {string} Hexadecimal color code. * @property on {boolean} Turns the debug information on and off. * * @class {object} Debug * @this Debug * @constructor */ function Debug (game) { this.game = game; this.x = this.game.width / 2; this.y = 20; this.color = "#FFF"; this.on = true; var graphics = game.add.graphics(0, 0), _this = this; } /** * @author Anthony Pizzimenti * * @desc Writes the current FPS to the game window. * * @this Debug */ Debug.prototype.fps = function () { if (this.on) { this.game.debug.text(this.game.time.fps, this.x, this.y, this.color); } }; /** * @author Anthony Pizzimenti * * @desc Writes the current mouse position to the game window. * * @param mouse {Mouse} Mouse object. * * @this Debug * * @see mouseTrack */ Debug.prototype.mousePos = function (mouse) { if (this.on) { this.game.debug.text(`${mouse.row}, ${mouse.col}`, this.x, this.y + 20, this.color); } }; /** * @author Anthony Pizzimenti * * @desc Displays debug information and bodies for one or more sprites. * * @param sprites {Player | Animal | Item} * * @this Debug */ Debug.prototype.sprite = function (sprites) { if (this.on) { var debugSprite = (sprite) => { try { var s = sprite.sprite; this.game.debug.body(s, "#FFFFFF", false); if (s.tile) { this.game.debug.body(s.tile.top, "#FF0000", false); } if (s.tile) { for (var tile in s.tile) { if (s.tile.hasOwnProperty(tile) && tile !== "top") { this.game.debug.body(s.tile[tile], "#FFDD00", false); } } } } catch (e) { console.warn(`${sprite.type} is not yet loaded`); } }; if (Array.isArray(sprites)) { for (var sprite of sprites) { debugSprite(sprite); } } else { debugSprite(sprites); } } }; /** * @author Anthony Pizzimenti * * @desc Displays blocked tiles' debug bodies. * * @param tiles {sprite[]} An array of tile sprites. * * @this Debug */ Debug.prototype.tiles = function (tiles) { if (this.on) { for (var i = 0; i < tiles.length; i++) { for (var j = 0; j < tiles[0].length; j++) { var tile = tiles[i][j]; if (tile.blocked) { this.game.debug.body(tiles[i][j], "#FFDD00", false); } } } } }; /** * @author Anthony Pizzimenti * * @desc Allows for future implementation of a _button on/off switch for displaying debug info. * * @this Debug * * @todo Implement buttons. */ Debug.prototype.switch = function () { this.on = !this.on; };
JavaScript
0.000001
@@ -713,19 +713,20 @@ is.on = -tru +fals e;%0A%0A @@ -788,16 +788,545 @@ this;%0A%0A + graphics.fixedToCamera = true;%0A graphics.lineStyle(1, 0xFFFFFF, 0);%0A graphics.beginFill(0, 0xFFFFFF, 0);%0A this.graphics = graphics;%0A%0A this.button = graphics.drawRect(20, 50, 62, 25);%0A this.button.inputEnabled = true;%0A this.button.input.useHandCursor = true;%0A%0A this.text = this.game.add.text(25, 50, %22debug%22, %7B%0A font: %22Courier%22,%0A fontSize: 20,%0A fill: %22white%22%0A %7D);%0A%0A this.text.fixedToCamera = true;%0A%0A this.button.events.onInputDown.add(() =%3E %7B%0A this._switch();%0A %7D);%0A %7D%0A%0A%0A/**%0A @@ -3165,9 +3165,9 @@ iles -' +%22 deb @@ -3770,49 +3770,33 @@ * @ -this Debug%0A *%0A * @todo Implement buttons. +private%0A *%0A * @this Debug %0A */ @@ -3813,16 +3813,17 @@ ototype. +_ switch =
3a08aab380592d194e58dc668b28d9228bd9691e
fix incorrect error name, remove data cloning
lib/transaction.js
lib/transaction.js
/** * `Transaction` dependencies */ var async = require('async'), redis = require('redis'), utils = require('./utils'), errors = require('waterline-errors'), present = utils.present, adapterErrors = errors.adapter; /** * Expose `Transaction` */ module.exports = Transaction; /** * A container object for executing redis commands, and * retrieve general information for key sets */ function Transaction() { this.config = {}; this.schema = null; this.connection = null; } /** * Overwrite config object with a new config object. * * @param {Object} config */ Transaction.prototype.configure = function(config) { this.config = utils.extend(this.config, config); }; /** * Register the `schema` with transaction * * @param {Object} schema */ Transaction.prototype.registerSchema = function(schema) { if(!this.schema) this.schema = schema; }; /** * Return the key name for an index * * @param {String} collection * @param {Number|String} key optional */ Transaction.prototype.indexKey = function(collection, index) { return 'waterline:' + collection + ':' + index; }; /** * Return the key name for a record * * @param {String} collection * @param {String} index * @param {String} key */ Transaction.prototype.recordKey = function(collection, index, key) { return 'waterline:' + collection + ':' + index + ':' + key; }; /** * Return the key name used for collection's meta data * * @param {String} collection * @return {String} */ Transaction.prototype.metaKey = function(collection) { return 'waterline:' + collection + ':_meta'; }; /** * Sanitize a key removing any spaces or reserved charaters * * @param {String} str */ Transaction.prototype.sanitize = function(str) { return typeof str === 'string' ? str.replace(/\s+/g, '_') : str; }; /** * Connect to the redis instance * * @param {Function} callback */ Transaction.prototype.connect = function(callback) { var config = this.config; if(this.connection !== null) return callback(); this.connection = config.password !== null ? redis.createClient(config.port, config.host, config.options).auth(config.password) : redis.createClient(config.port, config.host, config.options); this.connection.once('ready', callback); }; /** * Disconnect from the redis instance */ Transaction.prototype.disconnect = function() { this.connection.quit(); this.connection = null; }; /** * Execute `callback` in the context of `this.connection` * `done` is called after transaction is completed, passing any arguments * passed to the `this.exec` callback * * @param {Function} done called when transaction is complete * @param {Function} callback called on connection */ Transaction.prototype.exec = function(done, callback) { var self = this; this.connect(function() { callback.call(self, function() { self.disconnect(); return done.apply(null, arguments); }); }); }; /** * Check to ensure the data is unique to the schema, * connection to redis should already be established. * * @param {String} collection * @param {Object} data * @param {Function} callback */ Transaction.prototype.isUnique = function(collection, data, callback) { var error = null, unique = this.schema.unique(collection); // Ensure every key is unique async.every(unique, exists.bind(this), function(unique) { callback(error, unique); }); function exists(key, callback) { var index = this.indexKey(collection, key), record = this.recordKey(collection, key, this.sanitize(data[key])); this.connection.sismember(index, record, function(err, found) { if(err) error = err; callback(!found); }); } }; /** * Ensure no auto increment keys are set, and add them. * * @param {String} collection * @param {Object} data * @param {Function} callback */ Transaction.prototype.setIncrements = function(collection, data, callback) { var i, len, redis = this.connection, metaKey = this.metaKey(collection), primary = this.schema.primary(collection), increments = this.schema.increments(collection); // Clone data data = utils.extend(data); if(!present(data[primary]) && !~increments.indexOf(primary)) { return callback(errors.primaryKeyMissing); } for(i = 0, len = increments.length; i < len; i = i + 1) { if(present(data[increments[i]])) { return callback(adapterErrors.invalidAutoIncrement); } } redis.get(metaKey, function(err, meta) { if(err) return callback(err); // Support for changed schema without `flushdb` meta = utils.extend(defaultMeta(), JSON.parse(meta)); for(i = 0, len = increments.length; i < len; i = i + 1) { data[increments[i]] = meta.increments[increments[i]]++; } redis.set(metaKey, JSON.stringify(meta), function(err) { if(err) return callback(err); return callback(null, data); }); }); function defaultMeta() { var attributes = {}; for(i = 0, len = increments.length; i < len; i = i + 1) { attributes[increments[i]] = 1; } return { increments: attributes }; } };
JavaScript
0.000003
@@ -4137,54 +4137,8 @@ );%0A%0A - // Clone data%0A data = utils.extend(data);%0A%0A if @@ -4214,25 +4214,32 @@ rn callback( -e +adapterE rrors.primar
c57c31d5d50e76e0ca73d816b163900af37dd3ea
update expression example
src/expression/js/main.js
src/expression/js/main.js
function ExpressionsCtrl($scope) { $scope.attributes = {}; $scope.expressions = []; $scope.x=0; $scope.addAttribute = function() { console.group("AddAttribute"); console.log("%s", $scope.attrName); console.log("%s", $scope.attrValue); $scope[$scope.attrName] = $scope.attrValue; if (Number($scope.attrValue)!== NaN) { console.log("Number"); $scope.attributes[$scope.attrName] = Number($scope.attrValue); $scope[$scope.attrName] = Number($scope.attrValue); } else { console.log("String"); $scope.attributes[$scope.attrName] = $scope.attrValue; } console.groupEnd(); }; $scope.removeAttribute = function() { delete $scope[$scope.attrName]; delete $scope.attributes[$scope.attrName]; }; $scope.addExpression = function(exp) { console.info(exp); var value = $scope.$eval(exp); var obj = { exp: exp, value: value }; $scope.expressions.push(obj); }; }
JavaScript
0.000002
@@ -292,16 +292,23 @@ e;%0A%09%09if +(!isNaN (Number( @@ -328,15 +328,9 @@ lue) -!== NaN +) ) %7B%0A
e6d8fae2cbfa2c8bc87cad1ae87a2cb8f317607d
Modify insert-eqations repository regex to accept colon
tools/remark/plugins/remark-img-equations-src-urls/lib/git.js
tools/remark/plugins/remark-img-equations-src-urls/lib/git.js
'use strict'; // MODULES // var debug = require( 'debug' )( 'remark-img-equations-src-urls:git' ); var exec = require( 'child_process' ).execSync; // VARIABLES // // Regular expression to extract a repository slug: var RE = /(?:.+github\.com\/)(.+)\.(?:.+)/; // MAIN // /** * Returns git repository info. * * @private * @returns {Object} repository info */ function git() { var origin; var hslug; var rslug; var opts; var hash; var dir; var cmd; var out; // Get the local git repository path and remove any newline characters: dir = exec( 'git rev-parse --show-toplevel' ); dir = dir.toString().match( /(.+)/ )[ 1 ]; debug( 'Local repository directory: %s', dir ); opts = { 'cwd': dir }; // Get the remote origin: cmd = 'git config --get remote.origin.url'; out = exec( cmd, opts ); origin = out.toString(); debug( 'Remote origin: %s', origin ); // Extract the repository slug: rslug = origin.match( RE )[ 1 ]; debug( 'Repository slug: %s', rslug ); // Get the current Git hash and remove any newline characters: cmd = 'git rev-parse HEAD'; out = exec( cmd, opts ); hash = out.toString().match( /(.+)/ )[ 1 ]; debug( 'Current hash: %s', hash ); hslug = rslug+'/'+hash; debug( 'Hash slug: %s', hslug ); out = { 'dir': dir, 'slug': rslug, 'hash': hash, 'origin': origin, 'hslug': hslug }; return out; } // end FUNCTION git() // EXPORTS // module.exports = git();
JavaScript
0
@@ -243,10 +243,16 @@ .com -%5C/ +)(?:%5C/%7C: )(.+
2b9799c2848f4b35931ad6b336b10eba44d13999
Remove a commented out file
lib/ui-registry.js
lib/ui-registry.js
'use babel' import {CompositeDisposable} from 'atom' import Validate from './validate' export default class UIRegistry { constructor() { this.subscriptions = new CompositeDisposable() this.providers = new Map() } //add(provider, editors) { add(key, provider) { if (!this.providers.has(key)) { Validate.ui(key) this.subscriptions.add(provider) this.providers.set(key, provider) } } delete(provider) { this.providers.delete(provider) } notify(messages) { this.providers.forEach(function(provider) { provider.update(messages) }) } dispose() { this.providers.clear() this.subscriptions.dispose() } }
JavaScript
0
@@ -224,37 +224,8 @@ %7D%0A - //add(provider, editors) %7B%0A ad
62ad09b9e0d6aff0540e83c2815a39f2c6a5b0b7
Remove command to write to fs
lib/validateKey.js
lib/validateKey.js
var _ = require('lodash'); var moment = require('moment'); var Promise = require('bluebird'); var request = Promise.promisifyAll(require('request')); var debug = require('debug')('validate'); var os = require('os'); var nconf = require('nconf'); var cheerio = require('cheerio'); var fs = require('fs'); var mongo = require('./mongo'); var utils = require('./utils'); var error = require('./error'); var SPAM = "Personalisation Algorithm are a collective issue, and only collectively they can be addressed; today I am joining https://facebook.tracking.exposed and this technical message is necessary to link my user to this key: "; var M = "link my user to this key: "; function validateKey(req) { var permalink = req.body.permalink; var publicKey = req.body.publicKey; console.log("Looking for publicKey %s in %s", publicKey, permalink); return request .getAsync({ 'url': permalink, 'headers': { 'User-Agent': "User-Agent: curl/7.47.0" } }) .then(function(page) { var mndx = page.body.indexOf(publicKey); fs.writeFileSync('/home/vrde/repos/ESCVI/page.html', page.body); if(mndx === -1) { return utils .shmFileWrite('MatchError', page.body) .return({ 'json': { "results": "Error", "reason": "match not found" }}); } else { console.log("Match successful, procedding with NaCl import"); var $ = cheerio.load(page.body); console.log("element loaded"); var startUrl = page.body.indexOf("https://www.facebook.com/people/"); var endUrl = page.body.indexOf('"', startUrl); var url = page.body.slice(startUrl, endUrl); console.log(url); var userId = url.split('?')[0].split('/').pop(); console.log(userId); // Write in the Database the userId and its publicKey! /* * For whatever reason this doesn't work :( var userId = $('.userContentWrapper').find('a[href^="https://www.facebook.com/people/"]') .attr('href') .split('?')[0] .split('/').pop(); */ } }) .catch(function(a, b) { console.log("Something went bad"); console.log(a); console.log(b); return { 'json': { "results": "Error", "reason": "page.body โˆ‰ expectation" }}; }); }; module.exports = { validateKey: validateKey };
JavaScript
0.000001
@@ -1111,85 +1111,8 @@ y);%0A - fs.writeFileSync('/home/vrde/repos/ESCVI/page.html', page.body);%0A
0b0f296642d5a9bec1eaadfee20966a9c05e37b8
remove debugging
lib/vm/runBlock.js
lib/vm/runBlock.js
var async = require('async'), bignum = require('bignum'), Bloom = require('../bloom.js'), Account = require('../account.js'), rlp = require('rlp'), Trie = require('merkle-patricia-tree'); /** * process the transaction in a block and pays the miners * @param {Block} block the block we are processing * @param {Buffer} root the state root which to start from * @param {Boolean} [gen=false] whether to generate * @param {Function} cb the callback which is given an error string */ module.exports = function(block, root, gen, cb) { if (arguments.length === 3) { cb = gen; gen = false; } var trie = this.trie, self = this, bloom = new Bloom(), receiptTrie = new Trie(), minerReward = bignum('1500000000000000000'), uncleReward = bignum('1406250000000000000'), nephewReward = bignum('46875000000000000'), r = bignum(0), account; this.block = block; trie.checkpoint(); if (root) trie.root = root; /** * Processes all of the transaction in the block * @method processTransaction * @param {Function} cb the callback is given error if there are any */ function processTransactions(cb) { var gasUsed = bignum(0), //the totally amount of gas used processing this block results, i = 0; async.eachSeries(block.transactions, function(tx, cb2) { async.series([ function(cb3) { //run the tx through the VM self.runTx(tx, block, function(err, r) { results = r; gasUsed = gasUsed.add(results.gasUsed); //is the miner also the sender? if (block.header.coinbase.toString('hex') === tx.getSenderAddress().toString('hex')) { account = results.fromAccount; } //is the miner also the receiver? if (block.header.coinbase.toString('hex') === tx.to.toString('hex')) { account = results.toAccount; } //add the amount spent on gas to the miner's account account.balance = bignum .fromBuffer(account.balance) .add(results.amountSpent); //bitwise OR the blooms together bloom.or(r.bloom); cb3(err); }); }, function(cb3) { //save the miner's account trie.put(block.header.coinbase, account.serialize(), function(err) { if (gen) { block.header.bloom = bloom; block.transactionReceipts[i].state = trie.root; } cb3(err); }); }, //create the tx receipt function(cb3) { var txLogs = results.vm.logs ? results.vm.logs : []; var tr = [trie.root, gasUsed.toBuffer(), results.bloom.bitvector, txLogs]; var utils = require('../utils.js'); console.log(utils.baToJSON(tr)); receiptTrie.put(rlp.encode(i), rlp.encode(tr)); i++; cb3(); } ], cb2); }, cb); } //get the miners account function getMinerAccount(cb) { trie.get(block.header.coinbase, function(err, rawAccount) { account = new Account(rawAccount); cb(err); }); } //give the uncles thiers payout function payUncles(cb) { //iterate over the uncles async.each(block.uncleHeaders, function(uncle, cb2) { //acculmulate the nephewReward r = r.add(nephewReward); //get the miners account if (uncle.coinbase.toString('hex') === block.header.coinbase.toString('hex')) { account.balance = bignum.fromBuffer(account.balance) .add(uncleReward) .toBuffer(); cb2(); } else { trie.get(uncle.coinbase, function(err, rawAccount) { if (!err) { var uncleAccount = new Account(rawAccount); uncleAccount.balance = bignum.fromBuffer(uncleAccount.balance) .add(uncleReward) .toBuffer(); trie.put(uncle.coinbase, uncleAccount.serialize(), cb2); } else { cb2(err); } }); } }, cb); } //gives the mine the block reward and saves the miners account function saveMinerAccount(cb) { account.balance = bignum .fromBuffer(account.balance) .add(minerReward) .add(r) //add the accumlated nephewReward .toBuffer(); trie.put(block.header.coinbase, account.serialize(), cb); } //run everything async.series([ getMinerAccount, processTransactions, payUncles, saveMinerAccount ], function(err) { if (!err) { if (receiptTrie.root && receiptTrie.root.toString('hex') !== block.header.receiptTrie.toString('hex')) { err = 'invalid receiptTrie'; } else if (bloom.bitvector.toString('hex') !== block.header.bloom.toString('hex')) { err = 'invalid bloom'; } else if (trie.root.toString('hex') !== block.header.stateRoot.toString('hex')) { err = 'invalid block stateRoot'; } } if (err) { // trie.revert(); // cb(err); console.log('ours:' + trie.root.toString('hex')); console.log('thiers:' + block.header.stateRoot.toString('hex')); trie.commit(cb.bind(cb, err)); } else { if (gen) { block.header.stateRoot = trie.root; } trie.commit(cb); } }); };
JavaScript
0.000065
@@ -2786,98 +2786,8 @@ %5D;%0A%0A - var utils = require('../utils.js');%0A console.log(utils.baToJSON(tr));%0A%0A @@ -4934,19 +4934,16 @@ %7B%0A - // trie.re @@ -4955,19 +4955,16 @@ );%0A - // cb(err) @@ -4962,32 +4962,35 @@ cb(err);%0A + // console.log('ou @@ -5029,16 +5029,19 @@ );%0A + // console @@ -5099,24 +5099,27 @@ ex'));%0A + // trie.commit
c3c04b1a577bf4cdaddd1df8e133f82d4f4ba1b1
save frozen as global variable
src/frozen_fields/js21.js
src/frozen_fields/js21.js
function onFrozen(elem, idx) { pycmd("frozen:" + idx); } var hotkey_toggle_field = "%s"; var src_frozen = "%s"; var src_unfrozen = "%s"; function setFrozenFields(fields, frozen) { var txt = ""; for (var i=0; i<fields.length; i++) { var n = fields[i][0]; var f = fields[i][1]; if (!f) { f = "<br>"; } // ----------- mod start ----------- txt += "<tr><td style='width:28px'></td><td class=fname>"+n+"</td></tr><tr>"; if (frozen[i]) { txt += "<td style='width:28px'><div id=i"+i+" title='Unfreeze field ("+hotkey_toggle_field+")' onclick='onFrozen(this, "+i+");'><img src='"+src_frozen+"'/></div></td>"; } else { txt += "<td style='width:28px'><div id=i"+i+" title='Freeze field ("+hotkey_toggle_field+")' onclick='onFrozen(this, "+i+");'><img src='"+src_unfrozen+"'/></div></td>"; } txt += "<td width=100%%>" // ----------- mod end ----------- txt += "<div id=f"+i+" onkeydown='onKey(window.event);' oninput='onInput()' onmouseup='onKey(window.event);'"; txt += " onfocus='onFocus(this);' onblur='onBlur();' class='field clearfix' "; txt += "ondragover='onDragOver(this);' onpaste='onPaste(this);' "; txt += "oncopy='onCutOrCopy(this);' oncut='onCutOrCopy(this);' "; txt += "contentEditable=true class=field>"+f+"</div>"; // ----------- mod start ----------- txt += "</td>" // ----------- mod end ----------- txt += "</td></tr>"; } $("#fields").html("<table cellpadding=0 width=100%% style='table-layout: fixed;'>" + txt + "</table>"); maybeDisableButtons(); }
JavaScript
0.000001
@@ -52,16 +52,87 @@ + idx);%0A + wasFrozen = frozenFields%5Bidx%5D;%0A frozenFields%5Bidx%5D = !wasFrozen;%0A %7D%0A%0Avar h @@ -207,16 +207,42 @@ %22%25s%22;%0A%0A +var frozenFields = null;%0A%0A function @@ -272,24 +272,51 @@ , frozen) %7B%0A + frozenFields = frozen;%0A var txt
6074106b1c579966ab7af8730081a15d73229b59
refactor ractive & touch events
static/js/main.js
static/js/main.js
/* * Selfi data format * _id string * about string * isActive boolean * name string * picture url * uploaded timestamp */ document.addEventListener('DOMContentLoaded', function () { var x = new Backend.Api('http://selfies.tuvok.nl/api'), ractive; // get all selfies x.get('/selfies/12', { success: function(data, status, xhr){ console.info('Got ' + data.length + ' selfies!'); ractive = new Ractive({ el: '#selfies', template: '#selfiestpl', data: { selfies: data, getSrc: function(selfie){ return selfie.picture + "?" + selfie._id; } } }); ractive.on('flip', function(arg){ arg.node.classList.toggle('flipped'); }); } }); document.querySelector('.title').addEventListener('click', function(e){ document.querySelector('.wrapper').classList.toggle('open-sesame'); }, false); });
JavaScript
0
@@ -257,160 +257,10 @@ i'), - ractive;%0A%0A%09// get all selfies%0A%09x.get('/selfies/12', %7B%0A%09%09success: function(data, status, xhr)%7B%0A%09%09%09console.info('Got ' + data.length + ' selfies!');%0A%09%09%09 +%0A%09 ract @@ -359,20 +359,18 @@ elfies: -data +%7B%7D ,%0A%09%09%09 %09 @@ -468,17 +468,214 @@ %09%09%7D);%0A%0A%09 -%09 +// get all selfies%0A%09x.get('/selfies/12', %7B%0A%09%09success: function(data, status, xhr)%7B%0A%09%09%09console.info('Got ' + data.length + ' selfies!');%0A%09%09%09ractive.set('selfies', data);%0A%09%09%7D%0A%09%7D);%0A%0A%09// EVENT handling%0A %09ractive @@ -701,18 +701,16 @@ n(arg)%7B%0A -%09%09 %09%09arg.no @@ -745,24 +745,123 @@ ');%0A -%09%09 %09%7D);%0A -%09%09%7D%0A%09%7D +%0A%09var openSesameHander = function(e)%7B%0A%09%09document.querySelector('.wrapper').classList.toggle('open-sesame' );%0A +%09%7D %0A%09do @@ -913,101 +913,127 @@ er(' -click', function(e)%7B%0A%09%09document.querySelector('.wrapper').classList.toggle(' +mousedown', openSesameHander, false);%0A%09document.querySelector('.title').addEventListener('touchstart', open --s +S esame -');%0A%09%7D +Hander , fa