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
8cbc0205a81fbd353afa979f569861f4a71b799b
remove last mention of parse
src/index.js
src/index.js
import 'lie/polyfill' import 'whatwg-fetch' import React from 'react' React.initializeTouchEvents(true) // import {Parse} from 'parse' // if (process.env.NODE_ENV === 'production') { // window.Parse = Parse // Parse.initialize('3YmZ7OaEPjPzP7yg19Wts1VGYmVr2qCw36nZIDYD', 'lWmcTJJ7ADHlHh5pTWudTiimBODHy3lEUYz5vlnG') // Parse.Analytics.track('load', {browser: navigator.userAgent}) // } import './index.scss' import './start-things/bind-keys' import './start-things/start-notifications' import './start-things/start-global-pollution' import './start-things/start-data-loading' import './start-things/start-router'
JavaScript
0.001376
@@ -103,293 +103,8 @@ e)%0A%0A -// import %7BParse%7D from 'parse'%0A// if (process.env.NODE_ENV === 'production') %7B%0A// %09window.Parse = Parse%0A// %09Parse.initialize('3YmZ7OaEPjPzP7yg19Wts1VGYmVr2qCw36nZIDYD', 'lWmcTJJ7ADHlHh5pTWudTiimBODHy3lEUYz5vlnG')%0A// %09Parse.Analytics.track('load', %7Bbrowser: navigator.userAgent%7D)%0A// %7D%0A%0A impo
c535378c6c4bd3e6913911e1f1f4b63147a2194a
remove need for second parameter
src/index.js
src/index.js
import express from 'express'; import basicAuth from 'node-basicauth'; import bodyParser from 'body-parser'; import cookieParser from 'cookie-parser'; import compression from 'compression'; import fs from 'fs'; import morgan from 'morgan'; import { join } from 'path'; import favicon from 'serve-favicon'; import stylus from 'stylus'; import nib from 'nib'; import { isArray, isObject, isFunction } from 'magic-types'; import log from 'magic-server-log'; import router from './router'; import headers from './headers'; import handle404 from './errors/handle404'; import handle500 from './errors/handle500'; // import { init as initAdmin } from 'magic-admin'; // import blog from 'magic-blog'; // import db from 'magic-db'; export const Magic = (app, dir) => { const css = app.get('css') || stylus; // const dbSettings = app.get('dbOpts') || false; const routes = app.get('router'); const env = app.get('env') || 'production'; const faviconPath = join(dir, 'public', 'favicon.ico'); const publicDir = app.get('publicDir') || 'public'; const viewDir = app.get('viewDir') || 'views'; const appDirs = app.get('dirs'); const basicAuthConfig = app.get('basicAuth'); const port = app.get('port') || 5000; const viewEngine = app.get('view engine') || 'jade'; const dirs = { root: dir, public: join(dir, publicDir), views: join(dir, viewDir), ...appDirs, }; console.log({ dirs, env }); app.set('css', css); app.set('dirs', dirs); // set req.app to use in middleware app.use( (req, res, next) => { req.app = app; next(); }); // set expiry headers app.use(headers); // enable http basicAuth if (basicAuthConfig) { app.use(basicAuth(basicAuthConfig)); } // fs.existsSync only gets called once on first request if (!app.get('faviconChecked') && !app.get('faviconExists')) { app.set('faviconChecked', true); app.set('faviconExists', fs.existsSync(faviconPath)); } if (app.get('faviconExists')) { app.use(favicon(faviconPath)); } app.set('views', dirs.views); app.set('view engine', viewEngine); app.use(compression({ threshold: 128 })); const cssMiddleware = (str, path) => css(str) .set('filename', path) .set('compress', env === 'production') .use(nib()) .import('nib'); app.use(css.middleware({ src: dirs.public, maxage: '1d', compile: cssMiddleware, })); app.use(express.static(join(__dirname, 'public'), { maxAge: '1w' })); app.use(express.static(dirs.public, { maxAge: '1d' })); // if (dbSettings && !app.get('db')) { // app.use(db); // } // if (app.enabled('admin')) { // app.use(initAdmin); // } /* TODO: reenable if (app.get('blogRoot')) { let blogRoot = app.get('blogRoot'); if (typeof blogRoot !== 'string' && typeof blogRoot !== 'number') { blogRoot = 'blog'; } if (blogRoot.charAt(0) !== '/') { blogRoot = '/' + blogRoot; } else { app.set('blogRoot', blogRoot.substr(1)); } app.use(blogRoot, blog); } */ const logLevel = app.get('logLevel') || 'combined'; // logging app.use(morgan(logLevel)); // if host sets bodyparser to true, init it if (app.enabled('bodyParser')) { app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); } // if host sets cookieparser to true, init it: if (app.enabled('cookieParser')) { app.use(cookieParser()); } // load host specific router if (routes) { if (isArray(routes) || isObject(routes)) { Object.keys(routes).forEach( key => { if (isFunction(routes[key])) { app.use(routes[key]); } } ); } else if (isFunction(routes)) { app.use(routes); } } // default router app.use(router); // we are in a 404 error app.use(handle404); // oops, worst case fallback, 500 server error. app.use(handle500); app.get('*', (req, res, next) => { console.log('catchall'); res.status(200).send('yay'); }); app.listen(port, err => { if (err) { log.error(err); } log(`app listening to port ${port}`); }); return app; };
JavaScript
0.000052
@@ -179,24 +179,62 @@ mpression';%0A +import babel from 'babel-middleware';%0A import fs fr @@ -238,24 +238,24 @@ from 'fs';%0A - import morga @@ -783,23 +783,45 @@ c = -( app -, + =%3E %7B%0A const dir -) = -%3E %7B + process.cwd(); %0A c @@ -1329,16 +1329,56 @@ 'jade'; +%0A const babelConfig = app.get('babel'); %0A%0A cons @@ -1680,16 +1680,16 @@ next();%0A - %7D);%0A @@ -1685,24 +1685,91 @@ );%0A %7D);%0A%0A + if (babelConfig) %7B%0A app.use('/js/', babel(babelConfig));%0A %7D%0A%0A // set exp
5969da5230a7959c534dacf6ccd041b4f27d3db9
Increment version
src/index.js
src/index.js
//Promise polyfill https://github.com/taylorhakes/promise-polyfill if (typeof Promise !== 'function') { window.Promise = require('promise-polyfill'); } var Barba = { version: '0.0.8', Dispatcher: require('./Dispatcher/Dispatcher'), HistoryManager: require('./Pjax/HistoryManager'), BaseTransition: require('./Transition/BaseTransition'), BaseView: require('./View/BaseView'), Pjax: require('./Pjax/Pjax'), Prefetch: require('./Pjax/Prefetch'), Utils: require('./Utils/Utils') }; module.exports = Barba; window.Barba = Barba;
JavaScript
0.000002
@@ -182,9 +182,9 @@ 0.0. -8 +9 ',%0A
438041ab58c88fe913e92dc722063bcaffb357e6
Remove Core from exposed api
src/index.js
src/index.js
export { default } from './manageTranslations'; export { default as core } from './core'; export { default as readMessageFiles } from './readMessageFiles'; export { default as createSingleMessagesFile } from './createSingleMessagesFile'; export { default as getDefaultMessages } from './getDefaultMessages';
JavaScript
0.000001
@@ -46,50 +46,8 @@ ';%0A%0A -export %7B default as core %7D from './core';%0A expo
e16d9f2266a7c49ad164dd0d8269509354cab4bb
Update src/intro.js
src/intro.js
src/intro.js
/*jslint browser: true, onevar: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true */ /*global window: false, jQuery: false, console: false, define: false */ (function( window, document, undefined ) { "use strict"; // Enable ECMAScript "strict" operation for this function. See more: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/ // Uses AMD or browser globals to create a jQuery plugin. (function(factory) { if(typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if(jQuery && !jQuery.fn.qtip) { factory(jQuery); } } (function($) { // Munge the primitives - Paul Irish tip var TRUE = true, FALSE = false, NULL = null, // Side names and other stuff X = 'x', Y = 'y', WIDTH = 'width', HEIGHT = 'height', TOP = 'top', LEFT = 'left', BOTTOM = 'bottom', RIGHT = 'right', CENTER = 'center', FLIP = 'flip', FLIPINVERT = 'flipinvert', SHIFT = 'shift', // Shortcut vars QTIP, PLUGINS, MOUSE, usedIDs = {}, uitooltip = 'ui-tooltip', widget = 'ui-widget', disabled = 'ui-state-disabled', selector = 'div.qtip.'+uitooltip, defaultClass = uitooltip + '-default', focusClass = uitooltip + '-focus', hoverClass = uitooltip + '-hover', fluidClass = uitooltip + '-fluid', hideOffset = '-31000px', replaceSuffix = '_replacedByqTip', oldtitle = 'oldtitle', trackingBound; /* Thanks to Paul Irish for this one: http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/ */ function log() { log.history = log.history || []; log.history.push(arguments); // Make sure console is present if('object' === typeof console) { // Setup console and arguments var c = console[ console.warn ? 'warn' : 'log' ], args = Array.prototype.slice.call(arguments), a; // Add qTip2 marker to first argument if it's a string if(typeof arguments[0] === 'string') { args[0] = 'qTip2: ' + args[0]; } // Apply console.warn or .log if not supported a = c.apply ? c.apply(console, args) : c(args); } }
JavaScript
0
@@ -206,197 +206,8 @@ */%0A%0A -(function( window, document, undefined ) %7B%0A%22use strict%22; // Enable ECMAScript %22strict%22 operation for this function. See more: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/%0A%0A // U @@ -274,18 +274,64 @@ ion( + factory -) %7B +, window, document, undefined ) %7B%0A%09%22use strict%22; %0A%09if @@ -488,16 +488,164 @@ on($) %7B%0A +%09%22use strict%22; // Enable ECMAScript %22strict%22 operation for this function. See more: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/%0A%09%0A %09// Mung
19b5a62bec7a4ef66c2d1289ac32bf8e0fd1511f
Remove all use of cookies and depracated functions that rely on them.
includes/webm-plus-extension.js
includes/webm-plus-extension.js
// ==UserScript== // @include http://youtube.com/* // @include http://*.youtube.com/* // @include https://youtube.com/* // @include https://*.youtube.com/* // @exclude http://youtube.com/html5 // @exclude http://*.youtube.com/html5 // @exclude https://youtube.com/html5 // @exclude https://*.youtube.com/html5 // ==/UserScript== var oexYouTubeWebMPlus = function() { window.addEventListener('DOMContentLoaded', function() { if (!trialParticipant() && (widget.preferences.getItem('continueTesting') === 'true')) trialApplicant(); if (widget.preferences.getItem('videoSaveButton') === 'true') downloadVideoButton(); if (widget.preferences.getItem('filterSearch') === 'true') filterSearchResults(); if (widget.preferences.getItem('hideFlashPromo') === 'true') removeElementById('flash10-promo-div'); if (widget.preferences.getItem('hideFlashUpgrade') === 'true') setTimeout((function() { removeElementById('flash-upgrade'); }), 350); if (widget.preferences.getItem('preventFlash') === 'true') removeElementById('movie_player'); }, false); function _(string) { if (typeof(oexWebMPlusi18n) != 'undefined' && oexWebMPlusi18n[string]) { return oexWebMPlusi18n[string]; } return string; } var trialCookieValue = 'f2=40000000', trialCookie = 'PREF=' + trialCookieValue; function trialParticipant() { var test; setTimeout(test = cookieTester('PREF',trialCookieValue),1000); return test; } function trialApplicant() { var date = new Date(), expirationDate = (new Date(date.getTime()+(20908800000))).toUTCString(), // eight months cookieValue = cookieTester('PREF',false,true), isVideoPage = window.location.pathname.indexOf('/watch'); if (cookieValue != false && cookieValue != undefined && cookieValue != trialCookie) { cookieValue = cookieValue.substring(5).replace(/&f2=[0-9]{0,9}|f2=[0-9]{0,9}&|f2=[0-9]{0,9}/i,''); cookieValue = cookieValue.substring(5).replace(/&f3=[0-9]{0,9}|f3=[0-9]{0,9}&|f3=[0-9]{0,9}/i,''); document.cookie = trialCookie + '; expires=Thu, 01-Jan-1970 00:00:01 UTC; ;'; setTimeout((function() { document.cookie = trialCookie + '&' + cookieValue + '; path=/; domain=.youtube.com; ' + 'expires=' + expirationDate; }), 750); } else { document.cookie = trialCookie + '; path=/; domain=.youtube.com; ' + 'expires=' + expirationDate; } if (~isVideoPage) setTimeout((window.location = window.location.href), 1000); } function cookieTester(inCookie,inValue,returnValue) { var i, cookieJar = document.cookie.split(';'); for(i=0;i < cookieJar.length;i++) { var cookie = cookieJar[i]; while (cookie.charAt(0) == ' ') cookie = cookie.substring(1,cookie.length); if (cookie.indexOf(inCookie + '=') == 0 && inValue == null) return true; else if ((cookie.indexOf(inCookie + '=') == 0) && returnValue != null) return cookie; else if ((cookie.indexOf(inCookie + '=') == 0) && (!~(cookie.substring(inCookie + '='.length,cookie.length).indexOf(inValue))) && returnValue == null) return true; } return false; } function downloadVideoButton() { var text, video = document.getElementsByTagName('video'), container = document.getElementById('watch-actions-right'), button = document.createElement('button'); if (video.length > 0 && container != undefined) { button.setAttribute('class', 'yt-uix-button yt-uix-tooltip yt-uix-tooltip-reverse'); button.style.position = 'relative'; button.style.top = '-4px'; button.setAttribute('data-tooltip-text', _('Click, then press Ctrl+S to save.')); button.onclick = function() { window.location = video[0].src; } text = document.createTextNode(_('Download Video')); button.appendChild(text) container.appendChild(button); }} function removeElementById(id) { var element = document.getElementById(id); if (element != null) element.parentNode.removeChild(element); } function filterSearchResults() { var parameter, searchField = document.getElementById('masthead-search'); if (searchField != null) { parameter = document.createElement('input'); parameter.setAttribute('name', 'webm'); parameter.setAttribute('type', 'hidden'); parameter.setAttribute('value', '1'); searchField.appendChild(parameter); }}}();
JavaScript
0
@@ -426,117 +426,8 @@ %7B%0A - if (!trialParticipant() && (widget.preferences.getItem('continueTesting') === 'true')) trialApplicant();%0A @@ -1130,1898 +1130,8 @@ %7D%0A%0A - var trialCookieValue = 'f2=40000000',%0A trialCookie = 'PREF=' + trialCookieValue;%0A%0A function trialParticipant()%0A %7B%0A var test;%0A setTimeout(test = cookieTester('PREF',trialCookieValue),1000);%0A return test;%0A %7D%0A%0A function trialApplicant()%0A %7B%0A var date = new Date(),%0A expirationDate = (new Date(date.getTime()+(20908800000))).toUTCString(), // eight months%0A cookieValue = cookieTester('PREF',false,true),%0A isVideoPage = window.location.pathname.indexOf('/watch');%0A if (cookieValue != false && cookieValue != undefined && cookieValue != trialCookie)%0A %7B%0A cookieValue = cookieValue.substring(5).replace(/&f2=%5B0-9%5D%7B0,9%7D%7Cf2=%5B0-9%5D%7B0,9%7D&%7Cf2=%5B0-9%5D%7B0,9%7D/i,'');%0A cookieValue = cookieValue.substring(5).replace(/&f3=%5B0-9%5D%7B0,9%7D%7Cf3=%5B0-9%5D%7B0,9%7D&%7Cf3=%5B0-9%5D%7B0,9%7D/i,'');%0A document.cookie = trialCookie + '; expires=Thu, 01-Jan-1970 00:00:01 UTC; ;';%0A setTimeout((function() %7B document.cookie = trialCookie + '&' + cookieValue + '; path=/; domain=.youtube.com; ' + 'expires=' + expirationDate; %7D), 750);%0A %7D%0A else%0A %7B%0A document.cookie = trialCookie + '; path=/; domain=.youtube.com; ' + 'expires=' + expirationDate;%0A %7D%0A if (~isVideoPage) setTimeout((window.location = window.location.href), 1000);%0A %7D%0A%0A function cookieTester(inCookie,inValue,returnValue)%0A %7B%0A var i, cookieJar = document.cookie.split(';');%0A for(i=0;i %3C cookieJar.length;i++)%0A %7B%0A var cookie = cookieJar%5Bi%5D;%0A while (cookie.charAt(0) == ' ') cookie = cookie.substring(1,cookie.length);%0A if (cookie.indexOf(inCookie + '=') == 0 && inValue == null) return true;%0A else if ((cookie.indexOf(inCookie + '=') == 0) && returnValue != null) return cookie;%0A else if ((cookie.indexOf(inCookie + '=') == 0) && (!~(cookie.substring(inCookie + '='.length,cookie.length).indexOf(inValue))) && returnValue == null) return true;%0A %7D%0A return false;%0A %7D%0A%0A fu
453562a646731364eeaf16adcbc5394ef87b37a9
Update phylowidget.js
inst/htmlwidgets/phylowidget.js
inst/htmlwidgets/phylowidget.js
HTMLWidgets.widget({ name: 'phylowidget', type: 'output', initialize: function(el, width, height) { var svg=d3.select(el).append("svg") .attr("width",width) .attr("height",height); var tree=d3.layout.phylotree(el); return {"svg": svg, "tree": tree}; }, renderValue: function(el, x, instance) { var newick_string = x.nwk; var svg = instance.svg; var tree = instance.tree; var parsed_string = d3_phylotree_newick_parser(newick_string); tree.node_span ('equal'); tree.options ({'draw-size-bubbles' : false}, false); tree.font_size (14); tree.scale_bar_font_size (12); tree.node_circle_size (4); tree.spacing_x (16, true); tree(parsed_string).svg(svg).layout(); }, resize: function(el, width, height, instance) { var svg=d3.select("#"+el.id+" svg") .attr("width",width) .attr("height",height); } });
JavaScript
0.000001
@@ -240,20 +240,81 @@ tree(el) +.size (%5Bheight, width%5D).separation (function (a,b) %7Breturn 0;%7D) ;%0A - %0A r @@ -489,74 +489,8 @@ ee;%0A - var parsed_string = d3_phylotree_newick_parser(newick_string); %0A @@ -514,26 +514,25 @@ 'equal') -; %0A -tree + .options @@ -570,26 +570,25 @@ , false) -; %0A -tree + .font_si @@ -594,26 +594,25 @@ ize (14) -; %0A -tree + .scale_b @@ -628,26 +628,25 @@ ize (12) -; %0A -tree + .node_ci @@ -664,38 +664,8 @@ 4);%0A - tree.spacing_x (16, true); %0A @@ -859,12 +859,70 @@ t);%0A - %7D%0A + %0A instance.tree.size (%5Bheight, width%5D).layout();%0A %0A%0A %7D);%0A
aa354fedeb9b647ed12ed433f50546ac19dda712
Update proxy.js
src/proxy.js
src/proxy.js
const _ = require('lodash'); const url = require('url'); const httpProxy = require('http-proxy'); const headers = require('./lib/headers'); const cookie = require('cookie'); const Cookie = require('tough-cookie').Cookie; const harmon = require('harmon'); const srcset = require('srcset'); const cssUrlPattern = /url\(\s*(['"])((?:\\[\s\S]|(?!\1).)*)\1\s*\)|url\(((?:\\[\s\S]|[^)])*)\)/gi; module.exports = (proxyTarget, host) => { let proxy = httpProxy.createProxyServer(); let proxyUrl = url.parse(proxyTarget, false, true); let rewriteAttributes = [ 'action', 'href', 'link', 'src', 'srcset', 'style' ]; let rewriteElements = [ 'loc' ]; let rewrite = (link, baseUrl) => { let parsed = url.parse(link, false, true); if (matchesHost(parsed, proxyUrl.host)) { return host + baseUrl + parsed.pathname; } return link; }; proxy.on('proxyReq', (proxyReq, req) => { // Only forward standard headers. _.forEach(proxyReq.getHeaders(), (value, key) => { if (!headers.isRequestHeader(key)) { proxyReq.removeHeader(key); } }); // Remove Cloudflare cookies. if (proxyReq.getHeader('cookie')) { let cookies = _.omit(cookie.parse(proxyReq.getHeader('cookie')), '__cfduid'); proxyReq.setHeader('cookie', _.map(cookies, (value, name) => cookie.serialize(name, value)).join('; ')); } proxyReq.setHeader('X-Fowarded-For', req.ip); }); proxy.on('proxyRes', (proxyRes, req) => { // Only forward standard headers. _.forEach(proxyRes.headers, (value, key) => { if (!headers.isResponseHeader(key)) { delete proxyRes.headers[key]; } }); // Remove Cloudflare cookies. if (proxyRes.headers['set-cookie']) { proxyRes.headers['set-cookie'] = proxyRes.headers['set-cookie'].filter((string) => { return Cookie.parse(string).key !== '__cfduid'; }); if (!proxyRes.headers['set-cookie'].length) { delete proxyRes.headers['set-cookie']; } } // Rewrite redirects. if (proxyRes.headers.location) { proxyRes.headers.location = rewrite(proxyRes.headers.location, req.baseUrl); } }); return [ /** * Rewrite links in HTML. */ harmon([], rewriteAttributes.map((name) => { return { query: `[${name}]`, func (el, req) { el.getAttribute(name, (value) => { try { if (name === 'srcset') { value = srcset.stringify(srcset.parse(value).map(src => (src.url = rewrite(src.url, req.baseUrl), src))); } else if (name === 'style') { value = value.replace(cssUrlPattern, ($0, $1, $2, $3) => { return `url("${rewrite($2 || $3, req.baseUrl)}")`; }); } else { value = rewrite(value, req.baseUrl); } el.setAttribute(name, value); } catch (e) {} }); }, }; }).concat(rewriteElements.map((name) => { return { query: name, func (el, req) { let value = ''; let stream = el.createStream() .on('error', () => stream.end()) .on('data', chunk => value += chunk.toString()) .on('end', () => { try { stream.end(rewrite(value, req.baseUrl)); } catch (e) { stream.end(value); } }); }, }; })), true), /** * Fix for harmon with [email protected]+ * Harmon assumes writeHead() is called before write() which is not the case anymore - http-proxy doesn't call writeHead() at all, it's called by node code from write(). */ (req, res, next) => { let write = res.write; res.write = function (...args) { if (this.getHeader('content-type').includes('application/xml')) { res.isHtml = true; // Strip off the content length since it will change. res.removeHeader('Content-Length'); } if (!this.headersSent) { this.writeHead(this.statusCode); } return write.apply(this, args); }; return next(); }, /** * The main proxy middleware. */ (req, res, next) => { res.status(502); proxy.web(req, res, { target: proxyTarget, changeOrigin: true, protocolRewrite: 'https', cookieDomainRewrite: '', cookiePathRewrite: req.baseUrl, proxyTimeout: 10000, }, next); }, ]; }; function matchesHost (url, host) { return (!url.host && url.pathname.charAt(0) === '/') || url.host === host; }
JavaScript
0.000001
@@ -3477,210 +3477,8 @@ ) %7B%0A -%09%09%09%09if (this.getHeader('content-type').includes('application/xml')) %7B%0A%09%09%09%09%09res.isHtml = true;%0A%0A%09%09%09%09%09// Strip off the content length since it will change.%0A%09%09%09%09%09res.removeHeader('Content-Length');%0A%09%09%09%09%7D%0A%0A %09%09%09%09
8cce7fda06ac8d57bd09fe6caea150825d90dc63
Fix for code review issue https://github.com/mdn/webextensions-examples/issues/40
tabs-tabs-tabs/tabs.js
tabs-tabs-tabs/tabs.js
function firstUnpinnedTab(tabs) { for (var tab of tabs) { if (!tab.pinned) { return tab.index; } } } document.addEventListener("click", function(e) { function callOnActiveTab(callback) { chrome.tabs.query({currentWindow: true}, function(tabs) { for (var tab of tabs) { if (tab.active) { callback(tab, tabs); } } }); } if (e.target.id === "tabs-move-beginning") { callOnActiveTab((tab, tabs) => { var index = 0; if (!tab.pinned) { index = firstUnpinnedTab(tabs); } chrome.tabs.move([tab.id], {index}); }); } if (e.target.id === "tabs-move-end") { callOnActiveTab((tab, tabs) => { var index = -1; if (tab.pinned) { var lastPinnedTab = Math.max(0, firstUnpinnedTab(tabs) - 1); index = lastPinnedTab; } chrome.tabs.move([tab.id], {index}); }); } else if (e.target.id === "tabs-duplicate") { callOnActiveTab((tab) => { chrome.tabs.duplicate(tab.id); }); } else if (e.target.id === "tabs-reload") { callOnActiveTab((tab) => { chrome.tabs.reload(tab.id); }); } else if (e.target.id === "tabs-remove") { callOnActiveTab((tab) => { chrome.tabs.remove(tab.id); }); } });
JavaScript
0.000005
@@ -1275,12 +1275,34 @@ );%0A %7D%0A%0A + e.preventDefault();%0A %7D);%0A
20b16d15172f02dbe3895525831e6ce000ac8eed
Fix !ProgressBar aria attribute, and add aria tests, fixes #16564 on trunk !strict, thanks Mike (IBM, CCLA).
ProgressBar.js
ProgressBar.js
define([ "require", // require.toUrl "dojo/_base/declare", // declare "dojo/dom-class", // domClass.toggle "dojo/_base/lang", // lang.mixin "dojo/number", // number.format "./_Widget", "./_TemplatedMixin", "dojo/text!./templates/ProgressBar.html" ], function(require, declare, domClass, lang, number, _Widget, _TemplatedMixin, template){ // module: // dijit/ProgressBar return declare("dijit.ProgressBar", [_Widget, _TemplatedMixin], { // summary: // A progress indication widget, showing the amount completed // (often the percentage completed) of a task. // // example: // | <div data-dojo-type="ProgressBar" // | places="0" // | value="..." maximum="..."> // | </div> // progress: [const] String (Percentage or Number) // Number or percentage indicating amount of task completed. // Deprecated. Use "value" instead. progress: "0", // value: String (Percentage or Number) // Number or percentage indicating amount of task completed. // With "%": percentage value, 0% <= progress <= 100%, or // without "%": absolute value, 0 <= progress <= maximum. // Infinity means that the progress bar is indeterminate. value: "", // maximum: [const] Float // Max sample number maximum: 100, // places: [const] Number // Number of places to show in values; 0 by default places: 0, // indeterminate: [const] Boolean // If false: show progress value (number or percentage). // If true: show that a process is underway but that the amount completed is unknown. // Deprecated. Use "value" instead. indeterminate: false, // label: String? // Label on progress bar. Defaults to percentage for determinate progress bar and // blank for indeterminate progress bar. label:"", // name: String // this is the field name (for a form) if set. This needs to be set if you want to use // this widget in a dijit/form/Form widget (such as dijit/Dialog) name: '', templateString: template, // _indeterminateHighContrastImagePath: [private] URL // URL to image to use for indeterminate progress bar when display is in high contrast mode _indeterminateHighContrastImagePath: require.toUrl("./themes/a11y/indeterminate_progress.gif"), postMixInProperties: function(){ this.inherited(arguments); // Back-compat for when constructor specifies indeterminate or progress, rather than value. Remove for 2.0. if(!(this.params && "value" in this.params)){ this.value = this.indeterminate ? Infinity : this.progress; } }, buildRendering: function(){ this.inherited(arguments); this.indeterminateHighContrastImage.setAttribute("src", this._indeterminateHighContrastImagePath.toString()); this.update(); }, _setDirAttr: function(val){ // Normally _CssStateMixin takes care of this, but we aren't extending it domClass.toggle(this.domNode, "dijitProgressBarRtl", val == "rtl"); this.inherited(arguments); }, update: function(/*Object?*/attributes){ // summary: // Internal method to change attributes of ProgressBar, similar to set(hash). Users should call // set("value", ...) rather than calling this method directly. // attributes: // May provide progress and/or maximum properties on this parameter; // see attribute specs for details. // example: // | myProgressBar.update({'indeterminate': true}); // | myProgressBar.update({'progress': 80}); // | myProgressBar.update({'indeterminate': true, label:"Loading ..." }) // tags: // private // TODO: deprecate this method and use set() instead lang.mixin(this, attributes || {}); var tip = this.internalProgress, ap = this.domNode; var percent = 1; if(this.indeterminate){ ap.removeAttribute("aria-valuenow"); }else{ if(String(this.progress).indexOf("%") != -1){ percent = Math.min(parseFloat(this.progress)/100, 1); this.progress = percent * this.maximum; }else{ this.progress = Math.min(this.progress, this.maximum); percent = this.maximum ? this.progress / this.maximum : 0; } ap.setAttribute("aria-valuenow", this.progress); } // Even indeterminate ProgressBars should have these attributes ap.setAttribute("aria-describedby", this.labelNode.id); ap.setAttribute("aria-valuemin", 0); ap.setAttribute("aria-valuemax", this.maximum); this.labelNode.innerHTML = this.report(percent); domClass.toggle(this.domNode, "dijitProgressBarIndeterminate", this.indeterminate); tip.style.width = (percent * 100) + "%"; this.onChange(); }, _setValueAttr: function(v){ this._set("value", v); if(v == Infinity){ this.update({indeterminate:true}); }else{ this.update({indeterminate:false, progress:v}); } }, _setLabelAttr: function(label){ this._set("label", label); this.update(); }, _setIndeterminateAttr: function(indeterminate){ // Deprecated, use set("value", ...) instead this.indeterminate = indeterminate; this.update(); }, report: function(/*float*/percent){ // summary: // Generates message to show inside progress bar (normally indicating amount of task completed). // May be overridden. // tags: // extension return this.label ? this.label : (this.indeterminate ? "&#160;" : number.format(percent, { type: "percent", places: this.places, locale: this.lang })); }, onChange: function(){ // summary: // Callback fired when progress updates. // tags: // extension } }); });
JavaScript
0.000001
@@ -4139,15 +4139,14 @@ ria- -describ +labell edby
5e7158498d2a5f46c8126bbc20a2f96458bb9c4d
fix last albums fetch logic
server/users/member/blocks/albums.js
server/users/member/blocks/albums.js
'use strict'; module.exports = function (N) { var ALBUMS_COUNT = 7; // Fetch last user photos // N.wire.after('server:users.member', function fetch_last_photos(env, callback) { N.models.users.Album .find({ user_id: env.data.user._id, default: false }) .lean(true) .sort('-last_ts') .limit(ALBUMS_COUNT) .exec(function (err, albums) { if (err) { callback(err); return; } if (albums.length === 0) { callback(); return; } env.res.blocks = env.res.blocks || {}; env.res.blocks.albums = { albums: albums, user_hid: env.data.user.hid }; callback(); }); }); // Fetch user photos count // N.wire.after('server:users.member', function fetch_photos_count(env, callback) { if (!env.res.blocks.albums) { callback(); return; } N.models.users.Album.find({ user_id: env.data.user._id }).count(function (err, count) { if (err) { callback(err); return; } env.res.blocks.albums.count = count; callback(); }); }); };
JavaScript
0.000002
@@ -8,16 +8,43 @@ rict';%0A%0A +var _ = require('lodash');%0A %0Amodule. @@ -280,24 +280,8 @@ ._id -, default: false %7D)%0A @@ -347,16 +347,20 @@ MS_COUNT + + 1 )%0A @@ -541,32 +541,271 @@ urn;%0A %7D%0A%0A + // Try to remove default album%0A _.remove(albums, function (album) %7B return album.default; %7D);%0A%0A // No default album in array, remove last%0A if (albums.length %3E ALBUMS_COUNT) %7B%0A albums.pop();%0A %7D%0A%0A env.res. @@ -1110,34 +1110,28 @@ if (!env. -res.blocks +data .albums) %7B%0A
ffaaace4ece764a66887fce57eed2d8588b141b0
throw useful error if moderator attempts `/cycle init` when not associated with a chapter
server/graphql/models/Cycle/mutation.js
server/graphql/models/Cycle/mutation.js
import raven from 'raven' import {GraphQLNonNull, GraphQLString} from 'graphql' import {GraphQLError} from 'graphql/error' import {CYCLE_STATES} from '../../../../common/models/cycle' import {parseQueryError} from '../../../../server/db/errors' import {getModeratorById} from '../../../db/moderator' import {createNextCycleForChapter, getCyclesInStateForChapter} from '../../../db/cycle' import {userCan} from '../../../../common/util' import r from '../../../../db/connect' import {Cycle} from './schema' const sentry = new raven.Client(process.env.SENTRY_SERVER_DSN) export default { createCycle: { type: Cycle, args: {}, async resolve(source, args, {rootValue: {currentUser}}) { if (!userCan(currentUser, 'createCycle')) { throw new GraphQLError('You are not authorized to do that.') } try { const moderator = await getModeratorById(currentUser.id) if (!moderator) { throw new GraphQLError('You are not a moderator for the game.') } return await createNextCycleForChapter(moderator.chapterId) } catch (rawError) { const err = parseQueryError(rawError) sentry.captureException(err) throw err } } }, updateCycleState: { type: Cycle, args: { state: {type: new GraphQLNonNull(GraphQLString)}, }, resolve(source, args, {rootValue: {currentUser}}) { return changeCycleState(args.state, currentUser) } } } async function changeCycleState(newState, currentUser) { const newStateIndex = CYCLE_STATES.indexOf(newState) if (typeof newStateIndex === 'undefined') { throw new GraphQLError('Invalid cycle state given.') } if (newStateIndex === 0) { throw new GraphQLError(`You cannot change the cycle state back to ${newState}`) } if (!userCan(currentUser, 'updateCycle')) { throw new GraphQLError('You are not authorized to do that.') } try { const moderator = await getModeratorById(currentUser.id, {mergeChapter: true}) if (!moderator) { throw new GraphQLError('You are not a moderator for the game.') } const validOriginState = CYCLE_STATES[newStateIndex - 1] const cycles = await getCyclesInStateForChapter(moderator.chapter.id, validOriginState) if (!cycles.length > 0) { throw new GraphQLError(`No cycles for ${moderator.chapter.name} chapter (${moderator.chapter.id}) in ${validOriginState} state.`) } const cycle = cycles[0] const cycleUpdateResult = await r.table('cycles') .get(cycle.id) .update({state: newState, updatedAt: r.now()}, {returnChanges: 'always'}) .run() if (cycleUpdateResult.replaced) { const returnedCycle = Object.assign({}, cycleUpdateResult.changes[0].new_val, {chapter: cycle.chapter}) delete returnedCycle.chapterId return returnedCycle } throw new GraphQLError('Could not save cycle, please try again') } catch (err) { sentry.captureException(err) throw err } }
JavaScript
0
@@ -1004,24 +1004,162 @@ ')%0A %7D +%0A if (!moderator.chapterId) %7B%0A throw new GraphQLError('You must be assigned to a chapter to start a new cycle.')%0A %7D %0A%0A re
71a9ac3d1d3f487d1ca0f81aee1500e4b742a58b
Improve browserify plugin configurability
mix-browserify/index.js
mix-browserify/index.js
var prime = require('prime'); var Emitter = require('prime/emitter'); var Kefir = require('kefir'); var browserify = require('browserify'); var chokidar = require('chokidar'); var mix = require('mix'); var mixIn = require('mout/object/mixIn'); var path = require('path'); module.exports = function (options) { var currentSink = null; var pkgCache = {}; var depCache = {}; var firstPush = true; return function (tree) { if (tree.nodes.length !== 1) { throw new Error('Exactly one file must be specified for browserification'); } var node = tree.nodes[0]; var entrypoint = path.join(node.base, node.name); if (currentSink !== null) { currentSink.close(); currentSink = null; } return new mix.Stream(function (sink) { currentSink = sink; var watcher = new Watcher(); var disposed = false; var b = browserify(mixIn({}, options, { basedir: node.base })); b.on('package', function (file, pkg) { pkgCache[file] = pkg; }); b.on('dep', function (dep) { depCache[dep.id] = dep; if (dep.id !== entrypoint) { watcher.add(dep.id); } }); b.on('file', function (file) { if (file !== entrypoint) { watcher.add(file); } }); b.on('bundle', function (bundle) { bundle.on('transform', function (transform, mfile) { transform.on('file', function (file) { // TODO: handle file change }); }); }); watcher.on('change', function (files) { if (disposed) { return; } files.forEach(function (path) { delete depCache[path]; watcher.remove(path); }); pushBundle(); }); b.add(entrypoint); pushBundle(); function pushBundle() { var buffers = []; var totalLength = 0; var bundleOptions = { includePackage: true, packageCache: pkgCache }; if (!firstPush) { bundleOptions.cache = depCache; } var start = new Date(); var output = b.bundle(bundleOptions); output.on('data', function (buffer) { buffers.push(buffer); totalLength += buffer.length; }); output.on('error', function () { // TODO: handle }); output.on('end', function () { if (disposed) { return; } var outputTree = new mix.Tree([ mixIn({}, node, { data: Buffer.concat(buffers, totalLength) }) ]); sink.push(outputTree); console.log('generated bundle in ' + (new Date() - start) + ' ms'); }); } return function dispose() { watcher.dispose(); watcher = null; disposed = true; }; }); }; }; var Watcher = prime({ mixin: Emitter, constructor: function () { var watcher = null; var eventSink = null; Kefir.fromBinder(function (sink) { this._sink = sink; return function dispose() { if (watcher !== null) { watcher.close(); watcher = null; } this._sink = null; }.bind(this); }, this).scan({}, function (files, update) { var operation = update[0]; var path = update[1]; if (operation === '+') { files[path] = true; } else { delete files[path]; } return files; }).flatMap(debounce(600)).skipDuplicates(function (previous, next) { return filesToString(previous) === filesToString(next); }).onValue(function (files) { if (eventSink !== null) { eventSink(Kefir.END); } if (watcher !== null) { watcher.close(); } watcher = chokidar.watch(Object.keys(files), { persistent: false }); Kefir.fromBinder(function (sink) { eventSink = sink; watcher.on('change', function (path) { eventSink(['+', path]); }); }).scan({}, function (changed, update) { var operation = update[0]; var path = update[1]; if (operation === '+') { changed[path] = true; } else { delete changed[path]; } return changed; }).flatMap(debounce(10, 600)).onValue(function (changed) { var files = Object.keys(changed); if (files.length > 0) { files.forEach(function (path) { eventSink(['-', path]); }); this.emit('change', files); } }, this); }, this); function filesToString(files) { return Object.keys(files).sort().join(':'); } }, dispose: function () { this._sink(Kefir.END); }, add: function (path) { this._sink(['+', path]); }, remove: function (path) { this._sink(['-', path]); } }); function debounce(wait, maxWait) { var firstValueAt = null; var pendingSink = null; maxWait = maxWait || wait; return function (value) { if (pendingSink !== null) { pendingSink(Kefir.END); pendingSink = null; } if (firstValueAt === null) { firstValueAt = new Date(); } return Kefir.fromBinder(function (sink) { var timer; pendingSink = sink; var now = new Date(); var elapsed = now - firstValueAt; if (elapsed >= maxWait) { pushValue(); } else { var delay = Math.min(wait, maxWait - elapsed); timer = setTimeout(pushValue, delay); } function pushValue() { timer = null; sink(value); sink(Kefir.END); } return function dispose() { firstValueAt = null; pendingSink = null; if (timer !== null) { clearTimeout(timer); timer = null; } }; }); }; }
JavaScript
0.000001
@@ -293,16 +293,24 @@ nction ( +target, options) @@ -409,24 +409,285 @@ sh = true;%0A%0A + if (typeof target === 'object') %7B%0A options = target;%0A target = null;%0A %7D else %7B%0A target = target %7C%7C null;%0A options = options %7C%7C %7B%7D;%0A %7D%0A%0A var configure = options.configure %7C%7C function () %7B%7D;%0A delete options.configure;%0A%0A return f @@ -1275,24 +1275,51 @@ .base %7D));%0A%0A + configure(b);%0A%0A @@ -3398,16 +3398,99 @@ node, %7B +%0A name: target %7C%7C node.name,%0A data: B @@ -3523,16 +3523,40 @@ lLength) +%0A %7D)%0A
779bb8e52a8bdc0bb510b416cd40631859fe104f
Refactor check for specific categories
tools/utility.js
tools/utility.js
'use strict'; var _ = require('lodash'); var fs = require('fs'); var path = require('path'); var REPLACES, regex = {}, headerRegex = /^\s*\/\*((.|\r?\n)*?)\*/; REPLACES = { 'case_insensitive': 'cI', 'lexemes': 'l', 'contains': 'c', 'keywords': 'k', 'subLanguage': 'sL', 'className': 'cN', 'begin': 'b', 'beginKeywords': 'bK', 'end': 'e', 'endsWithParent': 'eW', 'illegal': 'i', 'excludeBegin': 'eB', 'excludeEnd': 'eE', 'returnBegin': 'rB', 'returnEnd': 'rE', 'relevance': 'r', 'variants': 'v', 'IDENT_RE': 'IR', 'UNDERSCORE_IDENT_RE': 'UIR', 'NUMBER_RE': 'NR', 'C_NUMBER_RE': 'CNR', 'BINARY_NUMBER_RE': 'BNR', 'RE_STARTERS_RE': 'RSR', 'BACKSLASH_ESCAPE': 'BE', 'APOS_STRING_MODE': 'ASM', 'QUOTE_STRING_MODE': 'QSM', 'PHRASAL_WORDS_MODE': 'PWM', 'C_LINE_COMMENT_MODE': 'CLCM', 'C_BLOCK_COMMENT_MODE': 'CBCM', 'HASH_COMMENT_MODE': 'HCM', 'NUMBER_MODE': 'NM', 'C_NUMBER_MODE': 'CNM', 'BINARY_NUMBER_MODE': 'BNM', 'CSS_NUMBER_MODE': 'CSSNM', 'REGEXP_MODE': 'RM', 'TITLE_MODE': 'TM', 'UNDERSCORE_TITLE_MODE': 'UTM', 'COMMENT': 'C', 'beginRe': 'bR', 'endRe': 'eR', 'illegalRe': 'iR', 'lexemesRe': 'lR', 'terminators': 't', 'terminator_end': 'tE', }; regex.replaces = new RegExp( '\\b(' + Object.keys(REPLACES).join('|') + ')\\b', 'g'); regex.classname = /(block|parentNode)\.cN/g; regex.header = /^\s*(\/\*((.|\r?\n)*?)\*\/)?\s*/; function replace(from, to) { return { regex: from, replace: to }; } function replaceClassNames(match) { return REPLACES[match]; } function parseHeader(content) { var headers, match = content.match(headerRegex); if (!match) { return null; } headers = _.compact(match[1].split('\n')); return _.foldl(headers, function(result, header) { var keyVal = header.trim().split(': '), key = keyVal[0], value = keyVal[1] || ''; if(key !== 'Description' && key !== 'Language') { value = value.split(/\s*,\s*/); } result[key] = value; return result; }, {}); } function filterByQualifiers(blob, languages, categories) { if(_.isEmpty(languages) && _.isEmpty(categories)) return true; var language = path.basename(blob.name, '.js'), fileInfo = parseHeader(blob.result), fileCategories = fileInfo.Category || []; if(!fileInfo) return false; return _.contains(languages, language) || _.any(fileCategories, function(fc) {return _.contains(categories, fc)}); } function buildFilterCallback(qualifiers) { var isCategory = _.matchesProperty(0, ':'), languages = _.reject(qualifiers, isCategory), categories = _(qualifiers).filter(isCategory) .map(function(c) {return c.slice(1);}) .value(); return function(blob) { return filterByQualifiers(blob, languages, categories); }; } function glob(pattern, encoding) { encoding = encoding || 'utf8'; return { pattern: pattern, limit: 50, encoding: encoding }; } function getStyleNames() { var stylesDir = path.join('src', 'styles'), stylesDirFiles = fs.readdirSync(stylesDir), styles = _.filter(stylesDirFiles, function(file) { return path.extname(file) === '.css' && file !== 'default.css'; }); return _.map(styles, function(style) { var basename = path.basename(style, '.css'), name = _.startCase(basename), pathName = path.join('styles', style); return { path: pathName, name: name }; }); } module.exports = { buildFilterCallback: buildFilterCallback, getStyleNames: getStyleNames, glob: glob, parseHeader: parseHeader, regex: regex, replace: replace, replaceClassNames: replaceClassNames };
JavaScript
0
@@ -2206,24 +2206,26 @@ guage + = path.basen @@ -2264,24 +2264,26 @@ eInfo + = parseHeade @@ -2319,16 +2319,18 @@ egories + = fileIn @@ -2346,16 +2346,74 @@ ry %7C%7C %5B%5D +,%0A containsCategory = _.curry(_.contains)(categories) ;%0A%0A if( @@ -2517,39 +2517,16 @@ es, -function(fc) %7Breturn _. contains (cat @@ -2525,25 +2525,16 @@ ains -(c +C ategor -ies, fc)%7D +y );%0A%7D
f43f83f8d8cc3c463826a7910e2b1d3fc85ae18f
Fix fee calculation on opencollective prepaid payment type
server/paymentProviders/opencollective/prepaid.js
server/paymentProviders/opencollective/prepaid.js
import Promise from 'bluebird'; import models from '../../models'; import { type as TransactionTypes } from '../../constants/transactions'; import roles from '../../constants/roles'; import * as paymentsLib from '../../lib/payments'; /** How much the platform charges per transaction: 5% */ export const PLATFORM_FEE = 0.05 export default { features: { recurring: false, waitToCharge: false }, getBalance: (paymentMethod) => { return Promise.resolve({ amount: paymentMethod.monthlyLimitPerMember, currency: paymentMethod.currency}); }, processOrder: (order) => { /* - use gift card PaymentMethod (PM) to transfer money from gift card issuer to User - mark original gift card PM as "archivedAt" (it's used up) - create new PM type "opencollective" and attach to User (User now has credit in the system) - Use new PM to give money from User to Collective */ const user = order.createdByUser; const originalPM = order.paymentMethod; let newPM, transactions; // Check that target Collective's Host is same as gift card issuer return order.collective.getHostCollective() .then(hostCollective => { if (hostCollective.id !== order.paymentMethod.CollectiveId) { console.log('Different host found'); return Promise.resolve(); } else { // transfer all money using gift card from Host to User const payload = { CreatedByUserId: user.id, FromCollectiveId: order.paymentMethod.CollectiveId, CollectiveId: user.CollectiveId, PaymentMethodId: order.PaymentMethodId, transaction: { type: TransactionTypes.CREDIT, OrderId: order.id, amount: order.paymentMethod.monthlyLimitPerMember, // treating this field as one-time limit amountInHostCurrency: order.paymentMethod.monthlyLimitPerMember, currency: order.paymentMethod.currency, hostCurrency: order.currency, // assuming all USD transactions for now hostCurrencyFxRate: 1, hostFeeInHostCurrency: 0, platformFeeInHostCurrency: 0, // we don't charge a fee until the money is used by User paymentProcessorFeeInHostCurrency: 0, description: order.paymentMethod.name, HostCollectiveId: order.paymentMethod.CollectiveId // hacky, HostCollectiveId doesn't quite make sense in this context but required by ledger. TODO: fix later. } }; return models.Transaction.createFromPayload(payload) // mark gift card as used, so no one can use it again .then(() => order.paymentMethod.update({archivedAt: new Date()})) // create new payment method to allow User to use the money .then(() => models.PaymentMethod.create({ name: originalPM.name, service: 'opencollective', type: 'collective', // changes to type collective confirmedAt: new Date(), CollectiveId: user.CollectiveId, CreatedByUserId: user.id, MonthlyLimitPerMember: originalPM.monthlyLimitPerMember, currency: originalPM.currency, token: null // we don't pass the gift card token on })) // Use the above payment method to donate to Collective .then(pm => newPM = pm) .then(() => { const hostFeeInHostCurrency = paymentsLib.calcFee( order.totalAmount, order.collective.hostFeePercent); const platformFeeInHostCurrency = paymentsLib.calcFee( order.totalAmount, PLATFORM_FEE); const payload = { CreatedByUserId: user.id, FromCollectiveId: order.FromCollectiveId, CollectiveId: order.CollectiveId, PaymentMethodId: newPM.id, transaction: { type: TransactionTypes.CREDIT, OrderId: order.id, amount: order.totalAmount, amountInHostCurrency: order.totalAmount, currency: order.currency, hostCurrency: order.currency, hostCurrencyFxRate: 1, hostFeeInHostCurrency, platformFeeInHostCurrency, paymentProcessorFeeInHostCurrency: 0, description: order.description } } return models.Transaction.createFromPayload(payload) .then(t => transactions = t) // add roles .then(() => order.collective.findOrAddUserWithRole({ id: user.id, CollectiveId: order.fromCollective.id}, roles.BACKER, { CreatedByUserId: user.id, TierId: order.TierId })) // Mark order row as processed .then(() => order.update({ processedAt: new Date() })) // Mark paymentMethod as confirmed .then(() => newPM.update({ confirmedAt: new Date() })) .then(() => transactions); // make sure we return the transactions created }) } }); } }
JavaScript
0
@@ -232,98 +232,66 @@ s';%0A -%0A/** How much the platform charges per transaction: 5%25 */%0Aexport const PLATFORM_FEE = 0.05 +import * as constants from '../../constants/transactions'; %0A%0Aex @@ -3665,20 +3665,32 @@ nt, -PLATFORM_FEE +constants.OC_FEE_PERCENT );%0A
c2cdf588e0bb38e03df0ebf6177e676791616cba
fix .findOrCreateAll() fallback function
lib/waterline/adapter/compoundQueries.js
lib/waterline/adapter/compoundQueries.js
/** * Compound Queries Adapter Normalization */ var _ = require('underscore'), normalize = require('../utils/normalize'); module.exports = { findOrCreate: function(criteria, values, cb) { var self = this; // If no values were specified, use criteria if (!values) values = criteria.where ? criteria.where : criteria; criteria = normalize.criteria(criteria); if(this.adapter.findOrCreate) { this.adapter.findOrCreate(this.collection, criteria, values, cb); return; } // Default behavior // WARNING: Not transactional! (unless your data adapter is) this.find(this.collection, criteria, function(err, result) { if(err) return cb(err); if(result) return cb(null, result); // Call Query .create() // This gives us the default values and timestamps self.query.create(values, cb); }); } };
JavaScript
0.000004
@@ -612,33 +612,16 @@ is.find( -this.collection, criteria
d866b41dd6675a8152adc9c54502d53ff32e17a7
Update comment-model.js
models/comment-model.js
models/comment-model.js
var mongoose = require('mongoose'); var Url = mongoose.SchemaTypes.Url; var CommentSchema = new mongoose.Schema({ title: String, url: Url, text: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, rating: {type: Number, default: 0}, date: Date, comment: { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' } }); //mongoose.model('Comment', CommentSchema); module.exports = mongoose.model('Comment', CommentSchema);
JavaScript
0
@@ -66,16 +66,71 @@ s.Url;%0A%0A +//Define the Database schema for %22comments%22 collection%0A var Comm @@ -172,23 +172,48 @@ title: -String, +%7B type: String, required: true %7D %0A url: @@ -505,28 +505,29 @@ l('Comment', CommentSchema); +%0A
0e58a811cefa7e52ca24b77c03e5c203504ef33a
update minified copy
js/badgeos-shortcode-embed.min.js
js/badgeos-shortcode-embed.min.js
(function(e){function t(){var e=n();var t=r(e);var i=o(e,t);window.send_to_editor(i)}function n(){return e("#select_shortcode").val()}function r(t){var n=[];var r=s(t);e.each(r,function(e,t){if(""!==t.value&&undefined!==t.value){n.push(t.name+'="'+t.value+'"')}});return n}function s(t){return e(".text, .select","#"+t+"_wrapper")}function o(t,n){var r="[";r+=t;if(n){for(i=0;i<n.length;i++){r+=" "+n[i]}e.trim(r)}r+="]";return r}function u(){e(".shortcode-section").hide()}function a(t){e("#"+t+"_wrapper").show()}e("#select_shortcode").on("change",function(){u();a(n())}).change();e("#badgeos_insert").on("click",function(e){e.preventDefault();t()});e("#badgeos_cancel").on("click",function(e){e.preventDefault();tb_remove()});e("#insert_badgeos_shortcodes").on("click",function(t){var n=e(".select2-container");e.each(n,function(t,n){e(n).select2("val","")})});var f={ajax:{url:ajaxurl,type:"POST",data:function(e){return{q:e,action:"get-achievements-select2"}},results:function(e,t){console.log(e);return{results:e.data}}},id:function(e){return e.ID},formatResult:function(e){return e.post_title},formatSelection:function(e){return e.post_title},placeholder:badgeos_shortcode_embed_messages.id_placeholder,allowClear:true,multiple:false};var l=e.extend(true,{},f,{multiple:true});e("#badgeos_achievement_id, #badgeos_nomination_achievement_id, #badgeos_submission_achievement_id").select2(f);e("#badgeos_achievements_list_include, #badgeos_achievements_list_exclude").select2(l);e("#badgeos_achievements_list_type").select2({ajax:{url:ajaxurl,type:"POST",data:function(e){return{q:e,action:"get-achievement-types"}},results:function(e,t){return{results:e.data}}},id:function(e){return e.name},formatResult:function(e){return e.label},formatSelection:function(e){return e.label},placeholder:badgeos_shortcode_embed_messages.post_type_placeholder,allowClear:true,multiple:true});e("#badgeos_achievements_list_user_id").select2({ajax:{url:ajaxurl,type:"POST",data:function(e){return{q:e,action:"get-users"}},results:function(e,t){return{results:e.data}}},id:function(e){return e.ID},formatResult:function(e){return e.user_login},formatSelection:function(e){return e.user_login},placeholder:badgeos_shortcode_embed_messages.user_placeholder,allowClear:true})})(jQuery)
JavaScript
0.000001
@@ -508,16 +508,384 @@ .show()%7D +function c(t)%7BsetTimeout(function()%7Be(%22#TB_window%22).addClass(%22badgeos-shortcode-thickbox%22);h(t)%7D,0)%7Dfunction h(t)%7BsetTimeout(function()%7Bvar n=t.attr(%22data-width%22);e(%22.badgeos-shortcode-thickbox%22).width(n);var r=e(%22.badgeos-shortcode-thickbox%22).height();e(%22.badgeos-shortcode-thickbox #TB_ajaxContent,%22+%22.badgeos-shortcode-thickbox .wrap%22).width(n-50).height(r-50)%7D,0)%7D e(%22#sele @@ -2619,16 +2619,175 @@ r:true%7D) +;e(%22body%22).on(%22click%22,%22#insert_badgeos_shortcodes%22,function(t)%7Bt.preventDefault();c(e(this))%7D);e(window).resize(function()%7Bh(e(%22#insert_badgeos_shortcodes%22))%7D) %7D)(jQuer
f3bd053fd06cbc5946c107179acf52553f6ae35d
Add license header to SimpleDAOController.
js/foam/ui/SimpleDAOController.js
js/foam/ui/SimpleDAOController.js
CLASS({ name: 'SimpleDAOController', package: 'foam.ui', extends: 'foam.ui.SimpleView', requires: [ 'foam.ui.TableView', ], properties: [ { model_: 'foam.core.types.DAOProperty', name: 'data', hidden: true, }, { name: 'daoView', lazyFactory: function() { var view = this.TableView.create({ data: this.data, scrollEnabled: true, editColumnsEnabled: true, }); return view }, postSet: function(o, n) { if (o) o.hardSelection$.removeListener(this.onHardSelection); if (n) n.hardSelection$.addListener(this.onHardSelection); }, }, { name: 'selection', view: 'foam.ui.DetailView', lazyFactory: function() { return this.data.model.create(); }, }, ], actions: [ { name: 'save', code: function() { this.data.put(this.selection.clone()); this.resetSelection(); }, }, { name: 'deleteSelected', isEnabled: function() { return this.selection.id; }, code: function() { this.data.remove(this.selection); this.resetSelection(); }, }, { name: 'deleteAll', code: function() { this.data.removeAll(); this.resetSelection(); }, }, ], listeners: [ { name: 'onHardSelection', code: function() { if (this.daoView.hardSelection) { this.selection = this.daoView.hardSelection.clone(); } }, }, { name: 'resetSelection', code: function() { this.selection = this.data.model.create(); this.daoView.hardSelection = undefined; }, }, ], templates: [ function toHTML() {/* <div style="height: 300px; overflow: hidden;"> %%daoView </div> $$deleteAll $$selection $$save $$deleteSelected */}, ] });
JavaScript
0
@@ -1,8 +1,638 @@ +/**%0A * @license%0A * Copyright 2016 Google Inc. All Rights Reserved.%0A *%0A * Licensed under the Apache License, Version 2.0 (the %22License%22);%0A * you may not use this file except in compliance with the License.%0A * You may obtain a copy of the License at%0A *%0A * http://www.apache.org/licenses/LICENSE-2.0%0A *%0A * Unless required by applicable law or agreed to in writing, software%0A * distributed under the License is distributed on an %22AS IS%22 BASIS,%0A * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A * See the License for the specific language governing permissions and%0A * limitations under the License.%0A */%0A%0A CLASS(%7B%0A
dd280a6c6501d9f5e161976d83b31ef3d65dec35
fix blind mode
ui/round/src/view/table.js
ui/round/src/view/table.js
var m = require('mithril'); var game = require('game').game; var status = require('game').status; var renderClock = require('../clock/view').renderClock; var renderCorrespondenceClock = require('../correspondenceClock/view'); var renderReplay = require('./replay'); var renderUser = require('./user'); var button = require('./button'); function playerAt(ctrl, position) { return ctrl.vm.flip ^ (position === 'top') ? ctrl.data.opponent : ctrl.data.player; } function topPlayer(ctrl) { return playerAt(ctrl, 'top'); } function bottomPlayer(ctrl) { return playerAt(ctrl, 'bottom'); } function compact(x) { if (Object.prototype.toString.call(x) === '[object Array]') { var elems = x.filter(function(n) { return n !== undefined }); return elems.length > 0 ? elems : null; } return x; } function renderPlayer(ctrl, player) { return player.ai ? m('div.username.user_link.online', [ m('i.line'), m('name', renderUser.aiName(ctrl, player)) ]) : renderUser.userHtml(ctrl, player); } function isSpinning(ctrl) { return ctrl.vm.loading || ctrl.vm.redirecting; } function spinning(ctrl) { if (isSpinning(ctrl)) return m.trust(lichess.spinnerHtml); } function renderTableEnd(ctrl) { var buttons = compact(spinning(ctrl) || [ button.backToTournament(ctrl) || [ button.answerOpponentRematch(ctrl) || button.cancelRematch(ctrl) || button.followUp(ctrl) ] ]); return [ renderReplay(ctrl), buttons ? m('div.control.buttons', buttons) : null, renderPlayer(ctrl, bottomPlayer(ctrl)) ]; } function renderTableWatch(ctrl) { var buttons = compact(spinning(ctrl) || button.watcherFollowUp(ctrl)); return [ renderReplay(ctrl), buttons ? m('div.control.buttons', buttons) : null, renderPlayer(ctrl, bottomPlayer(ctrl)) ]; } function renderTablePlay(ctrl) { var d = ctrl.data; var buttons = spinning(ctrl) || button.submitMove(ctrl) || compact([ button.forceResign(ctrl), button.threefoldClaimDraw(ctrl), button.cancelDrawOffer(ctrl), button.answerOpponentDrawOffer(ctrl), button.cancelTakebackProposition(ctrl), button.answerOpponentTakebackProposition(ctrl), (d.tournament && game.nbMoves(d, d.player.color) === 0) ? m('div.suggestion', m('div.text[data-icon=j]', ctrl.trans('youHaveNbSecondsToMakeYourFirstMove', d.tournament.nbSecondsForFirstMove) )) : null ]); return [ renderReplay(ctrl), (ctrl.vm.moveToSubmit || ctrl.vm.dropToSubmit) ? null : ( isSpinning(ctrl) ? null : m('div', { class: 'control icons' }, [ game.abortable(d) ? button.standard(ctrl, null, 'L', 'abortGame', 'abort') : button.standard(ctrl, game.takebackable, 'i', 'proposeATakeback', 'takeback-yes', ctrl.takebackYes), button.standard(ctrl, game.drawable, '2', 'offerDraw', 'draw-yes'), ctrl.vm.resignConfirm ? button.resignConfirm(ctrl) : button.standard(ctrl, game.resignable, 'b', 'resign', 'resign-confirm', ctrl.resign) ]) ), buttons ? m('div.control.buttons', buttons) : null, renderPlayer(ctrl, bottomPlayer(ctrl)) ]; } function whosTurn(ctrl, color) { var d = ctrl.data; if (status.finished(d) || status.aborted(d)) return; return m('div.whos_turn', d.game.player === color ? ( d.player.spectator ? ctrl.trans(d.game.player + 'Plays') : ctrl.trans( d.game.player === d.player.color ? 'yourTurn' : 'waitingForOpponent' ) ) : '' ); } function anyClock(ctrl, position) { var player = playerAt(ctrl, position); if (ctrl.clock && !ctrl.data.blind) return renderClock(ctrl, player, position); else if (ctrl.data.correspondence && ctrl.data.game.turns > 1) return renderCorrespondenceClock( ctrl.correspondenceClock, ctrl.trans, player.color, position, ctrl.data.game.player ); else return whosTurn(ctrl, player.color); } module.exports = function(ctrl) { return m('div.table_wrap', [ anyClock(ctrl, 'top'), m('div', { class: 'table' }, [ renderPlayer(ctrl, topPlayer(ctrl)), m('div.table_inner', ctrl.data.player.spectator ? renderTableWatch(ctrl) : ( game.playable(ctrl.data) ? renderTablePlay(ctrl) : renderTableEnd(ctrl) ) ) ]), anyClock(ctrl, 'bottom') ]); }
JavaScript
0.000001
@@ -3576,28 +3576,8 @@ lock - && !ctrl.data.blind ) re
9696525e5c86dcfff659d81c311963a73b63fd78
Add limit to 5 concurrent requests in downloadFiltered
utils/download_filtered.js
utils/download_filtered.js
'use strict'; const child_process = require('child_process'); const async = require('async'); const fs = require('fs-extra'); const tmp = require('tmp'); const _ = require('lodash'); const logger = require('pelias-logger').get('download'); function downloadFiltered(config, callback) { const targetDir = config.imports.openaddresses.datapath; const files = config.imports.openaddresses.files; logger.info(`Attempting to download selected data files: ${files}`); fs.ensureDir(targetDir, (err) => { if (err) { logger.error(`error making directory ${targetDir}`, err); return callback(err); } async.each(files, downloadSource.bind(null, targetDir), callback); }); } function downloadSource(targetDir, file, callback) { logger.info(`Downloading ${file}`); const source = _.replace(file, '.csv', '.zip'); const sourceUrl = `https://results.openaddresses.io/latest/run/${source}`; const tmpZipFile = tmp.tmpNameSync({postfix: '.zip'}); async.series( [ // download the zip file into the temp directory (callback) => { logger.debug(`downloading ${sourceUrl}`); child_process.exec(`curl -L -X GET -o ${tmpZipFile} ${sourceUrl}`, callback); }, // unzip file into target directory (callback) => { logger.debug(`unzipping ${tmpZipFile} to ${targetDir}`); child_process.exec(`unzip -o -qq -d ${targetDir} ${tmpZipFile}`, callback); }, // delete the temp downloaded zip file fs.remove.bind(null, tmpZipFile) ], callback); } module.exports = downloadFiltered;
JavaScript
0
@@ -634,15 +634,23 @@ each +Limit (files, + 5, dow @@ -1592,8 +1592,9 @@ iltered; +%0A
5a8841dafb98e2846076478d2e4f81cefae0d11a
Fix typos and faulty conditionals.
js/tinymce/classes/fmt/Preview.js
js/tinymce/classes/fmt/Preview.js
/** * Preview.js * * Released under LGPL License. * Copyright (c) 1999-2015 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * Internal class for generating previews styles for formats. * * Example: * Preview.getCssText(editor, 'bold'); * * @private * @class tinymce.fmt.Preview */ define("tinymce/fmt/Preview", [ "tinymce/util/Tools" ], function(Tools) { var each = Tools.each; function getCssText(editor, format) { var name, previewFrag, previewElm, elmChain, dom = editor.dom; var previewCss = '', parentFontSize, previewStyles; previewStyles = editor.settings.preview_styles; // No preview forced if (previewStyles === false) { return ''; } // Default preview if (!previewStyles) { previewStyles = 'font-family font-size font-weight font-style text-decoration ' + 'text-transform color background-color border border-radius outline text-shadow'; } function wrapIfRequired(elm, ancestors) { var elmName = elm.nodeName.toLowerCase(); var elmRule = editor.schema.getElementRule(elmName); var parent, parentName, parentsRequired = elmRule.parentsRequired; if (parentsRequired && parentsRequired.length) { parentName = parentsRequired[0]; if (ancestors && ancestors.length) { Tools.each(parentsRequired, function(parentRequired) { var idx = Tools.indexOf(ancestors, parentRequired); if (idx !== -1) { parentName = parentsRequired // remove candidates upto and including the matched ancestor ancestors.splice(0, idx + 1); return false; } }); } parent = dom.create(parentName); parent.appendChild(elm); return wrapIfRequired(parent, ancestors); } else { return elm; } } function extractTagsOnly(selector) { var ancestry; // take into account only first one selector = selector.split(/\s*,\s*/)[0]; // tighten selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1'); ancestry = selector.split(/(?:>|\s+)/); return Tools.map(ancestry, function(selector) { // if there are any sibling selectors we only take the target var siblings = selector.split(/(?:~\+|~|\+)/); selector = siblings[siblings.length - 1]; // strip off any IDs, CLASSes or PSEUDOS return Tools.trim(selector).replace(/[\.#:\[].+$/, ''); }).reverse(); } // Removes any variables since these can't be previewed function removeVars(val) { return val.replace(/%(\w+)/g, ''); } // Create block/inline element to use for preview if (typeof format == "string") { format = editor.formatter.get(format); if (!format) { return; } format = format[0]; } elmChain = extractTagsOnly(format.selector); name = elmChain.shift() || format.block || format.inline || 'span'; previewElm = dom.create(name); previewFrag = wrapIfRequired(previewElm, elmChain); // Add format styles to preview element each(format.styles, function(value, name) { value = removeVars(value); if (value) { dom.setStyle(previewElm, name, value); } }); // Add attributes to preview element each(format.attributes, function(value, name) { value = removeVars(value); if (value) { dom.setAttrib(previewElm, name, value); } }); // Add classes to preview element each(format.classes, function(value) { value = removeVars(value); if (!dom.hasClass(previewElm, value)) { dom.addClass(previewElm, value); } }); editor.fire('PreviewFormats'); // Add the previewElm outside the visual area dom.setStyles(previewElm, {position: 'absolute', left: -0xFFFF}); editor.getBody().appendChild(previewFrag); // Get parent container font size so we can compute px values out of em/% for older IE:s parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true); parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0; each(previewStyles.split(' '), function(name) { var value = dom.getStyle(previewElm, name, true); // If background is transparent then check if the body has a background color we can use if (name == 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) { value = dom.getStyle(editor.getBody(), name, true); // Ignore white since it's the default color, not the nicest fix // TODO: Fix this by detecting runtime style if (dom.toHex(value).toLowerCase() == '#ffffff') { return; } } if (name == 'color') { // Ignore black since it's the default color, not the nicest fix // TODO: Fix this by detecting runtime style if (dom.toHex(value).toLowerCase() == '#000000') { return; } } // Old IE won't calculate the font size so we need to do that manually if (name == 'font-size') { if (/em|%$/.test(value)) { if (parentFontSize === 0) { return; } // Convert font size from em/% to px value = parseFloat(value, 10) / (/%$/.test(value) ? 100 : 1); value = (value * parentFontSize) + 'px'; } } if (name == "border" && value) { previewCss += 'padding:0 2px;'; } previewCss += name + ':' + value + ';'; }); editor.fire('AfterPreviewFormats'); //previewCss += 'line-height:normal'; dom.remove(previewFrag); return previewCss; } return { getCssText: getCssText }; });
JavaScript
0
@@ -1290,16 +1290,17 @@ red%5B0%5D;%0A +%0A %09%09%09%09if ( @@ -1420,13 +1420,13 @@ s.in -dexOf +Array (anc @@ -1494,31 +1494,31 @@ tName = -parentsRequired +ancestors%5Bidx%5D; %0A%09%09%09%09%09%09%09 @@ -1655,24 +1655,25 @@ %09%09%7D);%0A%09%09%09%09%7D%0A +%0A %09%09%09%09parent = @@ -1868,16 +1868,90 @@ estry;%0A%0A +%09%09%09if (!selector %7C%7C typeof(selector) !== 'string') %7B%0A%09%09%09%09return %5B%5D;%0A%09%09%09%7D%0A%0A %09%09%09// ta
18b40082966cc01c4c5f56f2b154f6c86e41798b
Add no-return-await rule
index.js
index.js
/* eslint-disable filenames/no-index */ module.exports = { parser: 'babel-eslint', parserOptions: { ecmaVersion: 2019, sourceType: 'module', impliedStrict: true, ecmaFeatures: { jsx: true }, }, extends: [ 'eslint:recommended', 'plugin:react/recommended', 'plugin:ava/recommended', 'plugin:jsx-a11y/recommended', 'plugin:import/errors', 'plugin:import/warnings', 'plugin:jest/recommended', 'plugin:prettier/recommended', 'prettier/react', ], plugins: ['react', 'ava', 'import', 'jsx-a11y', 'filenames', 'react-hooks'], env: { es6: true, node: true }, settings: { 'import/ignore': ['node_modules'], react: { version: 'detect' }, }, rules: { 'arrow-body-style': ['error'], 'filenames/match-exported': ['warn'], 'filenames/match-regex': [ 'error', '^([A-Za-z]([A-Za-z0-9])*(\\.test|\\.test\\.skip|\\.stories)?)|(webpack.config.babel)$', ], 'filenames/no-index': ['warn'], 'import/no-anonymous-default-export': ['error'], 'import/no-extraneous-dependencies': ['error'], 'import/order': [ 'error', { groups: ['builtin', 'external', 'parent', 'sibling', 'index'] }, ], 'no-inline-comments': ['error'], 'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'], 'no-shadow': ['error'], 'no-sync': ['error'], 'no-use-before-define': ['error', 'nofunc'], 'no-var': ['error'], 'object-shorthand': ['error'], 'prefer-const': ['error'], 'prefer-destructuring': ['error'], 'prefer-template': ['error'], 'prettier/prettier': [ 'error', { singleQuote: true, tabWidth: 4, printWidth: 100, trailingComma: 'all' }, ], 'react-hooks/exhaustive-deps': ['error'], 'react-hooks/rules-of-hooks': ['error'], 'react/display-name': ['off'], 'react/jsx-filename-extension': ['error', { extensions: ['.js', '.jsx'] }], 'react/jsx-fragments': ['error'], 'react/jsx-key': ['warn'], 'react/no-array-index-key': ['warn'], 'react/prop-types': ['warn', { skipUndeclared: true }], 'react/require-default-props': ['off'], 'react/void-dom-elements-no-children': ['error'], strict: ['error'], }, overrides: [ { files: [ '*.test.js', 'webpack.config.babel.js', 'webpack.config.js', 'webpack.config.ava.js', ], rules: { 'import/no-extraneous-dependencies': ['error', { devDependencies: true }] }, }, ], };
JavaScript
0.000218
@@ -1470,24 +1470,62 @@ tatement'%5D,%0A + 'no-return-await': %5B'error'%5D,%0A 'no-
6768df7b75e122f4f7d2b17e448aea1e5a6767f6
add jsig annotations
index.js
index.js
var _ = function (x) { return x } // collection fns _.pair = function (key, val) { var o = {} o[key] = val return o } _.contains = function (obj, key) { for (var k in obj) { if (k === key) { return true } } return false } // quantifier _.some = function (obj, predicate) { predicate = predicate || function () { return true } for (var k in obj) { if (predicate(obj[k], k)) { return true } } return false } _.every = function (obj, predicate) { for (var k in obj) { if (!predicate(obj[k], k)) { return false } } return true } // collection _.count = function (obj, predicate) { if (typeof predicate !== 'function') { return Object.keys(obj).length } var c = 0 for (var k in obj) { if (predicate(obj[k])) { c++ } } return c } _.filter = function (obj, predicate) { var o = {} for (var k in obj) { if (predicate(obj[k])) { o[k] = obj[k] } } return o } _.forEach = function (obj, iterator) { for (var k in obj) { iterator(obj[k], k) } return obj } // algebraic fns _.map = function (obj, fn) { var o = {} for (var k in obj) { o[k] = fn(obj[k], k) } return o } _.reduce = function (obj, fn, seed) { var val = seed || {} for (var k in obj) { val = fn(val, obj[k], k) } return val } _.concat = function (objA, objB) { for (var k in objB) { objA[k] = objB[k] } return objA } /* i might be doing this wrong: * this applies a function to each key-value pair in a dictionary * where the function is (Pair) => Array * and returns a flattened Array */ _.flatMap = function (obj, fn) { return _.reduce(obj, function (arr, val, key) { return arr.concat(fn(val, key)) }, []) } module.exports = _
JavaScript
0.000001
@@ -1,12 +1,28 @@ +// (Any) =%3E Any%0A var _ = func @@ -62,16 +62,43 @@ ion fns%0A +// (String, Any) =%3E Object%0A _.pair = @@ -158,24 +158,55 @@ return o%0A%7D%0A%0A +// (Object, String) =%3E Boolean%0A _.contains = @@ -331,16 +331,111 @@ antifier +s%0A%0A// type Predicate : (value: Any, key?: String) =%3E Boolean%0A%0A// (Object, Predicate) =%3E Boolean %0A_.some @@ -618,16 +618,51 @@ false%0A%7D +%0A%0A// (Object, Predicate) =%3E Boolean %0A_.every @@ -807,16 +807,48 @@ llection +%0A%0A// (Object, Predicate?) =%3E Int %0A_.count @@ -1056,16 +1056,49 @@ rn c%0A%7D%0A%0A +// (Object, Predicate) =%3E Object%0A _.filter @@ -1237,16 +1237,48 @@ rn o%0A%7D%0A%0A +// (Object, Function) =%3E Object%0A _.forEac @@ -1393,16 +1393,70 @@ ic fns%0A%0A +// (Object, (val: Any, key: String) =%3E Any) =%3E Object%0A _.map = @@ -1555,16 +1555,123 @@ rn o%0A%7D%0A%0A +// type Reducer : (accumulator: Any, val: Any, key: String) =%3E Any%0A%0A// (Object, Reducer, seed: Any) =%3E Any%0A _.reduce @@ -1795,16 +1795,46 @@ val%0A%7D%0A%0A +// (Object, Object) =%3E Object%0A _.concat @@ -1930,17 +1930,17 @@ A%0A%7D%0A%0A/* -i +I might b @@ -2103,12 +2103,42 @@ ray%0A - */%0A +// (Object, Reducer) =%3E Array%0A _.fl
186f96e1222ee42aba6e325399dc6698f5c9d651
Change .break() API to instantly reject the promise.
index.js
index.js
const Worker = require('tiny-worker'); /** * Encapuslates the underlying Web Worker through asynchronous calls. */ exports.LMLayer = class LMLayer { constructor() { // Worker state this._worker = new Worker('lmlayer.js'); this._worker.onmessage = this._onmessage.bind(this); // Keep track of individual requests to make a nice async/await API. this._promises = new PromiseStore; // Keep track of tokens. this._currentToken = Number.MIN_SAFE_INTEGER; } /** * [async] Sends a context, transform, and token to the LMLayer. */ predictWithContext({transform, context, customToken}) { let token = customToken === undefined ? this._nextToken() : customToken; return new Promise((resolve, reject) => { this._promises.track(token, resolve, reject); this._cast('predict', { token, transform, context }); }); } /** * Throw an asynchronous method call (a "cast") over to the Web Worker. */ _cast(method, payload) { this._worker.postMessage({ method, ...payload }); } /** * Handles the wrapped worker's onmessage events. */ _onmessage(event) { const {method, token} = event.data; let accept = this._promises.keep(token); if (method === 'suggestions') { accept(event.data); } else { let reject = this._promises.break(token); reject(new Error(`Unknown message: ${method}`)); } } /** * Returns the next token. Note: mutates state. */ _nextToken() { let token = this._currentToken++; if (!Number.isSafeInteger(token)) { throw new RangeError('Ran out of usable tokens'); } return token; } }; /** * Associate tokens with promises. * * You can .track() them, and then .keep() them. You may also .break() them. */ class PromiseStore { constructor() { this._promises = new Map(); } /** * Associate a token with its respective resolve and reject callbacks. */ track(token, resolve, reject) { if (this._promises.has(token)) { reject(`Existing request with token ${token}`); } this._promises.set(token, {reject, resolve}); } /** * Fetch a promise's resolution function. * * Calling the resolution function will stop tracking the promise. */ keep(token) { let callbacks = this._promises.get(token); if (!callbacks) { throw new Error(`No promise associated with token: ${token}`); } let accept = callbacks.resolve; // This acts like the resolve function, BUT, it removes the promise from // the store -- because it's resolved! return (resolvedValue) => { this._promises.delete(token); return accept(resolvedValue); }; } /** * Fetch a promise's reject function. * * Calling the reject functino will stop tracking the promise. */ break(token) { let callbacks = this._promises.get(token); if (!callbacks) { throw new Error(`No promise associated with token: ${token}`); } let accept = callbacks.reject; // This acts like the resolve function, BUT, it removes the promise from // the store -- because it's resolved! return (error) => { this._promises.delete(token); return accept(error); }; } }
JavaScript
0
@@ -1313,21 +1313,8 @@ - let reject = thi @@ -1340,24 +1340,18 @@ oken -); +, %0A -reject( + new @@ -1385,16 +1385,23 @@ ethod%7D%60) +%0A );%0A %7D @@ -2700,111 +2700,71 @@ * -Fetch a promise's reject function.%0A *%0A * Calling the reject functino will stop tracking the promise +Instantly reject and forget a promise associated with the token .%0A @@ -2776,24 +2776,31 @@ break(token +, error ) %7B%0A let @@ -2939,190 +2939,8 @@ %7D%0A - let accept = callbacks.reject;%0A%0A // This acts like the resolve function, BUT, it removes the promise from%0A // the store -- because it's resolved!%0A return (error) =%3E %7B%0A @@ -2973,30 +2973,31 @@ n);%0A - return accep +callbacks.rejec t(error) @@ -2998,21 +2998,14 @@ error);%0A - %7D;%0A %7D%0A%7D%0A
ee88dfce4c7c3de9746e19aad635907bf3907f6a
Tidy source code.
index.js
index.js
var short = '-', long = '--', sre = /^-[^-]+/, lre = /^--[^-]+/, negate = /^--no-/; function camelcase(flag) { return flag.split('-').reduce(function(str, word){ return str + word[0].toUpperCase() + word.slice(1); }); } function toOptionKey(arg, negated) { var key = arg.replace(/^-+/, ''); if(negated) key = key.replace(/^no-/, '') key = camelcase(key); return key; } function unique(value, index, self) { return self.indexOf(value) === index; } function flags(arg, output) { arg = arg.replace(/^-/, ''); var keys = arg.split(''); keys = keys.filter(unique); keys.forEach(function(key) { output.flags[key] = true; }) } function options(arg, output, next) { var equals = arg.indexOf('='), value, result = false, negated; var flag = false, key; if(!next || (next && next.indexOf('-') == 0 && equals == -1)) { flag = true; } if(equals > -1) { value = arg.slice(equals + 1); arg = arg.slice(0, equals); }else if(next && !flag) { value = next; result = true; } negated = negate.test(arg); key = toOptionKey(arg, negated); // treating long option as a flag if(flag) { output.flags[key] = negated ? false : true; }else{ if(!output.options[key]) { output.options[key] = value; }else{ if(!Array.isArray(output.options[key])) { output.options[key] = [output.options[key]]; } output.options[key].push(value); } } return result; } function parse(args) { args = args || process.argv.slice(2); args = args.slice(0); var output = {flags: {}, options: {}, raw: args.slice(0), stdin: false}; var i, arg, l = args.length, key, skip; for(i = 0;i < l;i++) { arg = '' + args.shift(), skip = false; if(arg == short) { output.stdin = true; }else if(arg == long) { output.unparsed = args.slice(i); break; }else if(sre.test(arg)) { flags(arg, output); }else if(lre.test(arg)) { skip = options(arg, output, args[0]); if(skip) { args.shift(); i--; l--; continue; } } l--; i--; } return output; } module.exports = parse;
JavaScript
0
@@ -9,18 +9,16 @@ t = '-', -%0A long = @@ -21,19 +21,21 @@ g = '--' -,%0A +;%0Avar sre = / @@ -43,18 +43,16 @@ -%5B%5E-%5D+/, -%0A lre = / @@ -61,18 +61,16 @@ -%5B%5E-%5D+/, -%0A negate @@ -1094,44 +1094,8 @@ d);%0A - // treating long option as a flag%0A if
aa14dd7b2fc79fa3f95169c47e97a69e51b703ec
Add options for radius and location lookup
index.js
index.js
var koa = require('koa'), app = koa(), router = require('koa-router')(), json = require('koa-json'), moment = require('moment'), Partyflock = require('partyflock'); // extra environment vars var debug = false, endpoint = 'partyflock.nl'; if(process.env.DEBUG) { debug = !!process.env.DEBUG; } if(process.env.ENDPOINT) { endpoint = process.env.ENDPOINT; } // we need CONSUMERKEY and CONSUMERSECRET to operate successfully if(process.env.CONSUMERKEY && process.env.CONSUMERSECRET) { // instantiate partyflock var partyflockInstance = new Partyflock(process.env.CONSUMERKEY, process.env.CONSUMERSECRET, endpoint, debug); // router: fetch agenda for today router.get('/', function *() { var result = yield partyflockInstance.date.lookup(moment().format('YYYYMMDD')).then(function(res) { if(!res) { return Promise.reject('Agenda lookup failed!'); } return res.date.agenda.party; }).map(function(party) { var visitors = 0, location = '', name = '', id = ''; try { location = party.location.name; } catch(e) {} try { visitors = party.visitors.user.length; } catch(e) {} try { name = party.name; } catch(e) {} try { id = party.id; } catch(e) {} return { 'id': id, 'name': name, 'location': location, 'visitors': visitors }; }).then(function(res) { return {'success': true, 'data': res, 'message': ''}; }).catch(function(err) { return {'success': false, 'message': err}; }); this.body = result; }); // router: fetch for individual party router.get('/party/:id', function *() { var id = parseInt(this.params.id, 10); var headers = { 'Pf-ResultWish': 'party(name,genre(name),area(name,lineup(id,time_start,time_end,artist(name),type)))' }; var result = yield partyflockInstance.party.lookup(id, headers).then(function(res) { if(!res) { return Promise.reject('Party lookup failed!'); } return {'success': true, 'data': res, 'message': ''}; }).catch(function(err) { return {'success': false, 'message': err}; }); this.body = result; }); // middlewares app .use(router.routes()) .use(router.allowedMethods()) .use(json()); app.listen(process.env.PORT || 3000); } else { console.error('Process variables CONSUMERKEY and CONSUMERSECRET not set, exiting!'); process.exit(1); }
JavaScript
0
@@ -708,32 +708,745 @@ function *() %7B%0A + var headers = %7B%0A 'Pf-ResultWish': 'date(agenda(party(name,stamp,location(name),visitors(user(id)))))'%0A %7D;%0A if(this.request && this.request.query) %7B%0A if('latitude' in this.request.query && this.request.query.latitude) %7B%0A headers%5B'Pf-Latitude'%5D = parseFloat(this.request.query.latitude, 10);%0A %7D%0A if('longitude' in this.request.query && this.request.query.longitude) %7B%0A headers%5B'Pf-Longitude'%5D = parseFloat(this.request.query.longitude, 10);%0A %7D%0A if('radius' in this.request.query && this.request.query.radius) %7B%0A headers%5B'Pf-Radius'%5D = parseInt(this.request.query.radius, 10);%0A %7D%0A%0A console.log('params', this.request.query, headers);%0A %7D%0A %0A var result = @@ -1510,16 +1510,25 @@ YYMMDD') +, headers ).then(f
659819fc4a639d75cd00dca6651a32385c09c19d
Move parameter validation to the top
index.js
index.js
/* global module, process, require */ 'use strict'; var Promise = require('bluebird'); /** * Takes an EventEmitter and converts it into a function that returns a promise. * @param {object} params Object that contains parameters * @param {object} params.eventEmitter Function that returns an event emitter * @param {object} params.applyThis This function performs a params.eventEmitter.apply * If the "this" object needs to be different, set it here. * @param {object} params.listeners List of event listeners. * Must contain the following: * - on/once: the function to run 'on' all events or 'once' an event is emitted * - name: name of event * - isResult: when set to true, the argument passed into this function will be * treated as a result when the promise is resolved * - isError: the error handler * @param {function} params.transform Transforms the result before resolving it * @returns {function} */ var promisifyEventEmitter = function(params) { if (!params.eventEmitter) { throw new Error('params.eventEmitter is required'); } return function() { var args = arguments; var applyThis = params.applyThis || params.eventEmitter; var e = params.eventEmitter.apply(applyThis, args); var error; var result; var hasDataListener = false; var hasErrorListener = false; var hasEndListener = false; var addListener = function (listener, method) { e[method](listener.name, function (arg) { /** @namespace listener.isResult */ if (listener.isResult) { hasDataListener = true; result = arg; } /** @namespace listener.isError */ if (listener.isError) { hasErrorListener = true; error = arg; } listener[method](arg); if (listener.name === 'end') { hasEndListener = true; endFunction(); } }); }; params.listeners.forEach(function(listenerOptions) { if (!listenerOptions.name) { throw new Error('listener must have a name'); } /** @namespace listenerOptions.on */ /** @namespace listenerOptions.once */ if (listenerOptions.on) { addListener(listenerOptions, 'on'); } else if (listenerOptions.once) { addListener(listenerOptions, 'once'); } else { throw new Error('listener must either have an "on" or "once" function'); } }); if (!hasDataListener) { e.once('data', function(data) { result = data; }); } if (!hasErrorListener) { e.on('error', function(err) { error = err; }); } return new Promise(function(resolve, reject) { var endFunction = function() { if (error) { return reject(error); } var resolveThis = params.transform && result ? params.transform(result) : result; return resolve(resolveThis); }; if (!hasEndListener) { e.once('end', endFunction); } }); }; }; module.exports = promisifyEventEmitter;
JavaScript
0
@@ -1366,16 +1366,783 @@ ');%0A %7D%0A + if (params.listeners && !Array.isArray(params.listeners)) %7B%0A throw new Error('params.listeners must be an array of listener options objects');%0A %7D%0A if (params.listeners) %7B%0A params.listeners.forEach(function(listenerOption) %7B%0A if (!listenerOption.name) %7B%0A throw new Error('listener option must have a name');%0A %7D%0A if (!listenerOption.on && !listenerOption.once) %7B%0A throw new Error('listener option must have a %22once%22 or %22on%22 function');%0A %7D%0A if (listenerOption.on && typeof listenerOption.on !== 'function') %7B%0A throw new Error('%22on%22 must be a function');%0A %7D%0A if (listenerOption.once && typeof listenerOption.once !== 'function') %7B%0A throw new Error('%22once%22 must be a function');%0A %7D%0A %7D);%0A %7D%0A return @@ -2151,24 +2151,24 @@ unction() %7B%0A - var args @@ -3032,105 +3032,8 @@ ) %7B%0A - if (!listenerOptions.name) %7B%0A throw new Error('listener must have a name');%0A %7D%0A @@ -3225,32 +3225,32 @@ Options.once) %7B%0A + addListe @@ -3283,104 +3283,8 @@ ');%0A - %7D else %7B%0A throw new Error('listener must either have an %22on%22 or %22once%22 function');%0A
d4993202effb4f51c477e3b775892782c399e315
Replace comma first with always var
index.js
index.js
var util = require('util'); var url = require('url'); module.exports = function (everyauth) { if (! everyauth.oauth2) { everyauth.oauth2 = require("everyauth-oauth2")(everyauth); } everyauth.facebook = everyauth.oauth2.submodule('facebook') .configurable({ scope: 'specify types of access: See http://developers.facebook.com/docs/authentication/permissions/' , fields: 'specify returned fields: See http:/developers.facebook.com/docs/reference/api/user/' }) .apiHost('https://graph.facebook.com') .oauthHost('https://graph.facebook.com') .authPath('https://www.facebook.com/dialog/oauth') .authQueryParam('scope', function () { return this._scope && this.scope(); }) .authCallbackDidErr( function (req) { var parsedUrl = url.parse(req.url, true); return parsedUrl.query && !!parsedUrl.query.error; }) .fetchOAuthUser( function (accessToken) { var p = this.Promise(); var fieldsQuery = ""; if (this._fields && this._fields.length > 0){ fieldsQuery = "?fields=" + this.fields(); } this.oauth.get(this.apiHost() + '/me' + fieldsQuery, accessToken, function (err, data) { if (err) return p.fail(err); var oauthUser = JSON.parse(data); p.fulfill(oauthUser); }) return p; }) .moduleErrback( function (err, seqValues) { if (err instanceof Error) { var next = seqValues.next; return next(err); } else if (err.extra) { var facebookResponse = err.extra.res , serverResponse = seqValues.res; serverResponse.writeHead( facebookResponse.statusCode , facebookResponse.headers); serverResponse.end(err.extra.data); } else if (err.statusCode) { var serverResponse = seqValues.res; serverResponse.writeHead(err.statusCode); serverResponse.end(err.data); } else { console.error(err); throw new Error('Unsupported error type'); } }) ; everyauth.facebook.mobile = function (isMobile) { if (isMobile) { this.authPath('https://m.facebook.com/dialog/oauth'); } return this; }; everyauth.facebook.popup = function (isPopup) { if (isPopup) { this.authQueryParam('display', 'popup'); } return this; }; everyauth.facebook.AuthCallbackError = AuthCallbackError; return everyauth.facebook; }; function AuthCallbackError (req) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'AuthCallbackError'; var parsedUrl = url.parse(req.url, true); this.message = parsedUrl.query.error_description; } util.inherits(AuthCallbackError, Error);
JavaScript
0.999088
@@ -1478,26 +1478,27 @@ xtra.res +; %0A - , +var serverR
cd6ec7080bd01c111cd583bd0fca4379c22474a3
use strict, and fix ms
index.js
index.js
var u = require('./util') var Api = require('./api') var Muxrpc = require('muxrpc') var pull = require('pull-stream') var Rate = require('pull-rate') var MultiServer = require('multiserver') var Inactive = require('pull-inactivity') function isFunction (f) { return 'function' === typeof f } function isString (s) { return 'string' === typeof s } function isObject (o) { return o && 'object' === typeof o && !Array.isArray(o) } function toBase64 (s) { if(isString(s)) return s else s.toString('base64') //assume a buffer } function each(obj, iter) { if(Array.isArray(obj)) return obj.forEach(iter) for(var k in obj) iter(obj[k], k, obj) } function coearseAddress (address) { if(isObject(address)) { var protocol = 'net' if (address.host.endsWith(".onion")) protocol = 'onion' return [protocol, address.host, address.port].join(':') +'~'+['shs', toBase64(address.key)].join(':') } return address } var ip = require('ip') function parse(addr) { var parts = addr.split('~')[0].split(':') var protocol = parts[0], host = parts[1] return { protocol: protocol, group: (ip.isLoopback(host) || !host) ? 'loopback' : ip.isPrivate(host) ? 'local' : 'internet', host: host } } function msLogger (stream) { var meta = {tx: 0, rx:0, pk: 0} stream = Rate(stream, function (len, up) { meta.pk ++ if(up) meta.tx += len else meta.rx += len }) stream.meta = meta return stream } //opts must have appKey module.exports = function (opts) { //this weird thing were some config is loaded first, then the rest later... not necessary. var _opts = opts var appKey = (opts && opts.caps && opts.caps.shs || opts.appKey) opts.permissions = opts.permissions || {} var create = Api(opts.permissions ? [{ permissions: opts.permissions, init: function () {} }]: null) return create .use({ manifest: { auth: 'async', address: 'sync', manifest: 'sync', }, init: function (api, opts, permissions, manifest) { //legacy, but needed to pass tests. opts.appKey = opts.appKey || _opts.appKey //XXX: LEGACY CRUFT - TIMEOUTS var defaultTimeout = ( opts.defaultTimeout || 5e3 // 5 seconds. ) var timeout_inactivity if(opts.timers && !isNaN(opts.timers.inactivity)) timeout_inactivity = opts.timers.inactivity //if opts.timers are set, pick a longer default //but if not, set a short default (as needed in the tests) timeout_inactivity = timeout_inactivity || (opts.timers ? 600e3 : 5e3) var peers = api.peers = {} var transports = [] var transforms = [ //function () { return shs } ] var server, msServer, msClient function createServer () { if(server) return server var suites = [] if(transforms.length < 1) throw new Error('secret-stack needs at least 1 transform protocol') transforms.forEach(function (createTransform, instance) { transports.forEach(function (createTransport) { suites.push([ createTransport(instance), createTransform({}) ]) }) }) var ms = MultiServer(suites) server = ms.server(setupRPC) return server } setImmediate(createServer) function setupRPC (stream, manf, isClient) { var rpc = Muxrpc(create.manifest, manf || create.manifest)(api, stream.auth === true ? create.permissions.anonymous : stream.auth) var rpcStream = rpc.createStream() rpc.id = '@'+u.toId(stream.remote) if(timeout_inactivity > 0 && api.id !== rpc.id) rpcStream = Inactive(rpcStream, timeout_inactivity) rpc.meta = stream.meta pull(stream, rpcStream, stream) //keep track of current connections. if(!peers[rpc.id]) peers[rpc.id] = [] peers[rpc.id].push(rpc) rpc.once('closed', function () { peers[rpc.id].splice(peers[rpc.id].indexOf(rpc), 1) }) api.emit('rpc:connect', rpc, !!isClient) return rpc } return { config: opts, //can be called remotely. auth: function (pub, cb) { cb() }, address: function () { return this.getAddress() }, getAddress: function () { createServer(); return ms.stringify() }, manifest: function () { return create.manifest }, getManifest: function () { return this.manifest() }, //cannot be called remote. connect: function (address, cb) { createServer() ms.client(coearseAddress(address), function (err, stream) { return err ? cb(err) : cb(null, setupRPC(stream, null, true)) }) }, multiserver: { transport: function (fn) { if(server) throw new Error('cannot add protocol after server initialized') transports.push(fn); return this }, transform: function (fn) { transforms.push(fn); return this }, }, close: function (err, cb) { if(isFunction(err)) cb = err, err = null api.closed = true ;(server.close || server)(function (err) { api.emit('close', err) cb && cb(err) }) if(err) { each(peers, function (connections, id) { each(connections, function (rpc) { rpc.close(err) }) }) } } } } }) //default network plugins .use(require('./plugins/net')) .use(require('./plugins/shs')) }
JavaScript
0.000002
@@ -1,12 +1,25 @@ +'use strict'%0A var u @@ -2764,24 +2764,8 @@ , ms -Server, msClient %0A%0A @@ -3238,20 +3238,16 @@ -var ms = Mul
72ff3803c833acefb1c275a0f092968652896eef
Update to use new engine build options
index.js
index.js
'use strict'; var path = require('path'); var _ = require('lodash'); var PLUGIN_NAME = 'kalabox-plugin-git'; module.exports = function(kbox) { var events = kbox.core.events; var engine = kbox.engine; var globalConfig = kbox.core.deps.lookup('globalConfig'); kbox.whenApp(function(app) { // Helpers /** * Gets plugin conf from the appconfig or from CLI arg **/ var getOpts = function(options) { var defaults = app.config.pluginConf[PLUGIN_NAME]; _.each(Object.keys(defaults), function(key) { if (_.has(options, key)) { defaults[key] = options[key]; } }); return defaults; }; /** * Runs a git command on the app data container **/ var runGitCMD = function(payload, options, done) { var cmd = payload; var opts = getOpts(options); var gitUser; if (opts['git-username']) { gitUser = opts['git-username']; } else { gitUser = (process.platform === 'win32') ? process.env.USERNAME : process.env.USER; } var gitEmail = (opts['git-email']) ? opts['git-email'] : gitUser + '@kbox'; engine.run( 'kalabox/git:stable', cmd, { Env: [ 'APPNAME=' + app.name, 'APPDOMAIN=' + app.domain, 'GITUSER=' + gitUser, 'GITEMAIL=' + gitEmail ], HostConfig: { VolumesFrom: [app.dataContainerName] } }, { Binds: [app.config.homeBind + ':/ssh:rw'] }, done ); }; // Events // Install the util container for our things events.on('post-install', function(app, done) { // If profile is set to dev build from source var opts = { name: 'kalabox/git:stable', build: false, src: '' }; if (globalConfig.profile === 'dev') { opts.build = true; opts.src = path.resolve(__dirname, 'dockerfiles', 'git', 'Dockerfile'); } engine.build(opts, done); }); // Tasks // git wrapper: kbox git COMMAND kbox.tasks.add(function(task) { task.path = [app.name, 'git']; task.description = 'Run git commands.'; task.kind = 'delegate'; task.func = function(done) { // We need to use this faux bin until the resolution of // https://github.com/syncthing/syncthing/issues/1056 runGitCMD(this.payload, this.options, done); }; }); }); };
JavaScript
0
@@ -1727,314 +1727,91 @@ -// If profile is set to dev build from source%0A var opts = %7B%0A name: 'kalabox/git:stable',%0A build: false,%0A src: ''%0A %7D;%0A if (globalConfig.profile === 'dev') %7B%0A opts.build = true;%0A opts.src = path.resolve(__dirname, 'dockerfiles', 'git', 'Dockerfile'); +var opts = %7B%0A name: 'git',%0A srcRoot = path.resolve(__dirname) %0A %7D %0A @@ -1798,32 +1798,33 @@ dirname)%0A %7D +; %0A engine.bu
e91f74d36861f09edeb897fef6c3f09c2abebaae
Remove unused route (#5925)
ui/app/router.js
ui/app/router.js
import EmberRouter from '@ember/routing/router'; import config from './config/environment'; const Router = EmberRouter.extend({ location: config.locationType, rootURL: config.rootURL, }); Router.map(function() { this.route('jobs', function() { this.route('run'); this.route('job', { path: '/:job_name' }, function() { this.route('task-group', { path: '/:name' }); this.route('definition'); this.route('versions'); this.route('deployments'); this.route('evaluations'); this.route('allocations'); this.route('edit'); }); }); this.route('clients', function() { this.route('client', { path: '/:node_id' }); }); this.route('servers', function() { this.route('server', { path: '/:agent_id' }); }); this.route('allocations', function() { this.route('allocation', { path: '/:allocation_id' }, function() { this.route('task', { path: '/:name' }, function() { this.route('logs'); }); }); }); this.route('settings', function() { this.route('tokens'); }); if (config.environment === 'development') { this.route('freestyle'); } this.route('not-found', { path: '/*' }); }); export default Router;
JavaScript
0
@@ -544,34 +544,8 @@ ');%0A - this.route('edit');%0A
fbbb2c679220dd11e7f7500c0d4485c9d0d9a40c
add getScrollHeight() method
index.js
index.js
require("./style.css"); import React from 'react'; import classNames from 'classnames'; import throttle from 'lodash/function/throttle.js'; import ScreenAttributes, {getScreenAttributes} from 'screen-attributes-mixin'; const Scroller = React.createClass({ mixins: [ScreenAttributes], getInitialState(){ let {screenHeight} = getScreenAttributes(); return { screenHeight }; }, componentDidMount(){ this.scrollBottom(); if(this.props.onScroll){ this.throttledOnScroll = throttle(this.props.onScroll, 500); } }, componentWillUpdate(nextProps, nextState){ let ctn = this.refs.scroller.getDOMNode(); if (ctn.scrollTop + ctn.offsetHeight >= ctn.scrollHeight) { if(this.props.marginBottom < nextProps.marginBottom || this.state.screenHeight !== nextState.screenHeight){ this.needScrollToBottom = true; } } }, componentDidUpdate(prevProps, prevState){ if(this.needScrollToBottom){ this.needScrollToBottom = false; this.scrollBottom(); } }, needScrollToBottom: false, preventOnScrollEvent: false, throttledOnScroll: null, onScroll(e) { if(this.preventOnScrollEvent){ this.preventOnScrollEvent = false; return; } if (e.target.scrollTop + e.target.offsetHeight >= e.target.scrollHeight) { if (this.props.onScrollBottom) { this.props.onScrollBottom(); } } else if (e.target.scrollHeight > e.target.offsetHeight && e.target.scrollTop <= 0) { if (this.props.onScrollTop) { this.props.onScrollTop(); } } if (this.props.onScroll) { this.throttledOnScroll(e.target.scrollTop); } }, scrollBottom() { this.preventOnScrollEvent = true; let ctn = this.refs.scroller.getDOMNode(); ctn.scrollTop = ctn.scrollHeight - ctn.offsetHeight; }, setScrollTop(scrollTop) { this.preventOnScrollEvent = true; this.refs.scroller.getDOMNode().scrollTop = scrollTop; }, render() { let marginTop = this.props.marginTop; let marginBottom = this.props.marginBottom; if (typeof marginTop !== 'number') { marginTop = DEVICE_TYPE === 'desktop' ? 0 : 49; } if (typeof marginBottom !== 'number') { marginBottom = DEVICE_TYPE === 'desktop' ? 0 : 49; } let style = { height: this.state.screenHeight - marginTop - marginBottom, marginTop }; Object.assign(style, this.props.style); return ( <div ref="scroller" className={classNames("comm-scroller", this.props.className)} onScroll={this.onScroll} style={style}> {this.props.children} </div> ); } }); export default Scroller;
JavaScript
0.000001
@@ -1230,16 +1230,107 @@ : null,%0A + getScrollHeight()%7B%0A return this.refs.scroller.getDOMNode().scrollHeight;%0A %7D,%0A onSc
e905808f321fb8dd0cf4d23cec7f4f80da752e7b
Fix linting :joy-cat:.
index.js
index.js
class Guards { constructor () { this.guardRegex = /[^=<>!']=[^=]/ this.templateRegex = /[^|]\|[^|]/ } buildPredicate (constants, guard) { return new Function( '', [ `const { ${this.destructureProps(constants)} } = ${JSON.stringify(constants)}`, `return ${guard}` ].join(';') ) } destructureProps (constants) { return Object.keys(constants).join(',') } equal (constants) { const self = this // Inline guards need filtering. return template => template.raw[0] .split(this.templateRegex) .filter(g => g.trim() !== '') .map((g, i) => { // Remove break line and extract the guard. const parts = g.trim().split(this.guardRegex) return [ parts[0], JSON.parse(`${parts[1].trim().replace(/'/g, '"')}`) ] }) .find(g => self.buildPredicate(constants, g[0])())[1] } } module.exports = (c, t) => (new Guards()).equal(c, t)
JavaScript
0.000001
@@ -143,24 +143,56 @@ s, guard) %7B%0A + // eslint-disable-next-line%0A return n
b1149867160248e7030aa3dcf85fca3a47c2a53c
Remove rules that conflict with prettier
index.js
index.js
module.exports = { "env": { "browser": true }, "extends": [ "airbnb", // These prettier configs are used to disable inherited rules that conflict // with the way prettier will format code. Full info here: // https://github.com/prettier/eslint-config-prettier "prettier", "prettier/flowtype", "prettier/react" ], "parser": "babel-eslint", "plugins": [ "flowtype", "import", "react", "prettier" ], "rules": { "arrow-parens" : [0, "as-needed"], "flowtype/define-flow-type": "error", "flowtype/object-type-delimiter": ["error", "semicolon"], "flowtype/require-valid-file-annotation": [ 2, "always" ], "flowtype/semi": "error", "flowtype/space-after-type-colon": [ "error", "always" ], "flowtype/space-before-type-colon": [ "error", "never" ], "flowtype/type-id-match": [ "error", "^([A-Z][a-z0-9]+)+$" ], "flowtype/use-flow-type": "error", "import/no-duplicates": "error", "no-duplicate-imports": "off", "no-multiple-empty-lines": [ "error", { "max": 1, "maxBOF": 0, "maxEOF": 0 } ], "no-nested-ternary": "off", "no-warning-comments": [ "error", { "terms": [ "fixme" ] } ], "quote-props": [ "error", "as-needed", { "numbers": true } ], "react/no-unused-prop-types": "off", "no-confusing-arrow": "off", "prettier/prettier": [ "error", { // Options to pass to prettier: https://github.com/prettier/prettier#api "singleQuote": true, "trailingComma": "all" }, "@prettier" ] } };
JavaScript
0
@@ -468,47 +468,8 @@ : %7B%0A - %22arrow-parens%22 : %5B0, %22as-needed%22%5D,%0A @@ -524,312 +524,64 @@ ype/ -object-type-delimiter%22: %5B%22error%22, %22semicolon%22%5D,%0A %22flowtype/require-valid-file-annotation%22: %5B%0A 2,%0A %22always%22%0A %5D,%0A %22flowtype/semi%22: %22error%22,%0A %22flowtype/space-after-type-colon%22: %5B%0A %22error%22,%0A %22always%22%0A %5D,%0A %22flowtype/space-before-type-colon%22: %5B%0A %22error%22,%0A %22never +require-valid-file-annotation%22: %5B%0A 2,%0A %22always %22%0A @@ -782,138 +782,8 @@ f%22,%0A - %22no-multiple-empty-lines%22: %5B%0A %22error%22,%0A %7B%0A %22max%22: 1,%0A %22maxBOF%22: 0,%0A %22maxEOF%22: 0%0A %7D%0A %5D,%0A @@ -933,169 +933,34 @@ %22 -quote-props%22: %5B%0A %22error%22,%0A %22as-needed%22,%0A %7B%0A %22numbers%22: true%0A %7D%0A %5D,%0A %22react/no-unused-prop-types%22: %22off%22,%0A %22no-confusing-arrow +react/no-unused-prop-types %22: %22
e896c5d4cd90afe275331dece5810be2aee5520d
Remove text field from the linter messages
index.js
index.js
/** * @author Titus Wormer * @copyright 2015 Titus Wormer * @license MIT * @module atom:linter:alex * @fileoverview Linter. */ /* global atom */ 'use strict'; /* * Dependencies (alex is lazy-loaded later). */ var deps = require('atom-package-deps'); var minimatch = require('minimatch'); var alex; /* * Constants. */ var config = atom.config; /** * Activate. */ function activate() { deps.install('linter-alex'); } /** * Atom meets alex to catch insensitive, inconsiderate * writing. * * @return {LinterConfiguration} */ function linter() { var CODE_EXPRESSION = /`([^`]+)`/g; /** * Transform a (stringified) mdast range to a linter * nested-tuple. * * @param {Object} location - Positional information. * @return {Array.<Array.<number>>} - Linter range. */ function toRange(location) { return [[ Number(location.start.line) - 1, Number(location.start.column) - 1 ], [ Number(location.end.line) - 1, Number(location.end.column) - 1 ]]; } /** * Transform a reason for warning from alex into * pretty HTML. * * @param {string} reason - Messsage in plain-text. * @return {string} - Messsage in HTML. */ function toHTML(reason) { return reason.replace(CODE_EXPRESSION, '<code>$1</code>'); } /** * Transform VFile messages * nested-tuple. * * @see https://github.com/wooorm/vfile#vfilemessage * * @param {VFileMessage} message - Virtual file error. * @return {Object} - Linter error. */ function transform(message) { return { 'type': 'Error', 'text': message.reason, 'html': toHTML(message.reason), 'filePath': this.getPath(), 'range': toRange(message.location) }; } /** * Handle on-the-fly or on-save (depending on the * global atom-linter settings) events. Yeah! * * Loads `alex` on first invocation. * * @see https://github.com/atom-community/linter/wiki/Linter-API#messages * * @param {AtomTextEditor} editor - Access to editor. * @return {Promise.<Message, Error>} - Promise * resolved with a list of linter-errors or an error. */ function onchange(editor) { var settings = config.get('linter-alex'); if (minimatch(editor.getPath(), settings.ignoreFiles)) { return []; } return new Promise(function (resolve, reject) { var messages; if (!alex) { alex = require('alex'); } try { messages = alex(editor.getText()).messages; } catch (e) { reject(e); return; } resolve((messages || []).map(transform, editor)); }); } // He is such a douche So is she.. return { 'grammarScopes': [ 'source.gfm', 'source.pfm', 'text.git-commit', 'text.plain', 'text.plain.null-grammar' ], 'name': 'alex', 'scope': 'file', 'lintOnFly': true, 'lint': onchange } } /* * Expose. */ module.exports = { 'config': { 'ignoreFiles': { 'description': 'Disable files matching (minimatch) glob', 'type': 'string', 'default': '' } }, 'provideLinter': linter, 'activate': activate }
JavaScript
0
@@ -1701,42 +1701,8 @@ r',%0A - 'text': message.reason,%0A
b9483f69bb89105d53e50baa08c27a0dfe132b77
Update CPULoad to handle both formats
index.js
index.js
var _os = require('os'); var _param = require('./param.json'); var _request = require('request'); var _tools = require('graphdat-plugin-tools'); var _httpOptions; // username/password options for the URL var _previous = {}; // remember the previous poll data so we can provide proper counts // At a minimum, we need a way to contact apache if (!_param.url) { console.error('To get statistics from Apache, a statistics URL is required'); process.exit(-1); } // if there is no http or https, guess its http if (_param.url.substring(0,7) !== 'http://' && _param.url.substring(0,8) !== 'https://') _param.url = 'http://' + _param.url; // tell apache to make the output 'machine readable' if (_param.url.slice(-5) !== '?auto') _param.url += '?auto'; // This this is a URL and we have a name and password, then we need to add an auth header if (_param.username) _httpOptions = { auth: { user: _param.username, pass: _param.password, sendImmediately: true } }; // If we do not have a source, we prefix everything with the servers hostname _param.source = (_param.source || _os.hostname()).trim(); // If you do not have a poll intevarl, use 1000 as the default _param.pollInterval = _param.pollInterval || 1000; // get the natural difference between a and b function diff(a, b) { if (a == null || b == null) return 0; else return Math.max(a - b, 0); } function handleError(err) { console.error(err); process.exit(-1); } function poll(cb) { // call apache to get the stats page _request.get(_param.url, _httpOptions, function(err, resp, body) { if (err) return handleError(err); if (resp.statusCode !== 200) return handleError(new Error('Apache returned with an error - recheck the URL and credentials that you provided')); if (!body) return handleError(new Error('Apache statistics return empty')); var current = {}; var lines = body.split('\n'); lines.forEach(function(line) { // skip over empty lines if (!line) return; // parse the record var data = line.split(':'); var key = data[0].trim(); var value = data[1]; if (value == null || value === '') return; var fValue = parseFloat(value,10); if (fValue === 0 || fValue) current[key] = fValue; else current[key] = value.trim(); }); var totalWorkers = (current['BusyWorkers'] || 0) + (current['IdleWorkers'] || 0); var busyRatio = (totalWorkers) ? current['BusyWorkers'] / totalWorkers : 0; var requests = diff(current['Total Accesses'], _previous['Total Accesses']); // because of the interval cut off lines, on a really slow site you will get 0's // use the previous value if that happens current['totalBytes'] = diff(current['Total kBytes'], _previous['Total kBytes']) * 1024; if (requests > 0 && current['totalBytes'] === 0) current['totalBytes'] = _previous['totalBytes']; var bytesPerReq = (requests) ? current['totalBytes']/requests : 0; console.log('APACHE_REQUESTS %d %s', requests, _param.source); console.log('APACHE_BYTES %d %s', current['totalBytes'], _param.source); console.log('APACHE_BYTES_PER_REQUEST %d %s', bytesPerReq, _param.source); console.log('APACHE_CPU %d %s', current['CPULoad'] || 0, _param.source); console.log('APACHE_BUSY_WORKERS %d %s', current['BusyWorkers'], _param.source); console.log('APACHE_IDLE_WORKERS %d %s', current['IdleWorkers'], _param.source); console.log('APACHE_BUSY_RATIO %d %s', busyRatio, _param.source); _previous = current; setTimeout(poll, _param.pollInterval); }); } poll();
JavaScript
0
@@ -3217,24 +3217,124 @@ equests : 0; +%0A var cpuLoad = current%5B'CPULoad'%5D %7C%7C 0;%0A if (cpuLoad %3E 1)%0A cpuLoad /= 100; %0A%0A co @@ -3599,38 +3599,22 @@ d %25s', c -urrent%5B'CPULoad'%5D %7C%7C 0 +puLoad , _param
9d473a0d74dcb0d4de3d2b0707dc5057693f256e
debug links
index.js
index.js
var getUrl = function(url, callback) { var oReq = new XMLHttpRequest(); oReq.addEventListener("load", callback); oReq.open("GET", url); oReq.send(); } var extractHearingType = function(hearingRow) { return hearingRow.querySelectorAll('td')[4].textContent.trim(); }; var extractCaseReportLink = function(hearingRow) { return hearingRow.querySelectorAll('td')[2].querySelector('a').href.replace('criminalcalendar', 'criminalcasereport'); }; var isPrelim = function(hearingRow) { return extractHearingType(hearingRow) == "PRELIMINARY HEARING"; }; var hearingNodes = function() { return document.querySelectorAll('tr[id^="tr_row"]'); }; var nodeListToArray = function(nodeList) { var a = []; for (var i = 0, l = nodeList.length; i < l; i += 1) { a[a.length] = nodeList[i]; }; return a; }; var extractHearings = function() { return nodeListToArray(hearingNodes()); }; var filterPrelims = function(hearings) { return hearings.filter(isPrelim); }; var hearings = extractHearings(); var prelims = filterPrelims(hearings); var prelimLinks = prelims.forEach(extractCaseReportLink(element)); console.log("There are " + hearings.length + " hearings."); console.log("There are " + prelims.length + " prelims."); console.log(prelimLinks);
JavaScript
0
@@ -315,38 +315,42 @@ hearingRow) %7B%0A -return +var link = hearingRow.quer @@ -442,24 +442,60 @@ sereport');%0A + console.log(link);%0A return link;%0A %7D;%0Avar isPre
a35691fa39b82314ffc68c46a30bc8ae0cc952da
Fix non handled errors
index.js
index.js
'use strict'; var inquirer = require('inquirer'); var Promise = require('bluebird'); var fs = Promise.promisifyAll(require('fs')); var DB = require('./db'); var User = require('./lib/user.js'); var UserList = require('./lib/userList.js'); var VCardParser = require('./lib/vCardParser.js'); var db = new DB('users.json'); // Disable app when running from QUnit if (module.parent) { return; } console.log('Bienvenue dans l\'interface de simulation d\'utilisation du logiciel de gestion de conacts de ClearWater.'); var question = { type: 'list', name: 'main', message: 'Que souhaitez vous faire ?', choices: [ { name: 'Transmettre mes contacts au serveur', value: 't'}, { name: 'Exporter les contacts au format csv', value: 'e'}, ] }; /** * Save the db after choosing action * @param {DB} db The DB instance * @param {UserList} ul The UserList instance */ function saveUL (db, ul) { db.raw().users = []; ul.users.forEach(function (user) { db.table('users').push(user.toJSON()); }); db.save(); console.log('Enregistré dans users.json'); } inquirer.prompt(question, function (answer) { var questions; // Export to csv if (answer.main == 'e') { questions = [ { type: 'list', name: 'order', message: 'Comment voullez vous trier le fichier CSV ?', choices: [ { name: 'Par nom', value: 't'}, { name: 'Par prénom', value: 'e'}, { name: 'Par organisation', value: 'o'}, ] }, { type: 'list', name: 'ascending', message: 'Trier de façon', choices: [ { name: 'Alphabétique', value: 'y'}, { name: 'Anti-alphabétique', value: 'n'}, ] }, { type: 'input', name: 'path', message: 'Nom du fichier', default: 'out.csv' } ]; inquirer.prompt(questions, function (answer) { UserList .fromDB(db) .then(function (ul) { ul.sort(function (a, b) { if (answer.order === 't') { if (answer.ascending === 'y') { return a.lastName.localeCompare(b.lastName); } else { return b.lastName.localeCompare(a.lastName); } } else if (answer.order === 'e') { if (answer.ascending === 'y') { return a.firstName.localeCompare(b.firstName); } else { return b.firstName.localeCompare(a.firstName); } } else if (answer.order === 'o') { if (answer.ascending === 'y') { return a.organisation.localeCompare(b.organisation); } else { return b.organisation.localeCompare(a.organisation); } } }); return ul.toCSV(); }) .then(function (csv) { return fs.writeFileAsync(answer.path, csv); }); }); } // Treansmit contacts to server else { console.log('Lors d\'une utilsiation réel de cette bibliothèque les deux questions suivantes ' + 'n\'existerons pas car les réponses sont donnés automatiqument par le smartphone'); console.log('Vous êtes donc un commercial qui veut envoyer ses contacts sur le serveur.'); // TODO add default values for both questions questions = [ { type : 'input', name : 'name', message : 'Quel est votre nom ?', default : 'John Doe', validate: function (value) { var pass = value.match(/^[\w ]+$/i); if (pass) { return true; } else { return 'Merci d\'enter un nom de commercial valide'; } } }, { type : 'input', name : 'file', message: 'Veuillez entrer le chemin vers le fichier vcard à importer', default: 'test/testCard.vCard' } ]; inquirer.prompt(questions, function (answer) { var ul; UserList .fromDB(db) .then(function (ul_) { ul = ul_; return fs.readFileAsync(answer.file, 'utf8'); }) .then(function (vcard) { var parser = new VCardParser(vcard); var user = parser.parse(); if (ul.verify(user)) { var indexes = ul.findIndexesUser(user); var toComapreWith = ul.users[indexes[0]]; console.log('L\'utilisateur est déjà dans la base.\nVersion A (en base, datée du ' + toComapreWith.revision + ') : \n' + require('util').inspect(toComapreWith.toJSON()) + '\n\nVersion B (en ajout, datée du ' + user.revision + ') : \n' + require('util').inspect(user.toJSON())); questions = [ { type : 'list', name : 'action', message: 'Que voulez-vous faire ?', choices: [ { name: 'Garder A', value: User.ONLY_A }, { name: 'Garder B', value: User.ONLY_B }, { name: 'Fusionner', value: User.MERGE }, { name: 'Garder les deux', value: User.BOTH } ] } ]; inquirer.prompt(questions, function (answer) { ul.add(user); ul.merge(user, answer.action); saveUL(db, ul); }); } else { ul.add(user); saveUL(db, ul); } }); }); } });
JavaScript
0.001032
@@ -6916,32 +6916,204 @@ %7D%0A + %7D)%0A .catch(function (err) %7B%0A console.log('Erreur lors de l%5C'analyse du fichier: ');%0A console.log(err);%0A
a7ebc46165720b1419e9636aab9f34e52524812d
Optimize dividing the process in two stages: prototype generation + binding data to output object
index.js
index.js
function mapValues(obj, fn) { return Object.entries(obj).reduce((acc, [k, v]) => { const r = fn(k, v) if (r === undefined) return acc[k] = r return acc }, {}) } /** * A proxy for an Object that checks for existence of the keys, * and throws an error in case. */ function checkerProxy(data) { if (Proxy === undefined) { console.warn("Can't validate input data Object, because we need Proxy!") return data } return new Proxy(data, { get(target, key) { if (key in target) { return target[key] } else { throw new Error(`Data object is missing key '${key}':`) } }, }) } /** * Gettifize: getter + memoize * Transforms an Object of functions (input,output) => outputValue * in an Object of getters with closured 'input' and gettifized 'output'. */ function gettifize(obj, data) { const dataProxy = checkerProxy(data) const protoDefinitions = mapValues(obj, (k, fn) => ({ enumerable: true, get() { const value = fn(dataProxy, this) Object.defineProperty(this, k, { value, enumerable: true }) return value }, })) const proto = Object.defineProperties({}, protoDefinitions) const gettifized = Object.create(proto) return gettifized } function materialize(t) { const keys = Object.keys(Object.getPrototypeOf(t)) keys.forEach(k => t[k]) // Alternative: // for (let k in t) { t[k] } return t } export default function traph(o) { const transform = (i) => materialize(gettifize(o, i)) transform.lazy = (i) => gettifize(o, i) return transform }
JavaScript
0.99838
@@ -645,187 +645,62 @@ %0A%7D%0A%0A -/**%0A * Gettifize: getter + memoize%0A * Transforms an Object of functions (input,output) =%3E outputValue%0A * in an Object of getters with closured 'input' and gettifized 'output'.%0A */ +const DATA_ATTRIBUTE = Symbol('TRAPH_DATA_ATTRIBUTE')%0A %0Afun @@ -705,25 +705,30 @@ unction -g +buildG ettifize (obj, da @@ -723,61 +723,21 @@ fize -(obj, data +Proto(obj ) %7B%0A - const dataProxy = checkerProxy(data)%0A co @@ -838,34 +838,99 @@ nst -value = fn(dataProxy, this +input = this%5BDATA_ATTRIBUTE%5D%0A const output = this%0A const value = fn(input, output )%0A @@ -1093,47 +1093,62 @@ )%0A -const gettifized = Object.create +return proto%0A%7D%0A%0Afunction buildGettifizeBinder (proto) + %7B %0A r @@ -1157,56 +1157,45 @@ urn -gettifized%0A%7D%0A%0Afunction materialize( +function bindData(inpu t) %7B%0A + const keys @@ -1194,101 +1194,528 @@ nst -keys = Object.keys(Object.getPrototypeOf(t))%0A keys.forEach(k =%3E t%5Bk%5D)%0A // Alternative:%0A // +inputProxy = checkerProxy(input)%0A const output = Object.create(proto)%0A Object.defineProperty(output, DATA_ATTRIBUTE, %7B value: inputProxy %7D)%0A return output%0A %7D%0A%7D%0A%0A/**%0A * Gettifize: getter + memoize%0A * Transforms an Object of functions of the form (input,output) =%3E outputValue%0A * in an Object of auto-memoizing getters deriving from input && output.%0A */%0Afunction gettifize(obj) %7B%0A const proto = buildGettifizeProto(obj)%0A const binder = buildGettifizeBinder(proto)%0A return binder%0A%7D%0A%0Afunction materialize(t) %7B%0A for @@ -1782,24 +1782,58 @@ traph(o) %7B%0A + const dataBinder = gettifize(o)%0A const tran @@ -1859,29 +1859,27 @@ rialize( -gettifize(o, +dataBinder( i))%0A tr @@ -1904,21 +1904,19 @@ =%3E -gettifize(o, +dataBinder( i)%0A
ea9706c8af5b97b407247288b47923c2e6784730
print err.stack on fail when using ConsoleReporter
index.js
index.js
/*global System,global*/ import mocha from "mocha"; import chai, { expect } from "chai"; export { loadTestFile, loadTestFiles, runTestFiles, chai, mocha, expect }; function ConsoleReporter(runner) { var passes = 0; var failures = 0; runner.on('pass', function(test){ passes++; console.log('pass: %s', test.fullTitle()); }); runner.on('fail', function(test, err){ failures++; console.log('fail: %s -- error: %s', test.fullTitle(), err.message); }); runner.on('end', function(){ console.log('end: %d/%d', passes, passes + failures); }); } function mochaForFile(fileName, optMocha) { return loadTestFile(fileName, null/*parent*/, optMocha); } function gatherTests(suite, depth) { return [{title: suite.title, fullTitle: suite.fullTitle(), depth: depth, type: "suite"}] .concat(suite.tests.map(ea => ({title: ea.title, fullTitle: ea.fullTitle(), type: "test", depth: depth}))) .concat(suite.suites.reduce((tests, suite) => tests.concat(gatherTests(suite, depth + 1)), [])); } function loadTestFiles(files, optMocha, optGLOBAL, reporter) { var m = optMocha || new (mocha.constructor)({reporter: reporter || ConsoleReporter}), testState = {mocha: m, files: [], tests: []}; return files.reduce((nextP, f) => nextP .then(() => loadTestFile(f, null, m, optGLOBAL) .then(_testState => { testState.files.push(_testState.file); testState.tests = testState.tests.concat(_testState.tests); return testState; })), Promise.resolve()); } function loadTestFile(file, parent, optMocha, optGLOBAL, reporter) { var GLOBAL = optGLOBAL || (typeof window !== "undefined" ? window : global); return System.normalize(file, parent) .then((file) => { System.delete(file); // if (System.__lively_vm__) delete System.__lively_vm__.loadedModules[file] }) .then(() => prepareMocha(optMocha || new (mocha.constructor)({reporter: reporter || ConsoleReporter}), GLOBAL) .then(mocha => { mocha.suite.emit('pre-require', GLOBAL, file, mocha); return System.import(file) .then(imported => { mocha.suite.emit('require', imported, file, mocha) mocha.suite.emit('post-require', GLOBAL, file, mocha) return {mocha: mocha, file: file, tests: gatherTests(mocha.suite, 0)}; }) })); } function prepareMocha(mocha, GLOBAL) { mocha.suite.on('pre-require', context => { GLOBAL.afterEach = context.afterEach || context.teardown; GLOBAL.after = context.after || context.suiteTeardown; GLOBAL.beforeEach = context.beforeEach || context.setup; GLOBAL.before = context.before || context.suiteSetup; GLOBAL.describe = context.describe || context.suite; GLOBAL.it = context.it || context.test; GLOBAL.setup = context.setup || context.beforeEach; GLOBAL.suiteSetup = context.suiteSetup || context.before; GLOBAL.suiteTeardown = context.suiteTeardown || context.after; GLOBAL.suite = context.suite || context.describe; GLOBAL.teardown = context.teardown || context.afterEach; GLOBAL.test = context.test || context.it; GLOBAL.run = context.run; }); mocha.ui("bdd"); return Promise.resolve(mocha); } function runTestFiles(files, options) { if (!options) options = {}; return loadTestFiles(files, options.mocha, options.global, options.reporter) .then(testState => new Promise((resolve, reject) => { var mocha = testState.mocha; if (options.grep) mocha = mocha.grep(options.grep); return mocha.run(failures => resolve(failures)); })); } // runTestFiles(["http://localhost:9001/lively.ast-es6/tests/capturing-test.js"], {}).catch(show.curry("%s")).then(show.curry("%s"))
JavaScript
0.000001
@@ -462,15 +462,35 @@ err. -message +stack %7C%7C err.message %7C%7C err );%0A
a96277f6ca0cce7a83886f14e54d6bdab438e5e0
use tlsOptions instead of httpsOptions
index.js
index.js
require('app-module-path').addPath(__dirname); var express = require('express'); var passport = require('passport'); var session = require('express-session'); var http = require('http'); var https = require('https'); var app = express(); var inventory_router = require('api/inventory.js'); var reservations_router = require('api/reservations.js'); var auth = require('api/auth.js'); var users_router = require('api/users.js'); var letsencrypt = require('api/letsencrypt.js'); var letsencrypt_xp = letsencrypt.le_express; var do_cert_check = letsencrypt.do_cert_check; var auth_router = auth.router; var ensureAuthenticated = auth.ensureAuthenticated; /* Setup session middleware */ app.use(session({ secret: 'a secret key', cookie: { secure: false } })); app.use(passport.initialize()); app.use(passport.session()); app.use('/api', auth_router); /* Auth requests aren't behind the authentication barrier themselves */ app.use('/public', express.static('public')); /* For serving the login page, etc. */ app.get('/', (req, res) => { if(req.user) { res.redirect('/inventory.html'); } else { res.redirect('/public/login.html'); } }); /* API requests below this need to be authenticated */ app.use(ensureAuthenticated); app.use('/api', users_router); app.use('/api', inventory_router); app.use('/api', reservations_router); app.use(express.static('static')); http.createServer(letsencrypt_xp.middleware(require('redirect-https')())).listen( 80, () => { console.log("ACME http-01 challenge handler listening on port 80"); } ); https.createServer( letsencrypt_xp.httpsOptions, letsencrypt_xp.middleware(app) ).listen(443, () => { console.log("ACME tls-sni-01 / tls-sni-02 challenge handler and main app listening on port 443"); }); do_cert_check(); /* app.listen(80, () => { console.log("Server listening on port 80."); }); */
JavaScript
0.000001
@@ -1586,20 +1586,18 @@ rypt_xp. -http +tl sOptions
70f958d90610737ad0857d33b608c412cdeb8ac5
Add custom Views directory
index.js
index.js
'use strict'; /** * @fileoverview Punchcard CMS Init */ const bodyParser = require('body-parser'); const express = require('express'); const logger = require('morgan'); const nunjucks = require('nunjucks'); const path = require('path'); const config = require('config'); const contentTypes = require('punchcard-content-types'); const indexRoutes = require('./lib/routes/index'); const contentTypesRoutes = require('./lib/routes/content-types'); const session = require('./lib/auth/sessions'); let app = express(); app = session(app); // Nunjucks templating setup app.set('views', path.join(__dirname, 'views')); nunjucks.configure(['views', 'templates'], { 'autoescape': true, 'express': app, }); app.set('view engine', 'html'); // TODO: where does `dev` come from; should control with config app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(express.static(path.join(process.cwd(), 'public'))); /* @name sitewide persistent variables @description create variables which will work in any route */ app.locals.siteName = 'Punchcard CMS'; app.locals.contentTypesConfig = config.contentTypes; contentTypes().then(types => { // make content type object available to entire express app app.locals.contentTypesNames = types; return; }).catch(err => { console.error(err); }); /* @name home page route @description create route for the site landing page */ app.use('/', indexRoutes); /* @name content types route @description create routes for all content type configurations in ./content-types */ app.use('/content', contentTypesRoutes); /* @name 404 @description catch 404 and forward to error handler */ app.use((req, res, next) => { const 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((err, req, res) => { res.status(err.status || 500); res.render('error', { message: err.message, error: err, }); }); } // production error handler // no stacktraces leaked to user app.use((err, req, res) => { res.status(err.status || 500); res.render('error', { message: err.message, error: {}, }); }); /* @description run the server if and only if this file is being run directly */ if (!module.parent) { app.listen(config.env.port, () => { console.log(`Server starting on ${config.env.url}`); }); } module.exports = app;
JavaScript
0
@@ -567,57 +567,176 @@ tup%0A -app.set('views', path.join(__dirname, 'views')) +const views = %5B%0A path.join(process.cwd(), 'views'),%0A path.join(process.cwd(), 'templates'),%0A path.join(__dirname, 'views'),%0A path.join(__dirname, 'templates'),%0A%5D ;%0A +%0A nunj @@ -754,30 +754,13 @@ ure( -%5B' views -', 'templates'%5D , %7B%0A
c301c22cd4cd1d1dbabdfa2b6b04b297342514e5
Add git fetch to deploy operation.
index.js
index.js
var express = require('express'); var bodyParser = require('body-parser'); var morgan = require('morgan'); var async = require('async'); var spawn = require('child_process').spawn; var shellescape = require('shell-escape'); function shellExec(out, cmd, options, cb) { if (!cmd) { return cb(); } if (!options) { options = {}; } options.stdio = 'pipe'; var child = spawn('sh', [ '-c', cmd ], options); child.on('close', function(code) { cb(code == 0 ? undefined : code); }); child.stdout.on('data', function(data) { out.write(data); }); child.stderr.on('data', function(data) { out.write(data); }); return child; } var Deplorator = function(port, config) { var self = this; this.app = express(); this.port = port; this.config = config; this.queueRunning = false; this.queue = []; this.app.use(morgan()); this.app.use(bodyParser()); this.app.post('/:id/deploy', function(req, res) { self._processDeploy(req, res); }); }; Deplorator.prototype._deploy = function(res, name, commit, cb) { var self = this; var fullName = name + ':' + commit; var config = this.config[name]; console.log('Deploy start:', fullName) async.series([ function(cb) { shellExec(res, config.preDeploy, { cwd: config.path }, cb); }, function(cb) { shellExec(res, shellescape([ 'git', 'checkout', commit ]), { cwd: config.path }, cb); }, function(cb) { shellExec(res, shellescape([ 'git', 'submodule', 'update' ]), { cwd: config.path }, cb); }, function(cb) { shellExec(res, config.postDeploy, { cwd: config.path }, cb); } ], function(err) { if (err) { console.log('An error ocurred deploying ' + fullName + ':'); console.log(err); } console.log('Deploy end:', fullName); console.log('----------------------'); cb(err); }); }; Deplorator.prototype.run = function(cb) { this.app.listen(this.port, cb); }; Deplorator.prototype._processDeploy = function(req, res) { var self = this; var name = req.param('id') + ':' + req.param('commit'); if (!this.config[req.param('id')]) { return res.send(404, 'Invalid configuration: ' + req.param('id') + '.\n') } if (!req.param('commit')) { return res.send(400, 'Missing commit SHA!\n'); } res.writeHead(200, { 'Content-Type': 'text/plain', 'Transfer-Encoding': 'chunked' }); this._deploy(res, req.param('id'), req.param('commit'), function(err) { if (err) { res.write('\nERR: An error ocurred deploying ' + name + ', check deploy log.\n'); } else { res.write('\nOK: Deployed ' + name + '.\n'); } res.end(); }); }; module.exports = Deplorator;
JavaScript
0
@@ -1270,32 +1270,139 @@ %09function(cb) %7B%0A +%09%09%09shellExec(res, shellescape(%5B 'git', 'fetch' %5D), %7B%0A%09%09%09%09cwd: config.path%0A%09%09%09%7D, cb);%0A%09%09%7D,%0A%09%09function(cb) %7B%0A %09%09%09shellExec(res
06baf75532c4116584c5e28ca70f4ed4e7412f58
Update index.js
index.js
index.js
module.exports = function(namespace) { namespace = namespace || 'undefined'; this.attach = function(options) { this[namespace] = options; }; };
JavaScript
0
@@ -1,20 +1,99 @@ -module.exports = +var BasePlugin = require('../../index.js').Plugin;%0A%0Amodule.exports = BasePlugin.extend(%7B%0A get: fun @@ -111,16 +111,18 @@ pace) %7B%0A + namesp @@ -154,16 +154,18 @@ ined';%0A%0A + this.a @@ -192,24 +192,26 @@ ions) %7B%0A + this%5Bnamespa @@ -229,12 +229,21 @@ ns;%0A + %7D;%0A%0A -%7D; + %7D;%0A%7D);%0A
13204c2da7ee3658803d3f29f67a18afd3953c33
Add Bluebird to window if window is a thing
index.js
index.js
module.exports = require("./promise.js");
JavaScript
0.000003
@@ -1,18 +1,18 @@ -module.exports +const Bluebird = r @@ -34,8 +34,106 @@ se.js%22); +%0Amodule.exports = Bluebird%0A%0Aif (typeof window !== 'undefined') %7B%0A window.Bluebird = Bluebird;%0A%7D
21ec2f1df5668f76fe4d344afd473817dae5bb8f
handle just wake and sleep events
index.js
index.js
var pm = require('bindings')('pm.node'), EventEmitter = require('events').EventEmitter; var notify = new EventEmitter(); pm.registerNotifications(function(msg) { notify.emit(msg); }); module.exports = notify; notify.on('wake', function() { console.log('wake'); }); notify.on('sleep', function() { console.log('sleep'); });
JavaScript
0.000001
@@ -210,122 +210,4 @@ ify; -%0A%0Anotify.on('wake', function() %7B%0A%09console.log('wake');%0A%7D);%0A%0Anotify.on('sleep', function() %7B%0A%09console.log('sleep');%0A%7D);
f66046a2a11c43e8d36b6660bb6c9b6c6f8fd159
Fix infinite loop on Windows (closes #3)
index.js
index.js
var path = require('path') var url = require('url') var tokenKey = ':_authToken' module.exports = function (registryUrl, opts) { var options = opts || {} var npmrc = require('rc')('npm', {registry: 'https://registry.npmjs.org/'}) var parsed = url.parse(registryUrl || npmrc.registry, false, true) var match var pathname while (!match && pathname !== '/') { pathname = parsed.pathname || '/' var regUrl = '//' + parsed.host + pathname.replace(/\/$/, '') match = npmrc[regUrl + tokenKey] || npmrc[regUrl + '/' + tokenKey] if (match) { match = match.replace(/^\$\{?([^}]*)\}?$/, function (fullMatch, envVar) { return process.env[envVar] }) } if (!options.recursive) { return match } parsed.pathname = path.resolve(pathname, '..') } return match }
JavaScript
0
@@ -1,31 +1,4 @@ -var path = require('path')%0A var @@ -740,20 +740,19 @@ hname = -path +url .resolve
2f60fb82f69eb2c5ea9a702fad8d04c44ef8007e
Rename for clarity.
index.js
index.js
var shp = require("./shp"), dbf = require("./dbf"); exports.version = require("./package.json").version; exports.reader = function(filename, options) { var convertProperties, convertGeometry, encoding = null, ignoreProperties = false, dbfReader, shpReader; if (typeof options === "string") options = {encoding: options}; if (options) "encoding" in options && (encoding = options["encoding"]), "ignore-properties" in options && (ignoreProperties = !!options["ignore-properties"]); if (/\.shp$/.test(filename)) filename = filename.substring(0, filename.length - 4); if (!ignoreProperties) dbfReader = dbf.reader(filename + ".dbf", encoding); shpReader = shp.reader(filename + ".shp"); function readDbfHeader(callback) { dbfReader.readHeader(function(error, header) { if (header === end) error = new Error("unexpected EOF"); if (error) return callback(error); convertProperties = new Function("d", "return {" + header.fields.map(function(field, i) { return JSON.stringify(field.name) + ":d[" + i + "]"; }) + "};"); readShpHeader(callback); }); return this; } function readShpHeader(callback) { shpReader.readHeader(function(error, header) { if (header === end) error = new Error("unexpected EOF"); if (error) return callback(error); convertGeometry = convertGeometryTypes[header.shapeType]; callback(null, {bbox: header.box}); }); return this; } function readAllRecords(readRecord) { return function(callback) { var records = []; (function readNextRecord() { readRecord(function(error, record) { if (error) return callback(error); if (record === end) return callback(null, records); records.push(record); process.nextTick(readNextRecord); }); })(); return this; }; } function readDbfRecord(callback) { dbfReader.readRecord(function(error, dbfRecord) { if (dbfRecord === end) return callback(null, end); if (error) return callback(error); shpReader.readRecord(function(error, shpRecord) { if (shpRecord === end) error = new Error("unexpected EOF"); if (error) return callback(error); callback(null, { type: "Feature", properties: convertProperties(dbfRecord), geometry: shpRecord == null ? null : convertGeometry(shpRecord) }); }); }); return this; } function readShpRecord(callback) { shpReader.readRecord(function(error, shpRecord) { if (shpRecord === end) return callback(null, end); if (error) return callback(error); callback(null, { type: "Feature", properties: {}, geometry: shpRecord == null ? null : convertGeometry(shpRecord) }); }); return this; } function closeDbf(callback) { dbfReader.close(function(error) { if (error) return callback(error); closeShp(callback); }); return this; } function closeShp(callback) { shpReader.close(callback); return this; } return dbfReader ? { readHeader: readDbfHeader, readAllRecords: readAllRecords(readDbfRecord), readRecord: readDbfRecord, close: closeDbf, } : { readHeader: readShpHeader, readAllRecords: readAllRecords(readShpRecord), readRecord: readShpRecord, close: closeShp }; }; var end = exports.end = shp.end; var convertGeometryTypes = { 1: convertPoint, 3: convertPolyLine, 5: convertPolygon, 8: convertMultiPoint, 11: convertPoint, // PointZ 13: convertPolyLine, // PolyLineZ 15: convertPolygon, // PolygonZ 18: convertMultiPoint // MultiPointZ }; function readEmptyNextProperties(callback) { callback(null, {}); } function convertPoint(record) { return { type: "Point", coordinates: [record.x, record.y] }; } function convertPolyLine(record) { return record.parts.length === 1 ? { type: "LineString", coordinates: record.points } : { type: "MultiLineString", coordinates: record.parts.map(function(i, j) { return record.points.slice(i, record.parts[j + 1]); }) }; } function convertPolygon(record) { var parts = record.parts.map(function(i, j) { return record.points.slice(i, record.parts[j + 1]); }), polygons = [], holes = []; parts.forEach(function(part) { if (ringClockwise(part)) polygons.push([part]); else holes.push(part); }); holes.forEach(function(hole) { var point = hole[0]; polygons.some(function(polygon) { if (ringContains(polygon[0], point)) { polygon.push(hole); return true; } }) || polygons.push([hole]); }); return polygons.length > 1 ? {type: "MultiPolygon", coordinates: polygons} : {type: "Polygon", coordinates: polygons[0]}; } function convertMultiPoint(record) { return { type: "MultiPoint", coordinates: record.points }; } function ringClockwise(ring) { if ((n = ring.length) < 4) return false; var i = 0, n, area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1]; while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1]; return area >= 0; } function ringContains(ring, point) { var x = point[0], y = point[1], contains = false; for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) { var pi = ring[i], xi = pi[0], yi = pi[1], pj = ring[j], xj = pj[0], yj = pj[1]; if (((yi > y) ^ (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) contains = !contains; } return contains; }
JavaScript
0
@@ -748,27 +748,24 @@ unction read -Dbf Header(callb @@ -763,32 +763,32 @@ der(callback) %7B%0A + dbfReader.re @@ -1921,27 +1921,24 @@ unction read -Dbf Record(callb @@ -2882,19 +2882,16 @@ on close -Dbf (callbac @@ -3158,19 +3158,16 @@ er: read -Dbf Header,%0A @@ -3201,27 +3201,24 @@ Records(read -Dbf Record),%0A @@ -3234,19 +3234,16 @@ rd: read -Dbf Record,%0A @@ -3262,12 +3262,8 @@ lose -Dbf, %0A %7D
3dc4e342946af58856d6d27098ca5290973a0c6a
Remove global - use an argument. Functional FTW
index.js
index.js
let { get_next_topic, scrape, valid_links } = require("./util"); const base = "https://en.wikipedia.org/wiki/"; const target = "Philosophy"; const chain = []; function init() { let topic = process.argv[2].split(" ").reduce(function (words, word) { if (words.length === 0) { words = word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); } else { words = words + "_" + word.toLowerCase(); } return words; }, ""); console.log("Finding out how philosophical " + topic + " is"); visit_article(topic); } function visit_article(topic) { if (topic === target) { return console.log("Success! Got there in " + chain.length); } scrape(base + topic) .then((result) => valid_links(result.data)) .then((anchors) => { return get_next_topic(anchors, chain) .then((topic) => { console.log("%d: %s => %s%s", chain.length + 1, topic.title, base, topic.url); chain.push(topic.url); return topic.url; }); }) .then(visit_article) .catch(function (message) { console.warn(message); }); } if (process.argv.length !== 3) { console.log("Usage: node index.js subject"); console.log(" "); console.log("example: node index.js \"Nemesis (roller coaster)\""); return; } else { init(); }
JavaScript
0.000018
@@ -141,27 +141,8 @@ %22;%0A%0A -const chain = %5B%5D;%0A%0A func @@ -520,16 +520,20 @@ le(topic +, %5B%5D );%0A%7D%0A%0Afu @@ -558,16 +558,23 @@ le(topic +, chain ) %7B%0A if @@ -1025,29 +1025,62 @@ .then( -visit_article +(new_topic) =%3E visit_article(new_topic, chain) )%0A .c
ac318831732a5bca6ca9a36deedfe6ef3ecb533d
Move EventEmitter require and use new syntax
index.js
index.js
'use strict'; var EventEmitter = require('events').EventEmitter; function emitThen (event) { var args = Array.prototype.slice.call(arguments, 1); /* jshint validthis:true */ return Promise .all(this.listeners(event).map(listener => Promise.resolve().then(() => { var a1 = args[0], a2 = args[1]; switch (args.length) { case 0: return listener.call(this); case 1: return listener.call(this, a1); case 2: return listener.call(this, a1, a2); default: return listener.apply(this, args); } }))) .then(() => null); } emitThen.register = function () { EventEmitter.prototype.emitThen = emitThen; }; module.exports = emitThen;
JavaScript
0
@@ -12,59 +12,8 @@ ';%0A%0A -var EventEmitter = require('events').EventEmitter;%0A func @@ -562,20 +562,25 @@ %7B%0A -EventEmitter +require('events') .pro
db54134d7e19e9f758021548987caa110ca4dfa8
Support custom input extensions for files
index.js
index.js
'use strict'; var Filter = require('broccoli-filter'); var react = require('react-tools').transform; module.exports = ReactFilter; ReactFilter.prototype = Object.create(Filter.prototype); ReactFilter.prototype.constructor = ReactFilter; function ReactFilter (inputTree, options) { if (!(this instanceof ReactFilter)){ return new ReactFilter(inputTree, options); } this.inputTree = inputTree; this.options = options || {}; } ReactFilter.prototype.extensions = ['jsx']; ReactFilter.prototype.targetExtension = 'js'; ReactFilter.prototype.processString = function (string) { var result = react(string); return result; };
JavaScript
0
@@ -432,16 +432,90 @@ %7C%7C %7B%7D;%0A + if (options.extensions) %7B%0A this.extensions = options.extensions;%0A %7D%0A %7D%0A%0AReact @@ -708,8 +708,9 @@ sult;%0A%7D; +%0A
785c532ecfdff91e7fbe812cdf39966ca2322111
Update ValueDesc_ConvStageType.js
CNN/Unpacker/ValueDesc/ValueDesc_ConvStageType.js
CNN/Unpacker/ValueDesc/ValueDesc_ConvStageType.js
export { ConvStageType }; import { Int } from "./ValueDesc_Base.js"; /** Describe id, range, name of ConvStageType (Convolution Stage Type). * * Convert number value into integer between [ 0, 7 ] representing operation: * - 0: MOBILE_NET_V1 (i.e. no-add-inut-to-output, pointwise1 is same size of pointwise21) * - 1: MOBILE_NET_V1_PAD_VALID (i.e. no-add-inut-to-output, pointwise1 is same size of pointwise21, depthwise1 with ( pad = "valid" )) * - 2: MOBILE_NET_V2_THIN (i.e. add-inut-to-output, pointwise1 is same size of pointwise21) * - 3: MOBILE_NET_V2 (i.e. add-inut-to-output, pointwise1 is tiwce size of pointwise21) * - 4: SHUFFLE_NET_V2 (i.e. by channel shuffler) * - 5: SHUFFLE_NET_V2_BY_POINTWISE22 (i.e. by pointwise22) * - 6: SHUFFLE_NET_V2_BY_MOBILE_NET_V1 (i.e. by integrated pointwise1, depthwise1, pointwise21) * - 7: SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID (i.e. by depthwise1 with ( pad = "valid" ) ) */ class ConvStageType extends Int { constructor() { super( 0, 7, [ "MOBILE_NET_V1", // (0) "MOBILE_NET_V1_PAD_VALID", // (1) "MOBILE_NET_V2_THIN", // (2) "MOBILE_NET_V2", // (3) "SHUFFLE_NET_V2", // (4) "SHUFFLE_NET_V2_BY_POINTWISE22", // (5) "SHUFFLE_NET_V2_BY_MOBILE_NET_V1", // (6) "SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID", // (7) ] ); } /** * @param {number} nConvStageType The numeric identifier of ConvStageType. (ConvStageType.Singleton.Ids.Xxx) * @return {boolean} Return true, if it is MOBILE_NET_Xxx. */ static isMobileNet( nConvStageType ) { switch ( nConvStageType ) { case ConvStageType.Singleton.Ids.MOBILE_NET_V1: // (0) case ConvStageType.Singleton.Ids.MOBILE_NET_V1_PAD_VALID: // (1) case ConvStageType.Singleton.Ids.MOBILE_NET_V2_THIN: // (2) case ConvStageType.Singleton.Ids.MOBILE_NET_V2: // (3) return true; default: return false; } } /** * @param {number} nConvStageType The numeric identifier of ConvStageType. (ConvStageType.Singleton.Ids.Xxx) * @return {boolean} Return true, if it is MOBILE_NET_V2_Xxx. */ static isMobileNetV2( nConvStageType ) { switch ( nConvStageType ) { case ConvStageType.Singleton.Ids.MOBILE_NET_V2_THIN: // (2) case ConvStageType.Singleton.Ids.MOBILE_NET_V2: // (3) return true; default: return false; } } /** * @param {number} nConvStageType The numeric identifier of ConvStageType. (ConvStageType.Singleton.Ids.Xxx) * @return {boolean} Return true, if it is SHUFFLE_NET_Xxx. */ static isShuffleNet( nConvStageType ) { switch ( nConvStageType ) { case ConvStageType.Singleton.Ids.SHUFFLE_NET_V2: // (4) case ConvStageType.Singleton.Ids.SHUFFLE_NET_V2_BY_POINTWISE22: // (5) case ConvStageType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1: // (6) case ConvStageType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID: // (7) return true; default: return false; } } /** * @param {number} nConvStageType The numeric identifier of ConvStageType. (ConvStageType.Singleton.Ids.Xxx) * @return {boolean} Return true, if it is Xxx_PAD_VALID. */ static isPadValid() { switch ( nConvStageType ) { case ConvStageType.Singleton.Ids.MOBILE_NET_V1_PAD_VALID: // (1) case ConvStageType.Singleton.Ids.SHUFFLE_NET_V2_BY_MOBILE_NET_V1_PAD_VALID: // (7) return true; default: return false; } } } /** The only one ValueDesc.ConvStageType instance. */ ConvStageType.Singleton = new ConvStageType;
JavaScript
0
@@ -327,33 +327,33 @@ ze of pointwise2 -1 +0 )%0A * - 1: MOBI @@ -456,17 +456,17 @@ intwise2 -1 +0 , depthw @@ -601,33 +601,33 @@ ze of pointwise2 -1 +0 )%0A * - 3: MOBI @@ -720,33 +720,33 @@ ze of pointwise2 -1 +0 )%0A * - 4: SHUF @@ -848,17 +848,17 @@ INTWISE2 -2 +1 @@ -881,17 +881,17 @@ intwise2 -2 +1 )%0A * - @@ -982,33 +982,33 @@ ise1, pointwise2 -1 +0 )%0A * - 7: SHUF @@ -1491,17 +1491,17 @@ INTWISE2 -2 +1 %22, @@ -3078,17 +3078,17 @@ INTWISE2 -2 +1 : // (5)
85a3b8719eafde17307e8698e9ce1f98f70587c7
normalize the outputFile path
index.js
index.js
var os = require('os'); var path = require('path'); var fs = require('fs'); var builder = require('xmlbuilder'); var DEFAULT_JUNIT_REPORTER_CONFIG = { outputFile: 'test-results.xml', suite: '' }; var JUnitReporter = function(baseReporterDecorator, config, logger, helper, formatError) { config = config || DEFAULT_JUNIT_REPORTER_CONFIG; var outputFile = config.outputFile; var pkgName = config.suite; var log = logger.create('reporter.junit'); var xml; var suites; var pendingFileWritings = 0; var fileWritingFinished = function() {}; var allMessages = []; baseReporterDecorator(this); this.adapters = [function(msg) { allMessages.push(msg); }]; this.onRunStart = function(browsers) { suites = Object.create(null); xml = builder.create('testsuites'); }; this.onBrowserStart = function(browser) { var timestamp = (new Date()).toISOString().substr(0, 19); var suite = suites[browser.id] = xml.ele('testsuite', { name: browser.name, 'package': pkgName, timestamp: timestamp, id: 0, hostname: os.hostname() }); suite.ele('properties').ele('property', {name: 'browser.fullName', value: browser.fullName}); }; this.onBrowserComplete = function(browser) { var suite = suites[browser.id]; var result = browser.lastResult; suite.att('tests', result.total); suite.att('errors', result.disconnected || result.error ? 1 : 0); suite.att('failures', result.failed); suite.att('time', (result.netTime || 0) / 1000); suite.ele('system-out').dat(allMessages.join() + '\n'); suite.ele('system-err'); }; this.onRunComplete = function() { var xmlToOutput = xml; pendingFileWritings++; helper.mkdirIfNotExists(path.dirname(outputFile), function() { fs.writeFile(outputFile, xmlToOutput.end({pretty: true}), function(err) { if (err) { log.warn('Cannot write JUnit xml\n\t' + err.message); } else { log.debug('JUnit results written to "%s".', outputFile); } if (!--pendingFileWritings) { fileWritingFinished(); } }); }); suites = xml = null; allMessages.length = 0; }; this.specSuccess = this.specSkipped = this.specFailure = function(browser, result) { var spec = suites[browser.id].ele('testcase', { name: result.description, time: ((result.time || 0) / 1000), classname: (pkgName ? pkgName + ' ' : '') + browser.name + '.' + result.suite.join(' ').replace(/\./g, '_') }); if (result.skipped) { spec.ele('skipped'); } if (!result.success) { result.log.forEach(function(err) { spec.ele('failure', {type: ''}, formatError(err)); }); } }; // wait for writing all the xml files, before exiting this.onExit = function(done) { if (pendingFileWritings) { fileWritingFinished = done; } else { done(); } }; }; JUnitReporter.$inject = ['baseReporterDecorator', 'config.junitReporter', 'logger', 'helper', 'formatError']; // PUBLISH DI MODULE module.exports = { 'reporter:junit': ['type', JUnitReporter] };
JavaScript
0
@@ -111,95 +111,8 @@ );%0A%0A -var DEFAULT_JUNIT_REPORTER_CONFIG = %7B%0A outputFile: 'test-results.xml',%0A suite: ''%0A%7D;%0A %0Avar @@ -205,95 +205,100 @@ %7B%0A -config = config %7C%7C DEFAULT_JUNIT_REPORTER_CONFIG;%0A%0A var outputFile = config.outputFile +var log = logger.create('reporter.junit');%0A var reporterConfig = config.junitReporter %7C%7C %7B%7D ;%0A @@ -311,17 +311,25 @@ gName = -c +reporterC onfig.su @@ -331,24 +331,30 @@ ig.suite + %7C%7C '' ;%0A var log = lo @@ -349,44 +349,129 @@ var -log = logger.create('reporter.junit' +outputFile = helper.normalizeWinPath(path.resolve(config.basePath, reporterConfig.outputFile%0A %7C%7C 'test-results.xml') );%0A%0A @@ -2979,30 +2979,16 @@ 'config -.junitReporter ', 'logg @@ -3001,20 +3001,16 @@ helper', -%0A 'format
4d3acbf0d5f11c8df6a5ced73422af3dba440d75
Print out list of repos with tags.
index.js
index.js
var request = require("request"); var FastSet = require("collections/fast-set"); var async = require("async"); var config = require("config"); var jsonfile = require('jsonfile') var url = 'https://api.github.com/search/code'; var headers = { 'cache-control': 'no-cache', 'content-type': 'application/json', 'user-agent': 'github-metatag', 'authorization': 'token ' + config.get('api_key') }; var outFile = config.get('output'); var alloptions = { method: 'GET', url: url, qs: { q: 'meta-tags in:readme user:' + config.get('username') }, headers: headers }; var uniqueTags = FastSet(); var tagMap = {}; console.log("Getting metatags in repos for user: " + config.get('username')); request(alloptions, function (error, response, body) { if (error) throw new Error(error); repos = JSON.parse(body); //console.log(repos); //response['items'].forEach(function(repo) { async.each(repos['items'], function(repo, done) { var repoName = repo['repository']['name']; //console.log("Getting tags for repo: " + repo['url']); var options = { method: 'GET', url: repo['url'], headers: headers }; request(options, function (error, response, body) { if (error) throw new Error(error); //console.log("re: " + body); response = JSON.parse(body); var options = { method: 'GET', url: response['download_url'], headers: headers }; //console.log("Getting README: " + response['download_url']); request(options, function (error, response, body) { if (error) throw new Error(error); var metastring = body.match(/<!-- meta-tags:.*/)[0]; var tags = metastring.match(/vvv-[^, ]*/g); tags = tags.map(function (tag) { return tag.replace('vvv-', ''); }); tagMap[repoName] = tags; uniqueTags = uniqueTags.union(tags); done(); }); }); }, function(err) { // console.log("Repos found: " + getRepoList(tagMap)); console.log("Unique tags: " + uniqueTags.toArray()); jsonfile.writeFile(outFile, tagMap, function (err) { if (err) { console.error(err); } }); }); });
JavaScript
0
@@ -2042,18 +2042,16 @@ (err) %7B%0A -// cons @@ -2283,12 +2283,78 @@ %7D);%0A - %0A%0A%7D +%7D);%0A%0Avar getRepoList = function(tagMap) %7B%0A return Object.keys(tagMap );%0A +%7D%0A
caf2d4df670f56f7ed18dfbd21530bc63b9b9752
remove console.log
index.js
index.js
'use strict'; console.log("LOADING gettext PLUGIN"); var gettextParser = require('gettext-parser'); var fs = require('fs'); var process = require('process'); var DEFAULT_FUNCTION_NAMES = { gettext: ['msgid'], dgettext: ['domain', 'msgid'], ngettext: ['msgid', 'msgid_plural', 'count'], dngettext: ['domain', 'msgid', 'msgid_plural', 'count'], pgettext: ['msgctxt', 'msgid'], dpgettext: ['domain', 'msgctxt', 'msgid'], npgettext: ['msgctxt', 'msgid', 'msgid_plural', 'count'], dnpgettext: ['domain', 'msgctxt', 'msgid', 'msgid_plural', 'count'] }; var DEFAULT_FILE_NAME = 'gettext.po'; var DEFAULT_HEADERS = { 'content-type': 'text/plain; charset=UTF-8', 'plural-forms': 'nplurals = 2; plural = (n !== 1);' }; function getTranslatorComment(node) { var comments = []; (node.leadingComments || []).forEach(function(commentNode) { var match = commentNode.value.match(/^\s*translators:\s*(.*?)\s*$/im); if (match) { comments.push(match[1]); } }); return comments.length > 0 ? comments.join('\n') : null; } function plugin(babel) { var t = babel.types; var currentFileName; var data; var relocatedComments = {}; return { visitor: { VariableDeclaration(path) { var translatorComment = getTranslatorComment(path.node); if (!translatorComment) { return; } path.node.declarations.forEach(function(declarator) { var comment = getTranslatorComment(declarator); if (!comment) { var key = declarator.init.start + '|' + declarator.init.end; relocatedComments[key] = translatorComment; } }); }, CallExpression(path, config) { var gtCfg = config.opts || {}; var functionNames = gtCfg.functionNames || DEFAULT_FUNCTION_NAMES; var fileName = gtCfg.fileName || DEFAULT_FILE_NAME; var headers = gtCfg.headers || DEFAULT_HEADERS; var base = gtCfg.baseDirectory; if (base) { if (base === '.') { base = process.cwd() + '/'; } else { base = base.match(/^(.*?)\/*$/)[1] + '/'; } } if (fileName !== currentFileName) { currentFileName = fileName; data = { charset: 'UTF-8', headers: headers, translations: {context: {}} }; headers['plural-forms'] = headers['plural-forms'] || DEFAULT_HEADERS['plural-forms']; headers['content-type'] = headers['content-type'] || DEFAULT_HEADERS['content-type']; } var defaultContext = data.translations.context; var nplurals = /nplurals ?= ?(\d)/.exec(headers['plural-forms'])[1]; if (functionNames.hasOwnProperty(path.node.callee.name) || path.node.callee.property && functionNames.hasOwnProperty(path.node.callee.property.name)) { var functionName = functionNames[path.node.callee.name] || functionNames[path.node.callee.property.name]; var translate = {}; var args = path.node.arguments; for (var i = 0, l = args.length; i < l; i++) { var name = functionName[i]; if (name && name !== 'count' && name !== 'domain') { var arg = args[i]; var value = arg.value; if (value) { translate[name] = value; } if (name === 'msgid_plural') { translate.msgstr = []; for (var p = 0; p < nplurals; p++) { translate.msgstr[p] = ''; } } } } var fn = config.file.log.filename; if (base && fn && fn.substr(0, base.length) == base) { fn = fn.substr(base.length); } translate.comments = { reference: fn + ':' + path.node.loc.start.line }; var translatorComment = getTranslatorComment(path.node); if (!translatorComment) { translatorComment = getTranslatorComment(path.parentPath); if (!translatorComment) { translatorComment = relocatedComments[ path.node.start + '|' + path.node.end]; } } if (translatorComment) { translate.comments.translator = translatorComment; } var context = defaultContext; var msgctxt = translate.msgctxt; if (msgctxt) { data.translations[msgctxt] = data.translations[msgctxt] || {}; context = data.translations[msgctxt]; } context[translate.msgid] = translate; var output = gettextParser.po.compile(data); fs.writeFileSync(fileName, output); } } } }; }; module.exports = plugin;
JavaScript
0.000006
@@ -12,48 +12,8 @@ ';%0A%0A -console.log(%22LOADING gettext PLUGIN%22);%0A%0A var
4112a855f2e27f67cc4baa653b352d0d46d54e1d
test connection speed
index.js
index.js
var Botkit = require('botkit') var Witbot = require('witbot') var dateFormat = require('dateformat'); var slackToken = process.env.SLACK_TOKEN var witToken = process.env.WIT_TOKEN var openWeatherApiKey = process.env.OPENWEATHER_KEY var qpxApiKey = process.env.QPXKEY var amazonApiId = process.env.AMAZONAPIID var amazonSecret = process.env.AMAZONSECRET var amazonTag = process.env.AMAZONTAG var controller = Botkit.slackbot({ debug: false }) controller.spawn({ token: slackToken }).startRTM(function (err, bot, payload) { if (err) { throw new Error('Error connecting to slack: ', err) } console.log('Connected to slack') }) var witbot = Witbot(witToken) var wit; var weather = require('./weather')(openWeatherApiKey) var jokes = require('./jokes')() var flights = require('./flights')(qpxApiKey) var amazon = require('./amazon')(amazonApiId, amazonSecret, amazonTag) controller.hears('.*', 'direct_message,direct_mention', function (bot, message) { /* var wit = witbot.process(message.text, bot, message) wit.hears('hello',0.5, function(bot, message, outcome) { bot.reply(message, '> Greetings human! \n> :robot_face: :wave:') }) wit.hears('purpose',0.5, function(bot, message, outcome) { bot.reply(message, '> 42') }) wit.hears('how_are_you',0.5, function(bot, message, outcome) { bot.reply(message, "> I\'m a bot. I\'m doing as well as could be expected. \n> ¯\\_(ツ)_/¯") }) wit.hears('help',0.5, function(bot, message, outcome) { bot.reply(message, "> :partly_sunny_rain: I can give you the weather\n> :money_with_wings: I can help you buy things\n> :airplane: I can search for one-way flights\n> :face_with_rolling_eyes: Oh, and I can tell pretty terrible jokes") }) wit.hears('thanks',0.5, function(bot, message, outcome) { bot.reply(message, "> Where's the blushing bot emoji when you need it...") }) wit.hears('love',0.5, function(bot, message, outcome) { bot.reply(message, "> Right, right now... up the butt :point_right::ok_hand:") }) wit.hears('humanity',0.5, function(bot, message, outcome) { bot.reply(message, "> What does it really mean to be human?") }) wit.hears('name',0.5, function(bot, message, outcome) { bot.reply(message, "> My name is Reverend Dr. Raymond Arther James III, Esquire") }) wit.hears('joke',0.5, function(bot, message, outcome) { jokes.get(function(error, msg) { bot.reply(message, msg) }) }) wit.hears('button',0.5, function(bot, message, outcome) { var reply_with_attachments = { "text": "You have a new request to approve.", "attachments": [ { "text": "I would like six pens for my creation station please.", "fallback": "Pen request", "title": "Request approval", "callback_id": "approval_2715", "color": "#8A2BE2", "attachment_type": "default", "actions": [ { "name": "approve", "text": ":thumbsup: Approve", "style": "primary", "type": "button", "value": "yes", "confirm": { "title": "Are you sure?", "text": "This will approve the request.", "ok_text": "Yes", "dismiss_text": "No" } }, { "name": "decline", "text": ":thumbsdown: Decline", "style": "danger", "type": "button", "value": "no" } ] } ] } bot.reply(message, reply_with_attachments); //bot.reply(message, 'buttonszzzzz') }) wit.hears('amazon',0.5, function(bot, message, outcome) { if (Object.keys(outcome.entities).length === 0 && outcome.entities.constructor === Object) { console.log('object not found') bot.reply(message, "> :money_with_wings:Whachu tryna buy?") return } console.log('found: ' + outcome.entities.object[0].value) var item = outcome.entities.object[0].value; bot.reply(message, '> :mag:*' + item + '* coming right up...') amazon.get(item, function(error, msg) { bot.reply(message, msg) }) }) wit.hears('flight',0.5, function(bot, message, outcome) { if (!outcome.entities.origin || !outcome.entities.destination || !outcome.entities.datetime) { bot.reply(message,"> I can't read your mind! I need an origin, a destination and a date!"); return } console.log('getting flight info: ' + outcome.entities.origin[0].value + ' - ' + outcome.entities.destination[0].value + ' - ' + outcome.entities.datetime[0].value) var origin = outcome.entities.origin[0].value.toUpperCase() var destination = outcome.entities.destination[0].value.toUpperCase() var dateObj = new Date(outcome.entities.datetime[0].value) date = dateFormat(dateObj, "isoDate"); if (origin.length !== 3 || destination.length !== 3) { bot.reply(message,"> I only work with 3 letter airport codes for now"); return } flights.get(origin, destination, date, function(error, msg) { bot.reply(message, msg) }) }) wit.hears('weather',0.5, function(bot, message, outcome) { console.log('asking for weather from: ' + outcome.entities.location) if(!outcome.entities.location || outcome.entities.location.length == 0) { bot.reply(message,"> I'm a bot, not a psychic. I need your location first..."); return } var location = outcome.entities.location[0].value weather.get(location, function(error, msg) { if (error) { console.log(error) bot.reply(message, "> Beep boop pssskt :boom:") return } bot.reply(message, msg) }) }) */ wit.otherwise(function (outcome) { bot.reply(message, "> Beep boop pssskt :boom: I am a weather, one-way flight and joke bot \n> But I learn from every interaction... unlike most humans"); }) }) /* controller.hears('.*', 'direct_message,direct_mention', function(bot,message) { witbot.process(message.text, bot, message) //bot.reply(message,message.text) console.log('heard something: ', message.text) }) //when witbot hears a hello above .5 */
JavaScript
0
@@ -6012,16 +6012,177 @@ mans%22);%0A + //bot.reply(message, %22%3E Beep boop pssskt :boom: I am a weather, one-way flight and joke bot %5Cn%3E But I learn from every interaction... unlike most humans%22);%0A %7D)%0A%7D)%0A
58430a903dbba3fcb28deeca4e6ee40e970d2916
Fix indentation
index.js
index.js
var split = require('split2') var pumpify = require('pumpify') var through = require('through2') module.exports = function() { var re_ass = new RegExp("Dialogue:\\s\\d," + // get time and subtitle "(\\d+:\\d\\d:\\d\\d.\\d\\d)," + // start time "(\\d+:\\d\\d:\\d\\d.\\d\\d)," + // end time "([^,]*)," + // object "([^,]*)," + // actor "(?:[^,]*,){4}" + "(.*)$", "i"); // subtitle var re_newline = /\\n/ig; // replace \N with newline var re_style = /\{([^}]+)\}/; // replace style var i = 1; var write = function(line, enc, cb) { var m = line.match(re_ass); if (!m) { return cb(); } var start = m[1], end = m[2], what = m[3], actor = m[4], text = m[5]; var style, pos_style = "", tagsToClose = []; // Places to stash style info. // Subtitles may contain any number of override tags, so we'll loop through // to find them all. while ( (style = text.match(re_style)) ) { var tagsToOpen = [], replaceString = ''; if ( style[1] && style[1].split ) { // Stop throwing errors on empty tags. style = style[1].split("\\"); // Get an array of override commands. for (var j = 1; j < style.length; j++) { // Extract the current tag name. var tagCommand = style[j].match( /[a-zA-Z]+/ )[0]; // Give special reckognition to one-letter tags. var oneLetter = ( tagCommand.length == 1 ) ? tagCommand : ""; // "New" position commands. It is assumed that bottom center position is the default. if ( tagCommand === "an" ) { var posNum = Number(style[j].substring(2,3)); if ( Math.floor((posNum-1)/3) == 1) { pos_style += ' line:50%'; } else if ( Math.floor((posNum-1)/3) == 2) { pos_style += ' line:0'; } if ( posNum % 3 == 1 ) { pos_style += ' align:start'; } else if ( posNum % 3 == 0 ) { pos_style += ' align:end'; } // Legacy position commands. } else if ( oneLetter === "a" && !Number.isNaN(Number(style[j].substring(1,2))) ) { var posNum = Number(style[j].substring(1,2)); if ( posNum > 8 ) { pos_style += ' line:50%'; } else if ( posNum > 4 ) { pos_style += ' line:0'; } if ( (posNum-1) % 4 == 0 ) { pos_style += ' align:start'; } else if ( (posNum-1) % 4 == 2 ) { pos_style += ' align:end'; } // Map simple text decoration commands to equivalent WebVTT text tags. // NOTE: Strikethrough (the 's' tag) is not supported in WebVTT. } else if ( ['b', 'i', 'u', 's'].includes(oneLetter) ) { if ( Number(style[j].substring(1,2)) === 0 ) { // Closing a tag. if ( tagsToClose.includes(oneLetter) ) { // Nothing needs to be done if this tag isn't already open. // HTML tags must be nested, so we must ensure that any tag nested inside // the tag being closed are also closed, and then opened again once the // current tag is closed. while ( tagsToClose.length > 0 ) { var nowClosing = tagsToClose.pop(); replaceString += '</' + nowClosing + '>'; if ( nowClosing !== oneLetter ) { tagsToOpen.push(nowClosing); } else { // There's no need to close the tags that the current tag // is nested within. break; } } } } else { // Opening a tag. if ( !tagsToClose.includes( oneLetter ) ) { // Nothing needs to be done if the tag is already open. // If no, place the tag on the bottom of the stack of tags being opened. tagsToOpen.splice(0, 0, oneLetter); } } } else if (oneLetter === 'r') { // Resetting override tags, by closing all open tags. // TODO: The 'r' tag can also be used to switch to a different named style, // however, named styles haven't been implemented. while ( tagsToClose.length > 0) { replaceString += '</' + tagsToClose.pop() + '>'; } } // Insert open-tags for tags in the to-open list. while ( tagsToOpen.length > 0 ) { var nowOpening = tagsToOpen.pop(); replaceString += '<' + nowOpening + '>'; tagsToClose.push(nowOpening); } } } text = text.replace(re_style, replaceString); // Replace override tag. } text = text.replace(re_newline, "\r\n"); var content = i + "\r\n" content += "0" + start + "0 --> 0" + end + "0" + pos_style + "\r\n" content += "<v " + what + " " + actor + ">" + text while ( tagsToClose.length > 0 ) { content += '</' + tagsToClose.pop() + '>'; } content += "\r\n\r\n"; i++; cb(null, content) } var parse = through.obj(write) parse.push('WEBVTT\r\n\r\n') return pumpify(split(), parse) }
JavaScript
0.017244
@@ -1312,17 +1312,24 @@ g name.%0A -%09 + var ta @@ -1377,9 +1377,16 @@ 0%5D;%0A -%09 + //
83fcdee2ca3517f8cf05346552a5b3517855bfda
Fix typo of Towne Lake
index.js
index.js
(function(d3) { "use strict"; var unitMap = { "Tempe Arizona YSA Stake": "full_stake", "Horizon YSA Ward": "horizon", "McClintock YSA Ward": "mcclintock", "Mission Bay YSA Ward": "mission_bay", "San Marcos YSA Ward": "san_marcos", "South Mountain YSA Ward": "south_mountain", "Towne Lake YSA Ward": "towne_lake", "University YSA Ward": "university", "Southshore YSA Ward": "southshore", "Pioneer YSA Ward": "pioneer" }; var roundOneData = [ [ "university", "san_marcos", "horizon" ], [ "south_mountain", "towne_lake", "pioneer" ], [ "mission_bay", "mcclintock", "southshore" ] ]; var displayNames = { "university": "University", "san_marcos": "San Marcos", "horizon": "Horizon", "south_mountain": "South Mountain", "towne_lake": "Town Lake", "pioneer": "Pioneer", "mission_bay": "Mission Bay", "mcclintock": "McClintock", "southshore": "Southshore" }; var startCorrections = { "university": 572, "san_marcos": 83, "horizon": 20, "south_mountain": 0, "towne_lake": 49, "pioneer": 0, "mission_bay": 778, "mcclintock": 441, "southshore": 0 }; var ratios = { "university": 1.30, "san_marcos": 1.34, "horizon": 1.96, "south_mountain": 1.55, "towne_lake": 1.0, "pioneer": 1.60, "mission_bay": 1.46, "mcclintock": 2.04, "southshore": 1.72 }; d3.json("https://rawgit.com/anderspitman/march_madness_indexing_data/master/data.json", function(data) { var data = data.map(function(record) { record.Indexed = +record.Indexed; record.Arbitrated = +record.Arbitrated; record['Redo Batches'] = +record['Redo Batches']; return record; }); main(data); }); var allData; var width; function main(data) { firebaseStuff(); makeCharts(data); } function firebaseStuff() { var config = { apiKey: "AIzaSyAkHMLIBu1BMxSSrv7jX_6wnbg2WnujlCg", authDomain: "march-madness-indexing.firebaseapp.com", databaseURL: "https://march-madness-indexing.firebaseio.com", storageBucket: "march-madness-indexing.appspot.com", messagingSenderId: "554642006729" }; var firebaseApp = firebase.initializeApp(config); var db = firebase.database().ref('mmi/'); db.on('value', function(snapshot) { console.log(snapshot.val()); }); } function makeCharts(data) { allData = transformData(data); console.log(allData); var svg = d3.select('.container').append('svg') .style("width", "100%") .style("height", "100%"); width = parseInt(svg.style("width")); var roundOne = roundOneChart(); svg.call(roundOne); } function roundOneChart() { var faceoff = faceoffChart(); function my(selection) { var roundOne = selection.append("g") .attr("class", "round-one") .attr("transform", function(d, i) { return svgTranslateString(0, 50); }) roundOne.append("text") .attr("class", "title") .attr("dx", 0) .style("font-size", 36) .text("Round One (Mon 3/20 to Sun 3/26)"); roundOne.append("g") .attr("class", 'groups') .attr("transform", function(d, i) { return svgTranslateString(15, 50); }) .attr("alignment-baseline", "middle") .selectAll(".faceoff") .data(roundOneData) .enter() .call(faceoff); } return my; } function faceoffChart() { var ward = wardMaker(); function my(selection) { selection.append("g") .attr("class", "faceoff") .attr("transform", function(d, i) { return svgTranslateString(0, i*200); }) .selectAll(".ward") .data(function(d) { return d; }) .enter() .call(ward); } return my; } function wardMaker() { function my(selection) { var group = selection.append("g") .attr("transform", function(d, i) { return svgTranslateString(0, i*30); }); group.append("circle") .style("fill", "steelblue") .attr("r", 10); group.append("text") .attr("dx", 15) .attr("dy", 5) .text(function(d) { return displayNames[d]; }); group.append("text") .attr("dx", 150) .attr("dy", 5) .text(function(d) { if (allData[d] !== undefined) { return Math.floor(ratios[d] * (allData[d].Indexed - startCorrections[d])); } else { return "0"; } }); } return my; } function transformData(data) { var newData = {}; data.forEach(function(record) { if (unitMap[record.Name] !== undefined) { newData[unitMap[record.Name]] = record; } }); return newData; } function svgTranslateString(x, y) { return "translate(" + x + "," + y + ")"; } }(d3));
JavaScript
0.999997
@@ -880,16 +880,17 @@ %22: %22Town +e Lake%22,%0A
95de1446fe941aaa9f8ca4a12ed1cb27b33f0b4b
Fix code comments.
index.js
index.js
/** * @copyright (c) 2015 Xu Jin * @licence MIT */ /** * koa middleware for Nunjucks * @module koa-nunjucks2 */ 'use strict'; const isFunction = require('lodash/lang/isFunction'); const isString = require('lodash/lang/isString'); const assign = require('lodash/object/assign'); const merge = require('lodash/object/merge'); const partial = require('lodash/function/partial'); const nunjucks = require('nunjucks'); const defaultConfig = { /** * Template name suffix */ suffix: '.html', /** * Response Header:Content-Type */ contentType: 'text/html; charset=UTF-8', renderToResponseBody: true }; /** * Create koa middleware for Nunjucks * @param {String} templatesPath * @param {Object} [nunjucksOptions] the options of nunjucks * @param {{suffix: String, contentType: String, renderToResponseBody: Boolean}} [extConfig] Extended config of this middleware * @param {Function} [callback] The environment will pass to the callback function * @returns {Generator} */ module.exports = function (templatesPath, nunjucksOptions, extConfig, callback) { let environment = nunjucks.configure(templatesPath, nunjucksOptions); if(isFunction(callback)) { callback(environment); } extConfig = assign({}, defaultConfig, extConfig); return function* (next) { /** * Render the template * @param name Template name * @param context Hash object * @return {Promise} */ this.render = partial(function (environment, extConfig, name, context) { return new Promise(partial(function (koaContext, resolve, reject) { if(isString(name) && name.length > 0) { environment.render(isString(extConfig.suffix) && extConfig.suffix.length > 0 ? name + extConfig.suffix : name, merge({}, koaContext.state, context), partial(function (extConfig, error, result) { if(error) { reject(error); } else { if(extConfig.renderToResponseBody === true) { koaContext.type = extConfig.contentType; koaContext.body = result; } resolve(result); } }, extConfig)); } else { resolve(); } }, this)); }, environment, extConfig); yield next; } };
JavaScript
0
@@ -699,16 +699,17 @@ String%7D +%5B template @@ -713,16 +713,40 @@ atesPath +%5D Where is the templates %0A * @par @@ -1009,16 +1009,58 @@ function +, it can be used to add filters and so on. %0A * @ret
63240d25f8f3230771ef3caf45d0fd82d9e06baa
Improve error messages
index.js
index.js
#!/usr/bin/env node var fs = require("fs"); var http = require("http"); var URL = require("url"); var heuristic = require("./heuristic"); module.exports = main; function main(har, options) { var entries = har.log.entries; var config = options.config; var server = http.createServer(function (request, response) { request.parsedUrl = URL.parse(request.url, true); var entry = heuristic(entries, request); var where; for (var i = 0; i < config.mappings.length; i++) { if ((where = config.mappings[i](request.url))) { break; } } var content; if (where) { // If there's local content, but no entry in the HAR, create a shim // entry so that we can still serve the file // TODO: infer MIME type (maybe just use a static file serving package) if (!entry) { entry = { response: { status: 200, headers: [], content: {} } }; } // If we have a file location, then try and read it. If that fails, then // return a 404 try { // TODO: do this asynchronously content = fs.readFileSync(where); } catch (e) { console.error("Could not read", where, "requested from", request.url); entry = null; } } if (!entry) { console.log("Not found:", request.url); response.writeHead(404, "Not found", {"content-type": "text/plain"}); response.end("404 Not found" + (where ? ", while looking for " + where : "")); return; } for (var h = 0; h < entry.response.headers.length; h++) { var name = entry.response.headers[h].name; var value = entry.response.headers[h].value; if (name.toLowerCase() === "content-length") continue; if (name.toLowerCase() === "content-encoding") continue; if (name.toLowerCase() === "cache-control") continue; if (name.toLowerCase() === "pragma") continue; var existing = response.getHeader(name); if (existing) { if (Array.isArray(existing)) { response.setHeader(name, existing.concat(value)); } else { response.setHeader(name, [existing, value]); } } else { response.setHeader(name, value); } } // Try to make sure nothing is cached response.setHeader("cache-control", "no-cache, no-store, must-revalidate"); response.setHeader("pragma", "no-cache"); response.statusCode = entry.response.status; // We may already have content from a local file if (/^image\//.test(entry.response.content.mimeType)) { if (!content) { content = entry.response.content.text || ""; content = new Buffer(content, 'base64'); } } else { content = content || entry.response.content.text || ""; content = content.toString(); var context = { request: request, entry: entry }; config.replacements.forEach(function (replacement) { content = replacement(content, context); }); } response.end(content); }); server.listen(argv.port); } if (require.main === module) { var parseConfig = require("./parse-config"); var argv = require("yargs") .usage("Usage: $0 [options] <.har file>") .options({ c: { alias: "config", describe: "The config file to use" }, p: { alias: "port", describe: "The port to run the proxy server on", default: 8080 } }) .demand(1) .argv; var harPath = argv._[0]; var har = JSON.parse(fs.readFileSync(harPath)); var configPath = argv.config; var config = parseConfig(configPath ? fs.readFileSync(configPath, "utf8") : null); main(har, { config: config, port: argv.port }); console.log("Listening at http://localhost:" + argv.port); console.log("Try " + har.log.entries[0].request.url.replace(/^https/, "http")); }
JavaScript
0.000014
@@ -1415,16 +1415,23 @@ .error(%22 +Error: Could no @@ -3541,32 +3541,233 @@ %7D);%0A %7D%0A +%0A if (entry.response.content.size %3E 0 && !content && !where) %7B%0A console.error(%22Error:%22, entry.request.url, %22has a non-zero size, but there is no content in the HAR file%22);%0A %7D%0A%0A response
c2a89b632329863e917b283b0219475fa788e708
update TOSOs
index.js
index.js
//FIX fix difference between wsdl parsed by json-q and by old parser //TODO AMD support? //TODO add strings? (and remove _replace_escaped_operators) //TODO performance? const { get } = require('./lib/index'); module.exports = { get };
JavaScript
0
@@ -71,16 +71,156 @@ %0D%0A//TODO +? get rid of clone (https://github.com/pvorb/node-clone) as it uses Buffers which means adding 23k minified Buffers lib at browser?%0D%0A//TODO? AMD sup @@ -232,16 +232,17 @@ %0D%0A//TODO +? add str @@ -294,16 +294,17 @@ %0D%0A//TODO +? perform
1d261686ad74ab4a00fd7dbb17098a1a175bbbf0
fix parsing the index
index.js
index.js
/** * Module dependencies */ /** * Expose the Request object */ module.exports = Request; /** * Create a hyper-path request * * @param {String} path * @param {Client} client */ function Request(path, client, delim) { if (!(this instanceof Request)) return new Request(path, client); // init client this.client = client; if (!this.client) throw new Error('hyper-path requires a client to be passed as the second argument'); this.delim = delim || '.'; this.parse(path); this._listeners = {}; this._scope = {}; } /** * Set the root scope * * @param {Object} scope * @return {Request} */ Request.prototype.scope = function(scope) { this._scope = this.wrappedScope ? [scope] : scope; if (this._fn) this.get(); return this; }; /** * Call a function anytime the data changes in the request * * @param {Function} fn * @return {Request} */ Request.prototype.on = function(fn) { this._fn = fn; this.get(); return this; }; /** * Refresh the data down the path * * @return {Request} */ Request.prototype.get = Request.prototype.refresh = function(fn) { var self = this; var scope = self._scope; fn = fn || self._fn; // Clear any previous listeners this.off(); if (!self.isRoot) return self.traverse(scope, {}, 0, self.path, fn); this._listeners['.'] = self.client(function(err, body, links) { if (err) return fn(err); links = links || {}; self.traverse(body || scope, links, 1, self.path, fn); }); return this; }; /** * Parse the string with the following syntax * * Start at this.scope['path'] * * path.to.my.name * * Start at the client's root * * .path.to.my.name * * @param {String} str * @api private */ Request.prototype.parse = function(str) { var path = this.path = str.split(this.delim); if (path.length === 1) { this.wrappedScope = true; path.unshift(0); } this.index = path[0]; this.isRoot = this.index === ''; this.target = path[path.length - 1]; }; /** * unsubscribe from any emitters for a request * * @return {Request} */ Request.prototype.off = function() { for (var i = 0, listener; i < this._listeners; i++) { listener = this._listener[i]; if (listener) listener(); } return this; }; /** * Traverse properties in the api * * TODO support JSON pointer with '#' * * @param {Any} parent * @param {Integer} i * @param {Function} cb * @api private */ Request.prototype.traverse = function(parent, links, i, path, cb) { var request = this; // We're done searching if (i >= path.length) return cb(null, normalizeTarget(parent)); var key = path[i]; var value = get(key, parent, links); // We couldn't find the property if (!isDefined(value)) { var collection = parent.collection || parent.data; if (collection && collection.hasOwnProperty(key)) return request.traverse(collection, links, i, path, cb); // We have a single hop path so we're going to try going up the prototype. // This is necessary for frameworks like Angular where they use prototypal // inheritance. The risk is getting a value that is on the root Object. // We can at least check that we don't return a function though. if (this.wrappedScope) value = parent[key]; if (typeof value === 'function') value = void 0; return cb(null, value); } var next = i + 1; var nextProp = path[next]; // We don't have a link to use or it's set locally on the object if (!value.href || value.hasOwnProperty(nextProp)) return request.traverse(value, links, next, path, cb); // We're just getting the link if (nextProp === 'href') return cb(null, value); // It's a link var href = value.href; var listener = request._listeners[href]; request._listeners[href] = request.client.get(href, function(err, body, links) { if (err) return cb(err); if (!body && !links) return cb(null); links = links || {}; // Be nice to APIs that don't set 'href' if (!body.href) body.href = href; var pointer = href.split('#')[1]; if (!pointer) return request.traverse(body, links, i + 1, path, cb); pointer = pointer.split('/'); if (pointer[0] === '') pointer.shift(); request.traverse(body, links, 0, pointer, function(err, val) { if (err) return cb(err); request.traverse(val, links, i + 1, path, cb); }); }); // Unsubscribe and resubscribe if it was previously requested if (listener) listener(); } /** * Get a value given a key/object * * @api private */ function get(key, parent, fallback) { if (!parent) return undefined; if (parent.hasOwnProperty(key)) return parent[key]; if (fallback.hasOwnProperty(key)) return {href: fallback[key]}; return void 0; } /** * If the final object is an collection, pass that back * * @api private */ function normalizeTarget(target) { if (typeof target !== 'object') return target; var href = target.href; target = target.collection || target.data || target; // TODO deprecate 'data' target.href = href; return target; } /** * Check if a value is defined * * @api private */ function isDefined(value) { return typeof value !== 'undefined' && value !== null; }
JavaScript
0.000008
@@ -1805,16 +1805,40 @@ delim);%0A + this.index = path%5B0%5D;%0A if (pa @@ -1915,32 +1915,8 @@ %7D%0A - this.index = path%5B0%5D;%0A th
9a32d247aa6c42f988d1a06a8cf4e8673ad0e2e1
Update configuration property name
index.js
index.js
/* jshint node: true */ 'use strict'; var fs = require( 'fs' ); var mergeTrees = require( 'broccoli-merge-trees' ); var path = require( 'path' ); var writeFile = require( 'broccoli-file-creator' ); module.exports = { /** * Name of addon * * @type {String} */ name: 'ember-forge-ui', /** * Name of companion ember-forge-ui template addon * * @type {?String} */ emberForgeUiTemplateAddon: null, /** * Set name of companion ember-forge-ui template addon to local context if exists * * @param {String} environment * @param {Object} appConfig * @returns {undefined} */ config: function( environment, appConfig ) { if ( appConfig[this.name].emberForgeUiTemplateAddon ) { this.emberForgeUiTemplateAddon = appConfig[this.name].emberForgeUiTemplateAddon; } }, /** * Return templates if ember-forge-ui template addon is installed, default ones if not * * @param {Object} tree * @returns {Object} */ treeForAddonTemplates: function() { if ( this.emberForgeUiTemplateAddon ) { return this.treeGenerator( path.join( this.nodeModulesPath, this.emberForgeUiTemplateAddon, 'addon', 'templates' ) ); } else { var componentTemplateTrees = []; var files = fs.readdirSync( path.join( this.nodeModulesPath, this.name, 'addon', 'components' ) ); var placeholderContentPath = path.join( this.nodeModulesPath, this.name, 'addon', 'templates', 'components' ) + path.sep + 'placeholder-content.hbs'; var placeholderContent = require( placeholderContentPath ); files.forEach( function( element ) { componentTemplateTrees.push( writeFile( '/components/' + element.replace( '.js', '' ) + '.hbs', placeholderContent() ) ); }); return mergeTrees( componentTemplateTrees ); } } };
JavaScript
0.000001
@@ -739,33 +739,17 @@ me%5D. -emberForgeUiTemplateAddon +addonName ) %7B @@ -819,33 +819,17 @@ me%5D. -emberForgeUiTemplateAddon +addonName ;%0A
5d055571ae0ea2973b25de2b6afaf896672c11b6
Fix typos in object names
index.js
index.js
'use strict' const Promise = require('bluebird') const EventEmitter = require('events'); const Utils = require('./utils') let externals = {} class flowEmitter extends EventEmitter { } const INITIAL_STATE = 0 externals.Instance = (function () { function Instance(model, emitter, middlewares) { /*this.flow = flow this.id = id*/ this.model = model this.actualState = this.model.states[INITIAL_STATE] this.middlewares = [] this.internalEmitter = emitter this.middlewares = middlewares } Instance.prototype.searchNextState = function (stateName) { return new Promise((resolve, reject) => { this.model.states.forEach((v) => { if (v.name === stateName) { return resolve(v) } }) }) } Instance.prototype.validateTransition = function (transitionName) { return new Promise((resolve, reject) => { if (this.actualState.transitions) { this.actualState.transitions.forEach((v) => { if (Utils.matchRule(v.name, transitionName)) { return resolve(v) } }) return reject(new Error('No se pudo encontrar el estado en las transiciones')) } else { return reject(new Error('No se pudo encontrar el estado en las transiciones')) } }) } Instance.prototype.getState = function (data) { return new Promise((resolve, reject) => { if (data && data.action) { this.validateTransition(data.action).then((transition) => { this.searchNextState(transition.to).then((v) => { if (transition.use) { this.middlewares[transition.use](this.actualState, (data) => { this.actualState = v return resolve(this.actualState) }) } else { this.actualState = v if (this.actualState.onEnter) { if (this.actualState.onEnter.emit) { this.internalEmitter.emit(this.actualState.onEnter.emit, this.actualState.onEnter.data) } } return resolve(this.actualState) } }) }).catch((err) => { return resolve({ template: err }) }) } else { return resolve(this.actualState) } }) } return Instance })() externals.Flow = (function () { function Flow(name, model) { this.name = name this.model = model this.instances = [] this.middlewares = [] this.internalEmitter = new flowEmitter(); } Flow.prototype.newInstance = function (id) { this.instances[id] = new externals.Instance(this.model, this.internalEmitter, this.middlewares) return this.instances[id] } Flow.prototype.addInstance = function (instance) { this.instance[instance.id] = instance return this.instances[instance.id] } Flow.prototype.getInstance = function (id) { return this.instances[id] } Flow.prototype.on = function (eventName, eventFunction) { this.internalEmitter.on(eventName, eventFunction) } Flow.prototype.register = function (name, fn) { this.middlewares[name] = fn } return Flow })() module.exports = externals
JavaScript
0.00004
@@ -649,33 +649,37 @@ states.forEach(( -v +state ) =%3E %7B%0A i @@ -681,17 +681,21 @@ if ( -v +state .name == @@ -726,33 +726,37 @@ return resolve( -v +state )%0A %7D%0A @@ -976,17 +976,26 @@ orEach(( -v +transition ) =%3E %7B%0A @@ -1023,17 +1023,26 @@ tchRule( -v +transition .name, t @@ -1086,17 +1086,26 @@ resolve( -v +transition )%0A @@ -1579,17 +1579,25 @@ ).then(( -v +nextState ) =%3E %7B%0A @@ -1733,33 +1733,41 @@ s.actualState = -v +nextState %0A @@ -1871,17 +1871,25 @@ State = -v +nextState %0A
9a4a8aaf9977d1d3ff44b68cb2af365f3c7bc550
set port for deploy
index.js
index.js
var util = require('util') , koa = require('koa') , common = require('koa-common') , router = require('koa-router') , Q = require('q') , GitHubApi = require("github") , app = koa() , github = new GitHubApi({ // required version: '3.0.0', // optional debug: true, protocol: 'https', timeout: 5000 }) ; app.use(common.logger()); app.keys = ['FIXME']; app.use(common.session()); app.use(router(app)); app.get('/', function *(next) { // github api example var res = yield Q.denodeify(github.user.getFollowingFromUser)({ user: 'mikedeboer' }).then(function(res) { return res; }); // session example var n = this.session.views || 0; this.session.views = ++n; this.body = n + 'views\n\n' + util.inspect(res); }); app.get('/login', function *(next) { }); app.listen(3000);
JavaScript
0.000001
@@ -304,16 +304,50 @@ 5000%0A%7D)%0A +, port = process.env.PORT %7C%7C 3000%0A ;%0A%0Aapp.u @@ -830,15 +830,15 @@ .listen( -3000 +port );%0A
28147c56ab8b5f15896feff1510764916e76d12b
Update attachmentItemScript.js
DomainContent/AvatarStore/attachmentItemScript.js
DomainContent/AvatarStore/attachmentItemScript.js
// // attachmentItemScript.js // // This script is a simplified version of the original attachmentItemScript.js // Copyright 2017 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // (function() { var ATTACH_SOUND = SoundCache.getSound(Script.resolvePath('sound/attach_sound_1.wav')); var DETACH_SOUND = SoundCache.getSound(Script.resolvePath('sound/detach.wav')); var LEFT_RIGHT_PLACEHOLDER = '[LR]'; var ATTACH_DISTANCE = 0.35; var DETACH_DISTANCE = 0.5; var AUDIO_VOLUME_LEVEL = 0.2; var RELEASE_LIFETIME = 60; var TRIGGER_INTENSITY = 1.0; var TRIGGER_TIME = 0.2; var EMPTY_PARENT_ID = "{00000000-0000-0000-0000-000000000000}"; var MESSAGE_CHANNEL_BASE = "AvatarStoreObject"; var messageChannel; var _entityID; var _attachmentData; var _supportedJoints = []; var isAttached; var firstGrab = true; /** * * @param {Object} entityProperties * @param {touchJSONUserDataCallback} touchCallback */ var touchJSONUserData = function(entityProperties, touchCallback) { try { // attempt to touch the userData var userData = JSON.parse(entityProperties.userData); touchCallback.call(this, userData); entityProperties.userData = JSON.stringify(userData); } catch (e) { print('Something went wrong while trying to touch/modify the userData. Could be invalid JSON or problem with the callback function.'); } }; /** * This callback is displayed as a global member. * @callback touchJSONUserDataCallback * @param {Object} userData */ function AttachableItem() { } AttachableItem.prototype = { preload : function(entityID) { _entityID = entityID; var properties = Entities.getEntityProperties(entityID, ['parentID', 'userData']); _attachmentData = JSON.parse(properties.userData).Attachment; if (_attachmentData.joint.indexOf(LEFT_RIGHT_PLACEHOLDER) !== -1) { var baseJoint = _attachmentData.joint.substring(4); _supportedJoints.push("Left".concat(baseJoint)); _supportedJoints.push("Right".concat(baseJoint)); } else { _supportedJoints.push(_attachmentData.joint); } isAttached = _attachmentData.attached; if (Entities.getNestableType(properties.parentID) !== "avatar" && !isAttached) { messageChannel = MESSAGE_CHANNEL_BASE + properties.parentID; Messages.subscribe(messageChannel); } }, startNearGrab: function(entityID, args) { if (firstGrab) { if (!Entities.getEntityProperties(entityID, 'visible').visible) { Entities.editEntity(entityID, {visible: true}); } firstGrab = false; } }, releaseGrab: function(entityID, args) { var hand = args[0] === "left" ? 0 : 1; var properties = Entities.getEntityProperties(entityID, ['parentID', 'userData', 'position']); if (Entities.getNestableType(properties.parentID) === "entity") { Messages.sendMessage(messageChannel, "Removed Item :" + entityID); Messages.unsubscribe(messageChannel); Entities.editEntity(entityID, {parentID: EMPTY_PARENT_ID}); } var userData = properties.userData; var position = properties.position; var attachmentData = JSON.parse(userData).Attachment; isAttached = attachmentData.attached; if (!isAttached) { _supportedJoints.forEach(function(joint) { var jointPosition = MyAvatar.getJointPosition(joint); if (Vec3.distance(position, jointPosition) <= ATTACH_DISTANCE) { var newEntityProperties = Entities.getEntityProperties(_entityID, 'userData'); touchJSONUserData(newEntityProperties, function(userData) { userData.Attachment.attached = true; }); Entities.editEntity(_entityID, { parentID: MyAvatar.sessionUUID, parentJointIndex: MyAvatar.getJointIndex(joint), userData: newEntityProperties.userData, lifetime: -1 }); if (ATTACH_SOUND.downloaded) { Audio.playSound(ATTACH_SOUND, { position: MyAvatar.position, volume: AUDIO_VOLUME_LEVEL, localOnly: true }); } Controller.triggerHapticPulse(TRIGGER_INTENSITY, TRIGGER_TIME, hand); } }); } else if (isAttached) { var jointPosition = (properties.parentID === MyAvatar.sessionUUID) ? MyAvatar.getJointPosition(properties.parentJointIndex) : AvatarList.getAvatar(properties.parentID).getJointPosition(properties.parentJointIndex); if ( Vec3.distance(position, jointPosition) > DETACH_DISTANCE) { var newDetachEntityProperties = Entities.getEntityProperties(entityID); touchJSONUserData(newDetachEntityProperties, function(userData) { userData.Attachment.attached = false; }); Entities.editEntity(_entityID, { parentID: EMPTY_PARENT_ID, lifetime: Entities.getEntityProperties(_entityID, 'age').age + RELEASE_LIFETIME, userData: newDetachEntityProperties.userData }); if (DETACH_SOUND.downloaded) { Audio.playSound(DETACH_SOUND, { position: MyAvatar.position, volume:AUDIO_VOLUME_LEVEL, localOnly: true }); } Controller.triggerHapticPulse(TRIGGER_INTENSITY, TRIGGER_TIME, hand); } } } }; return new AttachableItem(); });
JavaScript
0
@@ -5468,17 +5468,16 @@ if ( - Vec3.dis
7c9bf1377587ec75dd9577356e6d3ceeee63a4fd
use central template by default
index.js
index.js
#!/usr/bin/env node var argv = require('optimist') .alias('i', 'inFile') .demand('i') .alias('o', 'outFile') .default('o', 'dmu.html') .alias('t', 'templateFile') .default('t', './template.jade') .argv, fs = require('fs'), request = require('request'), dmu2html = require('./dmu2html'), inFile = fs.createReadStream(argv.inFile); if (fs.existsSync(argv.templateFile)) { fs.readFile(argv.templateFile, function (err, content) { dmu2html(inFile, content, function (html) { fs.writeFile(argv.outFile, html); }); }); } else { request(argv.templateFile, function (err, response, content) { dmu2html(inFile, content, function (html) { fs.writeFile(argv.outFile, html); }); }); }
JavaScript
0
@@ -196,17 +196,49 @@ t('t', ' -. +http://ncgmp09.github.io/dmu2html /templat
47cba3340c7ccfdb79a9579ea4341679097b19ea
replace arrow functions so this doesn't require browserify
index.js
index.js
"use strict"; var rhMock = {}; module.exports = rhMock; rhMock.skipQueriesInList = [ "skip", "take", "rhcurrentpage", "search" ]; var apiRoot = ""; rhMock.setApiRoot = function ( _apiRoot ) { apiRoot = _apiRoot; if( !apiRoot ) { return; } var portAndPath = apiRoot.split( "://" )[ 1 ].split( ":" )[ 1 ]; if( !portAndPath ) { return; } rhMock.apiPort = portAndPath.split( "/" )[ 0 ] || ""; }; rhMock.$httpBackend = null; rhMock.create = function ( path, types, list ) { if( !rhMock.$httpBackend ) { throw new Error( "$httpBackend must be set" ); } if( types.indexOf( "GET" ) !== -1 ) { rhMock.$httpBackend.whenRoute( "GET", apiRoot + path ) .respond( rhMock.createList( list ) ); } if( types.indexOf( "POST" ) !== -1 ) { rhMock.$httpBackend.whenRoute( "POST", apiRoot + path ) .respond( rhMock.createPost( list ) ); } if( types.indexOf( "PUT" ) !== -1 ) { rhMock.$httpBackend.whenRoute( "PUT", apiRoot + path ) .respond( rhMock.createPut( list ) ); } if( types.indexOf( "DELETE" ) !== -1 ) { rhMock.$httpBackend.whenRoute( "DELETE", apiRoot + path ) .respond( rhMock.createDelete( list ) ); } }; rhMock.createList = function ( list ) { return function ( method, url, requestData, headers, params ) { var skip = Number( params.skip ) || 0; var take = Number( params.take ) || 1000; var page = Number( skip / take + 1 ) || 1; var data = angular.copy( list ); Object.keys( params ).forEach( key => { if( rhMock.skipQueriesInList.indexOf( key ) !== -1 || key === rhMock.apiPort ) { return; } data = data.filter( item => item[ key ] && item[ key ].toString() === params[ key ].toString() ); } ); var dataPage = data.slice( skip, skip + take ); return [ 200, { pageCount: Math.ceil( data.length / take ), currentPage: page, nextPage: page === 1, results: dataPage, next: page === 1 } ]; }; }; rhMock.createPost = function ( list ) { return function ( method, url, requestData ) { var newItem = angular.fromJson( requestData ); var lastId = list[ list.length - 1 ] ? list[ list.length - 1 ].id : 99; newItem.id = lastId + 1; list.push( newItem ); return [ 201, newItem ]; }; }; rhMock.createPut = function ( list ) { return function ( method, url, requestData ) { var updatedItem = angular.fromJson( requestData ); for( var i = 0; i < list.length; i++ ) { if( list[ i ].id === Number( updatedItem.id ) ) { list[ i ] = updatedItem; break; } } return [ 200, updatedItem ]; }; }; rhMock.createDelete = function ( list ) { return function ( method, url, requestData, headers, params ) { for( var i = 0; i < list.length; i++ ) { if( list[ i ].id === Number( params.id ) ) { list.splice( i, 1 ); break; } } return [ 204, null, { someHeader: "value" } ]; }; };
JavaScript
0.000008
@@ -1648,14 +1648,32 @@ ch( -key =%3E +function ( key )%0A %7B%0A @@ -1850,15 +1850,62 @@ er( -item =%3E +function ( item )%0A %7B%0A return ite @@ -1967,16 +1967,31 @@ String() +;%0A %7D );%0A
0f606e146f7048c1d86c46b1c2f119f2786af475
Set custom parser in non-hacky way (fixes #12)
index.js
index.js
module.exports.cli = require('./bin/cmd') module.exports.linter = Linter var defaults = require('defaults') var deglob = require('deglob') var dezalgo = require('dezalgo') var eslint = require('eslint') var extend = require('xtend') var findRoot = require('find-root') var fs = require('fs') var os = require('os') var path = require('path') var pkgConfig = require('pkg-config') var DEFAULT_PATTERNS = [ '**/*.js', '**/*.jsx' ] var DEFAULT_IGNORE = [ '**/*.min.js', '**/bundle.js', 'coverage/**', 'node_modules/**', 'vendor/**' ] function Linter (opts) { var self = this if (!(self instanceof Linter)) return new Linter(opts) opts = opts || {} self.cmd = opts.cmd || 'standard' self.eslintConfig = defaults(opts.eslintConfig, { useEslintrc: false, globals: [] }) if (!self.eslintConfig) { throw new Error('No eslintConfig passed.') } } /** * Lint text to enforce JavaScript Style. * * @param {string} text file text to lint * @param {Object=} opts options object * @param {Array.<string>=} opts.globals global variables to declare * @param {string=} opts.parser custom js parser (e.g. babel-eslint) * @param {function(Error, Object)} cb callback */ Linter.prototype.lintText = function (text, opts, cb) { var self = this if (typeof opts === 'function') { cb = opts opts = {} } opts = self.parseOpts(opts) cb = dezalgo(cb) var result try { result = new eslint.CLIEngine(self.eslintConfig).executeOnText(text) } catch (err) { return cb(err) } return cb(null, result) } /** * Lint files to enforce JavaScript Style. * * @param {Array.<string>} files file globs to lint * @param {Object=} opts options object * @param {Array.<string>=} opts.ignore file globs to ignore (has sane defaults) * @param {string=} opts.cwd current working directory (default: process.cwd()) * @param {Array.<string>=} opts.globals global variables to declare * @param {string=} opts.parser custom js parser (e.g. babel-eslint) * @param {function(Error, Object)} cb callback */ Linter.prototype.lintFiles = function (files, opts, cb) { var self = this if (typeof opts === 'function') { cb = opts opts = {} } opts = self.parseOpts(opts) cb = dezalgo(cb) if (typeof files === 'string') files = [ files ] if (files.length === 0) files = DEFAULT_PATTERNS var deglobOpts = { ignore: opts.ignore, cwd: opts.cwd, useGitIgnore: true, usePackageJson: true, configKey: self.cmd } deglob(files, deglobOpts, function (err, allFiles) { if (err) return cb(err) // undocumented – do not use (used by bin/cmd.js) if (opts._onFiles) opts._onFiles(allFiles) var result try { result = new eslint.CLIEngine(self.eslintConfig).executeOnFiles(allFiles) } catch (err) { return cb(err) } return cb(null, result) }) } Linter.prototype.parseOpts = function (opts) { var self = this if (!opts) opts = {} opts = extend(opts) if (!opts.cwd) opts.cwd = process.cwd() if (!opts.ignore) opts.ignore = [] opts.ignore = opts.ignore.concat(DEFAULT_IGNORE) setGlobals(opts.globals || opts.global) setParser(opts.parser) var root try { root = findRoot(opts.cwd) } catch (e) {} if (root) { var packageOpts = pkgConfig(self.cmd, { root: false, cwd: opts.cwd }) if (packageOpts) { setGlobals(packageOpts.globals || packageOpts.global) if (!opts.parser) setParser(packageOpts.parser) } } function setParser (parser) { if (!parser) return var configFile = JSON.parse(fs.readFileSync(self.eslintConfig.configFile, 'utf8')) configFile.parser = parser var tmpFilename = path.join(os.tmpdir(), '.eslintrc-' + randomNumber()) fs.writeFileSync(tmpFilename, JSON.stringify(configFile)) self.eslintConfig.configFile = tmpFilename } function setGlobals (globals) { if (!globals) return self.eslintConfig.globals = self.eslintConfig.globals.concat(globals) } function randomNumber () { return Math.random().toString().substring(2, 10) } return opts }
JavaScript
0
@@ -268,81 +268,8 @@ t')%0A -var fs = require('fs')%0Avar os = require('os')%0Avar path = require('path')%0A var @@ -3566,306 +3566,41 @@ -var configFile = JSON.parse(fs.readFileSync(self.eslintConfig.configFile, 'utf8'))%0A configFile.parser = parser%0A var tmpFilename = path.join(os.tmpdir(), '.eslintrc-' + randomNumber())%0A fs.writeFileSync(tmpFilename, JSON.stringify(configFile))%0A self.eslintConfig.configFile = tmpFilename +self.eslintConfig.parser = parser %0A %7D @@ -3743,95 +3743,8 @@ %7D%0A%0A - function randomNumber () %7B%0A return Math.random().toString().substring(2, 10)%0A %7D%0A%0A re
afdcdd62ed575d4cc99bfdc4342881912e21c3f8
update container only if it has variables
index.js
index.js
import React, {PropTypes} from 'react'; import {Observable, helpers} from 'rx'; import assign from 'object-assign'; import invariant from 'invariant'; const FETCH_FAILED = 'FETCH_FAILED'; const FETCH_ABORTED = 'FETCH_ABORTED'; export default { create: Container, fromPromise: Observable.fromPromise, fromValue: Observable.just, fromStore, FETCH_FAILED, FETCH_ABORTED, }; function Container(Component, options) { const { fragments = {}, shouldContainerUpdate = () => true, initialVariables = {}, } = options; const componentEnum = enumerate(Component); const displayName = `Transmitter(${componentEnum.success.displayName || componentEnum.success.name})`; const isRootContainer = options.hasOwnProperty('initialVariables'); return React.createClass({ displayName, propTypes: { variables: PropTypes.object, }, statics: { isRootContainer, getFragment(name, variables) { invariant(fragments.hasOwnProperty(name), `Fragment ${name} of ${displayName} doesn't exist`); const allVariables = assign({}, initialVariables, variables); return fragments[name](allVariables); }, }, getInitialState() { return { status: 'pending', fragments: {}, error: null, }; }, success(results) { const combinedFragments = results.reduce((a, b) => assign(a, b), {}); this.setState({status: 'success', fragments: combinedFragments}); }, failure(error, type) { const errorInstance = {type, error}; this.setState({status: 'failure', error: errorInstance}); }, pending() { this.setState({status: 'pending', error: null}); this.subscription.dispose(); }, fetchFragment(name, variables) { const fragmentContainer = fragments[name](variables); const observable = fromEverything(fragmentContainer); return observable.map(data => wrapFragment(name, data)); }, fetch(newVariables) { const variables = assign({}, initialVariables, newVariables); const streams = Object.keys(fragments) .map(name => { if (this.props.hasOwnProperty(name)) { return Observable.just(wrapFragment(name, this.props[name])); } return this.fetchFragment(name, variables); }); return Observable.combineLatest(streams) .subscribe( results => this.success(results), error => this.failure(error, FETCH_FAILED) ); }, refetch() { this.pending(); this.subscription = this.fetch(this.props.variables); }, abort() { this.subscription.dispose(); this.failure(null, FETCH_ABORTED); }, componentWillMount() { this.subscription = this.fetch(this.props.variables); }, componentWillUnmount() { this.subscription.dispose(); }, componentWillReceiveProps(nextProps) { if (shouldContainerUpdate.call(this, nextProps)) { this.pending(); this.subscription = this.fetch(nextProps.variables); } }, render() { const {fragments, error, status} = this.state; const onRetry = () => this.refetch(); const onAbort = () => this.abort(); switch (status) { case 'success': return React.createElement(componentEnum.success, assign({}, fragments, this.props)); case 'failure': return React.createElement(componentEnum.failure, assign({error, onRetry}, this.props)); case 'pending': // falls through default: return React.createElement(componentEnum.pending, assign({onAbort}, this.props)); } }, }); } const EmptyComponent = React.createClass({ render() { return null; } }); function wrapFragment(name, value) { return {[name]: value}; } function enumerate(target) { const isEnumerableComponent = typeof target === 'object'; if (isEnumerableComponent) { invariant(isReactComponentEnum(target), 'Success, Failure and Pending should be React components'); invariant(helpers.isFunction(target.success), 'Success component should be specified'); return assign({success: EmptyComponent, pending: EmptyComponent, failure: EmptyComponent}, target); } return {success: target, pending: EmptyComponent, failure: EmptyComponent}; } function isReactComponentEnum(target) { return ['success', 'failure', 'pending'] .filter(type => target.hasOwnProperty(type)) .every(type => helpers.isFunction(target[type])); } function fromEverything(object) { if (helpers.isPromise(object)) { return Observable.fromPromise(object); } if (helpers.isFunction(object)) { return Observable.just(object); } // assume that `object` is Observable by default return object; } function fromStore(store) { invariant(typeof store.getState === 'function', 'Store should have getState method which returns current state'); invariant(typeof store.subscribe === 'function', 'Store should have subscribe method which adds listener for change event'); return Observable.create(observer => { const pushState = () => observer.onNext(store.getState()); const unsubscribe = store.subscribe(pushState); invariant(typeof unsubscribe === 'function', 'Subscribe method should return a function which removes change listener when called'); return {dispose: unsubscribe}; }).startWith(store.getState()); }
JavaScript
0.000001
@@ -2724,16 +2724,35 @@ %0A%09%09%09if ( +isRootContainer && shouldCo
a5addbfad61701b8143fcda14a6ce16076d8123d
fix data collection
index.js
index.js
require('dotenv').config() const TelegramBot = require('node-telegram-bot-api'); const uuid = require('uuid/v4'); const sleeboard = require('./sleeboard.js'); const pg = require('pg'); var config = { user: process.env.PGUSER, database: process.env.PGDATABASE, password: process.env.PGPASSWORD, host: process.env.PGHOST, port: process.env.PGPORT, max: process.env.PGPOOL, idleTimeoutMillis: process.env.PGTIMEOUT, }; const Admin = process.env.ADMIN var pool = new pg.Pool(config); //this initializes a connection pool //it will keep idle connections open for a 30 seconds //and set a limit of maximum 10 idle clients // to run a query we can acquire a client from the pool, // run a query on the client, and then return the client to the pool // replace the value below with the Telegram token you receive from @BotFather const token = process.env.AMHARIC_BOT_TOKEN; // Create a bot that uses 'polling' to fetch new updates const bot = new TelegramBot(token, {polling: true}); bot.getMe().then(function(err, result){ console.log(err, result) }) // Add a data collection command bot.onText(/\/collect/, (msg, match) => { pool.connect(function(err, client, done) { if(err) { return } client.query('SELECT id FROM users WHERE id=$1;', [msg.chat.id], (err, result) => { // user found add it to the data collection if(result && result.rows.length > 0 && result.rows[0].id){ client.query('UPDATE users SET collect = $2 WHERE id = $1;', [msg.chat.id, true], function(err, result) { done(err); if(err) { return; } }); }else{ client.query('INSERT INTO users (id, collect) VALUES ($1, $2);', [msg.chat.id, true], function(err, result) { done(err); if(err) { return; } }); } // add the query the user sent and the answer they got to the data. }); }); bot.sendMessage(msg.chat.id, 'Thank you for allowing @AmharicBot to collect your data. Your Privacy is our Priority.'); }); // Get User count bot.onText(/\/count/, (msg, match) => { if(msg.chat.id == Admin){ pool.connect(function(err, client, done) { if(err) { return } client.query('SELECT COUNT(id) as count from users;', function(err, result) { done(err); if(err) { return; } bot.sendMessage(msg.chat.id, `Number of unique users using @AmharicBot is ${result.rows[0].count}`); }); }); } }); // Get Contributors count bot.onText(/\/contributors/, (msg, match) => { if(msg.chat.id == Admin){ pool.connect(function(err, client, done) { if(err) { return } client.query('SELECT COUNT(id) as count from users WHERE collect=$1;', [true], function(err, result) { done(err); if(err) { return; } bot.sendMessage(msg.chat.id, `Number of unique contributors @AmharicBot is ${result.rows[0].count}`); }); }); } }); // Matches "/echo [whatever]" bot.onText(/\/help/, (msg, match) => { // 'msg' is the received Message from Telegram // 'match' is the result of executing the regexp above on the text content // of the message const chatId = msg.chat.id; // send back the matched "whatever" to the chat bot.sendMessage(chatId, 'inside any chat just type @AmharicBot mukera'); }); bot.on("inline_query", (query) => { var searchTerm = query.query.trim(); var chatId = query.from.id; var answer = sleeboard.getAmharic(searchTerm) var term = searchTerm; // Check Telegram text display limit for description to that the user looks at what they are typeing // not the starting text if(searchTerm.length > 90){ term = ".."+ searchTerm.slice(-90); } var result = answer.map(item => { var itemResult = item.result; // Check Telegram text display limit for title to that the user looks at what they are typeing // not the starting text if(item.result.length > 48){ itemResult = ".."+item.result.slice(-52); } // Check Telegram inline bot return limit if(item.result.length > 256) { itemResult = "!!! CHARACTER LIMIT EXCEEDED !!!" } return { type: "article", id: uuid(), title: itemResult, description: term + item.chars, input_message_content: { message_text: item.result } } }) pool.connect(function(err, client, done) { if(err) { return; } // Add user to the list of users how use our bot client.query('INSERT INTO users VALUES ($1::int);', [query.from.id], function(err, result) { // Check if the user is a contributor if so add users userid to the data client.query('SELECT id FROM users WHERE id=$1 AND collect=$2;', [chatId, true], (err, result) => { var user = ''; // user found add it to the data collection if(result && result.rows.length > 0 && result.rows[0].id){ user = result.rows[0].id } // add the query the user sent and the answer they got to the data. client.query('INSERT INTO data ("user", "query", "options") VALUES ($1::int,$2,$3);', [user, searchTerm, answer[0]], (err, result) => { done(err); if(err) { return; } }); }); }); }); bot.answerInlineQuery(query.id, result); }); bot.on('polling_error', (error) => { console.log(error.code); });
JavaScript
0.000003
@@ -4884,10 +4884,9 @@ r = -'' +0 ;%0A
61a29c91322e505eebfa02810adb763ac602c106
add fullscreen menu item (#1)
index.js
index.js
const { app, BrowserWindow, shell, Menu } = require('electron'); const createRPC = require('./rpc'); const Session = require('./session'); const genUid = require('uid2'); const { resolve } = require('path'); const isDev = require('electron-is-dev'); if (isDev) { console.log('running in dev mode'); } else { console.log('running in prod mode'); } const url = 'file://' + resolve( isDev ? __dirname : app.getAppPath(), // in prod version, we copy over index.html and dist from 'app' // into one dist folder to avoid unwanted files in package isDev ? 'app' : 'build', 'index.html' ); console.log('electron will open', url); app.on('window-all-closed', () => { // by subscribing to this event and nooping // we prevent electron's default behavior // of quitting the app when the last // terminal is closed }); let winCount = 0; app.on('ready', () => { function createWindow (fn) { let win = new BrowserWindow({ width: 540, height: 380, titleBarStyle: 'hidden', title: 'HyperTerm', backgroundColor: '#000', transparent: true, // we only want to show when the prompt // is ready for user input show: process.env.HYPERTERM_DEBUG || isDev }); winCount++; win.loadURL(url); const rpc = createRPC(win); const sessions = new Map(); rpc.on('init', () => { win.show(); }); rpc.on('new', ({ rows = 40, cols = 100 }) => { initSession({ rows, cols }, (uid, session) => { sessions.set(uid, session); rpc.emit('new session', { uid }); session.on('data', (data) => { rpc.emit('data', { uid, data }); }); session.on('title', (title) => { rpc.emit('title', { uid, title }); }); session.on('exit', () => { rpc.emit('exit', { uid }); }); }); }); rpc.on('focus', ({ uid }) => { sessions.get(uid).focus(); }); rpc.on('blur', ({ uid }) => { sessions.get(uid).blur(); }); rpc.on('exit', ({ uid }) => { sessions.get(uid).exit(); }); rpc.on('resize', ({ cols, rows }) => { sessions.forEach((session) => { session.resize({ cols, rows }); }); }); rpc.on('data', ({ uid, data }) => { sessions.get(uid).write(data); }); rpc.on('open external', ({ url }) => { shell.openExternal(url); }); const deleteSessions = () => { sessions.forEach((session, key) => { session.removeAllListeners(); session.destroy(); sessions.delete(key); }); }; // we reset the rpc channel only upon // subsequent refreshes (ie: F5) let i = 0; win.webContents.on('did-navigate', () => { if (i++) { deleteSessions(); } }); // the window can be closed by the browser process itself win.on('close', () => { rpc.destroy(); deleteSessions(); winCount--; }); win.rpc = rpc; } // when opening create a new window createWindow(); // mac only. when the dock icon is clicked // and we don't have any active windows open, // we open one app.on('activate', () => { if (!winCount) { createWindow(); } }); // set menu Menu.setApplicationMenu(Menu.buildFromTemplate([ { label: 'Application', submenu: [ { role: 'quit' } ] }, { label: 'Shell', submenu: [ { label: 'New Window', accelerator: 'CmdOrCtrl+N', click (item, focusedWindow) { createWindow(); } }, { label: 'New Tab', accelerator: 'CmdOrCtrl+T', click (item, focusedWindow) { if (focusedWindow) { focusedWindow.rpc.emit('new tab'); } else { createWindow(); } } }, { label: 'Close', accelerator: 'CmdOrCtrl+W', click (item, focusedWindow) { if (focusedWindow) { focusedWindow.rpc.emit('close tab'); } } } ] }, { label: 'Edit', submenu: [ { label: 'Copy', accelerator: 'CmdOrCtrl+C', selector: 'copy:' }, { label: 'Paste', accelerator: 'CmdOrCtrl+V', selector: 'paste:' }, { label: 'Select All', accelerator: 'CmdOrCtrl+A', selector: 'selectAll:' } ] }, { label: 'View', submenu: [ { label: 'Reload', accelerator: 'CmdOrCtrl+R', click (item, focusedWindow) { if (focusedWindow) focusedWindow.reload(); } }, { label: 'Toggle Developer Tools', accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I', click (item, focusedWindow) { if (focusedWindow) { focusedWindow.webContents.toggleDevTools(); } } } ] }, { label: 'Window', submenu: [ { label: 'Select Previous Tab', accelerator: 'CmdOrCtrl+Left', click (item, focusedWindow) { if (focusedWindow) { focusedWindow.rpc.emit('move left'); } } }, { label: 'Select Next Tab', accelerator: 'CmdOrCtrl+Right', click (item, focusedWindow) { if (focusedWindow) { focusedWindow.rpc.emit('move right'); } } } ] } ])); }); function initSession (opts, fn) { genUid(20, (err, uid) => { if (err) throw err; fn(uid, new Session(opts)); }); }
JavaScript
0
@@ -4971,32 +4971,88 @@ %7D%0A %7D%0A + %7D,%0A %7B%0A role: 'togglefullscreen'%0A %7D%0A
cf5acdccc4ad0b619e7cdedb93b1dd30c9cc78b4
Remove unused variables: util, self
index.js
index.js
var fs = require('fs') , util = require('util') , findExec = require('find-exec') , child_process = require('child_process') , players = [ 'mplayer', 'afplay', 'mpg123', 'mpg321', 'play' ] function Play(opts){ var opts = opts || {} this.players = opts.players || players this.player = opts.player || findExec(this.players) var exec = child_process.exec this.play = function(what, next){ var self = this, next = next || function(){} if (!what) return next(new Error("No audio file specified")); try { if (!fs.statSync(what).isFile()){ return next(new Error(what + " is not a file")); } } catch (err){ return next(new Error("File doesn't exist: " + what)); } if (!this.player){ return next(new Error("Couldn't find a suitable audio player")) } exec(this.player + ' ' + what, function(err, stdout, stderr){ if (err) return next(err) return next(); }) } this.test = function(next) { this.play('./assets/test.mp3', next) } } module.exports = function(opts){ return new Play(opts) }
JavaScript
0.999967
@@ -34,47 +34,8 @@ s')%0A - , util = require('util')%0A , @@ -624,29 +624,8 @@ var -self = this,%0A next
8f6fd581c960db53ab15cf42aee4523458741c6c
Remove commented line and add comments on code
index.js
index.js
var yargs = require('yargs'); var fs = require('fs'); var http = require('http'); var debug = require('debug')('word-counter:index'); var client_parse = require('./lib/client_parse.js'); var argv = yargs .option('c', { alias: 'client', type: 'array' }) .option('s', { alias: 'search', type: 'string' }) .option('f', { alias: 'file', type: 'string' }) .argv; var clients = argv.client, search = argv.search, filename = argv.file, fileArray = [], client_count = 0, ocurrences = 0, options = { host: 'localhost', port: 5050, method: 'POST', path: '/', headers: { 'Content-Type': 'application/json' } }, request = null; // Lê o arquivo fs.readFile(filename, 'utf8', function(err, data) { if (err) throw err; // Separa o arquivo em pedaços e guarda no array `fileArray` fileArray = data.match(/([^\s]+\s\s*){1,200}/g); mountOptions(); }); // Monta as opções de cada client para enviar function mountOptions() { for (var i = 0; i < clients.length; i++) { var client = clients[i]; var postData = getPostData(); if (postData) { sendRequest(client, postData); } else { debug('End of file reached'); } } }; function getPostData() { var content = fileArray.pop(); if(content != null) { return JSON.stringify({ 'content': content, 'search': search }); } else { return false; } }; // Envia para o cliente um pedaço do texto e a palavra a ser buscada (Start dos requests) function sendRequest(client, postData) { var options = client_parse(client); var request = http.request(options, process_client.bind(null, client)); do_request(); request.on('error', function(e) { debug('Error processing request: ' + e.message); }); request.end(postData); }; function process_client(client, res) { res.setEncoding('utf8'); res.on('data', function (chunk) { var chunk = JSON.parse(chunk); debug('Client "%s" responded with %o', client, chunk); var searchReturned = chunk.search; var ocurrencesReturned = chunk.ocurrences; var postData = getPostData(); ocurrences += ocurrencesReturned; process_response(); if (postData) { sendRequest(client, postData); } }); }; function do_request() { client_count++; } function process_response() { client_count--; if (client_count === 0) { // console.log('end of requests'); console.log('Found %d ocurrences of "%s" on file %s.', ocurrences, search, filename); } }
JavaScript
0
@@ -1253,24 +1253,117 @@ %7D%0A %7D%0A%7D;%0A%0A +// Pega um peda%C3%A7o do texto e a palavra a ser buscada e monta um objeto para enviar ao client%0A function get @@ -1935,24 +1935,54 @@ tData);%0A%7D;%0A%0A +// Resposta enviada do client%0A function pro @@ -2345,24 +2345,99 @@ esponse();%0A%0A + // Se ainda h%C3%A1 algum peda%C3%A7o do arquivo ent%C3%A3o envia outro para o client%0A if (post @@ -2497,16 +2497,40 @@ %7D);%0A%7D;%0A%0A +// contador de requests%0A function @@ -2566,16 +2566,91 @@ t++;%0A%7D%0A%0A +// quando todos os requests retornarem mostra a mensagem final no terminal%0A function @@ -2721,47 +2721,8 @@ ) %7B%0A - // console.log('end of requests');%0A
e883fcf4da5a211e1ab1e08606a5e90712778b43
Fix crash on quit if timer is running
index.js
index.js
'use strict'; const menubar = require('menubar'); const Menu = require('menu'); const globalShortcut = require('global-shortcut'); const ipc = require('ipc'); const dialog = require('dialog'); const Stopwatch = require('timer-stopwatch'); const Hrt = require('human-readable-time'); const fs = require('fs'); const path = require('path'); const AutoLaunch = require('auto-launch'); // report crashes to the Electron project require('crash-reporter').start(); let timeFormat = new Hrt('%mm%:%ss%'); let workTimer = 1500000; let relaxTimer = 300000; let longRelaxTimer = 900000; let pomodoroCount = 0; let isRelaxTime = false; let showTimer = true; let launchOnStartup = false; let sender; let mb = menubar({ 'preloadWindow': true }); let options = {}; options.name = 'Pomodoro'; if(process.platform === 'darwin') { options.path = path.join(mb.app.getAppPath(), 'Pomodoro.app'); } else if(process.platform === 'win32') { options.path = path.join(mb.app.getAppPath(), 'Pomodoro.exe'); } let autolauncher = new AutoLaunch(options); getConfig(); global.timer = new Stopwatch(workTimer); global.isRelaxTime = isRelaxTime; process.on('uncaughtException', (err) => { dialog.showErrorBox('Uncaught Exception: ' + err.message, err.stack || ''); mb.app.quit(); }); mb.app.on('will-quit', () => { globalShortcut.unregisterAll(); }); mb.app.on('quit', () => { mb = null; }); global.timer.on('time', function(time) { if(showTimer) { if (time.ms !== workTimer || time.ms !== relaxTimer || time.ms !== longRelaxTimer) { mb.tray.setTitle(timeFormat(new Date(time.ms))); } } else { mb.tray.setTitle(''); } global.progress = getProgress(); sender.send('update-timer'); }); global.timer.on('done', function() { sender.send('end-timer'); if(isRelaxTime) { global.timer.reset(workTimer); isRelaxTime = false; } else { pomodoroCount++; if(pomodoroCount % 4 === 0) { global.timer.reset(longRelaxTimer); } else { global.timer.reset(relaxTimer); } isRelaxTime = true; } global.isRelaxTime = isRelaxTime; global.pomodoroCount = pomodoroCount; }); ipc.on('reset-timer', function(event) { global.timer.reset(workTimer); mb.tray.setTitle(''); global.progress = getProgress(); event.sender.send('update-timer', 0); }); ipc.on('start-timer', function(event) { sender = event.sender; if(global.timer.runTimer) { global.timer.stop(); sender.send('update-timer'); mb.tray.setTitle('Paused'); } else { global.timer.start(); } }); ipc.on('settings-updated', function(event) { getConfig(); if(sender) { sender.send('update-timer', getProgress()); } else { event.sender.send('update-timer', getProgress()); } }); ipc.on('request-config', function(event) { getConfig(); event.returnValue = { workTimer: workTimer / 60 / 1000, relaxTimer: relaxTimer / 60 / 1000, longRelaxTimer: longRelaxTimer / 60 / 1000, showTimer: showTimer, launchOnStartup: launchOnStartup }; }); ipc.on('quit', function(event) { mb.app.quit(); }); function getConfig() { try { var dataPath = path.join(mb.app.getDataPath(), 'config.json'); var data = JSON.parse(fs.readFileSync(dataPath)); workTimer = data.workTimer * 60 * 1000; relaxTimer = data.relaxTimer * 60 * 1000; longRelaxTimer = data.longRelaxTimer * 60 * 1000; showTimer = data.showTimer; launchOnStartup = data.launchOnStartup; if(launchOnStartup) { autolauncher.enable(); } else { autolauncher.disable(); } } catch(err) { console.log(err); console.log('Didn\'t found previous config. Using default settings'); } } function getProgress() { var progress; var max; if(isRelaxTime) { if(pomodoroCount % 4 === 0) { max = longRelaxTimer; } else { max = relaxTimer; } } else { max = workTimer; } progress = (max - timer.ms) / (max / 100) * 0.01; if(progress < 0) { progress = 0.01; } return progress; }
JavaScript
0.000007
@@ -1322,24 +1322,46 @@ isterAll();%0A +%09global.timer.stop();%0A %7D);%0A%0Amb.app.
40dddae51b7b3602bdc5d76c615268ca9261e0eb
Remove object y position.
web3d/static/js/src/web3d.js
web3d/static/js/src/web3d.js
/* Javascript for Web3dXBlock. */ function Web3dXBlock(runtime, element) { var container; var camera, scene, renderer; var controls; var width = 750; var height = 500; function animate() { requestAnimationFrame(animate); render(); controls.update(); } function render() { renderer.render(scene, camera); } $(function ($) { container = $(".container", element); camera = new THREE.PerspectiveCamera(45, width / height, 1, 2000); camera.position.z = 100; // scene scene = new THREE.Scene(); var ambient = new THREE.AmbientLight(0x444444); scene.add(ambient); var directionalLight = new THREE.DirectionalLight(0xffeedd); directionalLight.position.set(1, 1, 1).normalize(); scene.add(directionalLight); var directionalLight2 = new THREE.DirectionalLight(0xffeedd, 0.5); directionalLight2.position.set(-1, 1, 1).normalize(); scene.add(directionalLight2); // model var onProgress = function (xhr) {}; var onError = function (xhr) {}; THREE.Loader.Handlers.add(/\.dds$/i, new THREE.DDSLoader()); var loader = new THREE.OBJMTLLoader(); loader.load(container.data('obj'), container.data('mtl'), function (object) { object.position.y = -40; scene.add(object); }, onProgress, onError); // render renderer = new THREE.WebGLRenderer(); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(width, height); container.append(renderer.domElement); // controls controls = new THREE.TrackballControls( camera, renderer.domElement ); controls.rotateSpeed = 5; controls.minDistance = 5; controls.maxDistance = 200; controls.addEventListener( 'change', render ); animate(); }); }
JavaScript
0
@@ -1352,45 +1352,8 @@ %7B%0A%0A - object.position.y = -40;%0A
36bb1db36bc859836a89a1e65bfdd650d7523729
add appId
index.js
index.js
'use strict'; var Alexa = require('alexa-sdk'); var Guns = require('./lib/guns'); var guns = new Guns(); var handlers = { 'GetGunInformationIntent': function () { var gun = guns.find_by_name(this.event.request.intent.slots.Gun.value); if (gun) { var gunInformation = gun.name + '. ' + gun.notes + ' The ' + gun.name + ' has a quality of ' + gun.quality + ',' + ' and the damage is ' + gun.damage + '.' this.emit(':tell', gunInformation); } else { this.emit(':tell', 'NotFoundIntent'); } }, 'GetQualityIntent': function () { var gun = guns.find_by_name(this.event.request.intent.slots.Gun.value); if (gun) { this.emit(':tell', 'The quality for ' + gun.name + ' is ' + gun.quality + '.'); } else { this.emit(':tell', 'NotFoundIntent'); } }, 'GetDamageIntent': function () { var gun = guns.find_by_name(this.event.request.intent.slots.Gun.value); if (gun) { this.emit(':tell', 'The damage for ' + gun.name + ' is ' + gun.damage + '.'); } else { this.emit(':tell', 'NotFoundIntent'); } }, 'NotFoundIntent': function () { this.emit(':tell', 'I didn\'t find the item you asked for.'); }, 'Unhandled': function () { this.emit(':tell', 'Ask for information, quality or damage of an item.', 'Ask for information, quality or damage of an item.'); } }; exports.handler = function(event, context, callback) { var alexa = Alexa.handler(event, context); alexa.registerHandlers(handlers); alexa.execute(); };
JavaScript
0.000001
@@ -1490,16 +1490,146 @@ ntext);%0A +%0A if (typeof process.env.DEBUG === 'undefined') %7B%0A alexa.appId = 'amzn1.ask.skill.d16db6f9-e869-4345-ac89-fa86b73d7663';%0A %7D%0A%0A alexa.
0004be9223a33e423f8d87870b9f0d6533c18e4a
Remove hardcoded credentials
index.js
index.js
var Bot = require('slackbots'); var request = require('request'); // create a bot var settings = { token: '%%%', name: '%%%' }; var DEFAULT_REPO = '%%%'; var channels = {}; var bot = new Bot(settings); bot.on('message', function (data) { if (data.type === 'message') { if (data.username === '%%%') return; if (Object.keys(channels).indexOf(data.channel) === -1) return; var match = data.text.match(/([^#\s]+?)?#([0-9])+/g); if (!match) return; if (match.length === 1) { var str = match[0].split('#'); var repo = str[0] || DEFAULT_REPO; var no = str[1]; return request.get({ url: 'https://api.github.com/repos/%%%/' + repo + '/issues/' + no, auth: { user: '%%%', pass: '%%%' }, headers: { 'user-agent': 'request' }, json: true }, function (err, resp, body) { if (err || !body.title) return; var msg = body.title + ' - ' + 'https://github.com/%%%/' + repo + '/issues/' + no; bot.postMessageToChannel(channels[data.channel], msg); }); } var msg = match.map(function (str) { str = str.split('#'); var repo = str[0] || DEFAULT_REPO; var no = str[1]; return 'https://github.com/%%%/' + repo + '/issues/' + no; }).join(' - '); bot.postMessageToChannel(channels[data.channel], msg); } });
JavaScript
0.000765
@@ -108,30 +108,69 @@ en: -'%25%25%25',%0A name: '%25%25%25' +process.env.SLACK_TOKEN,%0A name: process.env.SLACK_BOT_NAME %0A%7D;%0A @@ -776,36 +776,77 @@ er: -'%25%25%25',%0A pass: '%25%25%25' +process.env.GITHUB_USERNAME,%0A pass: process.env.GITHUB_TOKEN %0A
15306d413157d7696ea68271badc7e7952658ba1
Fix ref error
index.js
index.js
/** * ajax-form.js v0.1.1 * author: Yoshiya Hinosawa ( http://github.com/kt3k ) * license: MIT */ (function ($) { 'use strict'; var initAjaxFormSingle = function (form) { var ATTR_INITIALIZED = 'data-ajax-form-initialized'; var ATTR_API = 'data-api'; var ATTR_METHOD = 'data-method'; var initialized = $(form).attr(ATTR_INITIALIZED); if (initialized) { return; } var initButton = function () { $('button', form).each(function () { var $btn = $(this); var api = $btn.attr(ATTR_API); var method = $btn.attr(ATTR_METHOD) || 'get'; if (!api) { $btn.addClass('disabled'); throw new Error('api is not specified: ' + api); } if (!/^(post|get|put|delete)$/.test(method)) { $btn.addClass('disabled'); throw new Error('method is invalid: ' + method); } var bindEvent = function () { $btn.one('click', function () { var paramList = $(form).serializeArray(); var params = {}; paramList.forEach(function (param) { params[param.name] = param.value; }); qwest[method](api, params).then(function (res) { $btn.trigger('success.ajax-form', res); }).catch(function (e) { $btn.trigger('failure.ajax-form', e); console.log(e); console.log(e.stack); }).then(bindEvent); }); }; bindEvent(); }); }; // init the button initButton(); // mark init done $(form).attr(ATTR_INITIALIZED, 'on'); }; var initAjaxForms = function () { $('.ajax-form').each(function () { initAjaxFormSingle(this); }); }; $(document).on('init.ajax-form', initAjaxForm); $(function () { $(document).trigger('init.ajax-form'); }); }(jQuery));
JavaScript
0.000004
@@ -2229,16 +2229,17 @@ AjaxForm +s );%0A%0A%0A
3359b76b0e9c01fb87c34ac9442f1a44eba96aa1
Add default value for config.baseApiPath
index.js
index.js
var path = require('path'); var express = require('express'); var favicon = require('serve-favicon'); module.exports = function (app, baseDir, config) { var servedDirectory = 'app'; if ('production' === app.get('env')) { servedDirectory = 'dist'; // prerender.io app.use(require('prerender-node').set('prerenderToken', process.env.PRERENDER_TOKEN).set('protocol', 'https')); } else { app.use(config.baseUrl + '/styles', express.static(path.join(__dirname, '.tmp', 'styles'))); // ugly hack to serve compiled SCSS; you will need to `grunt build` every time you change a style } servedDirectory = path.join(__dirname, servedDirectory); app.use(config.baseUrl, express.static(servedDirectory)); app.use(config.baseUrl + '/scripts/template.js', express.static(path.join(baseDir, config.scenarioTemplate))); app.get(config.baseUrl + '/scripts/constants.js', function (req, res) { res.type('application/javascript') .send('angular.module("ludwigConstants", []).constant("config", ' + // make config available to Angular's dependency management system JSON.stringify(config) + ');' ); }); app.use(favicon(path.join(servedDirectory, 'favicon.ico'))); app.route(config.baseUrl + '/*').get(function (req, res) { res.sendFile(path.join(servedDirectory, 'index.html')); }); };
JavaScript
0
@@ -145,24 +145,89 @@ , config) %7B%0A + config.baseApiPath = config.baseApiPath %7C%7C config.baseUrl;%0A%0A%0A var serv
ee9c33a108a6bae232057135e4f77d7cf50f38b2
use logs config
index.js
index.js
require('babel-polyfill'); var childProcess = require('child_process'); var http = require("http"); var httpProxy = require('http-proxy'); var spawn = childProcess.spawn; var ServiceManager = require('./service_manager'); var app = http.createServer(dispatch); var proxy = httpProxy.createProxyServer({ ws: true }); var config = require('./config'); var promisify = require('promisify-node'); var fs = promisify('fs'); var gitClone = require('git-clone'); var portForwardMatcher = /\/port\/([0-9]+)(\/.*)/; process.on('unhandledRejection', function(reason, p){ console.log("Possibly Unhandled Rejection at: Promise ", p, " reason: ", reason); }); function startLivelyServerInBackground() { console.log("start lively server") if (!fs.existsSync(config.logsDir)){ fs.mkdirSync(config.logsDir); } out = fs.openSync('./logs/lively-server.log', 'a'); err = fs.openSync('./logs/lively-server.log', 'a'); var livelyServerProcess = spawn('node', [ config.LIVELY_SERVER_PATH, '--port=' + config.LIVELY_SERVER_PORT, '--directory=services/', '--server='+config.LIVELY_SERVER_DIR, '--auto-commit=true', '--index-files=false' ], { stdio: [ 'ignore', out, err ] }); console.log('lively-server (#' + livelyServerProcess.pid + ') is listenting on ' + config.LIVELY_SERVER_PORT + '...'); } function dispatch(req, res) { // Set CORS headers res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Request-Method', '*'); res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS'); if (req.url.indexOf("/mount/") === 0) { req.url = req.url.substr('/mount'.length, req.url.length); proxy.web(req, res, { target: 'http://localhost:' + config.LIVELY_SERVER_PORT }); return; } if (req.url.indexOf("/debug/") === 0) { req.url = req.url.substr('/debug'.length, req.url.length); proxy.web(req, res, { target: 'http://localhost:' + config.NODE_INSPECTOR_WEB_PORT }); return; } var matches = portForwardMatcher.exec(req.url); if (matches) { var port = matches[1]; req.url = matches[2]; proxy.web(req, res, { target: 'http://localhost:' + parseInt(port) }); return; } if (req.method === "GET") { if (req.url === "/") { return jsonResponse(res, { status: 'running' }); } else if (req.url === "/list") { return jsonResponse(res, ServiceManager.listProcesses()); } else { notFound(res); } } else if (req.method === "POST") { var body = []; req.on('data', function(chunk) { body.push(chunk); }).on('end', function() { body = Buffer.concat(body).toString(); try { var data = JSON.parse(body); if (req.url === "/get") { postGet(req, res, data); } else if (req.url === "/start") { postStart(req, res, data); } else if (req.url === "/clone") { postClone(req, res, data); } else if (req.url === "/stop") { postStop(req, res, data); } else if (req.url === "/remove") { postRemove(req, res, data); } else { notFound(res); } } catch (ex) { console.error(ex); console.log("body: " + body) } }); } else if (req.method === "OPTIONS") { res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'); res.writeHead(200); res.end(); } else { notFound(res); } } function postGet(req, res, data) { return ServiceManager.getProcessInfo(data.id).then(function(info) { return jsonResponse(res, info); }).catch(function(error) { return jsonResponse(res, { status: 'failed', message: error }); }); } function postStart(req, res, data) { var promise; if (data.id !== undefined && ServiceManager.serviceExists(data.id)) { ServiceManager.killProcess(data.id); promise = Promise.resolve(); } else { promise = ServiceManager.addService(data.entryPoint).then(function(id) { data.id = id; }); } promise.then(function() { ServiceManager.spawnProcess(data.id); jsonResponse(res, { status: 'success', pid: data.id }); }).catch(function(error) { jsonResponse(res, { status: 'failed', message: error }); }); } function postClone(req, res, data) { var repoUrl = data.url; var repoName = repoUrl.split("/").slice(-1)[0].split(".git")[0]; var dirName = config.servicesDir + "/" + repoName; gitClone(repoUrl, dirName, function(error) { if (error) { jsonResponse(res, { status: 'failed', message: error }); } else { var npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'; var npmInstall = spawn(npm, ["install", "--dev"], {cwd : dirName}); npmInstall.stdout.on('data', function(data) { console.log(data.toString()); }); npmInstall.stderr.on('data', function(data) { console.log(data.toString()); }); npmInstall.on('close', function(exitCode) { jsonResponse(res, { status: 'success'}); }); } }); } function postStop(req, res, data) { ServiceManager.killProcess(data.id); return jsonResponse(res, { status: 'success' }); } function postRemove(req, res, data) { ServiceManager.removeProcess(data.id); return jsonResponse(res, { status: 'success'}); } function notFound(res) { res.writeHead(404); res.end(); } function jsonResponse(res, obj) { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)); } app.on('upgrade', function (req, socket, head) { var matches = portForwardMatcher.exec(req.url); if (matches) { var port = matches[1]; req.url = matches[2]; proxy.ws(req, socket, head, { target: 'ws://localhost:' + parseInt(port) }); return; } proxy.ws(req, socket, head, { target: 'ws://localhost:' + config.NODE_INSPECTOR_WEB_PORT }); }); function start(cb) { app.listen(config.PORT, function () { startLivelyServerInBackground(); ServiceManager.startDebugServer(); console.log('Listening on port ' + config.PORT + '...'); if (cb) { cb(); } }); } if (!module.parent) { // the script was directly executed start(); } module.exports = { start: start };
JavaScript
0
@@ -814,39 +814,50 @@ t = fs.openSync( -'./logs +config.logsDir + ' /lively-server.l @@ -891,15 +891,26 @@ ync( -'./logs +config.logsDir + ' /liv
422ca7a08007a6c648051dd8a0506e6e97d9c7dc
Allow node pinning
index.js
index.js
/** * Creates a force based layout that can be switched between 3d and 2d modes * Layout is used by ngraph.pixel * * @param {ngraph.graph} graph instance that needs to be laid out * @param {object} options - configures current layout. * @returns {ojbect} api to operate with current layout. Only two methods required * to exist by ngraph.pixel: `step()` and `getNodePosition()`. */ var eventify = require('ngraph.events'); var layout3d = require('ngraph.forcelayout3d'); var layout2d = layout3d.get2dLayout; module.exports = createLayout; function createLayout(graph, options) { options = options || {}; /** * Shuold the graph be rendered in 3d space? True by default */ options.is3d = options.is3d === undefined ? true : options.is3d; var is3d = options.is3d; var layout = is3d ? layout3d(graph, options.physics) : layout2d(graph, options.physics); var api = { //////////////////////////////////////////////////////////////////////////// // The following two methods are required by ngraph.pixel to be implemented // by all layout providers //////////////////////////////////////////////////////////////////////////// /** * Called by `ngraph.pixel` to perform one step. Required to be provided by * all layout interfaces. */ step: layout.step, /** * Gets position of a given node by its identifier. Required. * * @param {string} nodeId identifier of a node in question. * @returns {object} {x: number, y: number, z: number} coordinates of a node. */ getNodePosition: layout.getNodePosition, //////////////////////////////////////////////////////////////////////////// // Methods below are not required by ngraph.pixel, and are specific to the // current layout implementation //////////////////////////////////////////////////////////////////////////// /** * Sets position for a given node by its identifier. * * @param {string} nodeId identifier of a node that we want to modify * @param {number} x coordinate of a node * @param {number} y coordinate of a node * @param {number} z coordinate of a node */ setNodePosition: layout.setNodePosition, /** * Toggle rendering mode between 2d and 3d. * * @param {boolean+} newMode if set to true, the renderer will switch to 3d * rendering mode. If set to false, the renderer will switch to 2d mode. * Finally if this argument is not defined, then current rendering mode is * returned. */ is3d: mode3d, /** * Gets force based simulator of the current layout */ simulator: layout.simulator }; eventify(api); return api; function mode3d(newMode) { if (newMode === undefined) { return is3d; } if (newMode !== is3d) { toggleLayout(); } return api; } function toggleLayout() { var idx = 0; var oldLayout = layout; layout.dispose(); is3d = !is3d; var physics = copyPhysicsSettings(layout.simulator); if (is3d) { layout = layout3d(graph, physics); } else { layout = layout2d(graph, physics); } graph.forEachNode(initLayout); api.step = layout.step; api.setNodePosition = layout.setNodePosition; api.getNodePosition = layout.getNodePosition; api.simulator = layout.simulator; api.fire('reset'); function initLayout(node) { var pos = oldLayout.getNodePosition(node.id); // we need to bump 3d positions, so that forces are disturbed: if (is3d) pos.z = (idx % 2 === 0) ? -1 : 1; else pos.z = 0; layout.setNodePosition(node.id, pos.x, pos.y, pos.z); idx += 1; } } function copyPhysicsSettings(simulator) { return { springLength: simulator.springLength(), springCoeff: simulator.springCoeff(), gravity: simulator.gravity(), theta: simulator.theta(), dragCoeff: simulator.dragCoeff(), timeStep: simulator.timeStep() }; } }
JavaScript
0.000001
@@ -2654,16 +2654,446 @@ imulator +,%0A%0A /**%0A * Toggle node pinning. If node is pinned the layout algorithm is not allowed%0A * to change its position.%0A *%0A * @param %7Bstring%7D nodeId identifier of a node to work with;%0A * @param %7Bboolean+%7D isPinned if specified then the %60nodeId%60 pinning attribute%0A * is set to the to the value of this argument; Otherwise this method returns%0A * current pinning mode of the node.%0A */%0A pinNode: pinNode %0A %7D;%0A%0A @@ -4110,24 +4110,310 @@ %0A %7D%0A %7D%0A%0A + function pinNode(nodeId, isPinned) %7B%0A var node = graph.getNode(nodeId);%0A if (!node) throw new Error('Could not find node in the graph. Node Id: ' + nodeId);%0A if (isPinned === undefined) %7B%0A return layout.isNodePinned(node);%0A %7D%0A layout.pinNode(node, isPinned);%0A %7D%0A%0A function c
0e158e70ec3b74038460071ae3c1da5e0ed1de87
Update geojson source
index.js
index.js
mapboxgl.accessToken = 'pk.eyJ1IjoicGxhbmVtYWQiLCJhIjoiY2l2dzVxbzA3MDAwNDJzbDUzMzVzbXc5dSJ9.WZ4_UtVvuVmOw4ofNMkiJw'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/light-v9', zoom: 1.4, center: [21.6, 7.6], hash: true }); map.addControl(new MapboxGeocoder({ accessToken: mapboxgl.accessToken })); map.on('load', function() { map.addSource('wikidata-source', { type: 'vector', url: 'mapbox://amisha.wikidata' }); map.addLayer({ "id": "wikidata-layer", "type": "circle", "source": "wikidata-source", "source-layer": "wikidata", "paint": { "circle-radius": { "property": 'distance', 'stops': [ [0, 1], [5, 4], [10, 8], [100, 20] ] }, "circle-color": { "property": 'distance', "stops": [ [0, '#00ff00'], [5, '#ffff00'], [10, '#ff0000'] ] } } }); }); map.on('click', function(e) { var features = map.queryRenderedFeatures(e.point, { layers: ['wikidata-layer'] }); if (!features.length) { return; } var feature = features[0]; // Populate the popup and set its coordinates // based on the feature found. var popupHTML = "<h3>" + feature.properties.name + "</h3>"; popupHTML += "<a href='https://www.wikidata.org/wiki/" + feature.properties.wikidata + "'>Wikidata</a><br>"; popupHTML += JSON.stringify(feature.properties); var popup = new mapboxgl.Popup() .setLngLat(feature.geometry.coordinates) .setHTML(popupHTML) .addTo(map); }); map.on('mousemove', function(e) { var features = map.queryRenderedFeatures(e.point, { layers: ['wikidata-layer'] }); map.getCanvas().style.cursor = (features.length) ? 'pointer' : ''; });
JavaScript
0.000001
@@ -476,16 +476,31 @@ wikidata +_planet_geojson '%0A %7D)
671c8b6ec9b41b10ae4d640978242fca8a103993
Use module.parent's directory for resolving usage.txt
index.js
index.js
var path = require('path') , fs = require('fs') module.exports = function(file) { file = file || path.resolve('usage.txt') return function(code) { var rs = fs.createReadStream(file) rs.pipe(process.stdout) rs.on('close', function() { if (code) process.exit(code) }) } }
JavaScript
0.000004
@@ -95,11 +95,141 @@ file - %7C%7C +%0A ? file%0A : module.parent && module.parent.filename%0A ? path.resolve(path.dirname(module.parent.filename), 'usage.txt')%0A : pat
a75ed5e3a45a160415ed35de3067644852d1293a
Simplify negated (#7)
index.js
index.js
'use strict'; const escapeStringRegexp = require('escape-string-regexp'); const reCache = new Map(); function makeRe(pattern, shouldNegate) { const cacheKey = pattern + shouldNegate; if (reCache.has(cacheKey)) { return reCache.get(cacheKey); } let negated = false; if (pattern[0] === '!') { negated = true; pattern = pattern.slice(1); } pattern = escapeStringRegexp(pattern).replace(/\\\*/g, '.*'); if (negated && shouldNegate) { pattern = `(?!${pattern})`; } const re = new RegExp(`^${pattern}$`, 'i'); re.negated = negated; reCache.set(cacheKey, re); return re; } module.exports = (inputs, patterns) => { if (!(Array.isArray(inputs) && Array.isArray(patterns))) { throw new TypeError(`Expected two arrays, got ${typeof inputs} ${typeof patterns}`); } if (patterns.length === 0) { return inputs; } const firstNegated = patterns[0][0] === '!'; patterns = patterns.map(x => makeRe(x, false)); const ret = []; for (const input of inputs) { // If first pattern is negated we include everything to match user expectation let matches = firstNegated; // TODO: Figure out why tests fail when I use a for-of loop here for (let j = 0; j < patterns.length; j++) { if (patterns[j].test(input)) { matches = !patterns[j].negated; } } if (matches) { ret.push(input); } } return ret; }; module.exports.isMatch = (input, pattern) => makeRe(pattern, true).test(input);
JavaScript
0
@@ -247,18 +247,20 @@ );%0A%09%7D%0A%0A%09 -le +cons t negate @@ -267,21 +267,8 @@ d = -false;%0A%0A%09if ( patt @@ -285,29 +285,26 @@ '!' -) %7B%0A%09%09negated = true; +;%0A%0A%09if (negated) %7B %0A%09%09p @@ -1083,115 +1083,38 @@ %0A%0A%09%09 -// TODO: Figure out why tests fail when I use a for-of loop here%0A%09%09for (let j = 0; j %3C patterns.length; j++ +for (const pattern of patterns ) %7B%0A @@ -1127,20 +1127,16 @@ (pattern -s%5Bj%5D .test(in @@ -1169,12 +1169,8 @@ tern -s%5Bj%5D .neg
e086fbf84f6b34f21e4ac4336cbd986542786ba6
Don't run AST transform on freestyle itself, just on it's parent app/addon
index.js
index.js
'use strict'; module.exports = { name: require('./package').name, included(/*app, parentAddon*/) { this._super.included.apply(this, arguments); }, isDevelopingAddon() { return false; }, setupPreprocessorRegistry(type, registry) { let pluginObj = this._buildPlugin(); pluginObj.parallelBabel = { requireFile: __filename, buildUsing: '_buildPlugin', params: {}, }; registry.add('htmlbars-ast-plugin', pluginObj); }, _buildPlugin() { return { name: 'component-attributes', plugin: require('./lib/ast-transform'), baseDir() { return __dirname; }, }; }, };
JavaScript
0.999017
@@ -243,24 +243,73 @@ registry) %7B%0A + if (type !== 'parent') %7B%0A return;%0A %7D%0A let plug
52d4d3f2dcf1a658a497140212a053d707408234
Update up to changes in es5-ext
index.js
index.js
'use strict'; var toUint = require('es5-ext/number/to-uint') , firstKey = require('es5-ext/object/first-key') , d = require('d/d') , Message = require('./_message') , isArray = Array.isArray, defineProperties = Object.defineProperties; module.exports = function (locale) { var self, resolve; self = function (key/*, inserts*/) { var inserts = arguments[1], template = resolve.call(this, String(key)); if (!inserts) return template; return new Message(template, inserts); }; resolve = function (key, n) { var locale = self.locale, context, template, isMulti; if (!locale) return key; if ((locale = locale[key]) == null) return key; if (typeof locale === 'string') return locale; isMulti = (n != null); if (isMulti && (typeof locale === 'function')) return locale(n); if (!isMulti || !isArray(locale)) { context = ((this == null) || (this === self)) ? 'default' : this; if (locale[context] != null) { template = locale[context]; } else if (locale.default != null) { template = locale.default; } else { context = firstKey(locale); if (context == null) return key; template = locale[context]; } } else { template = locale; } if (!isMulti) return String(template); if (typeof template === 'function') return template(n); if (isArray(template)) { if (n) --n; while (n && (template[n] == null)) --n; if (template[n] != null) return template[n]; return key; } return String(template); }; return defineProperties(self, { locale: d(locale), _: d(self), _n: d(function (keyS, keyP, n/*, inserts*/) { var inserts = arguments[3], key = 'n\0' + keyS + '\0' + keyP, template; n = toUint(n); template = resolve.call(this, key, toUint(n)); if (template === key) template = (n > 1) ? keyP : keyS; if (!inserts) return template; return new Message(template, inserts); }) }); };
JavaScript
0
@@ -18,14 +18,14 @@ r to -Uint +PosInt = r @@ -54,12 +54,19 @@ /to- -uint +pos-integer ')%0A @@ -1691,18 +1691,20 @@ %09%09n = to -Ui +PosI nt(n);%0A%09 @@ -1746,10 +1746,12 @@ , to -Ui +PosI nt(n
49a6f7d0f5df3770032c772f036ef9b8450eddff
Make the Redis connection more robust
index.js
index.js
'use strict'; var redis = require('redis'), coRedis = require('co-redis'), koa = require('koa'); var app = koa(), client = redis.createClient( process.env.REDIS_PORT, process.env.REDIS_HOST ), dbCo = coRedis(client); if (process.env.REDIS_SECRET) { client.auth(process.env.REDIS_SECRET); } app.use(function* () { var indexkey; if (this.request.query.index_key) { indexkey = process.env.APP_NAME +':'+ this.request.query.index_key; } else { indexkey = yield dbCo.get(process.env.APP_NAME +':current'); } var index = yield dbCo.get(indexkey); this.body = index || ''; }); app.listen(process.env.PORT || 3000);
JavaScript
0
@@ -322,16 +322,101 @@ ET);%0A%7D%0A%0A +client.on('error', function (err) %7B%0A console.log('Redis client error: ' + err);%0A%7D);%0A %0Aapp.use
cec92bf498c804f3c2c3732b8c14627524658373
make components transparent
index.js
index.js
'use strict'; var React = require('react-native'); var {View, Navigator, Text, StyleSheet} = React; var alt = require('./alt'); var PageStore = require('./store'); var Actions = require('./actions'); var FetchActions = require('./FetchActions'); var FetchStore = require('./FetchStore'); var Animations = require('./Animations'); var Container = require('./Container'); // schema class represents schema for routes and it is processed inside Router component class Schema extends React.Component { render(){ return null; } } // schema class represents fetch call class API extends React.Component { render(){ return null; } } // route class processed inside Router component class Route extends React.Component { render(){ return null; } } /* Returns the class name of the argument or undefined if it's not a valid JavaScript object. */ function getClassName(obj) { if (obj.toString) { var arr = obj.toString().match( /function\s*(\w+)/); if (arr && arr.length == 2) { return arr[1]; } } return undefined; } let SchemaClassName = getClassName(Schema); let RouteClassName = getClassName(Route); let APIClassName = getClassName(API); class Router extends React.Component { constructor(props){ super(props); this.state = {}; this.routes = {}; this.apis = {}; this.schemas = {}; var self = this; var RouterActions = props.actions || Actions; var RouterStore = props.store|| PageStore; var initial = null; React.Children.forEach(props.children, function (child, index){ var name = child.props.name; if (child.type.name == SchemaClassName) { self.schemas[name] = child.props; } else if (child.type.name == RouteClassName) { if (child.props.initial || !initial || name==props.initial) { initial = child.props; self.initialRoute = child.props; } if (!(RouterActions[name])) { RouterActions[name] = alt.createAction(name, function (data) { if (typeof(data)!='object'){ data={data:data}; } var args = {name: name, data:data}; RouterActions.push(args); }); } self.routes[name] = child.props; if (!child.props.component && !child.props.children){ console.error("No route component is defined for name: "+name); return; } } else if (child.type.name == APIClassName) { self.apis[name] = child.props; // generate sugar actions like 'login' if (!(RouterActions[name])) { RouterActions[name] = alt.createAction(name, function (data) { if (typeof(data)!='object'){ data={data:data}; } FetchActions.fetch(name, data); }); } } }); // load all APIs to FetchStore FetchActions.load(this.apis); } onChange(page){ if (page.mode=='push'){ if (!page.name){ alert("Page name is not defined for action"); return; } var route = this.routes[page.name]; if (!route){ alert("No route is defined for name: "+page.name); return; } // check if route is popup if (route.schema=='popup'){ this.setState({modal: React.createElement(route.component, {data: page.data})}); } else { //console.log("PUSH"); this.refs.nav.push(this.getRoute(route, page.data)) } } if (page.mode=='pop'){ var num = page.num || 1; var routes = this.refs.nav.getCurrentRoutes(); // pop only existing routes! if (num < routes.length) { this.refs.nav.popToRoute(routes[routes.length - 1 - num]); } else { if (this.props.onExit){ this.props.onExit(routes[0], page.data || {}); } } } if (page.mode=='dismiss') { this.setState({modal: null}); } } componentDidMount(){ var RouterStore = this.props.store|| PageStore; this.routerUnlisten = RouterStore.listen(this.onChange.bind(this)); } onFetchChange(state){ } componentWillUnmount() { this.routerUnlisten(); } renderScene(route, navigator) { console.log("ROUTE: "+route.name) var Component = route.component; var navBar = route.navigationBar; if (navBar) { navBar = React.addons.cloneWithProps(navBar, { navigator: navigator, route: route }); } var child = Component ? <Component navigator={navigator} route={route} {...route.passProps}/> : React.Children.only(this.routes[route.name].children) return ( <View style={{flex:1}}> {navBar} {child} </View> ) } getRoute(route, data) { var schema = this.schemas[route.schema || 'default'] || {}; var sceneConfig = route.sceneConfig || schema.sceneConfig || Animations.None; var NavBar = route.navBar || schema.navBar; var navBar; if (NavBar){ navBar = <NavBar {...schema} {...route} {...data} /> } return { name: route.name, component: route.component, sceneConfig: { ...sceneConfig, gestures: {} }, navigationBar: route.hideNavBar ? null : navBar, passProps: { ...route, ...data } } } render(){ var modal = null; if (this.state.modal){ modal = (<View style={styles.container}> <View style={[styles.container,{backgroundColor:'black',opacity:0.5}]}/> {this.state.modal} </View> ); } return ( <View style={{flex:1}}> <Navigator renderScene={this.renderScene.bind(this)} configureScene={(route) => { return route.sceneConfig;}} ref="nav" initialRoute={this.getRoute(this.initialRoute)} /> {modal} </View> ); } } var styles = StyleSheet.create({ container: { position: 'absolute', top:0, bottom:0, left:0, right:0, backgroundColor:'transparent', justifyContent: 'center', alignItems: 'center', }, }); module.exports = {Router, Container, Actions, API, PageStore, Route, Animations, Schema, FetchStore, FetchActions, alt}
JavaScript
0.000001
@@ -5373,32 +5373,42 @@ View style=%7B -%7Bflex:1%7D +styles.transparent %7D%3E%0A @@ -6498,16 +6498,26 @@ le=%7B -%7Bflex:1%7D +styles.transparent %7D%3E%0A @@ -7124,16 +7124,92 @@ %0A %7D,%0A + transparent: %7B%0A flex:1,%0A backgroundColor: %22transparent%22%0A %7D%0A %7D);%0A%0Amod
292d8cfd05962b4ebee350954d9b26b9b06cdea6
Clean up the logging
index.js
index.js
"use strict"; var dynamo = require("dynamo"), when = require("when"), sequence = require("sequence"), winston = require("winston"); // Setup logger winston.loggers.add("app", { console: { 'level': "silly", 'timestamp': true, 'colorize': true } }); var log = winston.loggers.get("app"); // Models have many tables. // Girths are short hand for throughput. function Model(tableData){ this.connected = false; this.girths = {}; this.tables = {}; this.tableData = tableData; } Model.prototype.connect = function(key, secret, prefix, region){ this.prefix = prefix; this.region = region; if(process.env.NODE_ENV === "production"){ // Connect to DynamoDB console.log("Connecting to DynamoDB"); this.client = dynamo.createClient({ 'accessKeyId': key, 'secretAccessKey': secret }); this.client.useSession = false; this.db = this.client.get(this.region || "us-east-1"); } else { // Connect to Magneto console.log("Connecting to Magneto"); this.client = dynamo.createClient(); this.client.useSession = false; this.db = this.client.get(this.region || "us-east-1"); this.db.host = "localhost"; this.db.port = 8081; } this.tableData.forEach(function(table){ var schema = {}, typeMap = { 'N': Number, 'Number': Number, 'NS': [Number], 'NumberSet': [Number], 'S': String, 'String': String, 'SS': [String], 'StringSet': [String] }, tableName = (this.prefix || "") + table.table; this.tables[table.alias] = this.db.get(tableName); this.tables[table.alias].name = this.tables[table.alias].TableName; this.tables[table.alias].girth = { 'read': table.read, 'write': table.write }; // Parse table hash and range names and types defined in package.json schema[table.hashName] = typeMap[table.hashType]; if (table.rangeName){ schema[table.rangeName] = typeMap[table.rangeType]; } this.tables[table.alias].schema = schema; this.girths[table.alias] = { 'read': table.read, 'write': table.write }; }.bind(this)); this.connected = true; return this; }; Model.prototype.table = function(alias){ return this.tables[alias]; }; Model.prototype.createAll = function(){ var d = when.defer(); when.all(Object.keys(this.tables).map(this.ensureTable.bind(this)), d.resolve); return d.promise; }; Model.prototype.ensureTable = function(alias){ var d = when.defer(); sequence(this).then(function(next){ this.db.listTables({}, next); }).then(function(next, err, data){ if(!d.rejectIfError(err)){ next(data); } }).then(function(next, data){ if(data.TableNames.indexOf(this.table(alias).name) !== -1){ return d.resolve(false); } this.db.add({ 'name': this.table(alias).name, 'schema': this.table(alias).schema, 'throughput': this.table(alias).girth }).save(function(err, table){ if(!d.rejectIfError(err)){ d.resolve(true); } }); }); return d.promise; }; Model.prototype.get = function(alias, key, value){ log.silly("mambo: get " + alias + key + value); var d = when.defer(), query = {}; query[key] = value; this.table(alias).get(query).fetch(function(err, data){ if(!d.rejectIfError(err)){ d.resolve(data); } }); return d.promise; }; module.exports = Model;
JavaScript
0.000001
@@ -3561,19 +3561,31 @@ alias + -key +%22 %22 + key + %22 %22 + value
9b7730b5dd17a5909bb1c59b226d99521ed91e03
create root dir from app dir an arguments wd
index.js
index.js
var fs = require('fs'); var path = require('path'); var send = require('send'); var isFile = /\/[^.]+\.[a-z0-9]+$/gi; var cwd = process.cwd(); var url = require('url'); // your custom headers function headers(res, path, headers, dataHeaders) { headers = dataHeaders ? Object.assign(headers, dataHeaders) : headers; if (headers) { Object.keys(headers).forEach(key => res.setHeader(key, headers[key])); } // add http headers if (path.substr(-3, 3) === '.js') { res.setHeader('Content-Encoding', 'gzip'); } } exports.static = function (scope, inst, args, data, next) { if (!data.req || !data.res) { return next(new Error('Flow-static.static: No request or response stream found.')); } var file = args.file || data.file || data.params.name || url.parse(data.req.url).pathname; // normalize public path file = path.normalize(file); // add index.html to path /*if (file[file.length-1] === '/') { file = 'index.html'; }*/ // push the engine client directly //if (args.push && res.push) { /*push.args: { request: {accept: '*'+'/'+'*'}, response: { 'Content-Type': 'application/javascript', //'Content-Encoding': 'gzip', 'Content-Length': clientFile.length } }*/ //send(args.req, file, {root: path.join(this._env.workDir, args.wd || '')}) //.on('error', onError) //.on('headers', headers) //.pipe(res.push(args.push.url, args.push.args || {})); //} //console.log('Static file:', path.join(cwd, args.wd || ''), file); send(data.req, file, {root: path.join(cwd, args.wd || '')}) .on('error', function (err) { data.res.statusCode = err.status || 500; data.res.end(err.stack); }) .on('headers', (res, path) => headers(res, path, args.headers, data.headers)) .pipe(data.res); next(null, data); };
JavaScript
0.000001
@@ -115,33 +115,8 @@ gi;%0A -var cwd = process.cwd();%0A var @@ -1585,29 +1585,71 @@ file:', -path.join(cwd +scope.env._appDir, args.wd, path.join(scope.env._appDir , args.w @@ -1711,11 +1711,25 @@ oin( -cwd +scope.env._appDir , ar
250b2171e7ab1aff17822874b59b0e6873b3f517
fix error
index.js
index.js
module.exports = Socket var EventEmitter = require('events').EventEmitter var inherits = require('inherits') var once = require('once') var RECONNECT_TIMEOUT = 5000 inherits(Socket, EventEmitter) function Socket (url, opts) { if (!(this instanceof Socket)) return new Socket(url, opts) EventEmitter.call(this) if (!opts) opts = {} this._url = url this._reconnect = (opts.reconnect !== undefined) ? opts.reconnect : RECONNECT_TIMEOUT this._init() } Socket.prototype.send = function (message) { if (this._ws && this._ws.readyState === WebSocket.OPEN) { if (typeof message === 'object') message = JSON.stringify(message) this._ws.send(message) } } Socket.prototype.destroy = function (onclose) { if (onclose) this.once('close', onclose) try { this._ws.close() } catch (err) { this._onclose() } } Socket.prototype._init = function () { this._errored = false this._ws = new WebSocket(this._url) this._ws.onopen = this._onopen.bind(this) this._ws.onmessage = this._onmessage.bind(this) this._ws.onclose = this._onclose.bind(this) this._ws.onerror = once(this._onerror.bind(this)) } Socket.prototype._onopen = function () { this.emit('ready') } Socket.prototype._onerror = function (err) { this._errored = true // On error, close socket... this.close() // ...and try to reconnect after a timeout if (this._reconnect) { this._timeout = setTimeout(this._init.bind(this), this._reconnect) this.emit('warning', err) } else { this.emit('error', err) } } Socket.prototype._onmessage = function (event) { var message = event.data try { message = JSON.parse(event.data) } catch (err) {} this.emit('message', message) } Socket.prototype._onclose = function () { clearTimeout(this._timeout) if (this._ws) { this._ws.onopen = null this._ws.onerror = null this._ws.onmessage = null this._ws.onclose = null } this._ws = null if (!this._errored) this.emit('close') }
JavaScript
0.000002
@@ -1316,21 +1316,23 @@ %0A this. -close +destroy ()%0A%0A //
ee4d74c7a46ab30a7dc3614b246cbaf3ddff918f
rename variables
index.js
index.js
'use strict'; /* global document, window */ /* exported straube */ var screenSize = document.body.offsetWidth; var straube = function() { var STRAUBE_CLASS = 'straube'; var STRAUBE_WRAPPER_CLASS = 'straube-wrapper'; var elements = document.querySelectorAll('.' + STRAUBE_CLASS); var wrapperElement; var securityAlert = 500; var isSmaller = (document.body.offsetWidth - screenSize) < 0; screenSize = document.body.offsetWidth; var bigDelta = 1; var smallDelta = 0.1; if (isSmaller) { bigDelta = 0.1; smallDelta = 1; } Array.prototype.slice.call(elements).forEach(function(element){ securityAlert = 1500; if (element.textContent.replace(/\s+/g, '').length === 0) { return; } element.style.whiteSpace = 'pre'; wrapperElement = document.createElement('span'); wrapperElement.classList.add(STRAUBE_WRAPPER_CLASS); wrapperElement.innerHTML = element.outerHTML; //element.outerHTML = wrapperElement.outerHTML; element.parentNode.replaceChild(wrapperElement, element); element = wrapperElement.children[0]; // calculations var wrapperWidth = element.parentNode.offsetWidth; element.style.fontSize = parseFloat( window.getComputedStyle(element, null).getPropertyValue('font-size') ) + 'px'; while (element.offsetWidth < wrapperWidth && --securityAlert) { element.style.fontSize = parseFloat(element.style.fontSize, 10) + bigDelta + 'px'; } while (element.offsetWidth > wrapperWidth && securityAlert > 0) { element.style.fontSize = parseFloat(element.style.fontSize, 10) - smallDelta + 'px'; } if (securityAlert === 0) { alert('dupa'); } }); }; var resizeInterval; var resizeTimeout = 100; window.addEventListener('resize', function() { clearTimeout(resizeInterval); resizeInterval = setTimeout(straube, resizeTimeout); }); straube();
JavaScript
0.000039
@@ -442,19 +442,25 @@ %0A%0A var -big +increment Delta = @@ -468,21 +468,25 @@ ;%0A var -small +decrement Delta = @@ -510,27 +510,33 @@ ller) %7B%0A -big +increment Delta = 0.1; @@ -536,29 +536,33 @@ = 0.1;%0A -small +decrement Delta = 1;%0A @@ -1479,11 +1479,17 @@ -big +increment Delt @@ -1682,13 +1682,17 @@ -small +decrement Delt
729a8c142e36f73fb946b03658dad09bcd93ebb5
Remove commented out code
index.js
index.js
var hexaworld = require('hexaworld/game.js') var base = require('./base.js') var editor = require('./ui/editor.js') var maps = require('./ui/maps.js') var config = require('./ui/config.js') var editorContainer = document.getElementById('editor-container') var selectorContainer = document.getElementById('selector') var width = editorContainer.clientWidth var height = editorContainer.clientHeight var offset = selectorContainer.clientWidth var selected = 0 var init = [base(), base()] var maps = maps('maps', init) var init = {name: 'welcome', lives: 3, stages: 3, steps: 6} var config = config('config', init) var edit = editor('editor', maps.get(selected), {width: width, height: height, offset: offset}) maps.events.on('selected', function(id) { selected = id edit.reload(maps.get(selected)) }) var game = hexaworld('game-container', maps.get(selected)) game.pause() document.getElementById('game-container').style.display = 'none' document.getElementById('button-edit').onclick = function (event) { document.getElementById('editor').style.display = 'initial' document.getElementById('game-container').style.display = 'none' editorContainer.style.background = 'rgb(100,100,100)' game.pause() edit.resume() } document.getElementById('button-play').onclick = function (event) { game.reload(maps.get(selected)) game.resume() edit.pause() setTimeout(function() { editorContainer.style.background = 'rgb(55,55,55)' document.getElementById('editor').style.display = 'none' document.getElementById('game-container').style.display = 'block' }, 50) } document.getElementById('button-reset').onclick = function (event) { document.getElementById('editor').style.display = 'initial' document.getElementById('game-container').style.display = 'none' game.pause() maps.reset(selected) edit.reload(maps.get(selected)) edit.resume() } document.getElementById('button-save').onclick = function (event) { var blob = {config: config.get(), maps: maps.getall()} console.log(blob.config) var payload = encodeURIComponent(JSON.stringify(blob)) var el = document.getElementById('button-save-download') el.setAttribute('download', blob.config.name + '.json') el.setAttribute('href', 'data:application/text,' + payload) el.click() } document.getElementById('button-load-label').onclick = function (event) { document.getElementById('button-load').value = null } document.getElementById('button-load').onchange = function (event) { var reader = new FileReader() reader.onload = function (event) { var schema = JSON.parse(event.target.result) selected = 0 config.load(schema.config) maps.load(schema.maps) edit.reload(maps.get(selected)) } reader.readAsText(this.files[0]) } // Object.keys(schema.gameplay).forEach(function (key) { // createConfigField(key) // }) // function createConfigField (key) { // var fieldset = document.createElement('fieldset') // var label = document.createElement('label') // label.setAttribute('for', 'gameplay-' + key) // label.innerHTML = key // var input = document.createElement('input') // input.type = 'text' // input.className = 'gameplay-config' // input.name = 'gameplay-' + key // input.id = 'gameplay-config-' + key // input.value = schema.gameplay[key] // fieldset.appendChild(label) // fieldset.appendChild(input) // gameplay.appendChild(fieldset) // input.addEventListener('input', function (e) { // var value = e.target.value // schema.gameplay[key] = Number(value) // }) // } // function updateConfig (schema) { // Object.keys(schema.gameplay).forEach(function (key) { // var config = document.getElementById('gameplay-config-' + key) // if (config) { // config.value = schema.gameplay[key] // } else { // createConfigField(key) // } // }) // }
JavaScript
0
@@ -2751,1103 +2751,4 @@ %5D)%0A%7D -%0A%0A%0A%0A// Object.keys(schema.gameplay).forEach(function (key) %7B%0A// createConfigField(key)%0A// %7D)%0A%0A// function createConfigField (key) %7B%0A// var fieldset = document.createElement('fieldset')%0A%0A// var label = document.createElement('label')%0A// label.setAttribute('for', 'gameplay-' + key)%0A// label.innerHTML = key%0A%0A// var input = document.createElement('input')%0A// input.type = 'text'%0A// input.className = 'gameplay-config'%0A// input.name = 'gameplay-' + key%0A// input.id = 'gameplay-config-' + key%0A// input.value = schema.gameplay%5Bkey%5D%0A%0A// fieldset.appendChild(label)%0A// fieldset.appendChild(input)%0A// gameplay.appendChild(fieldset)%0A%0A// input.addEventListener('input', function (e) %7B%0A// var value = e.target.value%0A// schema.gameplay%5Bkey%5D = Number(value)%0A// %7D)%0A// %7D%0A%0A// function updateConfig (schema) %7B%0A// Object.keys(schema.gameplay).forEach(function (key) %7B%0A// var config = document.getElementById('gameplay-config-' + key)%0A// if (config) %7B%0A// config.value = schema.gameplay%5Bkey%5D%0A// %7D else %7B%0A// createConfigField(key)%0A// %7D%0A// %7D)%0A// %7D%0A%0A
31a247654eb5d1f652fd4eb15fce0d0cdf65bc0f
[ERROR] unreleasable
index.js
index.js
var archiver = require('archiver'); var concatStream = require('concat-stream'); module.exports = function(options, modified, total, callback) { var list = options.modified ? modified : total; if (!list.length) { return false; } var filename = options.filename || 'all.tar.gz'; var root = fis.project.getProjectPath(); var tarfile = archiver('tar', { gzip: /\.tar\.gz$/i.test(filename) }); list.forEach(function(file) { var filepath = file.getHashRelease().substring(1); tarfile.append(file.getContent(), { name: filepath, mode: null }); }); tarfile.finalize(); tarfile.pipe(concatStream(function(data) { var file = fis.file(root, filename); file.setContent(data); if (!options.keep) { modified.splice(0, modified.length); total.splice(0, total.length); } modified.push(file); total.push(file); callback(); })) }; module.exports.options = { // 是否保留原始文件。 keep: false, // 是否只打包修改过的。 modified: false, // zip 文件名 filename: 'all.tar.gz' };
JavaScript
0.999975
@@ -438,24 +438,50 @@ ion(file) %7B%0A + if (file.release) %7B%0A var file @@ -528,16 +528,18 @@ );%0A%0A + tarfile. @@ -562,24 +562,26 @@ ontent(), %7B%0A + name: @@ -596,16 +596,18 @@ ,%0A + mode: nu @@ -613,20 +613,28 @@ ull%0A + %7D);%0A + %7D%0A %7D);%0A%0A
ff994c818bccf69c9c7ed88aae0f2338f3f47468
normalize input
index.js
index.js
/*! * tokens-map <https://github.com/jonschlinkert/tokens-map> * * Copyright (c) 2014 Jon Schlinkert, contributors. * Licensed under the MIT license. */ 'use strict'; /** * Module dependencies */ var rand = require('randomatic'); /** * Expose `Tokens` */ module.exports = Tokens; /** * Create an instance of `Tokens` with the given `string`. * * ```js * var Tokens = require('map-tokens'); * var tokens = new Tokens(string); * ``` * * @param {String} `string` * @api public */ function Tokens(str) { this.input = str ? this._input(str) : ''; this.result = ''; this.patterns = []; this.tokens = {}; } /** * Register a `regex` pattern to use for matching tokens. * * ```js * tokens.pattern(/def/); * ``` * * @param {RegExp} `regex` * @api public */ Tokens.prototype._input = function(str) { return str.replace(/(?:^\uFEFF)|\r/g, ''); }; /** * Register a `regex` pattern to use for matching tokens. * * ```js * tokens.pattern(/def/); * ``` * * @param {RegExp} `regex` * @api public */ Tokens.prototype.pattern = function(re) { this.patterns.push(re); return this; }; /** * Run the registered patterns on the `input` string, * which inserts tokens in place of matching strings. * * ```js * tokens.extract(); * // or * tokens.extract([/def/]); * ``` * * @param {Array} `patterns` Optionally pass an array of regex patterns to use * @api public */ Tokens.prototype.extract = function(str, patterns) { if (Array.isArray(str)) { patterns = str; str = null; } str = str || this.input; if (typeof str !== 'string') { throw new Error('map-tokens#extract expects a string'); } patterns = patterns || this.patterns; var len = patterns.length; var i = 0; var o = {}; o.tokens = {}; while (i < len) { var re = patterns[i++]; var match; var ii = 0; while (match = re.exec(str)) { ii++; var id = '__TOKEN_ID' + rand('A0', 6) + '__'; o.tokens[id] = match[0]; str = str.replace(match[0], id); } o.content = str; } this.tokens = o.tokens; this.content = o.content; return o.tokens; }; /** * Restore previously inserted tokens. * * ```js * tokens.restore(); * // or * tokens.restore(obj); * ``` * * @param {Object} `obj` Optionally pass an object with `tokens` and `content` properties to use. * @api public */ Tokens.prototype.restore = function(str, obj) { if (typeof str !== 'string') { obj = str; str = null; } str = str || this.content; obj = obj || this; if (typeof str !== 'string') { throw new Error('map-tokens#extract expects a string'); } this.result = str; var tokens = obj.tokens; var keys = Object.keys(tokens); var len = keys.length - 1; var i = -1; while (i < len && this.result.indexOf('__TOKEN_ID') !== -1) { var key = keys[len--]; this.result = this.result.replace(new RegExp(key, 'g'), tokens[key]); } return this.result; };
JavaScript
0.999985
@@ -1541,26 +1541,44 @@ str = str -%7C%7C +? this._input(str) : this.input; @@ -2514,18 +2514,36 @@ r = str -%7C%7C +? this._input(str) : this.co
9ea7b244d0be88ba07d0dc2f770b234180c654fd
Add missing semicolon
index.js
index.js
'use strict'; var binary = require('node-pre-gyp'); var path = require('path') var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json'))); var binding = require(binding_path); module.exports = sleep; function sleep(milliseconds) { var start = Date.now(); if (milliseconds !== (milliseconds | 0)) { throw new TypeError('sleep only accepts an integer number of milliseconds'); } milliseconds = milliseconds | 0; if (milliseconds < 0) { throw new TypeError('sleep only accepts a positive number of milliseconds'); } var result = binding.sleep(milliseconds); var end = Date.now(); return end - start; }
JavaScript
0.999999
@@ -72,16 +72,17 @@ ('path') +; %0Avar bin
185257d59bd544c649e76f4917dcbb9f3ef70f97
Update url replace code for dupe check
index.js
index.js
/** * Upload files to Amazon S3 of the IMG, A, LINK and SCRIPT tags and replaces the url for gulp 3. **/ var through = require('through2'), gutil = require('gulp-util'), extend = require('extend'), path = require('path'), Promise = require('promise'), fs = require('fs'), md5 = require('MD5'), s3 = require('s3'); const PLUGIN_NAME = 'gulp-s3-replace'; const linksRegExp = /(src|href)="([^\'\"]+)/ig; function gulpS3Replace(options) { options = extend({ basePath: process.cwd(), bucketName: '', fileExtensions: ['jpg', 'png', 'gif', 'svg', 'doc', 'pdf', 'js', 'css'], s3: { maxAsyncS3: 20, s3RetryCount: 3, s3RetryDelay: 1000, multipartUploadThreshold: 20 * 1024 * 1024, // 20971520 multipartUploadSize: 15 * 1024 * 1024, // 15728640 s3Options: { signatureVersion: 'v3', accessKeyId: "", secretAccessKey: "" } } }, options || {}); var s3Client = s3.createClient(options.s3); return through.obj(function (file, enc, callback) { var self = this; var basePath = path.normalize(options.basePath); if (basePath[basePath.length - 1] !== '/') { basePath = basePath + '/'; } if (file.isNull()) { return callback(null, file); // return empty file } if (file.isStream()) { self.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streams are not supported!')); return callback(); } if (file.isBuffer()) { var match; var promises = []; var content = file.contents.toString(); syncLoop(false, function (loop) { var match = linksRegExp.exec(content); if (null === match) { loop.break(true); loop.next(); return; } var originalFilePath = match[2]; if (options.fileExtensions.indexOf(path.extname(originalFilePath).substring(1)) === -1) { loop.next(); return; } promises.push(createUploadPromise(basePath, options.bucketName, originalFilePath, s3Client)); loop.next(); }, function () { if (promises.length === 0) { callback(null, file); } Promise.all(promises).then(function (urls) { for (var i = 0; i < urls.length; i++) { content = content.replace(urls[i].originalUrl, urls[i].publicUrl); } file.contents = new Buffer(content); callback(null, file); }) }); } }); } function syncLoop(iterations, process, exit) { var index = 0, done = false, shouldExit = false; var loop = { next: function () { if (done) { if (shouldExit && exit) { return exit(); } } if (false === iterations) { process(loop); } else { if (index < iterations) { index++; process(loop); } else { done = true; if (exit) { exit(); } } } }, iteration: function () { return index - 1; }, break: function (end) { done = true; shouldExit = end; } }; loop.next(); return loop; } function createUploadPromise(basePath, bucketName, destOriginalFilePath, s3Client) { return new Promise(function (resolve, reject) { var destFilePath = destOriginalFilePath[0] === '/' ? destOriginalFilePath.substring(1) : destOriginalFilePath; var filePath = basePath + destFilePath; var uploaderParams = { localFile: filePath, s3Params: { Bucket: bucketName, Key: destFilePath } }; var uploader = s3Client.uploadFile(uploaderParams); var publicUrl = s3.getPublicUrlHttp(bucketName, destFilePath); var metaDir = basePath + '.meta'; if (!directoryExists(metaDir)) { fs.mkdirSync(metaDir); } var metaPath = metaDir + '/' + md5(filePath) + '.meta'; var fileInfo = fs.statSync(filePath); var metaInfo = { utime: 0 }; if(!fileExists(metaPath)) { fs.writeFileSync(metaPath, JSON.stringify(metaInfo)); } else { metaInfo = JSON.parse(fs.readFileSync(metaPath)); } if(fileInfo['ctime'].getTime() <= metaInfo.utime) { gutil.log(gutil.colors.yellow('[SUCCESS]', destFilePath + " -> " + publicUrl)); resolve({originalUrl: destOriginalFilePath, publicUrl: publicUrl}); return; } metaInfo.utime = fileInfo['ctime'].getTime(); fs.writeFileSync(metaPath, JSON.stringify(metaInfo)); uploader.on('error', function (err) { self.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Unable to upload:' + err.stack)); callback() }); uploader.on('end', function () { gutil.log(gutil.colors.green('[SUCCESS]', destFilePath + " -> " + publicUrl)); resolve({originalUrl: destOriginalFilePath, publicUrl: publicUrl}); }); }); } function directoryExists(path) { try { stats = fs.statSync(path); if (stats.isDirectory()) { return true; } } catch (e) { return false; } } function fileExists(path) { try { stats = fs.statSync(path); if (stats.isFile()) { return true; } } catch (e) { return false; } } module.exports = gulpS3Replace;
JavaScript
0.000001
@@ -2277,24 +2277,82 @@ gth; i++) %7B%0A + if (!content.includes(urls%5Bi%5D.publicUrl)) %7B%0A @@ -2377,16 +2377,27 @@ replace( +new RegExp( urls%5Bi%5D. @@ -2408,16 +2408,22 @@ inalUrl, + 'g'), urls%5Bi%5D @@ -2435,16 +2435,30 @@ icUrl);%0A + %7D%0A
0a8fcb4c7cc0266b836c33af3f7db843b21cd6bd
Use log instead of error when fallback to default nightwatch config
index.js
index.js
#!/usr/bin/env node var selenium = require('selenium-standalone'); var cp = require('child_process'); var path = require('path'); var fs = require('fs'); var mkdirp = require('mkdirp'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var webpackConfig = require(process.env.WEBPACK_CONFIG ? path.resolve(process.env.WEBPACK_CONFIG) : path.resolve(process.cwd(), 'webpack.config.js')); var logDir = process.env.LOG_DIR ? path.resolve(process.env.LOG_DIR) : path.resolve(process.cwd(), 'reports'); var reportDir = process.env.REPORT_DIR ? path.resolve(process.env.REPORT_DIR) : path.resolve(process.cwd(), 'reports', 'test-e2e'); var nightwatchConfig = process.env.NIGHTWATCH_CONFIG ? path.resolve(process.env.NIGHTWATCH_CONFIG) : path.resolve(process.cwd(), 'nightwatch.json'); mkdirp.sync(reportDir); try { require(nightwatchConfig); } catch (err) { console.error(err); console.log(err.stack); console.log('Fallback to default nightwatch.json config'); nightwatchConfig = path.resolve(__dirname, 'nightwatch.json'); } var seleniumLog = fs.createWriteStream(path.resolve(logDir, 'selenium.log')); var which = require('npm-which')(__dirname); var nightwatchRunner = which.sync('nightwatch'); function startServer(cb) { var server = new WebpackDevServer(webpack(webpackConfig), {quiet: true}); server.listen(process.env.PORT || 8080, '0.0.0.0', cb); } function onServerStarted(seleniumChild) { return function (err) { if (err) { console.error(err); console.log(err.stack); throw err; } cp.fork(nightwatchRunner, [ '--config', nightwatchConfig, '--output', reportDir ]) .on('error', function (err2) { console.error(err2); console.log(err2.stack); throw err2; }) .on('close', function (code) { seleniumChild.kill('SIGINT'); process.exit(code); }); }; } function onSeleniumStarted(err, seleniumChild) { if (err) { console.error(err); console.log(err.stack); throw err; } seleniumChild.stdout.pipe(seleniumLog); seleniumChild.stderr.pipe(seleniumLog); process.on('uncaughtException', function (err2) { console.error(err2); console.log(err2.stack); seleniumChild.kill('SIGINT'); throw err2; }); startServer(onServerStarted(seleniumChild)); } function onSeleniumInstalled(err) { if (err) { console.error(err); console.log(err.stack); throw err; } selenium.start({seleniumArgs: ['-debug']}, onSeleniumStarted); } selenium.install({}, onSeleniumInstalled);
JavaScript
0
@@ -902,56 +902,8 @@ ) %7B%0A - console.error(err);%0A console.log(err.stack);%0A co