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 |
|---|---|---|---|---|---|---|---|
e0a8e5fa19620b40a454588e9b83019d37245c3f | Send a message when tests complete, see https://github.com/phetsims/aqua/issues/26 | js/qunit-connector.js | js/qunit-connector.js | // Copyright 2017, University of Colorado Boulder
/**
* When running unit tests in an iframe, connects to the parent frame to give results.
* @author Sam Reid (PhET Interactive Simulations)
*/
(function() {
'use strict';
QUnit.log( function( details ) {
window.parent && window.parent.postMessage( JSON.stringify( {
type: 'qunit-test',
main: 'scenery',
result: details.result,
module: details.module,
name: details.name,
message: details.message,
source: details.source // TODO: consider expected/actual, or don't worry because we'll run finer tests once it fails.
} ), '*' );
} );
// TODO: convert to use on('runEnd'), see https://github.com/phetsims/aqua/issues/25
QUnit.done( function( details ) {
window.parent && window.parent.postMessage( JSON.stringify( {
type: 'qunit-done',
failed: details.failed,
passed: details.passed,
total: details.total
} ), '*' );
} );
})(); | JavaScript | 0 | @@ -191,16 +191,17 @@
s)%0A */%0A(
+
function
@@ -222,16 +222,314 @@
rict';%0A%0A
+ // By default, QUnit runs tests when load event is triggered on the window. If you%E2%80%99re loading tests asynchronously,%0A // you can set this property to false, then call QUnit.start() once everything is loaded.%0A // See https://api.qunitjs.com/config/QUnit.config%0A QUnit.config.autostart = false;%0A%0A
QUnit.
@@ -942,43 +942,26 @@
%0A%0A
-// TODO: convert to use
+QUnit.
on(
+
'runEnd'
), s
@@ -960,71 +960,9 @@
End'
-)
,
- see https://github.com/phetsims/aqua/issues/25%0A QUnit.done(
fun
@@ -961,38 +961,35 @@
nd', function( d
-e
+a
ta
-ils
) %7B%0A window.
@@ -1084,21 +1084,29 @@
ailed: d
-etail
+ata.testCount
s.failed
@@ -1122,21 +1122,29 @@
assed: d
-etail
+ata.testCount
s.passed
@@ -1159,21 +1159,29 @@
total: d
-etail
+ata.testCount
s.total%0A
@@ -1204,12 +1204,13 @@
%7D );%0A%7D
+
)();
|
ff1e78dce280e86ec6fabb084cc0c0e7b3078c0c | Fix private tab settings | js/state/userPrefs.js | js/state/userPrefs.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
let registeredCallbacks = []
let registeredSessions = []
let registeredPrivateSessions = []
// TODO(bridiver) move this to electron so we can call a simpler api
const setUserPrefType = (ses, path, value) => {
switch (typeof value) {
case 'object':
ses.userPrefs.setDictionaryPref(path, value)
break
case 'string':
ses.userPrefs.setStringPref(path, value)
break
case 'array':
ses.userPrefs.setListPref(path, value)
break
case 'number':
if ((/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i).test(value.to_s())) {
ses.userPrefs.setDoublePref(path, value)
} else {
ses.userPrefs.setIntegerPref(path, value)
}
break
case 'boolean':
ses.userPrefs.setBooleanPref(path, value)
break
default:
console.warn(`Attempting to set an invalid preference value type for ${path}:`, value)
}
}
const runCallback = (cb, name, incognito) => {
let prefs = cb(incognito)
if (typeof prefs !== 'object') {
console.warn('userPrefs callback did not return an object:', prefs)
return
}
if (name) {
if (prefs[name]) {
module.exports.setUserPref(name, prefs[name], incognito)
return true
}
return false
}
for (name in prefs) {
module.exports.setUserPref(name, prefs[name], incognito)
}
return true
}
module.exports.setUserPref = (path, value, incognito = false) => {
value = value.toJS ? value.toJS() : value
let partitions = incognito ? Object.keys(registeredPrivateSessions) : Object.keys(registeredSessions)
partitions.forEach((partition) => {
setUserPrefType(registeredSessions[partition], path, value)
registeredSessions[partition].webRequest.handleBehaviorChanged()
})
}
module.exports.init = (ses, partition, isPrivate) => {
if (isPrivate) {
registeredPrivateSessions[partition] = ses
}
registeredSessions[partition] = ses
registeredCallbacks.forEach((fn) => fn(null, isPrivate))
}
module.exports.registerUserPrefs = (cb) => {
let fn = runCallback.bind(this, cb)
registeredCallbacks.push(fn)
return fn
}
| JavaScript | 0 | @@ -1115,14 +1115,8 @@
(cb,
- name,
inc
@@ -1286,159 +1286,17 @@
%0A%0A
-if (name) %7B%0A if (prefs%5Bname%5D) %7B%0A module.exports.setUserPref(name, prefs%5Bname%5D, incognito)%0A return true%0A %7D%0A return false%0A %7D%0A%0A
for (
+let
name
@@ -1369,24 +1369,25 @@
ognito)%0A %7D%0A
+%0A
return tru
@@ -1994,14 +1994,8 @@
fn(
-null,
isPr
|
1138c13885f7d72326dfd844b512709c653a6ab2 | fix console page render error | app/routes/index.js | app/routes/index.js |
/*
* GET home page.
*/
var contactCollection;
var home = require('../config/home');
var partner = require('../config/partner');
function extend(dst, src) {
for (var key in src) {
if (src.hasOwnProperty(key)) {
dst[key] = src[key];
}
}
}
exports.setDb = function(db) {
contactCollection = db.collection('contact');;
};
exports.index = function(req, res) {
var model = {};
// set cookies
if (req.cookies.views) {
model.displayCookie = true;
} else {
// set cookie
model.displayCookie = false;
// IE8 doesn't support max-age, so have to fallback to expires,
// though a bit older
if (req.secure) {
res.cookie('views', '1', { expires: new Date(2030, 1, 1), secure: true});
} else {
res.cookie('views', '1', { expires: new Date(2030, 1, 1)});
}
}
if (req.path == "/") {
extend(model, home);
res.render('index', model);
} else if (req.path == "/partner") {
extend(model, partner);
res.render('index', model);
} else {
res.status(404);
res.render('404', {pageTitle: 'Page Not Found'});
}
};
exports.contact = function(req, res){
var data = req.body;
data.date = (new Date()).toDateString();
contactCollection.insert(data, function(error, docs) {
res.json({error: !!error});
});
};
exports.console = function (req, res) {
var model = {
head: {
title: "console | ten20live"
}
};
res.render('console', model);
};
| JavaScript | 0 | @@ -1338,17 +1338,16 @@
res) %7B%0A
-%0A
var mo
|
799f1c0f0f1bc64d68e41bbe9b59559742d46cc2 | change loading message | app/routes/login.js | app/routes/login.js | import Ember from 'ember';
export default Ember.Route.extend({
beforeModel: function(/*transition*/) {
if (this.session.isNotExpired()) {
this.transitionTo('index');
}
},
model: function() {
if (this.get('provider')) {
var session = this.get('session');
return session.authorize().then(function(response) {
session.get('auth').trigger('redirect', response);
}, function(error) {
session.get('auth').trigger('error', error);
});
}
},
setupController: function(controller/*, model*/) {
if (this.session.isExpired()) {
controller.set('currentUser', null);
}
},
actions: {
authenticate: function(provider) {
var router = this;
var session = this.get('session');
// set the provider
router.set('provider', provider);
session.provider(provider);
session.get('auth').on('success', function() {
router.controllerFor('session').loadUser();
});
session.get('auth').on('error', function(error) {
Ember.Logger.error('Error: ' + error);
});
// refresh route
router.refresh();
},
loading: function(transition, originRoute) {
alert('loading');
}
}
});
| JavaScript | 0 | @@ -1169,16 +1169,18 @@
unction(
+/*
transiti
@@ -1194,16 +1194,18 @@
ginRoute
+*/
) %7B%0A
@@ -1210,19 +1210,39 @@
-alert('load
+Ember.Logger.debug('authenticat
ing'
|
af62a41aa6f248014b1a4be87c4479952763fe27 | Fix for sourcemaps 404's | app/routesStatic.js | app/routesStatic.js | 'use strict';
var express = require('express'),
less = require('less-middleware'),
uglify = require("uglifyjs-middleware"),
favicon = require('serve-favicon');
var path = require('path');
module.exports = function routesStatic(app) {
var staticOptions = { maxAge: app.get('env') === 'development' ? 0 : '30d' };
app.use(favicon(path.join('.', 'public', 'favicon.ico'), staticOptions));
// Needs to be before Express static on public folder.
app.use(less(path.join('.', 'public')));
app.use('/js', uglify(path.join('.', 'public', 'js'), {
generateSourceMap: app.get('env') === 'development'
}));
app.use(express.static(path.join('.', 'public'), staticOptions));
app.use(express.static(path.join('.', 'locales'), staticOptions));
app.use('/vendor/:vendor/:file', function (req, res, next) {
var dir;
switch (req.params.vendor) {
case 'bootstrap': {
dir = path.join('.', 'bower_components', 'bootstrap', 'dist', req.params.file);
break;
}
case 'jquery': {
dir = path.join('.', 'bower_components', 'jquery', 'dist', req.params.file);
break;
}
case 'jquery.floatThead': {
dir = path.join('.', 'bower_components', 'jquery.floatThead', 'dist', req.params.file);
break;
}
case 'moment': {
dir = path.join('.', 'node_modules', 'moment', 'min', req.params.file);
break;
}
default: return next();
}
return express.static(dir, staticOptions).apply(this, arguments);
});
};
| JavaScript | 0 | @@ -400,370 +400,8 @@
);%0A%0A
- // Needs to be before Express static on public folder.%0A app.use(less(path.join('.', 'public')));%0A%0A app.use('/js', uglify(path.join('.', 'public', 'js'), %7B%0A generateSourceMap: app.get('env') === 'development'%0A %7D));%0A%0A app.use(express.static(path.join('.', 'public'), staticOptions));%0A%0A app.use(express.static(path.join('.', 'locales'), staticOptions));%0A%0A
ap
@@ -1165,11 +1165,360 @@
%0A %7D);%0A%0A
+ // Needs to be before Express static on public folder.%0A app.use(less(path.join('.', 'public')));%0A%0A app.use(uglify(path.join('.', 'public'), %7B%0A generateSourceMap: app.get('env') === 'development'%0A %7D));%0A%0A app.use(express.static(path.join('.', 'public'), staticOptions));%0A%0A app.use(express.static(path.join('.', 'locales'), staticOptions));%0A%0A
%7D;%0A
|
36a69f7b8350b3fef96f24765eecaa3f8d53eaaf | Tackle Chrome buffering bug on refresh | app/scripts/main.js | app/scripts/main.js | $(document).ready(function() {
var animateText = function(
nameDuration, baseListDelay, contactDuration, contactLabelDelay, animationTimeout
) {
$('.name').fadeIn(nameDuration);
$('li').each(function(index) {
var delay = baseListDelay;
if (index === 1) {
delay = baseListDelay + 200;
} else if (index === 2) {
delay = baseListDelay + 300;
}
$(this).textillate({ in: { effect: 'fadeInLeft' }, initialDelay: delay });
});
setTimeout(function() {
$('.contact').fadeIn(contactDuration, function() {
var bottomClass = '.bottom';
var topClass = '.top';
var opacity = 'opacity';
$(this)
.mouseover(function() {
$(bottomClass).css(opacity, 1);
$(topClass).css(opacity, 0);
})
.mouseout(function() {
$(bottomClass).css(opacity, 0);
$(topClass).css(opacity, 1);
})
.click(function(){
window.location = 'mailto:caripearl10@gmail.com';
});
});
$('.contact-label').textillate({
in: { effect: 'fadeInUp' },
initialDelay: contactLabelDelay
});
}, animationTimeout);
};
if (window.orientation === undefined) { // use video on desktop
$('.image-wrapper').remove();
var $player = $('#player');
var player = $player.get(0);
var $parent = $player.parent();
var $win = $(window);
var resizeTimeout = null;
var shouldResize = false;
var shouldPosition = false;
var videoRatio = 854 / 460;
player.volume = 0.5; // half of system volume
player.load(); // explicitly load to always trigger metadata listener
var resize = function() {
if (!shouldResize) { return; }
var height = $parent.height();
var width = $parent.width();
var viewportRatio = width / height;
var scale = 1;
if (videoRatio < viewportRatio) {
// viewport more widescreen than video aspect ratio
scale = viewportRatio / videoRatio;
} else if (viewportRatio < videoRatio) {
// viewport more square than video aspect ratio
scale = videoRatio / viewportRatio;
}
var offset = positionVideo(scale, width, height);
setVideoTransform(scale, offset);
};
var setVideoTransform = function(scale, offset) {
offset = $.extend({ x: 0, y: 0 }, offset);
var transform = 'translate(' + Math.round(offset.x) + 'px,' + Math.round(offset.y) +
'px) scale(' + scale + ')';
$player.css({
'-webkit-transform': transform,
'transform': transform
});
};
// accounts for transform origins on scaled video
var positionVideo = function(scale, width, height) {
if (!shouldPosition) { return false; }
var x = parseInt($player.data('origin-x'), 10);
var y = parseInt($player.data('origin-y'), 10);
setVideoOrigin(x, y);
var viewportRatio = width / height;
var scaledHeight = scale * height;
var scaledWidth = scale * width;
var percentFromX = (x - 50) / 100;
var percentFromY = (y - 50) / 100;
var offset = {};
if (videoRatio < viewportRatio) {
offset.x = (scaledWidth - width) * percentFromX;
} else if (viewportRatio < videoRatio) {
offset.y = (scaledHeight - height) * percentFromY;
}
return offset;
};
var setVideoOrigin = function(x, y) {
var origin = x + '% ' + y + '%';
$player.css({
'-webkit-transform-origin': origin,
'transform-origin': origin
});
};
$win.on('resize', function() {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resize, 100);
});
shouldResize = true;
shouldPosition = true;
resize();
var playVideoAndAnimateText = function() {
$('#spinner').remove();
$player.css('visibility', 'visible');
player.play();
setTimeout(function() {
animateText(2300, 200, 1400, 200, 3100);
}, 4700);
};
var checkIfLoaded = function() {
if (
player.buffered.length &&
player.duration - player.buffered.end(0) < 1 // Firefox never completely fills buffer!
) {
clearInterval(loadingInterval);
playVideoAndAnimateText();
}
};
var loadingInterval;
player.addEventListener('loadedmetadata', function() {
loadingInterval = setInterval(checkIfLoaded, 30);
});
} else { // revert to animated images on mobile
$('#spinner').remove();
$('#player').remove();
$('body').addClass('mobile');
var baseFade = 2500;
$('.image-wrapper').children().each(function(index) {
$(this).delay(1000 * index).fadeTo(baseFade, 1, function() {
$(this).fadeTo(baseFade - 600, 0);
if ($(this).is(':last-child')) {
// would prefer to use a callback (here and elsewhere), but the animations feel more
// cohesive and fluid with some overlap
setTimeout(function() {
animateText(3000, 700, 2000, 400, 3900);
}, baseFade - 1300);
}
});
});
}
});
| JavaScript | 0 | @@ -1021,18 +1021,16 @@
to:c
-ari
pearl
-10
+613
@gma
@@ -4058,42 +4058,515 @@
var
-checkIfLoaded = function() %7B%0A
+isLocalStorageSupported = function() %7B // Safari incognito mode support%0A var testKey = 'test';%0A%0A try %7B%0A window.localStorage.setItem(testKey, '1');%0A window.localStorage.removeItem(testKey);%0A return true;%0A %7D catch (error) %7B%0A return false;%0A %7D%0A %7D;%0A%0A var checkIfLoaded = function() %7B%0A if (isLocalStorageSupported() && window.localStorage.getItem('isVideoCached')) %7B%0A clearInterval(loadingInterval);%0A playVideoAndAnimateText();%0A %7D else
if
@@ -4738,32 +4738,145 @@
adingInterval);%0A
+ if (isLocalStorageSupported()) %7B%0A window.localStorage.setItem('isVideoCached', true);%0A %7D%0A
playVide
|
5d7bcc75bebf9ab7bd331e5beff15edad6f3850d | add escape key binding | app/scripts/main.js | app/scripts/main.js | /* jshint devel:true */
(function( $ ){
'use strict';
$( document ).foundation();
$( '.play-button' ).click( function ( e ) {
e.preventDefault();
$( '#video-modal' ).foundation( 'reveal', 'open' );
$( 'iframe' ).attr( 'src', '//player.vimeo.com/video/121852108?autoplay=1&color=7e8b9e&title=0&byline=0&portrait=0' );
});
$( '.close-reveal-modal ').click( function ( e ) {
e.preventDefault();
$( '#video-modal' ).foundation( 'reveal', 'close' );
$( 'iframe').attr('src', '//player.vimeo.com/video/121852108?autoplay=0&color=7e8b9e&title=0&byline=0&portrait=0');
});
})( jQuery );
| JavaScript | 0 | @@ -603,16 +603,220 @@
%0A %7D);%0A%0A
+ $( document ).keyup( function ( e ) %7B%0A if ( e.keyCode == 27 ) %7B%0A $( 'iframe').attr('src', '//player.vimeo.com/video/121852108?autoplay=0&color=7e8b9e&title=0&byline=0&portrait=0');%0A %7D%0A %7D);%0A%0A
%7D)( jQue
|
78cde60355ef9ca07684093c7064cffebc978d3d | implement tick event | TimeCounter.js | TimeCounter.js | /**
* This is a simple time counter.
* It counts only how long it runs in following format:
* <b>hh:mm:ss</b>
*
* @param autostart boolean
*/
function TimeCounter(autostart) {
var autostart = autostart || false;
/**
* Private members
*/
var count = 0;
var hours = 0;
var minutes = 0;
var secs = 0;
var _intervalTimer;
/**
* Define getters and setters
*/
Object.defineProperty(this, 'count', {
get: function () {
return count;
},
set: function (value) {
count = value;
}
});
Object.defineProperty(this, 'hours', {
get: function () {
return this.formatNumber(hours);
},
set: function (value) {
hours = value;
}
});
Object.defineProperty(this, 'minutes', {
get: function () {
return this.formatNumber(minutes);
},
set: function (value) {
minutes = value;
}
});
Object.defineProperty(this, 'secs', {
get: function () {
return this.formatNumber(secs);
},
set: function (value) {
secs = value;
}
});
if (autostart) {
this.start();
}
}
/**
* Define class methods.
*/
TimeCounter.prototype = {
/**
* Starts the counter
*/
start: function () {
this._intervalTimer = window.setInterval(this.tick, 1000, this);
},
/**
* Stops counter and reset props
*/
stop: function () {},
/**
* Resets the counter props
*/
reset: function () {},
/**
* Returns the whole time string.
*/
getTime: function () {
return [this.hours, this.minutes, this.secs].join(':');
},
/**
* Handler called on each tick of the timer.
*
* @param timeCounter TimeCounter
*/
tick: function (timeCounter) {
timeCounter.count++;
timeCounter.secs++;
if(timeCounter.secs % 60 === 0) {
// have one minute completed
timeCounter.secs = 0;
timeCounter.minutes++;
if(timeCounter.minutes % 60 === 0) {
// have an hour completed
timeCounter.minutes = 0;
timeCounter.hours++;
}
}
console.debug(timeCounter.getTime());
},
/**
* Triggers the tick event.
* Includes the current time of the tick.
*/
triggerTickEvent: function () {},
/**
* 'Formats' the given number
*
* @param number int
*/
formatNumber: function (number) {
return (number < 10) ? '0' + number : number;
}
}; | JavaScript | 0.000017 | @@ -2345,22 +2345,8 @@
-console.debug(
time
@@ -2357,17 +2357,25 @@
ter.
+trig
ge
-tTime()
+rTickEvent(
);%0A
@@ -2471,24 +2471,24 @@
ck.%0A */%0A
-
triggerT
@@ -2502,32 +2502,166 @@
t: function () %7B
+%0A var ev = new CustomEvent('TimeCounter:tick', %7B'detail': %7B'time': this.getTime()%7D %7D);%0A document.dispatchEvent(ev);%0A
%7D,%0A%0A /**%0A
|
822789e92b8022634d82ba1e7e3b69b982b6d682 | Update formatting of fake summary and added TODO | fake/fake-request-summary.js | fake/fake-request-summary.js | 'use strict';
var chance = require('./fake-extension');
var fakeSession = require('./fake-request-user');
var moment = require('moment');
function generate(dateTime) {
var mvcAction = chance.mvcAction();
var httpStatus = chance.httpStatus();
var networkTime = chance.integerRange(0, 15);
var serverLowerTime = chance.integerRange(5, 10);
var serverUpperTime = chance.integerRange(60, 100);
var serverTime = chance.integerRange(serverLowerTime, serverUpperTime); // TODO: Bug with these two lines
var actionTime = chance.integerRange(serverLowerTime - 1, serverTime); // TODO: Need to verify that this works
var viewTime = serverTime - actionTime;
var clientTime = chance.integerRange(20, 120);
var queryTime = chance.integerRange(2, Math.max(actionTime / 3, 3));
var pick = {
user: function () {
return fakeSession.pickUser();
},
abstract: function () {
return {
networkTime: networkTime,
serverTime: serverTime,
clientTime: clientTime,
controller: mvcAction.controller,
action: mvcAction.action,
actionTime: actionTime,
viewTime: viewTime,
queryTime: queryTime,
queryCount: chance.integerRange(1, 4)
};
},
index: function () {
return {
uri: mvcAction.url,
dateTime: dateTime || moment().toISOString(),
method: chance.httpMethod(),
contentType: chance.httpContentType(),
user: pick.user(),
duration: clientTime + serverTime + networkTime,
statusCode: httpStatus.code,
statusText: httpStatus.text,
};
},
context: function () {
return { type: 'request', id: chance.guid() };
}
};
var generate = {
messages: function() {
var context = pick.context();
var index = pick.index();
var abstract = pick.abstract();
var messages = [
{
type: 'request-start',
context: context,
index: {
uri: index.url,
dateTime: index.dateTime,
method: index.method,
contentType: index.contentType,
user: index.user
}
},
{
type: 'request-framework',
context: context,
abstract: abstract
},
{
type: 'request-end',
context: context,
index: {
duration: index.duration,
statusCode: index.statusCode,
statusText: index.statusText,
}
}
];
var request = index;
request.abstract = abstract;
return {
data: mvcAction,
context: context,
messages: messages,
request: request
};
}
};
return generate.messages();
}
// TODO: Need to genrate message bases responses as well as request based
// responses.
module.exports = {
generate: generate
};
| JavaScript | 0 | @@ -133,16 +133,84 @@
ent');%0A%0A
+// TODO: Even though this works, structure of this is kinda crummy%0A%0A
function
@@ -2097,28 +2097,8 @@
te =
- %7B%0A messages:
fun
@@ -2103,28 +2103,24 @@
unction() %7B%0A
-
var
@@ -2149,28 +2149,24 @@
();%0A
-
var index =
@@ -2175,28 +2175,24 @@
ck.index();%0A
-
var
@@ -2220,20 +2220,16 @@
act();%0A%0A
-
@@ -2253,34 +2253,26 @@
- %7B%0A
+%7B%0A
@@ -2298,20 +2298,16 @@
start',%0A
-
@@ -2340,36 +2340,32 @@
-
index: %7B%0A
@@ -2349,36 +2349,32 @@
index: %7B%0A
-
@@ -2389,28 +2389,24 @@
index.url,%0A
-
@@ -2451,36 +2451,32 @@
-
method: index.me
@@ -2481,20 +2481,16 @@
method,%0A
-
@@ -2533,20 +2533,16 @@
ntType,%0A
-
@@ -2582,34 +2582,26 @@
- %7D%0A
+%7D%0A
@@ -2595,36 +2595,32 @@
%0A %7D,%0A
-
%7B%0A
@@ -2625,36 +2625,32 @@
-
type: 'request-f
@@ -2668,36 +2668,32 @@
-
context: context
@@ -2686,36 +2686,32 @@
ntext: context,%0A
-
@@ -2733,36 +2733,32 @@
act%0A
-
%7D,%0A
@@ -2752,34 +2752,26 @@
- %7B%0A
+%7B%0A
@@ -2803,36 +2803,32 @@
-
context: context
@@ -2837,36 +2837,32 @@
-
index: %7B%0A
@@ -2846,36 +2846,32 @@
index: %7B%0A
-
@@ -2912,36 +2912,32 @@
-
statusCode: inde
@@ -2946,28 +2946,24 @@
statusCode,%0A
-
@@ -2996,28 +2996,24 @@
statusText,%0A
-
@@ -3030,32 +3030,26 @@
- %7D%0A
+%7D%0A
%5D;%0A
@@ -3044,17 +3044,11 @@
-
%5D;%0A
-
@@ -3076,28 +3076,24 @@
ex;%0A
-
request.abst
@@ -3110,36 +3110,32 @@
tract;%0A%0A
-
return %7B%0A
@@ -3119,36 +3119,32 @@
return %7B%0A
-
@@ -3168,36 +3168,32 @@
-
context: context
@@ -3186,36 +3186,32 @@
ntext: context,%0A
-
@@ -3230,20 +3230,16 @@
ssages,%0A
-
@@ -3275,32 +3275,18 @@
- %7D;%0A
%7D
+;
%0A %7D;%0A
@@ -3309,17 +3309,8 @@
rate
-.messages
();%0A
|
7862c5311ffef815b4507ff3691a01e61f723f64 | send rpc contract call | src/store/contractActions.js | src/store/contractActions.js | import { rpc } from '../lib/rpc';
import log from 'loglevel';
export function loadContractList() {
return (dispatch) => {
dispatch({
type: 'CONTRACT/LOADING',
});
rpc.call('emerald_contracts', []).then((result) => {
dispatch({
type: 'CONTRACT/SET_LIST',
contracts: result,
});
// load Contract details?
}).catch(error => {
log.error(`emerald_contracts rpc call: ${JSON.stringify(error)}`);
});
};
}
export function addContract(address, name, abi, version, options, txhash) {
return (dispatch) =>
rpc.call('emerald_addContract', [{
address,
name,
abi,
version,
options,
txhash,
}]).then((result) => {
dispatch({
type: 'CONTRACT/ADD_CONTRACT',
address,
name,
abi,
version,
options,
txhash,
});
});
}
export function estimateGas(data) {
return (dispatch) =>
rpc.call('eth_estimateGas', [{ data }]).then((result) => {
return isNaN(parseInt(result)) ? 0 : parseInt(result);
});
}
| JavaScript | 0 | @@ -54,16 +54,65 @@
glevel';
+%0Aimport %7B functionToData %7D from '../lib/convert';
%0A%0Aexport
@@ -1113,24 +1113,744 @@
%7D);%0A%7D%0A%0A
+export function callContract(accountId, password, to, gas, value, func, inputs) %7B%0A console.log(func)%0A return (dispatch) =%3E %7B%0A let pwHeader = null;%0A if (password)%0A pwHeader = new Buffer(password).toString('base64');%0A const data = functionToData(func, inputs);%0A return rpc.call('eth_call', %5B%7B%0A to,%0A from: accountId,%0A gas,%0A value,%0A data,%0A %7D, 'latest'%5D, %7B%0A Authorization: pwHeader,%0A %7D).then((result) =%3E %7B%0A dispatch(%7B%0A type: 'ACCOUNT/CALL_CONTRACT',%0A accountId,%0A txHash: result,%0A %7D);%0A return result;%0A %7D);%0A %7D;%0A%7D%0A%0A
export funct
|
be02920a1880c7672e0705f19a26eb7703216d9d | Remove unneeded statement | src/storyline_test_runner.js | src/storyline_test_runner.js | import deepEqual from 'deep-equal';
import {
combineReducers as reduxCombineReducers,
createStore,
applyMiddleware
} from 'redux';
import StorylineTestAPI from './storyline_test_api';
export const IO = (fn, context, ...args) => ({ fn, context, args });
const _start = Symbol("start");
const _storyline = Symbol("storyline");
export default class StorylineRunner {
constructor(storyline, {
initialState = {},
reducers,
middlewares = [],
combineReducers = reduxCombineReducers
}) {
this._pendingIO = [];
this._pendingIOPromises = [];
this._waitingFor = null;
this._notifyIsBlocked = null;
this.done = false;
const makeReducer = () => {
if (reducers) {
return reduxCombineReducers(Object.keys(reducers).reduce(
(rc, reducerName) => ({
[reducerName]: reducers[reducerName], ...rc })
, {})
);
} else {
return state => state;
}
};
const finalReducer = makeReducer();
const storylineMiddleware = store => next => action => {
const result = next(action);
if (this._waitingFor) {
const { predicateFn, resolve } = this._waitingFor;
if (predicateFn(action)) {
resolve();
this._waitingFor = null;
}
}
return result;
};
const allMiddleware = [...middlewares, storylineMiddleware];
this.store = createStore(
finalReducer,
initialState,
applyMiddleware(...allMiddleware)
);
this[_start](storyline);
}
getState() {
return this.store.getState();
}
async dispatch(action) {
await this.store.dispatch(action);
await this._untilDoneOrBlocked();
}
async _untilDoneOrBlocked() {
if (this._pendingIO.length > 0) {
await new Promise((resolve) => {
this._notifyIsBlocked = () => {
this._notifyIsBlocked = null;
resolve();
};
});
}
}
async [_start](storyline) {
await storyline(new StorylineTestAPI(this));
this._done = true;
this._blocked();
}
async _waitFor(predicateOrActionType) {
const predicateFn = typeof predicateOrActionType === 'string' ?
(action) => action.type === predicateOrActionType
: (action) => predicateOrActionType(action);
return await new Promise((resolve, reject) => {
this._waitingFor = {predicateFn, resolve};
});
}
pendingIO() {
return this._pendingIO.map(({io}) => io);
}
async resolveIO(io, value) {
const found = this._pendingIO.find((candidate) => {
return deepEqual(candidate.io, io, {strict: true});
});
if (found) {
found.resolve(value);
const index =this._pendingIO.indexOf(found);
this._pendingIO.splice(index, 1);
const doneIO = this._pendingIOPromises.splice(index, 1);
await doneIO;
await this._untilDoneOrBlocked();
} else {
return Promise.reject("could not find IO to resolve");
}
}
isDone() {
return this._done;
}
_blocked() {
if (this._notifyIsBlocked) {
this._notifyIsBlocked();
}
}
};
| JavaScript | 0.999259 | @@ -2053,29 +2053,8 @@
ue;%0A
- this._blocked();%0A
%7D%0A
|
35b82fe166eb4d9e48b5c151ad8c0da88f0795f0 | fix bibparsing | bibliography/static/js/workers/importer/biblatex.js | bibliography/static/js/workers/importer/biblatex.js | import {BibLatexParser} from "biblatex-csl-converter"
export class BibLatexImportWorker {
constructor(fileContents, sendMessage) {
this.fileContents = fileContents
this.sendMessage = sendMessage
}
/** Second step of the BibTeX file import. Takes a BibTeX file object,
* processes client side and cuts into chunks to be uploaded to the server.
*/
init() {
let bibData = new BibLatexParser(this.fileContents)
this.tmpDB = bibData.parse()
this.bibKeys = Object.keys(this.tmpDB)
if (!this.bibKeys.length) {
this.sendMessage({type: 'error', errorCode: 'no_Entries', done: true})
return
} else {
this.bibKeys.forEach((bibKey) => {
let bibEntry = this.tmpDB[bibKey]
// We add an empty category list for all newly imported bib entries.
bibEntry.entry_cat = []
// If the entry has no title, add an empty title
if (!bibEntry.fields.title) {
bibEntry.fields.title = []
}
// If the entry has no date, add an uncertain date
if (!bibEntry.fields.date) {
bibEntry.fields.date = 'uuuu'
}
// If the entry has no editor or author, add empty author
if (!bibEntry.fields.author && !bibEntry.fields.editor) {
bibEntry.fields.author = [{'literal': []}]
}
})
bibData.errors.forEach(error => {
error.errorType = error.type
error.errorCode = 'entry_error'
error.type = 'error'
this.sendMessage(error)
})
bibData.warnings.forEach(warning => {
warning.errorCode = warning.type
warning.type = 'warning'
this.sendMessage(warning)
})
this.totalChunks = Math.ceil(this.bibKeys.length / 50)
this.currentChunkNumber = 0
this.processChunk()
}
}
processChunk() {
if (this.currentChunkNumber < this.totalChunks) {
let fromNumber = this.currentChunkNumber * 50
let toNumber = fromNumber + 50
let currentChunk = {}
this.bibKeys.slice(fromNumber, toNumber).forEach((bibKey)=>{
currentChunk[bibKey] = this.tmpDB[bibKey]
})
this.sendMessage({type: 'data', data: currentChunk})
this.currentChunkNumber++
this.processChunk()
} else {
this.sendMessage({type: 'ok', done: true})
}
}
}
| JavaScript | 0.000021 | @@ -396,26 +396,28 @@
) %7B%0A
-le
+cons
t bibData =
@@ -454,16 +454,62 @@
ntents)%0A
+ const bibDataOutput = bibData.parse()%0A
@@ -520,24 +520,25 @@
.tmpDB =
+
bibData
.parse()
@@ -525,32 +525,38 @@
B = bibData
-.parse()
+Output.entries
%0A thi
|
f92b6d8b4b4c75c09d115b9975426ccb244fe439 | FIx typo | fileupload/static/js/main.js | fileupload/static/js/main.js | /*
* jQuery File Upload Plugin JS Example 8.8.2
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, regexp: true */
/*global $, window, blueimp */
'use strict';
let dominator = {
init: function(DOMelement) {
this.el = DOMelement;
this.files = new Map(); // Metadata related to uploaded files
this.queueFiles = 0; // Files in the process queue
this.queueReady = false;
this.processedFiles = 0; // Number of succesfully processed files
},
/**
* Callback function triggered when files have been added to upload queue
*/
add: (e, data) => {
dominator.queueFiles++
let element = $('select#' + data.files[0].name.split('.')[0]);
if(dominator.queueFiles <= 2) {
dominator.files.set(element[0].id,
{
type: ''
}
);
element.on('change', (e) => {
dominator.setType(element[0].id, e.currentTarget.value);
});
} else {
console.log('aborta mision');
data.abort(); // TODO make it abort add
}
},
/**
* Callback that fires after uploads are done, upload status does not matter
*/
afterUpload: () => {
$('button.start').attr('disabled', 'disabled');
},
/**
* Callback triggered when Process button is clicked and sets some additional
* data to be sent in the request
*/
beforeUpload: data => {
if(dominator.queueFiles == 2) {
let name = data.get('file').name.split('.')[0];
let file_type = dominator.files.get(name).type;
data.set('file_type', file_type);
$('button.process').removeAttr('disabled');
} else {
alert('There must be at least 2 files to upload!');
}
return data;
},
/**
* Callback function to send uploaded files to processing in sqlizer
*/
processFiles: data => {
let key = undefined;
let file = data.result.files[0];
$.get('/process/' + file.resource_id,
{},
function(response) {
// TODO Weird, if I disable the process button outside the $.get request,
// it is triggered automatically on diabling the button programatically
$('button.process').attr('disabled', 'disabled');
if(response.Status === 'Complete') {
if(dominator.processedFiles < 2) {
dominator.files.get(response.FileName.split('.')[0]).data = response
dominator.processedFiles++;
}
if(dominator.processedFiles == 2) {
//Send only file type and name of the table created.
let data = {};
dominator.files.forEach((k, v) => {
data[k.type] = k.data.TableName;
});
dominator.processed(data);
}
}
});
},
/**
* Callback funtion that triggers when each file returns a succesful state
* from sqlizer
*/
processed: data => {
console.log('FALTA BLOQUEAR PANTALLA');
$('button.delete').hide();
$('input.toggle').hide();
$.get('/postproc/',
data,
function(response) {
console.log(response);
});
console.log('LIBERAR PANTALLA');
},
/**
* Mutex function for file types
*/
setType: (file_id, file_type) => {
// TODO still does not work, various use cases fail
// FIX IT ASAP!
let count = 0;
let sel = $('select#' + file_id);
dominator.files.forEach((v, k) => {
if(sel.val() != undefined || sel.val().length > 0) {
// Check values in select to be different
if(file_id !== k) {
if(dominator.files.get(k).type === sel.val()) {
$('button.start').attr('disabled', 'disabled');
sel.val("");
dominator.files.get(k).type = "";
alert("Files can't be of the same type");
return;
}
}
dominator.files.get(file_id).type = file_type;
if(v.type != undefined && v.type.length != 0
&& dominator.queueFiles == 2) {
count++;
if(count == 2) {
// Enable start upoad button only when files have file type
dominator.queueReady = true;
$('button.start').removeAttr('disabled');
}
}
}
});
},
}
// App starts here!
$(function () {
'use strict';
dominator.init($('#fileupload')); // Initialize the dominator
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
uploadTemplate: dominator.uploadTemplate
})
.on('fileuploadadded', dominator.add)
.on('fileuploadalways', dominator.afterUpload)
.on('fileuploadcompleted', function(e, data) {
$('#fileupload_control .process').on('click',
dominator.processFiles(data));
})
.on('fileuploadsend', function(e, data) {
data.data = dominator.beforeUpload(data.data);
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
});
| JavaScript | 0.00002 | @@ -769,16 +769,17 @@
eFiles++
+;
%0A let
|
5a6e2d763ccf2533d2992452f4814b8112cdb45d | Add local storage for movie data | src/Components/App/App.js | src/Components/App/App.js | import React, { Component } from 'react';
import CardContainer from '../CardContainer/CardContainer';
import Aside from '../Aside/Aside';
import Header from '../Header/Header';
import Nav from '../Nav/Nav';
import { getVehicleData, getPersonData, getPlanetData } from '../../apiHelpers';
import Button from '../Button/Button';
class App extends Component {
constructor () {
super();
this.state = {
movieArray: [],
displayArray: [],
favoritesArray: [],
displayArrayType: '',
}
this.cardClicked = this.cardClicked.bind(this);
this.displayFavorites = this.displayFavorites.bind(this);
this.handleSectionClick = this.handleSectionClick.bind(this);
}
cardClicked(url) {
let tempFavoritesArray = this.state.favoritesArray.filter( favorite => favorite !== url)
if (tempFavoritesArray.length === this.state.favoritesArray.length) {
tempFavoritesArray.push(url);
}
this.setState({
favoritesArray: tempFavoritesArray
})
}
displayFavorites() {
const favoritesUnresolvedPromises = this.state.favoritesArray.map(
(favorite) => {
if (Object.keys(localStorage).find( (key) => key===favorite ) ) {
return JSON.parse(localStorage[favorite])
} else {
return fetch(favorite)
.then( rawData => rawData.json())
.then(favoriteObject => {
if ( /^https:\/\/swapi.co\/api\/vehicle/.test(favorite) ) {
return getVehicleData(favoriteObject)
}
if ( /^https:\/\/swapi.co\/api\/people/.test(favorite) ) {
return getPersonData(favoriteObject);
}
if ( /^https:\/\/swapi.co\/api\/planet/.test(favorite) ) {
return getPlanetData(favoriteObject);
}
})
}
}
)
Promise.all(favoritesUnresolvedPromises)
.then(resolvedPromiseArray => {
resolvedPromiseArray.forEach( (favoriteObject) => {
if (!localStorage[favoriteObject.url]) {
localStorage.setItem(favoriteObject.url, JSON.stringify(favoriteObject))
}
});
this.setState({
displayArray: resolvedPromiseArray,
displayArrayType: 'Favorites'
})
})
}
handleSectionClick(section) {
if ( section === "people" ) {
this.getPeopleData('https://swapi.co/api/people/')
}
if ( section === "planets" ) {
this.getPlanetsData('https://swapi.co/api/planets/')
}
if ( section === "vehicles" ) {
this.getVehiclesData('https://swapi.co/api/vehicles/')
}
}
getMovieData(url){
fetch(url)
.then( rawData => rawData.json() )
.then( data => data.results.map( movie => {
return {
title: movie.title,
date: movie.created.slice(0, 10),
text: movie.opening_crawl
}
} ) ).then( response => this.setState({movieArray: response}) )
}
getPeopleData(url){
if (Object.keys(localStorage).find( (key) => key===url ) ) {
this.setState({
displayArray: JSON.parse(localStorage[url]),
displayArrayType: 'People'
})
} else {
fetch(url)
.then(raw => raw.json())
.then(parsedData => {
const unresolvedPromises = parsedData.results.map( (person) => {
return getPersonData(person)
})
Promise.all(unresolvedPromises)
.then(promiseAllResults => {
localStorage.setItem(url, JSON.stringify(promiseAllResults))
this.setState({
displayArray: promiseAllResults,
displayArrayType: 'People'
})
})
})
}
}
getPlanetsData(url){
if (Object.keys(localStorage).find( (key) => key===url ) ) {
this.setState({
displayArray: JSON.parse(localStorage[url]),
displayArrayType: 'Planets'
})
} else {
fetch(url)
.then(raw => raw.json())
.catch(err => { console.log(`danger will robinson: ${err}`);})
.then(parsedData => {
const unresolvedPromises = parsedData.results.map( (planet) => {
return getPlanetData(planet);
})
Promise.all(unresolvedPromises)
.then(promiseAllResults => {
localStorage.setItem(url, JSON.stringify(promiseAllResults))
this.setState({
displayArray: promiseAllResults,
displayArrayType: 'Planets'
})
})
})
}
}
getVehiclesData(url) {
if (Object.keys(localStorage).find( (key) => key===url ) ) {
this.setState({
displayArray: JSON.parse(localStorage[url]),
displayArrayType: 'Vehicles'
})
} else {
fetch(url)
.then(rawVehiclesData => rawVehiclesData.json())
.then(vehiclesData => {
return vehiclesData.results.map( (vehicle) => {
return getVehicleData(vehicle);
})
})
.then(vehiclesResolvedPromises => {
localStorage.setItem(url, JSON.stringify(vehiclesResolvedPromises))
this.setState({
displayArray: vehiclesResolvedPromises,
displayArrayType: 'Vehicles'
})
});
}
}
componentDidMount() {
this.getMovieData('https://swapi.co/api/films');
this.getVehiclesData('https://swapi.co/api/vehicles');
}
render() {
if( !this.state.movieArray.length ||
!this.state.displayArray.length
){
return(
<div className="loading-container">
<img className="almost-there" src={require('../../Assets/Images/almost-there.gif')} alt="Pixel art GIF of X-wing flying through the Death Star trench" />
</div>
)
}
return (
<div className="App">
<Aside
movieData={this.state.movieArray} />
<Header
numberOfFavorites={this.state.favoritesArray.length}
favoriteButtonClick={this.displayFavorites} />
<Nav
buttonCallback={this.handleSectionClick} />
<CardContainer
displayArrayType={this.state.displayArrayType}
nounObjects={this.state.displayArray}
onCardClick={this.cardClicked}
favoritesArray={this.state.favoritesArray} />
</div>
);
}
}
export default App;
| JavaScript | 0.000001 | @@ -2593,35 +2593,199 @@
a(url)%7B%0A
-fetch(url)%0A
+if (Object.keys(localStorage).find( (key) =%3E key===url ) ) %7B%0A this.setState(%7B%0A movieArray: JSON.parse(localStorage%5Burl%5D),%0A %7D)%0A %7D else %7B%0A fetch(url)%0A
.then(
@@ -2813,16 +2813,18 @@
son() )%0A
+
@@ -2873,24 +2873,26 @@
%7B%0A
+
return %7B%0A
@@ -2900,16 +2900,18 @@
+
+
title: m
@@ -2922,16 +2922,18 @@
.title,%0A
+
@@ -2982,16 +2982,18 @@
+
text: mo
@@ -3012,34 +3012,38 @@
crawl%0A
+
+
%7D%0A
+
%7D ) ).th
@@ -3099,16 +3099,24 @@
nse%7D) )%0A
+ %7D%0A
%7D%0A%0A g
|
dbf951585da70e5108ccf614e2a82ec0a5f34255 | Fix eslint warnings | src/Data/EuclideanRing.js | src/Data/EuclideanRing.js | "use strict";
exports.intDegree = function (x) {
return Math.min(Math.abs(x), 2147483647);
};
// See the Euclidean definition in
// https://en.m.wikipedia.org/wiki/Modulo_operation.
exports.intDiv = function (x) {
return function (y) {
if (y == 0) return 0;
return y > 0 ? Math.floor(x / y) : -Math.floor(x / -y);
};
};
exports.intMod = function (x) {
return function (y) {
if (y == 0) return 0;
var yy = Math.abs(y);
return ((x % yy) + yy) % yy;
};
};
exports.numDiv = function (n1) {
return function (n2) {
return n1 / n2;
};
};
| JavaScript | 0.000013 | @@ -239,32 +239,33 @@
) %7B%0A if (y ==
+=
0) return 0;%0A
@@ -399,16 +399,17 @@
if (y ==
+=
0) retu
|
8fedfa537f57d2e9c03499205396ea90bdceb182 | Add test | src/Dialog/Dialog.spec.js | src/Dialog/Dialog.spec.js | // @flow weak
/* eslint-env mocha */
import React from 'react';
import { assert } from 'chai';
import { createShallowWithContext } from 'test/utils';
import Dialog, { styleSheet } from './Dialog';
describe('<Dialog />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallowWithContext();
classes = shallow.context.styleManager.render(styleSheet);
});
it('should render a Modal', () => {
const wrapper = shallow(<Dialog />);
assert.strictEqual(wrapper.is('Modal'), true, 'should be a Modal');
});
it('should put Modal specific props on the root Modal node', () => {
const onBackdropClick = () => {};
const onEscapeKeyUp = () => {};
const onRequestClose = () => {};
const wrapper = shallow(
<Dialog
open
transitionDuration={100}
onBackdropClick={onBackdropClick}
onEscapeKeyUp={onEscapeKeyUp}
onRequestClose={onRequestClose}
hideOnBackdropClick={false}
hideOnEscapeKeyUp={false}
/>,
);
assert.strictEqual(wrapper.prop('show'), true);
assert.strictEqual(wrapper.prop('backdropTransitionDuration'), 100);
assert.strictEqual(wrapper.prop('onBackdropClick'), onBackdropClick);
assert.strictEqual(wrapper.prop('onEscapeKeyUp'), onEscapeKeyUp);
assert.strictEqual(wrapper.prop('onRequestClose'), onRequestClose);
assert.strictEqual(wrapper.prop('hideOnBackdropClick'), false);
assert.strictEqual(wrapper.prop('hideOnEscapeKeyUp'), false);
});
it('should spread custom props on the paper (dialog "root") node', () => {
const wrapper = shallow(<Dialog data-my-prop="woof" />);
assert.strictEqual(wrapper.prop('data-my-prop'), 'woof', 'custom prop should be woof');
});
it('should render with the user classes on the root node', () => {
const wrapper = shallow(<Dialog className="woof" />);
assert.strictEqual(wrapper.hasClass('woof'), true, 'should have the "woof" class');
});
it('should render Fade > Paper > children inside the Modal', () => {
const children = <p>Hello</p>;
const wrapper = shallow(<Dialog>{children}</Dialog>);
const fade = wrapper.childAt(0);
assert.strictEqual(
fade.length === 1 && fade.is('Fade'),
true,
'immediate wrapper child should be Fade',
);
const paper = fade.childAt(0);
assert.strictEqual(
paper.length === 1 && paper.is('Paper'),
true,
'fade child should be Paper',
);
assert.strictEqual(paper.hasClass(classes.dialog), true, 'should have the dialog class');
});
it('should not be open by default', () => {
const wrapper = shallow(<Dialog />);
assert.strictEqual(wrapper.prop('show'), false, 'should pass show=false to the Modal');
assert.strictEqual(wrapper.find('Fade').prop('in'), false, 'should pass in=false to the Fade');
});
it('should be open by default', () => {
const wrapper = shallow(<Dialog open />);
assert.strictEqual(wrapper.prop('show'), true, 'should pass show=true to the Modal');
assert.strictEqual(wrapper.find('Fade').prop('in'), true, 'should pass in=true to the Fade');
});
it('should fade down and make the transition appear on first mount', () => {
const wrapper = shallow(<Dialog />);
assert.strictEqual(
wrapper.find('Fade').prop('transitionAppear'),
true,
'should pass transitionAppear=true to the Fade',
);
});
describe('prop: paperClassName', () => {
it('should add the class on the Paper element', () => {
const className = 'foo';
const wrapper = shallow(<Dialog paperClassName={className} />);
assert.strictEqual(wrapper.find('Paper').hasClass(className), true,
'should have the class provided',
);
});
});
describe('prop: maxWidth', () => {
it('should use the right className', () => {
const wrapper = shallow(<Dialog maxWidth="xs" />);
assert.strictEqual(wrapper.find('Paper').hasClass(classes['dialogWidth-xs']), true,
'should have the class provided',
);
});
});
});
| JavaScript | 0.000005 | @@ -1952,32 +1952,294 @@
class');%0A %7D);%0A%0A
+ it('should render with the fullscreen class on the Paper element', () =%3E %7B%0A const wrapper = shallow(%3CDialog fullscreen /%3E);%0A assert.strictEqual(wrapper.find('Paper').hasClass(classes.fullscreen), true,%0A 'should have the %22fullscreen%22 class');%0A %7D);%0A%0A
it('should ren
|
31cf79ec73895b6b96f376003ebdad2d53f05e85 | Break the loop if the callback returns false | src/utils/CollectionUtils.js | src/utils/CollectionUtils.js | /*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $ */
/**
* Utilities functions related to data collections (arrays & maps)
*/
define(function (require, exports, module) {
"use strict";
/**
* Returns the first index in 'array' for which isMatch() returns true, or -1 if none
* @param {!Array.<*>|jQueryObject} array
* @param {!function(*, Number):boolean} isMatch Passed (item, index), same as with forEach()
*/
function indexOf(array, isMatch) {
// Old-fashioned loop, instead of Array.some, to support jQuery "arrays"
var i;
for (i = 0; i < array.length; i++) {
if (isMatch(array[i], i)) {
return i;
}
}
return -1;
}
/**
* Iterates over all the properties in an object or elements in an array. Differs from
* $.each in that it iterates over array-like objects like regular objects.
* @param {*} object The object or array to iterate over.
* @param {function(value, key)} callback The function that will be executed on every object.
*/
function forEach(object, callback) {
var keys = Object.keys(object),
len = keys.length,
i;
for (i = 0; i < len; i++) {
callback(object[keys[i]], keys[i]);
}
}
// Define public API
exports.indexOf = indexOf;
exports.forEach = forEach;
});
| JavaScript | 0.999371 | @@ -2183,16 +2183,18 @@
%7D object
+ -
The obj
@@ -2268,16 +2268,18 @@
callback
+ -
The fun
@@ -2323,16 +2323,95 @@
object.%0A
+ * If the function returns false the loop will break at that iteration.%0A
*/%0A
@@ -2594,16 +2594,20 @@
+if (
callback
@@ -2632,17 +2632,66 @@
keys%5Bi%5D)
-;
+ === false) %7B%0A break;%0A %7D
%0A
|
aee7033a72f7f2c588450534af890ef38ff6b8d2 | Replace reserved word | src/modelSync.js | src/modelSync.js | 'use strict';
angular.module('robbyronk.model-sync', [])
.service('Model', function Model($cacheFactory, $rootScope, $http, $q) {
var cache = $cacheFactory('cache');
var thisModel = this;
this.create = function (path, object) {
return $http.post(path, object).then(function (response) {
var createdObjectPath = response.headers('Location');
var createdObject = response.data;
cache.put(createdObjectPath, createdObject);
if (cache.get(path)) {
thisModel.get(path).then(function (parentCollection) {
parentCollection.push(createdObject);
cache.put(path, parentCollection);
$rootScope.$broadcast(path, parentCollection);
});
}
var suffix = /\/$/.exec(path) ? 'new' : '/new';
$rootScope.$broadcast(path + suffix, createdObject);
return angular.copy(createdObject);
});
};
this.get = function (path) {
if (cache.get(path)) {
return $q.when(angular.copy(cache.get(path)));
} else {
return $http.get(path).then(function (response) {
cache.put(path, response.data);
return angular.copy(response.data);
});
}
};
this.delete = function (path) {
$http.delete(path).then(function () {
cache.remove(path);
$rootScope.$broadcast(path);
var match = /\/?(.*\/)(.+)$/.exec(path);
var parentPath = match[1];
var removedObjectId = match[2];
if (cache.get(parentPath)) {
thisModel.get(parentPath).then(function (oldParentCollection) {
var parentCollection = _.reject(oldParentCollection, { id: removedObjectId });
cache.put(parentPath, parentCollection);
$rootScope.$broadcast(parentPath, parentCollection);
});
}
});
};
this.subscribe = function (scope, name, path) {
scope.$watch(name, function (object) {
if (angular.isDefined(object)) {
var cb = function () {
cache.put(path, angular.copy(object));
$rootScope.$broadcast(path, object, scope.$id);
};
thisModel.update(path, object, cb);
}
}, true);
scope.$on(path, function (event, object, originScopeId) {
if (scope.$id !== originScopeId) {
scope[name] = angular.copy(object);
}
});
thisModel.get(path).then(function (object) {
scope[name] = angular.copy(object);
});
};
this.update = function (path, object, cb) {
var callback = cb || function () {
cache.put(path, angular.copy(object));
$rootScope.$broadcast(path, object);
};
if (angular.equals(object, cache.get(path))) {
// do nothing
} else {
$http.put(path, object).then(callback);
}
};
this.query = function () {
var withoutPrefix = function (value) {
if(_.contains(['-', '+'], value[0])) {
return value.substr(1);
} else {
return value;
}
};
var generatePredicate = function (name, arity) {
return function () {
if (arity && arguments.length !== arity) {
throw new Error('Expected ' + arity + ' arguments, got ' + arguments.length);
}
return name + '(' + _.toArray(arguments).join(',') + ')';
};
};
var predicates = {};
angular.forEach(['and', 'or', 'in', 'nin'], function (name) {
predicates[name] = generatePredicate(name);
});
angular.forEach(['gt', 'lt', 'gte', 'lte', 'eq', 'neq'], function (name) {
predicates[name] = generatePredicate(name, 2);
});
predicates.not = generatePredicate('not', 1);
var selecting, sortedBy, limitTo, offsetBy, filterBy;
return {
fields: function (/* fields */) {
selecting = _.uniq(arguments).sort();
return this;
},
sort: function (/* fields */) {
sortedBy = _.filter(arguments, function (field, index, fields) {
return index === _.findIndex(fields, function (otherField) {
return field === otherField || withoutPrefix(field) === withoutPrefix(otherField);
});
});
return this;
},
limit: function (int) {
limitTo = parseInt(int, 10);
return this;
},
offset: function (int) {
offsetBy = parseInt(int, 10);
return this;
},
predicates: predicates,
filter: function (predicate) {
filterBy = predicate;
return this;
},
get: function (path) {
var queryParts = [
selecting ? 'fields=' + selecting.join(',') : '',
filterBy ? 'filter=' + filterBy : '',
limitTo ? 'limit=' + limitTo : '',
offsetBy ? 'offset=' + offsetBy : '',
sortedBy ? 'sort=' + sortedBy.join(',') : ''
];
var queryString = '?' + _.remove(queryParts).join('&');
return $http.get(path + queryString).then(function (response) {
return response.data;
})
}
}
};
}); | JavaScript | 0.002105 | @@ -4326,32 +4326,36 @@
t: function (int
+eger
) %7B%0A li
@@ -4366,32 +4366,36 @@
o = parseInt(int
+eger
, 10);%0A
@@ -4448,16 +4448,20 @@
ion (int
+eger
) %7B%0A
@@ -4489,16 +4489,20 @@
eInt(int
+eger
, 10);%0A
|
17eb3661767b5140dd00f112e1cf22bb15d96f57 | fix task.gradeAnswer | pemFioi/beaver-task.js | pemFioi/beaver-task.js | 'use strict';
/*
* This file is to be included by beaver contest tasks, it defines a basic
* implementation of the main functions of the task object, as well as a grader.
*
* Task can overwrite these definitions.
*
*/
var task = {};
task.showViews = function(views, callback) {
if (views.forum || views.hint || views.editor) {
//console.error("this task does not have forum, hint nor editor specific view, showing task view instead.");
views.task = true;
}
$.each(['task', 'solution'], function(i, view) {
if (views[view]) {
$('#'+view).show();
} else {
$('#'+view).hide();
}
});
if (typeof task.hackShowViews === 'function') {task.hackShowViews(views);}
callback();
};
task.getViews = function(callback) {
// all beaver tasks have the same views
var views = {
task: {},
solution: {},
hints: {requires: "task"},
forum: {requires: "task"},
editor: {requires: "task"},
submission: {requires: "task"}
};
callback(views);
};
task.updateToken = function(token, callback) {
callback();
};
task.getHeight = function(callback) {
callback(parseInt($("html").outerHeight(true)));
};
task.unload = function(callback) {
if (typeof Tracker !== 'undefined') {
Tracker.endTrackInputs();
}
callback();
};
task.getState = function(callback) {
var res = {};
task.getAnswer(function(displayedAnswer) {
res.displayedAnswer = displayedAnswer;
});
callback(JSON.stringify(res));
};
task.getMetaData = function(callback) {
if (typeof json !== 'undefined') {
callback(json);
} else {
callback({nbHints:0});
}
};
task.reloadAnswer = function(strAnswer, callback) {
if (!strAnswer) {
task.reloadAnswerObject(task.getDefaultAnswerObject());
} else {
task.reloadAnswerObject(JSON.parse(strAnswer));
}
callback();
};
task.reloadState = function(state, callback) {
var stateObject = JSON.parse(state);
if (typeof stateObject.displayedAnswer !== 'undefined') {
task.reloadAnswer(stateObject.displayedAnswer, callback);
} else {
callback();
}
};
task.getAnswer = function(callback) {
var answerObj = task.getAnswerObject();
callback(JSON.stringify(answerObj));
};
var grader = grader ? grader : {
acceptedAnswers : null,
getAcceptedAnswers: function(callback) {
if (grader.acceptedAnswers) {
callback(grader.acceptedAnswers);
}
if (json && json.acceptedAnswers) {
callback(json.acceptedAnswers);
}
if (typeof getTaskResources === 'function') {
getTaskResources(function(json) {
if (json && json.acceptedAnswers) {
callback(json.acceptedAnswers);
}
});
}
},
gradeTask: function (answer, answerToken, callback) {
grader.getAcceptedAnswers(function(acceptedAnswers) {
platform.getTaskParams(null, null, function (taskParams) {
var score = taskParams.noScore;
if (acceptedAnswers && acceptedAnswers[0]) {
if ($.inArray("" + answer, acceptedAnswers) > -1) {
score = taskParams.maxScore;
} else {
score = taskParams.minScore;
}
}
callback(score, "");
});
});
}
};
task.gradeAnswer = grader.gradeTask;
var DelayedExec = {
timeouts: {},
intervals: {},
animations: {},
setTimeout: function(name, callback, delay) {
DelayedExec.clearTimeout(name);
DelayedExec.timeouts[name] = setTimeout(function() {
delete DelayedExec.timeouts[name];
callback();
}, delay);
},
clearTimeout: function(name) {
if (DelayedExec.timeouts[name]) {
clearTimeout(DelayedExec.timeouts[name]);
delete DelayedExec.timeouts[name];
}
},
setInterval: function(name, callback, period) {
DelayedExec.clearInterval(name);
DelayedExec.intervals[name] = setInterval(callback, period);
},
clearInterval: function(name) {
if (DelayedExec.intervals[name]) {
clearInterval(DelayedExec.intervals[name]);
delete DelayedExec[name];
}
},
animateRaphael: function(name, object, params, time) {
DelayedExec.animations[name] = object;
object.animate(params, time, function() {
delete DelayedExec.animations[name];
});
},
stopAnimateRaphael: function(name) {
if (DelayedExec.animations[name]) {
DelayedExec.animations[name].stop();
delete DelayedExec.animations[name];
}
},
stopAll: function() {
for(var name in DelayedExec.timeouts) {
clearTimeout(DelayedExec.timeouts[name]);
delete DelayedExec.timeouts[name];
}
for(name in DelayedExec.intervals) {
clearInterval(DelayedExec.intervals[name]);
delete DelayedExec.intervals[name];
}
for(name in DelayedExec.animations) {
DelayedExec.animations[name].stop();
delete DelayedExec.animations[name];
}
}
};
$('document').ready(function() {
platform.initWithTask(window.task);
});
| JavaScript | 0.999999 | @@ -2843,32 +2843,38 @@
nswerToken,
-callback
+success, error
) %7B%0A gr
@@ -3322,24 +3322,23 @@
-callback
+success
(score,
@@ -3397,24 +3397,115 @@
r =
-grader.gradeTask
+function(answer, answerToken, success, error) %7B%0A grader.gradeTask(answer, answerToken, success, error);%0A%7D
;%0A%0Av
|
e358c4a4371bc85b6ba92d991204d884ee71fe0e | Fix typo in backend | backend/workers/psa/psa.jobs.js | backend/workers/psa/psa.jobs.js | 'use strict';
var request = require('request');
var workersUtils = require('../utils');
var SERVER = 'https://api.mpsa.com/bgd/jdmc/1.0';
var CLIENT_ID = '3636b9ef-0217-4962-b186-f0333117ddcd';
var CLIENT_SECRET = 'C1xV6pC3yX7cB3jV8oM6tW4vK2mU7fV0nT6eB2fG2fO4mT7gS0';
var psaJobs = {
A_PSA_SYNC: psaSyncJob,
A_PSA_SIGNUP: psaSignupJob,
};
var SECONDS = [6, 12, 18, 24, 30, 36, 42, 48, 54, 60];
var lastLatitude;
var lastLongitude;
module.exports = psaJobs;
// Sample: https://api.mpsa.com/bgd/jdmc/1.0/place/lastposition/VF7NC9HD8DY611112?contract=620028501&listsecond=6,12,18,24,30,36,42,48,54,60&client_id=3636b9ef-0217-4962-b186-f0333117ddcd
// For each user retrieve current GPS location
// Check for nice places around if the vehicle is stopped
// Save the location event with some useful informations
function psaSyncJob(context, event) {
// Get every current trips involving psa
return workersUtils.getCurrentTrips(context, {
carOnly: true,
})
.then(function handlePSATrips(tripsEvents) {
return Promise.all(tripsEvents.map(function(tripEvent) {
return context.db.collection('users').findOne({
_id: tripEvent.owner_id,
cars: { $elemMatch: {
_id: tripEvent.trip.car_id,
} },
}).then(function(user) {
var car = user.cars.filter(function(car) {
return tripEvent.trip.car_id.toString() === car._id.toString() &&
'psa' === car.type;
})[0];
if(!car) {
return Promise.resolve();
}
return new Promise(function psaPositionPromise(resolve, reject) {
request.get(
SERVER +
'/place/lastposition/' + car.vin +
'?contract=' + car.contract +
'&listsecond=' + SECONDS.join(',') +
'&client_id=' + CLIENT_ID,
function(err, res, data) {
if(err) {
return reject(err);
}
try {
data = JSON.parse(data);
} catch(err) {
return reject(err);
}
resolve(data);
});
}).then(function(data) {
var bestSecond;
var geo;
//context.logger.debug('Data', JSON.stringify(data, null, 2));
// Get the best precision possible
bestSecond = SECONDS.reduce(function(best, second) {
if(data.nbsat && (!best) || best.nbsat < data.nbsat[second]) {
return {
nbsat: data.nbsat[second],
second: second,
};
}
return best;
}, { second: SECONDS[0], nbsat: 0 }).second;
geo = [
data.latitude[bestSecond],
data.longitude[bestSecond],
data.altitude[bestSecond],
];
context.logger.debug('Got positions:', geo, bestSecond);
if (data.latitude[bestSecond] !== lastLatitude
|| data.longitude[bestSecond] !== lastLongitude
) {
context.logger.info(
'Got positions: %s http://maps.google.com/maps?q=%s,%s',
geo.join(' '),
data.latitude[bestSecond],
data.longitude[bestSecond]
);
request
.get(
'http://maps.googleapis.com/maps/api/geocode/json?latlng=' +
data.latitude[bestSecond] + ',' +
data.longitude[bestSecond],
function(err, res, body) {
var address;
if (err) {
context.logger.error(err);
}
body = JSON.parse(body);
address = body.results[0].formatted_address;
context.logger.info(
'Je suis au : %s, attendez moi signé patrick! @hackthemobility',
address,
);
// Save the coordinates as an event
return context.db.collection('events').findOneAndUpdate({
'contents.type': 'psa-geo',
'contents.trip_id': tripEvent._id,
'contents.date': new Date(transformPSADate(data.lastUpdate)),
}, {
$set: {
'contents.geo': geo,
'contents.address': address,
},
$setOnInsert: {
'contents.date': new Date(transformPSADate(data.lastUpdate)),
'contents.trip_id': tripEvent._id,
'contents.type': 'psa-geo',
trip: tripEvent.trip,
},
}, {
upsert: true,
returnOriginal: false,
});
}
)
;
}
lastLongitude = data.longitude[bestSecond];
lastLatitude = data.latitude[bestSecond];
});
});
}));
});
}
function psaSignupJob(context, event) {
return context.db.collection('users').findOne({
_id: event.contents.user_id,
})
.then(function handlePSASignup(user) {
// Sample: https://api.mpsa.com/bgd/jdmc/1.0/vehicle/information/VF7NC9HD8DY611112?contract=620028501&listsecond=6,12,18,24,30,36,42,48,54,60&client_id=3636b9ef-0217-4962-b186-f0333117ddcd
// Get the user car specs, save the color to customize the app
// The event should be triggered at signup for one of the signup mechanisms
});
}
function transformPSADate(psaDate) {
return new Date(
psaDate.substr(0, 4) + '-' +
psaDate.substr(4, 2) + '-' +
psaDate.substr(6, 2) + 'T' +
psaDate.substr(8, 2) + ':' +
psaDate.substr(10, 2) + ':' +
psaDate.substr(12, 2) + '.000Z'
);
}
| JavaScript | 0.998349 | @@ -3952,33 +3952,32 @@
address
-,
%0A
|
49d613bbd6817febf2cbdcdcf626992c28b44b0d | Send git commit info to sentry (#376) | bat-utils/lib/runtime-sentry.js | bat-utils/lib/runtime-sentry.js | const { URL } = require('url')
const Raven = require('raven')
const SDebug = require('sdebug')
const underscore = require('underscore')
const debug = new SDebug('sentry')
const Sentry = function (config, runtime) {
if (!(this instanceof Sentry)) return new Sentry(config, runtime)
if (!config.sentry.dsn) {
process.on('unhandledRejection', (ex) => {
console.log(ex.stack)
debug('sentry', ex)
})
}
// NOTE If sentry dsn if falsey, events will be consumed without error
// with no attempt to send them
Raven.config(config.sentry.dsn, {
captureUnhandledRejections: true
}).install()
runtime.captureException = (ex, optional) => {
if (optional && optional.req) {
const request = optional.req
optional.req = { // If present rewrite the request into sentry format
method: request.method,
query_string: request.query,
headers: underscore.omit(request.headers, [ 'authorization', 'cookie' ])
}
try {
const url = new URL(request.path, runtime.config.server)
if (url) optional.req['url'] = url
} catch (ex) { }
optional.extra = underscore.extend(optional.extra, { timestamp: request.info.received, id: request.id })
}
Raven.captureException(ex, optional)
}
if (!config.sentry && process.env.NODE_ENV === 'production') {
throw new Error('config.sentry undefined')
}
}
module.exports = Sentry
| JavaScript | 0 | @@ -163,24 +163,82 @@
('sentry')%0A%0A
+const release = process.env.HEROKU_SLUG_COMMIT %7C%7C 'test'%0A%0A
const Sentry
@@ -628,16 +628,29 @@
.dsn, %7B%0A
+ release,%0A
capt
|
417cc44825a86b62479243ce5a197a708ea3d627 | Fix hyphen typo error. (#12496) | www/src/pages/docs/index.js | www/src/pages/docs/index.js | import React from "react"
import { Link } from "gatsby"
import { Helmet } from "react-helmet"
import Layout from "../../components/layout"
import { itemListDocs } from "../../utils/sidebar/item-list"
import Container from "../../components/container"
import EmailCaptureForm from "../../components/email-capture-form"
import DocSearchContent from "../../components/docsearch-content"
class IndexRoute extends React.Component {
render() {
return (
<Layout location={this.props.location} itemList={itemListDocs}>
<DocSearchContent>
<Container>
<Helmet>
<title>Docs</title>
</Helmet>
<h1 id="gatsby-documentation" css={{ marginTop: 0 }}>
Gatsby.js Documentation
</h1>
<p>Gatsby is a blazing fast modern site generator for React.</p>
<h2>Get Started</h2>
<p>There are four main ways to get started with Gatsby:</p>
<ol>
<li>
<Link to="/tutorial/">Tutorial</Link>: The tutorial is written
to be as accessible as possible to people without much web
development experience.
</li>
<li>
<Link to="/docs/quick-start">Quick start</Link>: The quick start
is intended for intermediate to advanced developers who prefer
to dig straight in.
</li>
<li>
<Link to="/docs/recipes">Recipes</Link>: A happy medium between
the tutorial and the quick start, find some quick answers for
how to accomplish some specific, common tasks with Gatsby.
</li>
<li>
Choose your own adventure and peruse the various sections of the
Gatsby docs:
</li>
<ul>
<li>
<strong>Guides</strong>: Dive deeper into different topics
around building with Gatsby, like sourcing data, deployment,
and more.
</li>
<li>
<strong>Ecosystem</strong>: Check out libraries for Gatsby
starters and plugins, as well as external community resources.
</li>
<li>
<strong>API Reference</strong>: Learn more about Gatsby APIs
and configuration.
</li>
<li>
<strong>Releases & Migration</strong>: Find release notes
and guides for migration between major versions.
</li>
<li>
<strong>Conceptual Guide</strong>: Read high level overviews
of the Gatsby approach.
</li>
<li>
<strong>Behind the Scenes</strong>: Dig into how Gatsby works
under the hood.
</li>
<li>
<strong>Advanced Tutorials</strong>: Learn about topics that
are too large for a doc and warrant a tutorial.
</li>
</ul>
</ol>
<p>
Visit the <Link to="/contributing">Contributing</Link> section to
find guides on the Gatsby community, code of conduct, and how to
get started contributing to Gatsby.
</p>
<EmailCaptureForm signupMessage="Want to keep up with the latest tips & tricks? Subscribe to our newsletter!" />
</Container>
</DocSearchContent>
</Layout>
)
}
}
export default IndexRoute
| JavaScript | 0.00041 | @@ -2733,17 +2733,17 @@
ead high
-
+-
level ov
|
a685c50264631e297be9f6a5ec6d32a63697585b | fix linter warning | xod-espruino/src/runtime.js | xod-espruino/src/runtime.js |
function nullFunc() {}
var PULSE = {type: 'pulse'};
var identity = function(x) { return x; };
function identityNode() {
return {
evaluate: function(e) { return {PIN: e.inputs.PIN}; }
};
}
/**
* @typedef {{
* lazy: boolean,
* nodeId: number,
* key: string
* }} OutLink
*/
/**
* @param {function} setup
* node’s setup function
* @param {function} evaluate
* node’s evaluation function (aka implementation)
* @param {boolean} pure
* whether `impl` should receive `fire` function as argument
* @param {Object.<string, function>} inputTypes
* input type coercing functions
* @param {Object.<string, Array.<OutLink>>} outLinks
* map from output name to outgoing link description
* @param {Object.<number, Node>} nodes
* map from ID to `Node` instances
*/
function Node(args) {
this._id = args.id;
this._setup = args.setup || nullFunc;
this._evaluate = args.evaluate || nullFunc;
this._pure = (args.pure === undefined) ? true : args.pure;
this._inputTypes = args.inputTypes || {};
this._outLinks = args.outLinks || {};
this._props = args.props || {};
this._nodes = args.nodes;
this._context = {};
this._cachedInputs = {};
this._pendingOutputs = {};
this._dirty = false;
}
/**
* Fires new signals at arbitrary point of time.
*
* The method is used by impure nodes to trigger external signals.
* It is used by pure nodes as well but only in their setup to send
* initial values.
*/
Node.prototype.fire = function(outputs) {
var self = this;
Object.keys(outputs).forEach(function(key) {
self._pendingOutputs[key] = outputs[key];
});
this.emit('fire');
};
/**
* Transaction start handler.
*
* It would be called from outside once before each transaction.
*/
Node.prototype.onTransactionStart = function() {
this._sendOutputs(this._pendingOutputs);
this._pendingOutputs = {};
};
/**
* Returns whether any inputs were changed and node requires evaluation
* in current transaction.
*/
Node.prototype.isDirty = function() {
return this._dirty;
};
/**
* Initializes the `Node`, sends initial signals.
*
* Called once the graph is ready at the very beginning of program execution.
*/
Node.prototype.setup = function() {
this._setup({
fire: this.fire.bind(this),
props: this._props,
context: this._context
});
};
/**
* Evaluates the `Node` taking input signals and producting output signals.
*/
Node.prototype.evaluate = function() {
var fire, inputs, result, self;
if (!this._dirty) {
return;
}
fire = this._pure ? null : this.fire.bind(this);
inputs = this._cachedInputs.clone();
result = this._evaluate({
inputs: inputs,
fire: fire,
context: this._context,
props: this._props
}) || {};
// remove "outdated" pulses
self = this;
Object.keys(this._cachedInputs).forEach(function(key) {
if (self._cachedInputs[key] === PULSE) {
delete self._cachedInputs[key];
}
});
this._sendOutputs(result);
this._dirty = false;
};
Node.prototype._receiveInput = function(name, value, lazy) {
this._cachedInputs[name] = this._inputTypes[name](value);
this._dirty = this._dirty || !lazy;
};
Node.prototype._sendOutputs = function(signals) {
var self = this;
Object.keys(signals).forEach(function(outputName) {
var val;
var outLinks = self._outLinks[outputName];
if (!outLinks) {
return;
}
val = signals[outputName];
outLinks.forEach(function(link) {
self._nodes[link.nodeId]._receiveInput(link.key, val, !!link.lazy);
});
});
};
/**
* @param {Object.<number, Node>} args.nodes
* map from ID to Node instances
* @param {Array.<number, number>} args.topology
* sorted node index list that defines an order
* of the graph traversal
*/
function Project(args) {
this._nodes = args.nodes;
this._topology = args.topology;
this._pendingTransaction = false;
this._inTransaction = false;
}
/**
* Setups all nodes all starts graph execution.
*/
Project.prototype.launch = function() {
var fire = this.onNodeFire.bind(this);
this.forEachNode(function(node) { node.on('fire', fire); });
this._inSetup = true;
try {
this.forEachNode(function(node) { node.setup(); });
} finally {
this._inSetup = false;
}
this.flushTransaction();
};
/**
* Starts a new transaction if required and possible.
*
* If ran it lead to cascade evaluation of all dirty nodes.
*/
Project.prototype.flushTransaction = function() {
if (!this._pendingTransaction || this._inTransaction || this._inSetup) {
return;
}
this._pendingTransaction = false;
this._inTransaction = true;
try {
this.forEachNode(function(node) { node.onTransactionStart(); });
this.forEachDirtyNode(function(node) { node.evaluate(); });
} finally {
this._inTransaction = false;
}
setTimeout(this.flushTransaction.bind(this), 0);
};
/**
* Returns the first `Node` that should be evaluated according
* to topological sort indexes. Returns `undefined` if all nodes
* are up to date in current transaction.
*/
Project.prototype.getFirstDirtyNode = function() {
var i, nodeId, node;
var len = this._topology.length;
for (i = 0; i < len; ++i) {
nodeId = this._topology[i];
node = this._nodes[nodeId];
if (node.isDirty()) {
return node;
}
}
return null;
};
Project.prototype.forEachDirtyNode = function(callback) {
var node;
for (node = this.getFirstDirtyNode(); node; node = this.getFirstDirtyNode()) {
callback(node);
}
};
/**
* Node fire handler.
*
* Gets called when any node uses `Node.fire` to issue an external signal
* or an initial signal.
*/
Project.prototype.onNodeFire = function() {
this._pendingTransaction = true;
this.flushTransaction();
};
/**
* Executes `callback` with `node` argument for every node in the graph.
*/
Project.prototype.forEachNode = function(callback) {
var self = this;
Object.keys(this._nodes).forEach(function(id) { callback(self._nodes[id]); });
};
if (typeof module !== 'undefined') {
// Export some entities for tests
module.exports.Node = Node;
module.exports.Project = Project;
module.exports.PULSE = PULSE;
module.exports.identity = identity;
}
| JavaScript | 0.000001 | @@ -91,16 +91,52 @@
x; %7D;%0A%0A
+/* eslint-disable no-unused-vars */%0A
function
@@ -229,16 +229,51 @@
%7D%0A %7D;%0A%7D
+%0A/* eslint-enable no-unused-vars */
%0A%0A/**%0A
|
2c99dd86598742f9ad6eb4a0a0856ee47bbbdca3 | Update plug-in : GettyImages | plugins/gettyimages.js | plugins/gettyimages.js | var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'gettyimages.com',
version:'0.1',
prepareImgLinks:function (callback) {
var res = [];
hoverZoom.urlReplace(res,
'img[src*="gettyimages"]',
/\?.*/,
''
);
callback($(res));
}
}); | JavaScript | 0 | @@ -111,9 +111,9 @@
:'0.
-1
+2
',%0A
@@ -186,127 +186,1210 @@
-%0A hoverZoom.urlReplace(res,%0A 'img%5Bsrc*=%22gettyimages%22%5D',%0A /%5C?.*/,%0A ''%0A );
+ var regex = /(.*)%5C?(.*)/;%0A var patch = '$1?s=2048x2048';%0A %0A hoverZoom.urlReplace(res,%0A 'img%5Bsrc%5D',%0A regex,%0A patch%0A );%0A %0A $('%5Bstyle*=background%5D').each(function() %7B%0A var link = $(this);%0A // extract url from style%0A var backgroundImage = this.style.backgroundImage;%0A if (backgroundImage.indexOf(%22url%22) != -1) %7B%0A var reUrl = /.*url%5Cs*%5C(%5Cs*(.*)%5Cs*%5C).*/i%0A backgroundImage = backgroundImage.replace(reUrl, '$1');%0A // remove leading & trailing quotes%0A var backgroundImageUrl = backgroundImage.replace(/%5E%5B'%22%5D/,%22%22).replace(/%5B'%22%5D+$/,%22%22);%0A var fullsizeUrl = backgroundImageUrl.replace(regex, patch);%0A if (fullsizeUrl != backgroundImageUrl) %7B%0A%0A if (link.data().hoverZoomSrc == undefined) %7B link.data().hoverZoomSrc = %5B%5D %7D%0A if (link.data().hoverZoomSrc.indexOf(fullsizeUrl) == -1) %7B %0A link.data().hoverZoomSrc.unshift(fullsizeUrl);%0A res.push(link);%0A %7D%0A %7D%0A %7D%0A %7D);%0A
%0A
@@ -1408,16 +1408,27 @@
k($(res)
+, this.name
);%0A %7D
|
13222126822d2df554b93e07de0d9e0b5ac82705 | update marker | webmaps/js/rm10k.js | webmaps/js/rm10k.js | function main() {
var map = new L.Map('map', {
zoomControl: false,
center: [44.908, -75.83],
zoom: 15
});
L.tileLayer(
'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ',
maxZoom: 16
}).addTo(map);
// load 10k course route
$.getJSON("10k.geojson", function(data) {
// add GeoJSON layer to the map once the file is loaded
L.geoJson(data).addTo(map);
});
// Creates a red marker with the coffee icon
var redMarker = L.AwesomeMarkers.icon({
icon: 'coffee',
markerColor: 'red'
});
// load 10k course route features
$.getJSON("features.geojson", function(data) {
//add GeoJSON layer to the map once the file is loaded
L.geoJson(data, {
//style: function(feature) {
//return {
//color: "red"
//};
//},
pointToLayer: function(feature, latlng) {
return new L.marker(latlng, {
icon: redMarker
//radius: 10,
//fillOpacity: 0.85
});
},
//onEachFeature: function(feature, layer) {
//layer.bindPopup(feature.properties.cng_Meters);
//}
}).addTo(map);
});
}
// you could use $(window).load(main);
window.onload = main; | JavaScript | 0.000001 | @@ -655,14 +655,16 @@
%7D);%0A
-%09%09 %0A%09%09
+
//
@@ -677,40 +677,22 @@
s a
-red
marker
- with the coffee icon%0A
+%0A
va
@@ -729,16 +729,25 @@
.icon(%7B%0A
+
icon
@@ -753,17 +753,37 @@
n: '
-coffee',%0A
+fa-flag-checkered',%0A
@@ -807,15 +807,18 @@
'%0A
-%7D);%0A%09%09
+ %7D);
%0A
@@ -1016,174 +1016,8 @@
, %7B%0A
- //style: function(feature) %7B%0A //return %7B%0A //color: %22red%22%0A //%7D;%0A //%7D,%0A
@@ -1167,74 +1167,8 @@
ker%0A
-%09%09%09%09%09%09 //radius: 10,%0A //fillOpacity: 0.85%0A
@@ -1265,28 +1265,24 @@
e, layer) %7B%0A
-
|
4a38af9ca804e21a40687857513237b5e9478e91 | Fix test | lib/node_modules/@stdlib/math/constants/float64-sqrt-pi/test/test.js | lib/node_modules/@stdlib/math/constants/float64-sqrt-pi/test/test.js | 'use strict';
// MODULES //
var tape = require( 'tape' );
var SQRT_PI = require( './../lib' );
// TESTS //
tape( 'main export is a number', function test( t ) {
t.ok( true, __filename );
t.equal( typeof SQRT_PI, 'number', 'main export is a number' );
t.end();
});
tape( 'export is a double-precision floating-point number equal to `1.7724538509055159`', function test( t ) {
t.equal( SQRT_PI, 1.7724538509055159, 'equals 1.7724538509055159' );
t.end();
});
| JavaScript | 0.000004 | @@ -350,18 +350,18 @@
85090551
-59
+60
%60', func
@@ -412,18 +412,18 @@
85090551
-59
+60
, 'equal
@@ -444,10 +444,10 @@
0551
-59
+60
' );
|
e364ed1c9d577ea607042638c71a4dccd786f732 | Update scripts | packages/soya-next-cli/src/index.js | packages/soya-next-cli/src/index.js | import fs from 'fs-extra';
import path from 'path';
import spawn from 'cross-spawn';
import yargs from 'yargs';
const argv = yargs
.version()
.usage('Usage: $0 <project-directory>')
.option('verbose', {
type: 'boolean',
describe: 'Show more details',
default: false,
})
.alias('help', 'h')
.alias('version', 'v')
.help()
.example('$0 todo-app', 'Create "todo-app" project relative to current directory')
.strict()
.argv;
const projectDirectory = argv._[0];
const dependencies = [
'next',
'prop-types',
'react',
'react-cookie',
'react-dom',
'react-redux',
'redux',
'soya-next',
'soya-next-scripts',
];
if (projectDirectory) {
const root = path.resolve(projectDirectory);
const name = path.basename(root);
const cwd = process.cwd();
console.log(`Creating ${name} in ${root}.`);
console.log();
fs.ensureDirSync(projectDirectory);
fs.copy(path.resolve(__dirname, '../templates'), root, { overwrite: false })
.then(async () => {
try {
await fs.move(path.join(root, 'gitignore'), path.join(root, '.gitignore'));
} catch (err) {
if (err.code === 'EEXIST') {
fs.unlink(path.join(root, 'gitignore'));
} else {
throw err;
}
}
});
fs.writeJsonSync(path.join(root, 'package.json'), {
name,
version: '1.0.0',
main: 'server.js',
scripts: {
build: 'next build',
start: 'node .',
},
}, { spaces: 2 });
process.chdir(root);
console.log('Installing dependencies.');
console.log();
let cmd;
const args = [];
const { status } = spawn.sync('which', ['yarn'], { stdio: 'ignore' });
if (status === 0) {
cmd = 'yarn';
args.push('add');
} else {
cmd = 'npm';
args.push('install', '--save');
}
args.push(...dependencies);
if (argv.verbose) {
args.push('--verbose');
}
spawn.sync(cmd, args, { stdio: 'inherit' });
console.log();
console.log(`Successfully created ${name} in ${root}.`);
console.log('Run the following commands to start the app:');
console.log();
let target;
if (path.isAbsolute(projectDirectory)) {
target = root;
} else {
target = path.relative(cwd, root);
}
if (target !== '') {
console.log(` cd ${target}`);
}
console.log(` ${cmd} start`);
console.log();
} else {
yargs.showHelp();
}
| JavaScript | 0.000001 | @@ -1350,31 +1350,8 @@
0',%0A
- main: 'server.js',%0A
@@ -1379,41 +1379,149 @@
d: '
-next build',%0A start: 'node .
+soya-next-scripts build',%0A eject: 'soya-next-scripts eject',%0A start: 'soya-next-scripts start',%0A test: 'soya-next-scripts test
',%0A
|
b70182ae9538aecb9d7587b86dd460e39a8762b6 | remove address fields, singularize model name, IN PROG: model association - waiting on order-product table | db/models/order.js | db/models/order.js | 'use strict'
const {STRING, ARRAY, INTEGER, NOW, ENUM} = require('sequelize')
module.exports = db => db.define('orders', {
email: {
type: STRING,
validate: {
isEmail: true,
notEmpty: true
}
},
shippingHouseNum: {
type: STRING,
allowNull: false
},
shippingZipCode: {
type: INTEGER,
allowNull: false,
},
shippingCity: {
type: STRING,
allowNull: false
},
shippingState: {
type: STRING,
allowNull: false
},
billingHouseNum: {
type: STRING,
allowNull: false
},
billingZipCode: {
type: INTEGER,
allowNull: false,
},
billingCity: {
type: STRING,
allowNull: false
},
billingState: {
type: STRING,
allowNull: false
},
// timestamp: NOW,
status: {
type: ENUM,
values: ['created', 'processing', 'cancelled', 'completed'],
defaultValue: 'created'
}
})
// {
// validate: {
// itemsInCart() {
// if (!this.itemIds.length) {
// throw new Error('Order must contain at least one item')
// }
// },
// zipValid() {
// if (this.shippingZipCode.length !== 5) {
// throw new Error('Zip code must be valid')
// }
// }
// }
// }
module.exports.associations = (Order, {User, Product}) => {
Order.belongsTo(User)
}
| JavaScript | 0 | @@ -111,17 +111,16 @@
e('order
-s
', %7B%0A e
@@ -221,990 +221,132 @@
%0A s
-hippingHouseNum: %7B%0A type: STRING,%0A allowNull: false%0A %7D,%0A shippingZipCode: %7B%0A type: INTEGER,%0A allowNull: false,%0A %7D,%0A shippingCity: %7B%0A type: STRING,%0A allowNull: false%0A %7D,%0A shippingState: %7B%0A type: STRING,%0A allowNull: false%0A %7D,%0A billingHouseNum: %7B%0A type: STRING,%0A allowNull: false%0A %7D,%0A billingZipCode: %7B%0A type: INTEGER,%0A allowNull: false,%0A %7D,%0A billingCity: %7B%0A type: STRING,%0A allowNull: false%0A %7D,%0A billingState: %7B%0A type: STRING,%0A allowNull: false%0A %7D,%0A // timestamp: NOW,%0A status: %7B%0A type: ENUM,%0A values: %5B'created', 'processing', 'cancelled', 'completed'%5D,%0A defaultValue: 'created'%0A %7D%0A%7D)%0A// %7B%0A// validate: %7B%0A// itemsInCart() %7B%0A// if (!this.itemIds.length) %7B%0A// throw new Error('Order must contain at least one item')%0A// %7D%0A// %7D,%0A// zipValid() %7B%0A// if (this.shippingZipCode.length !== 5) %7B%0A// throw new Error('Zip code must be valid')%0A// %7D%0A// %7D%0A// %7D%0A// %7D
+tatus: %7B%0A type: ENUM,%0A values: %5B'created', 'processing', 'cancelled', 'completed'%5D,%0A defaultValue: 'created'%0A %7D%0A%7D)
%0A%0Amo
@@ -427,10 +427,56 @@
o(User)%0A
+ Order.belongsToMany(Product, %7Bthrough: ''%7D)%0A
%7D%0A
|
af713c11ed1744aa53e7a68c1f61591b66e625a2 | Change the vote up/down buttons into thumbs up/down. | packages/telescope-lib/lib/icons.js | packages/telescope-lib/lib/icons.js | // ------------------------------ Dynamic Icons ------------------------------ //
/**
* Take an icon name (such as "open") and return the HTML code to display the icon
* @param {string} iconName - the name of the icon
* @param {string} [iconClass] - an optional class to assign to the icon
*/
Telescope.utils.getIcon = function (iconName, iconClass) {
var icons = Telescope.utils.icons;
var iconCode = !!icons[iconName] ? icons[iconName] : iconName;
var iconClass = (typeof iconClass === 'string') ? ' '+iconClass : '';
return '<i class="icon fa fa-' + iconCode + ' icon-' + iconName + iconClass+ '" aria-hidden="true"></i>';
};
/**
* A directory of icon keys and icon codes
*/
Telescope.utils.icons = {
open: "plus",
close: "minus",
upvote: "chevron-up",
voted: "check",
downvote: "chevron-down",
facebook: "facebook-square",
twitter: "twitter",
googleplus: "google-plus",
linkedin: "linkedin-square",
comment: "comment-o",
share: "share-square-o",
more: "ellipsis-h",
menu: "bars",
subscribe: "envelope-o",
delete: "trash-o",
edit: "pencil",
popularity: "fire",
time: "clock-o",
best: "star",
search: "search"
};
| JavaScript | 0.000001 | @@ -758,23 +758,24 @@
pvote: %22
-chevron
+thumbs-o
-up%22,%0A
@@ -807,15 +807,16 @@
e: %22
-chevron
+thumbs-o
-dow
|
80b2361f1baa7fbbe3a2787b78427b5eb41db887 | Update identification.js | mainRPi/sockets/serverSocket/identification.js | mainRPi/sockets/serverSocket/identification.js | var fs=require('fs');
var async=require('../../../async');
var constants= require('../../../constants.js');
var envVariables=require('../../../envVariables.js');
var Reading=require('../../../server/models/reading.js');
module.exports=function(socket){
socket.emit('identification', {mainRPiID: constants.MAIN_ID}, function(err,res){
if(err){
throw err;
}
if(res.status){
if(res.new){
fs.writeFile(constants.MAIN_ID_PATH, res.mainRPiID, 'utf8', function(err){
if(err){
throw err;
}
constants.MAIN_ID=res.id;
socket.disconnect();
});
}
else{
envVariables.serverConnectionStatus=true;
Reading.find({},function(err,docs){
if(err){
throw err;
}
//MainRPi states what monitors are currently connected to it
socket.emit('connectedMonitors',{envVariables.monitorIDs},function(err,res){
if(err){
throw err;
}
//TODO: add success logic.
});
var i=0;
var j=0;
async.whilst(function(){i<docs.length},function(){
async.whilst(function(){i==j},function(){
socket.emit('rReading',docs[i],function(err,res){
if(err){
throw err;
}
if(res.status){
Reading.findById(docs[i]._id,function(err,doc){
if(err){
throw err;
}
doc.remove(function(err,res){
if(err){
throw err;
}
});
});
i++;
}
});
j++;
},function(){});
},function(){});
});
}
}
else{
if(res.error){
console.log(res.error);
}
socket.disconnect();
}
});
}
| JavaScript | 0.000001 | @@ -903,16 +903,25 @@
itors',%7B
+monitors:
envVaria
|
640b4704bdcab69e2b2c9ea88792b2d604883a14 | fix issue with empty response codes. | react-frontend/server/ForwarderService.js | react-frontend/server/ForwarderService.js | var request = require('superagent');
module.exports = function(endpoint) {
return function(req, res, next) {
request(req.method, endpoint + req.params.path)
.set(req.headers)
.send(req.body)
.end( function(err, resBackend) {
if(err) {
console.log("Error forwarding request", endpoint, err.status);
res.status(err.status).send(err);
}
else {
res.send(resBackend);
}
});
}
} | JavaScript | 0 | @@ -105,16 +105,25 @@
next) %7B%0A
+%09%09try %7B%0A%09
%09%09reques
@@ -167,16 +167,17 @@
ath)%0A%09%09%09
+%09
.set(req
@@ -189,16 +189,17 @@
ers)%0A%09%09%09
+%09
.send(re
@@ -206,16 +206,17 @@
q.body)%0A
+%09
%09%09%09.end(
@@ -248,16 +248,17 @@
) %7B%0A%09%09%09%09
+%09
if(err)
@@ -255,24 +255,25 @@
%09%09if(err) %7B%0A
+%09
%09%09%09%09%09console
@@ -277,17 +277,17 @@
ole.log(
-%22
+'
Error fo
@@ -306,9 +306,9 @@
uest
-%22
+'
, en
@@ -322,63 +322,197 @@
err
-.status);%0A%09%09%09%09%09res.status(err.status).send(err);%0A%09%09%09%09%7D%0A
+);%0A%09%09%09%09%09%09if(err.status %3E 100 && err.status %3C 999) %7B%0A%09%09%09%09%09%09%09res.status(err.status).send(err);%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09else res.status(500).send('Undefined status code returned from Backend');%0A%09%09%09%09%09%7D%0A%09
%09%09%09%09
@@ -518,16 +518,17 @@
%09else %7B%0A
+%09
%09%09%09%09%09res
@@ -554,17 +554,144 @@
%09%09%09%09
+%09
%7D%0A
+%09
%09%09%09%7D);%0A
+%09%09%7D%0A%09%09catch (ex) %7B%0A%09%09%09console.log('Exception occurred while forwarding request', req);%0A%09%09%09res.status(500).send('Error');%0A%09%09%7D%0A
%09%7D%0A%7D
|
e4fae3bdc596fc2370a4b7beb08a839e33051e4d | Fix update schedule | view/components/users-table.js | view/components/users-table.js | 'use strict';
var toNatural = require('es5-ext/number/to-pos-integer')
, object = require('es5-ext/object/valid-object')
, value = require('es5-ext/object/valid-value')
, memoize = require('memoizee/plain')
, ObservableValue = require('observable-value')
, ObservableSet = require('observable-set')
, ReactiveTable = require('reactive-table')
, ReactiveList = require('reactive-table/list')
, location = require('mano/lib/client/location')
, db = require('mano').db
, fixLocationQuery = require('../../utils/fix-location-query')
, serializeSnapshotKey = require('../../utils/serialize-to-snapshot-key')
, getFilter = require('../../utils/get-users-filter')
, Pagination = require('./pagination')
, ceil = Math.ceil, create = Object.create, keys = Object.keys;
var resolveUsers = function (value) {
if (!value) return [];
return value.split(',').map(function (id) {
return db.objects.unserialize(id, db.User);
});
};
var getUsersSnapshot = memoize(function (observable) {
var set = new ObservableSet(resolveUsers(observable.value));
observable.on('change', function (event) {
set._postponed_ += 1;
set.clear();
resolveUsers(event.newValue).forEach(set.add, set);
set._postponed_ -= 1;
});
return set;
}, { normalizer: function (args) { return args[0].dbId; } });
module.exports = function (snapshots, options) {
var list, table, pagination, i18n, columns
, statusQuery, searchQuery, pathname, pageLimit, statusMap
, active, update, appName, pageQuery, inSync, isPartial;
var getPageCount = function (value) {
if (!value) return 1;
return ceil(value / pageLimit);
};
object(options);
columns = object(options.columns);
i18n = options.i18n ? object(options.i18n) : create(null);
appName = value(options.appName);
pathname = value(options.pathname);
value(options.cacheLimits);
pageLimit = options.cacheLimits.usersPerPage;
statusMap = object(options.users);
inSync = new ObservableValue(true);
isPartial = (function () {
var snapshotTokens = [appName];
if (statusMap[i18n.all || 'all']) snapshotTokens.push(i18n.all || 'all');
return db.User.dataSnapshots.get(serializeSnapshotKey(snapshotTokens))
._totalSize.map(function (value) { return value > options.cacheLimits.listedUsers; });
}());
update = function () {
var status, search, normalizedSearch, page, snapshot, usersSnapshot
, snapshotTokens, snapshotKey, maxPage, users;
if (!active) return;
snapshotTokens = [appName];
// Resolve status
if (statusQuery) {
if (statusQuery.value && !statusMap[statusQuery.value]) {
fixLocationQuery(i18n.status || 'status');
} else {
status = statusQuery.value || '';
}
users = statusMap[status];
if (status) snapshotTokens.push(status);
} else {
users = statusMap[''];
}
// Resolve search
if (searchQuery) {
search = searchQuery.value;
if (search != null) {
normalizedSearch = search.trim().toLowerCase();
if (search !== normalizedSearch) {
search = normalizedSearch;
fixLocationQuery(i18n.search || 'search', search || null);
}
}
if (search) {
users = users.filter(getFilter(search));
snapshotTokens.push(search);
}
}
snapshot = db.User.dataSnapshots.get(serializeSnapshotKey(snapshotTokens));
pagination.count.value = isPartial.value
? snapshot._totalSize.map(getPageCount) : users._size.map(getPageCount);
maxPage = pagination.count.value;
// Resolve page
if (pageQuery.value != null) {
page = toNatural(pageQuery.value) || null;
if (page === 1) page = null;
if (page) {
if (maxPage < page) page = (maxPage > 1) ? maxPage : null;
}
if (page) page = String(page);
if (page !== pageQuery.value) fixLocationQuery(i18n.page || 'page', page);
if (page) page = Number(page);
}
pagination.current.value = page || 1;
// Update table
if (isPartial.value) {
// We rely on snapshots functionality
snapshotTokens.unshift(page || 1);
// Inform remote
snapshotKey = serializeSnapshotKey(snapshotTokens);
if (snapshots.last !== snapshotKey) snapshots.add(snapshotKey);
if (page) {
// Rely on remote prepared snapshot
usersSnapshot = getUsersSnapshot(snapshot._get(page));
inSync.value = usersSnapshot._size.gt(0);
list.set = usersSnapshot;
list.page = 1;
return;
}
inSync.value = snapshot._totalSize.map(function (value) {
if (value == null) return false;
return users._size.gtOrEq(value > pageLimit ? pageLimit : value);
});
} else {
// Assure that we have all data on board
snapshotTokens = [appName];
if (statusMap[i18n.all || 'all']) snapshotTokens.push(i18n.all || 'all');
snapshotKey = serializeSnapshotKey(snapshotTokens);
if (snapshots.last !== snapshotKey) snapshots.add(snapshotKey);
}
list.set = users;
list.page = page || 1;
inSync.value = true;
};
// Setup
// Status filter
if (keys(statusMap).length > 1) {
statusQuery = location.query.get(i18n.status || 'status');
statusQuery.on('change', update);
}
// Search filter
if (options.searchFilter) {
searchQuery = location.query.get(i18n.search || 'search');
searchQuery.on('change', update);
}
// Pagination
pageQuery = location.query.get(i18n.page || 'page');
pageQuery.on('change', update);
// Table configuration
list = new ReactiveList(statusMap[''], options.compare);
list.limit = pageLimit;
table = new ReactiveTable(document, list, columns);
table.pagination = pagination = new Pagination(pathname);
table.inSync = inSync;
inSync.on('change', function (event) {
table.table.classList[event.newValue ? 'remove' : 'add']('not-in-sync');
});
if (options.id) table.table.id = options.id;
if (options.class) table.table.className = options.class;
location.on('change', function () {
active = (this.pathname === pathname);
update();
});
active = location.pathname === pathname;
isPartial.on('change', update);
window.addEventListener('focus', update, false);
update();
return table;
};
| JavaScript | 0 | @@ -256,24 +256,78 @@
zee/plain')%0A
+ , once = require('timers-ext/once')%0A
, Observab
@@ -2464,16 +2464,21 @@
pdate =
+once(
function
@@ -5039,16 +5039,17 @@
true;%0A%09%7D
+)
;%0A%0A%09// S
|
bacab5ce35107287ecfc2856a8c6b3404eb69036 | rename package | www/CanvasCamera.js | www/CanvasCamera.js | //
// CanvasCamera.js
// PhoneGap iOS Cordova Plugin to capture Camera streaming into a HTML5 Canvas or an IMG tag.
//
// Created by Diego Araos <d@wehack.it> on 12/29/12.
//
// MIT License
cordova.define("cordova/plugin/CanvasCamera", function(require, exports, module) {
var exec = require('cordova/exec');
var CanvasCamera = function(){
var _orientation = 'landscape';
var _obj = null;
var _context = null;
var _camImage = null;
var _x = 0;
var _y = 0;
var _width = 0;
var _height = 0;
};
CanvasCamera.prototype.initialize = function(obj) {
var _this = this;
this._obj = obj;
this._context = obj.getContext("2d");
this._camImage = new Image();
this._camImage.onload = function() {
_this._context.clearRect(0, 0, _this._width, _this._height);
if (window.orientation == 90
|| window.orientation == -90)
{
_this._context.save();
// rotate 90
_this._context.translate(_this._width/2, _this._height/2);
_this._context.rotate((90 - window.orientation) *Math.PI/180);
_this._context.drawImage(_this._camImage, 0, 0, 352, 288, -_this._width/2, -_this._height/2, _this._width, _this._height);
//
_this._context.restore();
}
else
{
_this._context.save();
// rotate 90
_this._context.translate(_this._width/2, _this._height/2);
_this._context.rotate((90 - window.orientation)*Math.PI/180);
_this._context.drawImage(_this._camImage, 0, 0, 352, 288, -_this._height/2, -_this._width/2, _this._height, _this._width);
//
_this._context.restore();
}
};
// register orientation change event
window.addEventListener('orientationchange', this.doOrientationChange);
this.doOrientationChange();
};
CanvasCamera.prototype.capture = function(data) {
this._camImage.src = data;
};
CanvasCamera.prototype.start = function(options) {
cordova.exec(function(){alert('yowzer');}, false, "CanvasCamera", "startCapture", [options]);
};
CanvasCamera.prototype.setFlashMode = function(flashMode) {
cordova.exec(function(){}, function(){}, "CanvasCamera", "setFlashMode", [flashMode]);
};
CanvasCamera.prototype.setCameraPosition = function(cameraPosition) {
cordova.exec(function(){}, function(){}, "CanvasCamera", "setCameraPosition", [cameraPosition]);
};
CanvasCamera.prototype.doOrientationChange = function() {
switch(window.orientation)
{
case -90:
case 90:
this._orientation = 'landscape';
break;
default:
this._orientation = 'portrait';
break;
}
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var pixelRatio = window.devicePixelRatio || 1; /// get pixel ratio of device
this._obj.width = windowWidth;// * pixelRatio; /// resolution of canvas
this._obj.height = windowHeight;// * pixelRatio;
this._obj.style.width = windowWidth + 'px'; /// CSS size of canvas
this._obj.style.height = windowHeight + 'px';
this._x = 0;
this._y = 0;
this._width = windowWidth;
this._height = windowHeight;
};
CanvasCamera.prototype.takePicture = function(onsuccess) {
cordova.exec(onsuccess, function(){}, "CanvasCamera", "captureImage", []);
};
var myplugin = new CanvasCamera();
module.exports = myplugin;
});
var CanvasCamera = cordova.require("cordova/plugin/CanvasCamera");
var DestinationType = {
DATA_URL : 0,
FILE_URI : 1
};
var PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
var EncodingType = {
JPEG : 0,
PNG : 1
};
var CameraPosition = {
BACK : 0,
FRONT : 1
};
var CameraPosition = {
BACK : 1,
FRONT : 2
};
var FlashMode = {
OFF : 0,
ON : 1,
AUTO : 2
};
CanvasCamera.DestinationType = DestinationType;
CanvasCamera.PictureSourceType = PictureSourceType;
CanvasCamera.EncodingType = EncodingType;
CanvasCamera.CameraPosition = CameraPosition;
CanvasCamera.FlashMode = FlashMode;
module.exports = CanvasCamera;
| JavaScript | 0.000002 | @@ -2071,9 +2071,12 @@
;%0A%0A%0A
-%09
+
Canv
@@ -2094,23 +2094,21 @@
ototype.
-capture
+start
= funct
@@ -2111,20 +2111,23 @@
unction(
-data
+options
) %7B%0A
@@ -2134,33 +2134,77 @@
-this._camImage.src = data
+cordova.exec(false, false, %22CanvasCamera%22, %22startCapture%22, %5Boptions%5D)
;%0A
@@ -2201,32 +2201,34 @@
ions%5D);%0A %7D;%0A%0A
+%0A%0A
CanvasCamera
@@ -2230,37 +2230,39 @@
amera.prototype.
-start
+capture
= function(opti
@@ -2249,39 +2249,36 @@
ture = function(
-options
+data
) %7B%0A cord
@@ -2277,100 +2277,33 @@
-cordova.exec(function()%7Balert('yowzer');%7D, false, %22CanvasCamera%22, %22startCapture%22, %5Boptions%5D)
+this._camImage.src = data
;%0A
@@ -2300,35 +2300,32 @@
= data;%0A %7D;%0A%0A
-%0A%0A%0A
CanvasCamera
|
b013013ad0f2c5f971f08a94c36ce77632ce91e0 | return object | www/PhotoLibrary.js | www/PhotoLibrary.js | console.log("[PhotoLibrary] installing...");
var exec = require("cordova/exec");
module.exports = {
getRandomPhotos: function (howMany, callback) {
console.log("[PhotoLibrary] getRandomPhotos");
if (navigator.userAgent.indexOf("Android") !== -1) {
// Android done in JS (TODO)
callback(null, []);
} else {
exec(function success(result) {
callback(null, _.map(result || [], function (path) {
var obj = {};
obj.path = path;
if (path.indexOf('/var/mobile') !== -1) {
obj.cdvfile = 'cdvfile://localhost/persistent/' + path.replace(/.*Documents\//, '');
}
return obj;
}));
}, function error(err) {
callback(err, null);
}, "PhotoLibrary", "getRandomPhotos", [howMany]);
}
}
};
console.log("[PhotoLibrary] installed."); | JavaScript | 0.999999 | @@ -416,111 +416,49 @@
%09%09%09%09
-var obj = %7B%7D;%0A
+return %7B
%0A%09%09%09%09%09
-obj.
+%09
path
- =
+:
path
-;%0A%09%09%09%09%09if (path.indexOf('/var/mobile') !== -1) %7B
+,
%0A%09%09%09%09%09%09
-obj.
cdvfile
- =
+:
'cd
@@ -527,33 +527,15 @@
'')
-;
%0A%09%09%09%09%09%7D
-%0A%0A%09%09%09%09%09return obj
;%0A%09%09
|
1590375452e316361c717a0c089642d1958aa074 | use Date in key | level-revisions.js | level-revisions.js | var after = require('after')
, forkdb = require('forkdb')
, streamToJSON = require('stream-to-json')
, merge = require('./lib/merge')
, add = function (db, key, data, callback) {
var date = typeof(data.date) === 'string' ? data.date : data.date.toJSON()
, meta = { key: [ key, date ] }
, w = db.createWriteStream(meta, function (err) {
callback(err)
})
w.write(JSON.stringify(data))
w.end()
}
, read = function (db, hash, callback) {
streamToJSON(db.createReadStream(hash), function (err, obj) {
if (err) return callback(err)
obj.date = new Date(obj.date)
callback(null, obj)
})
}
, getFromRevisionKey = function (db, key, callback) {
db.heads(key, function (err, metadata) {
if (err) return callback(err)
var done = after(metadata.length, callback)
, revisions = Array(metadata.length)
metadata.forEach(function (meta, index) {
read(db, meta.hash, function (err, data) {
if (err) return done(err)
revisions[index] = data
done(null, revisions)
})
})
})
}
, flatten = function (array) {
return array.reduce(function (result, current) {
current.forEach(function (row) { result.push(row) })
return result
}, [])
}
, get = function (db, key, callback) {
var keys = db.keys({ gt: [ key, '0' ], lt: [ key, '3' ] })
, results = []
, count = 0
, bailed = false
, ended = false
, index = 0
, maybeFinish = function () {
if (bailed) return
if (count === 0 && ended) {
callback(null, merge(flatten(results)))
}
}
, onError = function (err) {
if (bailed) return
bailed = true
callback(err)
}
keys.on('data', function (meta) {
var currentIndex = index
index++
count++
getFromRevisionKey(db, meta.key, function (err, array) {
if (bailed) return
if (err) return onError(err)
results[currentIndex] = array
count--
maybeFinish()
})
})
keys.once('end', function () {
ended = true
maybeFinish()
})
keys.once('err', onError)
}
, levelRevisions = function (db) {
return {
add: function (key, data, callback) {
add(db, key, data, callback)
}
, get: function (key, callback) {
get(db, key, callback)
}
}
}
module.exports = levelRevisions | JavaScript | 0.000001 | @@ -203,53 +203,17 @@
e =
-typeof(data.date) === 'string' ? data.date :
+new Date(
data
@@ -221,16 +221,8 @@
date
-.toJSON(
)%0A
@@ -1414,11 +1414,12 @@
ey,
-'0'
+null
%5D,
@@ -1433,11 +1433,17 @@
ey,
-'3'
+undefined
%5D %7D
|
7f045264ef2389eadc38b41d74636b0e269840df | Move routing reducer last in redux store | ui/src/store/configureStore.js | ui/src/store/configureStore.js | import {createStore, applyMiddleware, compose} from 'redux'
import {combineReducers} from 'redux'
import {routerReducer, routerMiddleware} from 'react-router-redux'
import thunkMiddleware from 'redux-thunk'
import makeQueryExecuter from 'src/shared/middleware/queryExecuter'
import resizeLayout from 'src/shared/middleware/resizeLayout'
import adminReducer from 'src/admin/reducers/admin'
import sharedReducers from 'src/shared/reducers'
import dataExplorerReducers from 'src/data_explorer/reducers'
import rulesReducer from 'src/kapacitor/reducers/rules'
import dashboardUI from 'src/dashboards/reducers/ui'
import persistStateEnhancer from './persistStateEnhancer'
const rootReducer = combineReducers({
routing: routerReducer,
...sharedReducers,
...dataExplorerReducers,
admin: adminReducer,
rules: rulesReducer,
dashboardUI,
})
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
export default function configureStore(initialState, browserHistory) {
const routingMiddleware = routerMiddleware(browserHistory)
const createPersistentStore = composeEnhancers(
persistStateEnhancer(),
applyMiddleware(thunkMiddleware, routingMiddleware, makeQueryExecuter(), resizeLayout),
)(createStore)
// https://github.com/elgerlambert/redux-localstorage/issues/42
// createPersistantStore should ONLY take reducer and initialState
// any store enhancers must be added to the compose() function.
return createPersistentStore(
rootReducer,
initialState,
)
}
| JavaScript | 0 | @@ -703,34 +703,8 @@
s(%7B%0A
- routing: routerReducer,%0A
..
@@ -808,16 +808,42 @@
oardUI,%0A
+ routing: routerReducer,%0A
%7D)%0A%0Acons
|
d5b342955145fa5950507c23d800cdc4938722dc | fix tourney user mouseover badge | ui/tournament/src/view/util.js | ui/tournament/src/view/util.js | var m = require('mithril');
var partial = require('chessground').util.partial;
var boardContent = m('div.cg-board-wrap', m('div.cg-board'));
function miniGame(game) {
return m('div', [
m('a', {
key: game.id,
href: '/' + game.id + (game.color === 'white' ? '' : '/black'),
class: 'mini_board live_' + game.id + ' parse_fen is2d',
'data-color': game.color,
'data-fen': game.fen,
'data-lastmove': game.lastMove,
config: function(el, isUpdate) {
if (!isUpdate) lichess.parseFen($(el));
}
}, boardContent),
m('div.vstext.clearfix', [
m('div.left', [
game.user1.name,
m('br'),
game.user1.title ? game.user1.title + ' ' : '',
game.user1.rating
]),
m('div.right', [
game.user2.name,
m('br'),
game.user2.rating,
game.user2.title ? ' ' + game.user2.title : ''
])
])
]);
}
module.exports = {
title: function(ctrl) {
if (ctrl.data.schedule && ctrl.data.schedule.freq.indexOf('marathon') !== -1)
return m('h1.marathon_title', [
m('span.fire_trophy.marathonWinner', m('span[data-icon=\\]')),
ctrl.data.fullName
]);
return m('h1', {
class: 'text',
'data-icon': ctrl.data.isFinished ? '' : 'g'
}, [
ctrl.data.greatPlayer ? [
m('a', {
href: ctrl.data.greatPlayer.url,
target: '_blank'
}, ctrl.data.greatPlayer.name),
' tournament'
] : ctrl.data.fullName,
ctrl.data.private ? [
' ',
m('span.text[data-icon=a]', ctrl.trans('isPrivate'))
] : null
]);
},
currentPlayer: function(ctrl, pag) {
if (!ctrl.userId) return null;
return pag.currentPageResults.filter(function(p) {
return p.name.toLowerCase() === ctrl.userId;
})[0] || null;
},
player: function(p, tag) {
var perf, tag = tag || 'a';
if (p.perf > 0) perf = m('span.positive[data-icon=N]', p.perf);
else if (p.perf < 0) perf = m('span.negative[data-icon=M]', -p.perf);
var rating = p.rating + p.perf + (p.provisional ? '?' : '');
var fullName = (p.title ? p.title + ' ' : '') + p.name;
return {
tag: tag,
attrs: {
class: 'ulpt user_link' + (fullName.length > 15 ? ' long' : ''),
href: tag === 'a' ? '/@/' + p.name : null
},
children: [
fullName,
m('span.progress', [rating, perf])
]
};
},
games: function(games) {
return m('div.game_list.playing', games.map(miniGame));
},
clock: function(time) {
return function(el, isUpdate) {
if (!isUpdate) $(el).clock({
time: time
});
};
},
ratio2percent: function(r) {
return Math.round(100 * r) + '%';
}
};
| JavaScript | 0 | @@ -2178,50 +2178,22 @@
-return %7B%0A tag: tag,%0A
+var
attrs
-:
+ =
%7B%0A
-
@@ -2263,26 +2263,29 @@
'),%0A
+%7D;%0A
-href:
+attrs%5B
tag ===
@@ -2295,36 +2295,94 @@
? '
-/@/' + p.name : null%0A %7D
+href' : 'data-href'%5D = '/@/' + p.name;%0A return %7B%0A tag: tag,%0A attrs: attrs
,%0A
|
6eb24ce096230ac6eac561822fd8d73beb8a7acf | add asset wrappers to templateUrls | client/app/scripts/superdesk/directives/sdSlider.js | client/app/scripts/superdesk/directives/sdSlider.js | define(['angular'], function (angular) {
'use strict';
return angular.module('superdesk.slider.directives', []).
/**
* Slider directive
*
* Usage:
* <div sd-slider data-value="urgency" data-list="newsvalue" data-unique="value" data-invert="true" data-update="update(item)">
* </div>
*
* Params:
* @scope {Object} value - current selected value, if nothing is selected it will use min value
* @scope {Object} list - list of options
* @scope {Boolen} disabled - disable or enable slider functionality
* @scope {Object} invert - inverts min and max value
* @scope {Function} update - callback when slider value is changed
*
*/
directive('sdSlider', function () {
return {
transclude: true,
templateUrl: 'scripts/superdesk/views/sdSlider.html',
scope: {
value: '=',
list: '=',
unique: '@',
field: '@',
disabled: '=',
invert: '=',
update: '&'
},
link: function (scope, element, attrs, controller) {
scope.$watch('list', function (list) {
if (!list) {
return false;
}
var value = scope.invert ?
-Math.abs(parseInt(scope.value)) :
parseInt(scope.value),
minValue = scope.invert ?
-Math.abs(parseInt(scope.list[scope.list.length - 1][scope.unique])) :
parseInt(scope.list[0][scope.unique]),
maxValue = scope.invert ?
-Math.abs(parseInt(scope.list[0][scope.unique])) :
parseInt(scope.list[scope.list.length - 1][scope.unique]);
if (!value) {
value = minValue;
}
$('[sd-slider]').slider({
range: 'max',
min: minValue,
max: maxValue,
value: value,
disabled: scope.disabled,
create: function () {
$(this).find('.ui-slider-thumb')
.css('left', ((value - minValue) * 100) / (maxValue - minValue) + '%')
.text(scope.invert ? Math.abs(value) : value);
},
slide: function (event, ui) {
$(this).find('.ui-slider-thumb')
.css('left', ((ui.value - minValue) * 100) / (maxValue - minValue) + '%')
.text(scope.invert ? Math.abs(ui.value) : ui.value);
scope.update({
item: scope.invert ? scope.list[Math.abs(ui.value) - 1] : scope.list[ui.value] - 1,
field: scope.field
});
},
start: function () {
$(this).find('.ui-slider-thumb').addClass('ui-slider-thumb-active');
},
stop: function () {
$(this).find('.ui-slider-thumb').removeClass('ui-slider-thumb-active');
}
});
});
}
};
});
});
| JavaScript | 0.000001 | @@ -791,16 +791,26 @@
Slider',
+ %5B'asset',
functio
@@ -804,32 +804,37 @@
set', function (
+asset
) %7B%0A
@@ -909,17 +909,27 @@
rl:
-'scripts/
+asset.templateUrl('
supe
@@ -954,16 +954,17 @@
er.html'
+)
,%0A
@@ -3902,15 +3902,16 @@
%7D
+%5D
);%0A%7D);%0A
|
db404aef324eee93bb85e352eab59514c576ea0b | Remove unneccesary alert | www/js/loginPage.js | www/js/loginPage.js | //window.addEventListener('load', loadHandler);
function submitLogin() {
jQuery(document).ready(function() {
var uri = 'http://pjcdbrebuild.gear.host/api/Login';
var day = new Date();
var now = day.getTime();
var login = {
'UserName': $('#username').val(),
'Password': $('#password').val(),
'RememberMe': $('#remember').is(':checked')};
$.ajax({
type: 'POST',
dataType: 'json',
data: login,
url: uri,
success: function (data) {
window.localStorage.setItem("token", data);
window.location.href = 'splash.html';
//$.mobile.changePage('splash.html', {transition: "slideup", changeHash: false});
//$('#data').html(window.localStorage.getItem("token"));
},
error: function () {
alert("failure");
jQuery("#error").text("Username or password is incorrect");
}
});
});
}
jQuery(document).ready(function() {
if (window.localStorage.getItem("token") !== null) {
window.location.href = 'splash.html';
}
}); | JavaScript | 0.000014 | @@ -908,43 +908,8 @@
) %7B%0A
- alert(%22failure%22);%0A
@@ -982,16 +982,72 @@
rect%22);%0A
+ jQuery(%22#error%22).css(%22color%22, %22red%22);%0A
|
8123f7df8091f9091537445a8d779ccf0e0b7aca | remove log | client/assets/components/facetFields/facetFields.js | client/assets/components/facetFields/facetFields.js | (function () {
'use strict';
angular
.module('fusionSeedApp.components.facetFields', ['fusionSeedApp.services.config',
'foundation.core'
])
.directive('facetFields', facetFields);
/* @ngInject */
function facetFields() {
return {
restrict: 'EA',
templateUrl: 'assets/components/facetFields/facetFields.html',
scope: true,
controller: Controller,
controllerAs: 'vm',
bindToController: {
facetName: '@facetName'
}
};
}
Controller.$inject = ['ConfigService', 'Orwell', 'FoundationApi', '$log'];
/* @ngInject */
function Controller(ConfigService, Orwell, FoundationApi, $log) {
var vm = this;
vm.facetCounts = [];
var resultsObservable = Orwell.getObservable('queryResults');
activate();
function activate() {
resultsObservable.addObserver(function (data) {
var facetFields = data.facet_counts.facet_fields;
if (facetFields.hasOwnProperty(vm.facetName)) {
// Transform an array of values in format [‘aaaa’, 1234,’bbbb’,2345] into an array of objects.
vm.facetCounts = _.transform(facetFields[vm.facetName], function (result,
value, index) {
if (index % 2 === 1) {
result[result.length - 1] = {
title: result[result.length - 1],
amount: value,
hash: FoundationApi.generateUuid()
};
} else {
result.push(value);
}
});
}
// $log.debug('filter observer', data.facet_counts.facet_fields[vm.facetName]);
// $log.debug('filter observer', facetFields[vm.facetName]);
$log.debug('facet counts', vm.facetCounts);
});
}
}
})();
| JavaScript | 0.000001 | @@ -570,16 +570,8 @@
Api'
-, '$log'
%5D;%0A%0A
@@ -650,14 +650,8 @@
nApi
-, $log
) %7B%0A
@@ -1514,217 +1514,8 @@
%7D%0A
- // $log.debug('filter observer', data.facet_counts.facet_fields%5Bvm.facetName%5D);%0A // $log.debug('filter observer', facetFields%5Bvm.facetName%5D);%0A $log.debug('facet counts', vm.facetCounts);%0A
|
09ce017cd54723957b7de2c51ac9c263ec82b925 | fix android detection | modules/CustomButton/resources/customButton.js | modules/CustomButton/resources/customButton.js | ( function( mw, $ ) {"use strict";
mw.PluginManager.add( 'customButton', mw.KBaseComponent.extend({
//indicates we were explicitly asked to show the button (will be used when re-enabling the button)
shouldShow : false,
isDisabled: false,
defaultConfig: {
'parent': 'videoHolder',
'order': 20
},
setup: function() {
this.addBindings();
},
addBindings: function() {
var _this = this;
this.bind('onpause onRemovePlayerSpinner', function(){
if( !_this.embedPlayer.isPlaying() && !_this.embedPlayer.isInSequence() ){
_this.show();
}
});
this.bind('playing AdSupport_StartAdPlayback onAddPlayerSpinner onHideControlBar', function(){
_this.hide(true);
});
this.bind('onPlayerStateChange', function(e, newState, oldState){
if( newState == 'load' ){
_this.hide(true);
}
if( newState == 'pause' && _this.getPlayer().isPauseLoading ) {
_this.hide();
}
if (newState == 'start') {
_this.hide(true);
}
if (newState == 'play') {
_this.hide(true);
}
});
},
show: function(){
if ( !this.isDisabled ) {
this.getComponent().show();
}
this.shouldShow = true;
},
hide: function( force ){
this.hideComponent( force );
this.shouldShow = false;
},
hideComponent: function( force ) {
if( force ) {
this.getComponent().hide();
}
},
clickButton: function( event ){
event.preventDefault();
event.stopPropagation();
this.getPlayer().sendNotification('custom_button_clicked', this.embedPlayer.currentTime);
},
onEnable: function(){
this.isDisabled = false;
if ( this.shouldShow ) {
this.getComponent().show();
}
},
onDisable: function(){
this.isDisabled = true;
this.hideComponent();
},
getComponent: function() {
var _this = this;
var eventName = 'click';
if (mw.isMobileDevice()){
eventName = 'touchstart';
}
if( !this.$el ) {
this.$el = $( '<a />' )
.attr( {
'tabindex': '-1',
'href' : '#',
'title' : gM( 'mwe-customButton-label' ),
'class' : this.getCssClass()
} )
.hide()
// Add click hook:
.on(eventName, function(e) {
_this.clickButton(e);
} );
}
return this.$el;
}
})
);
} )( window.mw, window.jQuery );
| JavaScript | 0.000005 | @@ -1914,20 +1914,15 @@
w.is
-MobileDevice
+Android
())%7B
|
fc1950eaca596b8b4db7ac1863fdff02708250bf | add some initial models to dev mode | packages/models/tests/dummy/cardstack/seeds/development/ephemeral.js | packages/models/tests/dummy/cardstack/seeds/development/ephemeral.js | /* eslint-env node */
module.exports = [
{
type: 'plugin-configs',
id: '@cardstack/ephemeral',
attributes: {
module: '@cardstack/ephemeral'
}
},
{
type: 'data-sources',
id: 'default',
attributes: {
'source-type': '@cardstack/ephemeral'
}
},
{
type: 'plugin-configs',
id: '@cardstack/hub',
attributes: {
module: '@cardstack/hub'
},
relationships: {
'default-data-source': {
data: { type: 'data-sources', id: 'default' }
}
}
}
];
| JavaScript | 0 | @@ -14,16 +14,578 @@
node */
+%0Aconst JSONAPIFactory = require('@cardstack/test-support/jsonapi-factory');%0A%0Afunction initialModels() %7B%0A let initial = new JSONAPIFactory();%0A%0A initial.addResource('content-types', 'posts')%0A .withRelated('fields', %5B%0A initial.addResource('fields', 'title').withAttributes(%7B%0A fieldType: '@cardstack/core-types::string'%0A %7D)%0A %5D);%0A initial.addResource('posts', '1')%0A .withAttributes(%7B%0A title: 'hello world'%0A %7D);%0A initial.addResource('posts', '2')%0A .withAttributes(%7B%0A title: 'second'%0A %7D);%0A return initial.getModels();%0A%7D
%0A%0Amodule
@@ -829,32 +829,96 @@
stack/ephemeral'
+,%0A params: %7B%0A initialModels: initialModels()%0A %7D
%0A %7D%0A %7D,%0A %7B%0A
|
9f4ae415e2bd61e0d168f236c5be911f96f8696b | Enable ES7 spread transform when using --harmony | vendor/fbtransform/visitors.js | vendor/fbtransform/visitors.js | /*global exports:true*/
var es6ArrowFunctions = require('jstransform/visitors/es6-arrow-function-visitors');
var es6Classes = require('jstransform/visitors/es6-class-visitors');
var es6Destructuring = require('jstransform/visitors/es6-destructuring-visitors');
var es6ObjectConciseMethod = require('jstransform/visitors/es6-object-concise-method-visitors');
var es6ObjectShortNotation = require('jstransform/visitors/es6-object-short-notation-visitors');
var es6RestParameters = require('jstransform/visitors/es6-rest-param-visitors');
var es6Templates = require('jstransform/visitors/es6-template-visitors');
var react = require('./transforms/react');
var reactDisplayName = require('./transforms/reactDisplayName');
/**
* Map from transformName => orderedListOfVisitors.
*/
var transformVisitors = {
'es6-arrow-functions': es6ArrowFunctions.visitorList,
'es6-classes': es6Classes.visitorList,
'es6-destructuring': es6Destructuring.visitorList,
'es6-object-concise-method': es6ObjectConciseMethod.visitorList,
'es6-object-short-notation': es6ObjectShortNotation.visitorList,
'es6-rest-params': es6RestParameters.visitorList,
'es6-templates': es6Templates.visitorList,
'react': react.visitorList.concat(reactDisplayName.visitorList)
};
/**
* Specifies the order in which each transform should run.
*/
var transformRunOrder = [
'es6-arrow-functions',
'es6-object-concise-method',
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'es6-destructuring',
'react'
];
/**
* Given a list of transform names, return the ordered list of visitors to be
* passed to the transform() function.
*
* @param {array?} excludes
* @return {array}
*/
function getAllVisitors(excludes) {
var ret = [];
for (var i = 0, il = transformRunOrder.length; i < il; i++) {
if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) {
ret = ret.concat(transformVisitors[transformRunOrder[i]]);
}
}
return ret;
}
exports.getAllVisitors = getAllVisitors;
exports.transformVisitors = transformVisitors;
| JavaScript | 0.000001 | @@ -599,24 +599,110 @@
visitors');%0A
+var es7SpreadProperty = require('jstransform/visitors/es7-spread-property-visitors');%0A
var react =
@@ -1265,16 +1265,72 @@
orList,%0A
+ 'es7-spread-property': es7SpreadProperty.visitorList,%0A
'react
@@ -1651,16 +1651,41 @@
uring',%0A
+ 'es7-spread-property',%0A
'react
|
0d361adcfd121acc740c01ac681d5fbeb76d110b | Allow hiding main window with Cmd+1 | app/main.js | app/main.js | 'use strict'
// Handle the Squirrel.Windows install madnesss
if (require('electron-squirrel-startup')) return
const electron = require('electron')
const contextMenu = require('./context-menu')
const autoUpdater = require('./auto-updater')
const dockMenu = require('./dock-menu')
const errorHandlers = require('./error-handlers')
const mainMenu = require('./menu')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const globalShortcut = electron.globalShortcut
const Menu = electron.Menu
const windowState = require('electron-window-state')
const SoundCloud = require('./soundcloud')
const windowOpenPolicy = require('./window-open-policy')
var mainWindow = null
var aboutWindow = null
const argv = require('optimist')
.default('auto-updater', true)
.default('quit-after-last-window', process.platform != 'darwin')
.argv
const baseUrl = argv['base-url']
const developerTools = argv['developer-tools']
const profile = argv['profile']
const quitAfterLastWindow = argv['quit-after-last-window']
const useAutoUpdater = argv['auto-updater']
const userData = argv['user-data-path']
if (userData)
app.setPath('userData', userData)
else if (profile)
app.setPath('userData', app.getPath('userData') + ' ' + profile)
var quitting = false
app.on('before-quit', function() {
quitting = true
})
const shouldQuit = app.makeSingleInstance(() => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore()
mainWindow.show()
mainWindow.focus()
}
})
if (shouldQuit) app.quit()
if (useAutoUpdater) autoUpdater()
windowOpenPolicy(app)
app.on('activate', () => {
if (mainWindow) mainWindow.show()
})
app.on('ready', function() {
const menu = mainMenu({ developerTools })
Menu.setApplicationMenu(menu)
const mainWindowState = windowState({
defaultWidth: 1024,
defaultHeight: 640
})
mainWindow = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
minWidth: 640,
minHeight: 320,
webPreferences: {
nodeIntegration: false,
preload: `${__dirname}/preload.js`
}
})
const soundcloud = new SoundCloud(mainWindow)
contextMenu(mainWindow, soundcloud)
errorHandlers(mainWindow)
if (process.platform == 'darwin')
dockMenu(soundcloud)
mainWindowState.manage(mainWindow)
mainWindow.on('close', (event) => {
// Due to (probably) a bug in Spectron this prevents quitting
// the app in tests:
// https://github.com/electron/spectron/issues/137
if (!quitting && !quitAfterLastWindow) {
event.preventDefault()
mainWindow.hide()
}
})
mainWindow.on('closed', function() {
if (process.platform !== 'darwin')
app.quit()
mainWindow = null
})
globalShortcut.register('MediaPlayPause', () => {
soundcloud.playPause()
})
globalShortcut.register('MediaNextTrack', () => {
soundcloud.nextTrack()
})
globalShortcut.register('MediaPreviousTrack', () => {
soundcloud.previousTrack()
})
menu.events.on('playPause', () => {
soundcloud.playPause()
})
menu.events.on('nextTrack', () => {
soundcloud.nextTrack()
})
menu.events.on('previousTrack', () => {
soundcloud.previousTrack()
})
menu.events.on('home', () => {
soundcloud.goHome()
})
menu.events.on('back', () => {
soundcloud.goBack()
})
menu.events.on('forward', () => {
soundcloud.goForward()
})
menu.events.on('main-window', () => {
mainWindow.show()
})
menu.events.on('about', () => {
showAbout()
})
require('electron').powerMonitor.on('suspend', () => {
soundcloud.isPlaying().then(isPlaying => {
if (isPlaying)
soundcloud.playPause()
})
})
soundcloud.on('play', (title, subtitle) => {
mainWindow.webContents.send('notification', title, subtitle)
})
mainWindow.webContents.once('did-start-loading', () => {
mainWindow.setTitle('Loading soundcloud.com...')
})
mainWindow.loadURL(getUrl())
})
function getUrl() {
if (baseUrl)
return baseUrl
else
return 'https://soundcloud.com'
}
function showAbout() {
if (aboutWindow)
aboutWindow.show()
else {
aboutWindow = new BrowserWindow({
fullscreen: false,
fullscreenable: false,
height: 520,
maximizable: false,
resizable: false,
show: false,
skipTaskbar: true,
width: 385,
modal: true,
parent: mainWindow
})
aboutWindow.setMenu(null)
aboutWindow.once('ready-to-show', () => {
aboutWindow.show()
})
aboutWindow.on('close', () => {
aboutWindow = null
})
aboutWindow.loadURL(`file://${__dirname}/about.html`)
}
}
| JavaScript | 0.000003 | @@ -3489,32 +3489,99 @@
indow', () =%3E %7B%0A
+ if (mainWindow.isVisible())%0A mainWindow.hide()%0A else%0A
mainWindow.s
|
2b609725fae135447147d7087fe87322af4db0c3 | Remove unused prop | packages/node_modules/@ciscospark/react-redux-spark/src/component.js | packages/node_modules/@ciscospark/react-redux-spark/src/component.js | import {Component} from 'react';
import PropTypes from 'prop-types';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {
updateSparkStatus,
registerDevice,
storeSparkInstance
} from './actions';
import createSpark from './spark';
const metricName = {
SPARK_AUTHENTICATED: {
resource: 'spark',
event: 'authentication',
action: 'authenticated'
},
DEVICE_REGISTERED: {
resource: 'device',
event: 'registration',
action: 'registered'
}
};
const injectedPropTypes = {
mercury: PropTypes.object.isRequired,
metrics: PropTypes.object.isRequired,
spark: PropTypes.object.isRequired,
storeSparkInstance: PropTypes.func.isRequired,
updateSparkStatus: PropTypes.func.isRequired
};
const propTypes = {
accessToken: PropTypes.string.isRequired,
...injectedPropTypes
};
class SparkComponent extends Component {
static setupDevice(spark, props) {
const {
authenticated,
registered,
registerError,
registering
} = props.spark.get('status').toJS();
if (authenticated && !registered && !registering && !registerError) {
props.registerDevice(spark);
}
}
componentDidMount() {
const {props} = this;
const {
accessToken,
metrics
} = this.props;
let spark = props.spark.get('spark');
if (!spark) {
spark = createSpark(accessToken, this.props);
props.storeSparkInstance(spark);
}
spark.listenToAndRun(spark, 'change:canAuthorize', () => {
if (metrics && spark.canAuthorize) {
metrics.sendElapsedTime(metricName.SPARK_AUTHENTICATED, spark);
}
props.updateSparkStatus({authenticated: spark.canAuthorize});
});
spark.listenToAndRun(spark, 'change:isAuthenticating', () => {
props.updateSparkStatus({authenticating: spark.isAuthenticating});
});
spark.listenToAndRun(spark.internal.device, 'change:registered', () => {
if (metrics && spark.internal.device.registered) {
metrics.sendElapsedTime(metricName.DEVICE_REGISTERED, spark);
}
props.updateSparkStatus({registered: spark.internal.device.registered});
});
SparkComponent.setupDevice(spark, props);
}
componentWillReceiveProps(nextProps) {
const spark = nextProps.spark.get('spark');
SparkComponent.setupDevice(spark, nextProps);
}
shouldComponentUpdate(nextProps) {
const {props} = this;
return nextProps.spark !== props.spark;
}
render() {
return null;
}
}
SparkComponent.propTypes = propTypes;
export default connect(
(state) => ({
mercury: state.mercury,
spark: state.spark
}),
(dispatch) => bindActionCreators({
updateSparkStatus,
registerDevice,
storeSparkInstance
}, dispatch)
)(SparkComponent);
| JavaScript | 0.000005 | @@ -537,48 +537,8 @@
= %7B%0A
- mercury: PropTypes.object.isRequired,%0A
me
@@ -2547,36 +2547,8 @@
(%7B%0A
- mercury: state.mercury,%0A
|
9c9ad0e4061bb9aa75d863f6a6633233c7fbd626 | support before save and close | src/toolbar/InsertModalFooter.js | src/toolbar/InsertModalFooter.js | import React, { PropTypes } from 'react';
import Const from '../Const';
const InsertModalFooter = ({
saveBtnText,
closeBtnText,
closeBtnContextual,
saveBtnContextual,
closeBtnClass,
saveBtnClass,
onModalClose,
onSave
}) =>
<div>
<button
type='button'
className={ `btn ${closeBtnContextual} ${closeBtnClass}` }
onClick={ onModalClose }>{ closeBtnText }</button>
<button
type='button'
className={ `btn ${saveBtnContextual} ${saveBtnClass}` }
onClick={ onSave }>{ saveBtnText }</button>
</div>;
InsertModalFooter.propTypes = {
saveBtnText: PropTypes.string,
closeBtnText: PropTypes.string,
closeBtnContextual: PropTypes.string,
saveBtnContextual: PropTypes.string,
closeBtnClass: PropTypes.string,
saveBtnClass: PropTypes.string,
onSave: PropTypes.func,
onModalClose: PropTypes.func
};
InsertModalFooter.defaultProps = {
saveBtnText: Const.SAVE_BTN_TEXT,
closeBtnText: Const.CLOSE_BTN_TEXT,
closeBtnContextual: 'btn-default',
saveBtnContextual: 'btn-primary',
closeBtnClass: '',
saveBtnClass: '',
onSave: PropTypes.func,
onModalClose: PropTypes.func
};
export default InsertModalFooter;
| JavaScript | 0 | @@ -8,16 +8,27 @@
React, %7B
+ Component,
PropTyp
@@ -80,37 +80,357 @@
t';%0A
-const InsertModalFooter = (%7B%0A
+%0Aclass InsertModalFooter extends Component %7B%0A%0A handleCloseBtnClick = e =%3E %7B%0A const %7B beforeClose, onModalClose %7D = this.props;%0A beforeClose && beforeClose(e);%0A onModalClose();%0A %7D%0A%0A handleSaveBtnClick = e =%3E %7B%0A const %7B beforeSave, onSave %7D = this.props;%0A beforeSave && beforeSave(e);%0A onSave();%0A %7D%0A%0A render() %7B%0A const %7B%0A
sa
@@ -432,32 +432,36 @@
saveBtnText,%0A
+
closeBtnText,%0A
@@ -460,16 +460,20 @@
tnText,%0A
+
closeB
@@ -486,16 +486,20 @@
extual,%0A
+
saveBt
@@ -511,16 +511,20 @@
extual,%0A
+
closeB
@@ -532,16 +532,20 @@
nClass,%0A
+
saveBt
@@ -554,41 +554,47 @@
lass
-,
%0A
-onModalClose,%0A onSave%0A%7D) =%3E%0A
+ %7D = this.props;%0A%0A return (%0A
%3Cd
@@ -597,32 +597,36 @@
%3Cdiv%3E%0A
+
+
%3Cbutton%0A
type='
@@ -605,32 +605,36 @@
%3Cbutton%0A
+
type='butt
@@ -635,32 +635,36 @@
='button'%0A
+
+
className=%7B %60btn
@@ -704,32 +704,36 @@
Class%7D%60 %7D%0A
+
onClick=%7B onModa
@@ -726,28 +726,40 @@
Click=%7B
-onModalClose
+this.handleCloseBtnClick
%7D%3E%7B clo
@@ -779,16 +779,20 @@
button%3E%0A
+
%3Cbut
@@ -797,24 +797,28 @@
utton%0A
+
+
type='button
@@ -815,24 +815,28 @@
pe='button'%0A
+
classN
@@ -888,24 +888,28 @@
s%7D%60 %7D%0A
+
onClick=%7B on
@@ -906,22 +906,39 @@
Click=%7B
-onSave
+this.handleSaveBtnClick
%7D%3E%7B sav
@@ -961,16 +961,20 @@
on%3E%0A
+
%3C/div%3E
;%0A%0AI
@@ -969,18 +969,29 @@
%3C/div%3E
-;
%0A
+ );%0A %7D%0A%7D
%0AInsertM
@@ -1230,16 +1230,77 @@
string,%0A
+ beforeClose: PropTypes.func,%0A beforeSave: PropTypes.func,%0A
onSave
@@ -1580,62 +1580,55 @@
,%0A
-onSave: PropTypes.func,%0A onModalClose: PropTypes.func
+beforeClose: undefined,%0A beforeSave: undefined
%0A%7D;%0A
|
1bd976c7b4a5662bea03b8135688e81a6d6a21a9 | fix bug: transition cannot found el | src/view/element-own-attached.js | src/view/element-own-attached.js | /**
* @file 完成元素 attached 后的行为
* @author errorrik(errorrik@gmail.com)
*/
var bind = require('../util/bind');
var empty = require('../util/empty');
var isBrowser = require('../browser/is-browser');
var trigger = require('../browser/trigger');
var NodeType = require('./node-type');
var elementGetTransition = require('./element-get-transition');
var eventDeclarationListener = require('./event-declaration-listener');
var getPropHandler = require('./get-prop-handler');
var warnEventListenMethod = require('./warn-event-listen-method');
/**
* 双绑输入框CompositionEnd事件监听函数
*
* @inner
*/
function inputOnCompositionEnd() {
if (!this.composing) {
return;
}
this.composing = 0;
trigger(this, 'input');
}
/**
* 双绑输入框CompositionStart事件监听函数
*
* @inner
*/
function inputOnCompositionStart() {
this.composing = 1;
}
function xPropOutputer(xProp, data) {
getPropHandler(this.tagName, xProp.name).output(this, xProp, data);
}
function inputXPropOutputer(element, xProp, data) {
var outputer = bind(xPropOutputer, element, xProp, data);
return function (e) {
if (!this.composing) {
outputer(e);
}
};
}
/**
* 完成元素 attached 后的行为
*
* @param {Object} element 元素节点
*/
function elementOwnAttached() {
this._toPhase('created');
var isComponent = this.nodeType === NodeType.CMPT;
var data = isComponent ? this.data : this.scope;
/* eslint-disable no-redeclare */
// 处理自身变化时双向绑定的逻辑
var xProps = this.aNode.hotspot.xProps;
for (var i = 0, l = xProps.length; i < l; i++) {
var el = this.el;
var xProp = xProps[i];
switch (xProp.name) {
case 'value':
switch (this.tagName) {
case 'input':
case 'textarea':
if (isBrowser && window.CompositionEvent) {
this._onEl('change', inputOnCompositionEnd);
this._onEl('compositionstart', inputOnCompositionStart);
this._onEl('compositionend', inputOnCompositionEnd);
}
this._onEl(
('oninput' in el) ? 'input' : 'propertychange',
inputXPropOutputer(this, xProp, data)
);
break;
case 'select':
this._onEl('change', bind(xPropOutputer, this, xProp, data));
break;
}
break;
case 'checked':
switch (this.tagName) {
case 'input':
switch (el.type) {
case 'checkbox':
case 'radio':
this._onEl('click', bind(xPropOutputer, this, xProp, data));
}
}
break;
}
}
// bind events
var events = isComponent
? this.aNode.events.concat(this.nativeEvents)
: this.aNode.events;
for (var i = 0, l = events.length; i < l; i++) {
var eventBind = events[i];
var owner = isComponent ? this : this.owner;
// 判断是否是nativeEvent,下面的warn方法和事件绑定都需要
// 依此指定eventBind.expr.name位于owner还是owner.owner上
if (eventBind.modifier.native) {
owner = owner.owner;
data = this.scope || owner.data;
}
// #[begin] error
warnEventListenMethod(eventBind, owner);
// #[end]
this._onEl(
eventBind.name,
bind(
eventDeclarationListener,
owner,
eventBind,
0,
data
),
eventBind.modifier.capture
);
}
this._toPhase('attached');
if (this._isInitFromEl) {
this._isInitFromEl = false;
}
else {
var transition = elementGetTransition(this);
if (transition && transition.enter) {
transition.enter(el, empty);
}
}
}
exports = module.exports = elementOwnAttached;
| JavaScript | 0 | @@ -1570,34 +1570,8 @@
) %7B%0A
- var el = this.el;%0A
@@ -2177,16 +2177,21 @@
put' in
+this.
el) ? 'i
@@ -2670,16 +2670,21 @@
switch (
+this.
el.type)
@@ -4064,16 +4064,21 @@
n.enter(
+this.
el, empt
|
b28a111dd27072708b99f22949eef5766f03ac27 | Fix updating collections in root select widget | clients/web/src/views/widgets/RootSelectorWidget.js | clients/web/src/views/widgets/RootSelectorWidget.js | import _ from 'underscore';
import CollectionCollection from 'girder/collections/CollectionCollection';
import UserCollection from 'girder/collections/UserCollection';
import View from 'girder/views/View';
import events from 'girder/events';
import { getCurrentUser } from 'girder/auth';
import RootSelectorWidgetTemplate from 'girder/templates/widgets/rootSelectorWidget.pug';
/**
* This widget creates a dropdown box allowing the user to select
* "root" paths for a hierarchy widget.
*
* @emits RootSelectorWidget#g:selected The selected element changed
* @type {object}
* @property {Model|null} root The selected root model
* @property {string|null} group The selection group
*
* @emits RootSelectorWidget#g:group A collection group was updated
* @type {object}
* @property {Collection} collection
*/
var RootSelectorWidget = View.extend({
events: {
'change #g-root-selector': '_selectRoot'
},
/**
* Initialize the widget. The caller can configure the list of items
* that are present in the select box. If no values are given, then
* appropriate rest calls will be made to fetch models automatically.
*
* Additional categories of roots can be provided via an object mapping,
* for example:
*
* {
* friends: new UserCollection([...]),
* saved: new FolderCollection([...])
* }
*
* Only a single page of results are displayed for each collection provided.
* The default maximum number can be configured, but for more sophisticated
* behavior, the caller should act on the collection objects directly and
* rerender.
*
* @param {object} settings
* @param {UserModel} [settings.home=getCurrentUser()]
* @param {object} [settings.groups] Additional collection groups to add
* @param {number} [settings.pageLimit=25] The maximum number of models to fetch
* @param {Model} [settings.selected] The default/current selection
* @param {string[]} [settings.display=['Home', 'Collections', 'Users'] Display order
* @param {boolean} [settings.reset=true] Always fetch from offset 0
*/
initialize: function (settings) {
settings = settings || {};
this.pageLimit = settings.pageLimit || 25;
// collections are provided for public access here
this.groups = {
'Collections': new CollectionCollection(),
'Users': new UserCollection()
};
this.groups.Collections.pageLimit = settings.pageLimit;
this.groups.Users.pageLimit = settings.pageLimit;
this.groups.Users.sortField = 'login';
// override default selection groups
_.extend(this.groups, settings.groups);
// attach collection change events
_.each(this.groups, _.bind(function (group) {
this.listenTo(group, 'g:changed', this._updateGroup);
}, this));
// possible values that determine rendered behavior for "Home":
// - model: show this model as Home
// - undefined|null: use getCurrentUser()
this.home = settings.home;
// we need to fetch the collections and rerender on login
this.listenTo(events, 'g:login', this.fetch);
this.selected = settings.selected;
this.display = settings.display || ['Home', 'Collections', 'Users'];
this.fetch();
},
render: function () {
this._home = this.home || getCurrentUser();
this.$el.html(
RootSelectorWidgetTemplate({
home: this._home,
groups: this.groups,
display: this.display,
selected: this.selected,
format: this._formatName
})
);
},
/**
* Called when the user selects a new item. Resolves the
* model object from the DOM and triggers the g:selected event.
*/
_selectRoot: function (evt) {
var sel = this.$(':selected');
var id = sel.val();
var group = sel.data('group') || null;
this.selected = null;
if (_.has(this.groups, group)) {
this.selected = this.groups[group].get(id);
} else if (this._home && this._home.id === id) {
this.selected = this._home;
}
this.trigger('g:selected', {
root: this.selected,
group: group
});
},
/**
* Called when a collection is modified... rerenders the view.
*/
_updateGroup: function (collection) {
this.trigger('g:group', {
collection: collection
});
this.render();
},
/**
* Return a string to display for the given model.
*/
_formatName: function (model) {
var name = model.id;
switch (model.get('_modelType')) {
case 'user':
name = model.get('login');
break;
case 'folder':
case 'collection':
name = model.get('name');
break;
}
return name;
},
/**
* Fetch all collections from the server.
*/
fetch: function () {
var reset = this.reset;
_.each(this.groups, function (collection) {
collection.fetch(null, reset);
});
}
});
export default RootSelectorWidget;
| JavaScript | 0 | @@ -2799,32 +2799,16 @@
ups,
- _.bind(function
(group)
%7B%0A
@@ -2803,16 +2803,19 @@
(group)
+ =%3E
%7B%0A
@@ -2859,44 +2859,83 @@
d',
-this._updateGroup);%0A %7D, this)
+() =%3E %7B%0A this._updateGroup(group);%0A %7D);%0A %7D
);%0A%0A
|
99dd3480e96c362f09ddbbe00d59338844cb8a43 | Fix progress bar width... | clients/web/src/views/widgets/TaskProgressWidget.js | clients/web/src/views/widgets/TaskProgressWidget.js | /**
* This widget renders the state of a progress notification.
*/
girder.views.TaskProgressWidget = Backbone.View.extend({
initialize: function (settings) {
this.progress = settings.progress;
},
render: function () {
var width = '0', barClass = [], progressClass = [];
if (this.progress.data.state === 'active') {
if (this.progress.data.total <= 0) {
width = '100%';
barClass.push('progress-bar-warning');
progressClass.push('progress-striped', 'active');
} else {
width = Math.round(
this.progress.data.current / this.progress.data.total) + '%';
}
} else if (this.progress.data.state === 'success') {
width = '100%';
barClass.push('progress-bar-success');
} else if (this.progress.data.state === 'error') {
width = '100%';
barClass.push('progress-bar-danger');
}
this.$el.html(jade.templates.taskProgress({
progress: this.progress,
width: width,
barClass: barClass.join(' '),
progressClass: progressClass.join(' ')
}));
return this;
},
update: function (progress) {
this.progress = progress;
this.render();
}
});
| JavaScript | 0 | @@ -607,16 +607,21 @@
h.round(
+100 *
%0A
|
7c3a417bece8f305549582e3051ba6d4c7f73b97 | Add comment | packages/veritone-react-common/src/components/FormBuilder/helpers.js | packages/veritone-react-common/src/components/FormBuilder/helpers.js | import _ from 'lodash';
export function errorChain({ data, settings }) {
return function getError(funcs) {
if (_.isFunction(funcs)) {
return funcs({ data, settings });
}
if (_.isArray(funcs)) {
for (let i = 0; i < funcs.length; i++) {
const error = funcs[i]({ data, settings });
if (!_.isEmpty(error)) {
return error;
}
}
}
}
}
export function validateEmail({ data, settings }) {
const { name } = settings;
const re = /.+@.+\..+/;
return re.test(String(data[name]).toLowerCase()) ? '' : 'Please enter a valid email address';
}
export function validateEmpty({ data, settings }) {
const { name, required } = settings;
if (!required) {
return;
}
return _.isEmpty(data[name]) ? `${name.toUpperCase()} is required` : '';
}
export function validateRange({ data, settings }) {
const { name, min, max } = settings;
if (_.isNumber(min) && _.isNumber(max) && (data[name] < min || data[name] > max)) {
return `${name} must be between ${min} and ${max}`;
}
if (_.isNumber(min) && data[name] < min) {
return `Minimum required ${name} is ${min}`;
}
if (_.isNumber(max) && data[name] > max) {
return `Maximum ${name} can be ${max}`;
}
return '';
}
| JavaScript | 0 | @@ -18,16 +18,297 @@
dash';%0A%0A
+// errorChain function which get all data and configuration from form%0A// it return a function which can get a function or an array of functions which%0A// recieve data and settings and return error text.%0A// error validation can be chained mean we can compose many validate functions%0A
export f
@@ -644,16 +644,38 @@
n error;
+ // Return first error
%0A
|
8ba89235d5794e81a720e989724a905bf8087885 | Fail the level if we run out of instructions | game/static/game/js/level.js | game/static/game/js/level.js | 'use strict';
var ocargo = ocargo || {};
ocargo.Level = function(map, van, ui) {
this.map = map;
this.van = van;
this.ui = ui;
this.correct = 0;
}
ocargo.Level.prototype.play = function(program){
// $.post('/game/submit', JSON.stringify(program.stack));
program.startBlock.select();
var stepFunction = stepper(this);
program.stepCallback = stepFunction;
this.program = program;
setTimeout(stepFunction, 500);
};
ocargo.Level.prototype.step = function(){
if(this.program.canStep()) {
this.program.step(this);
} else {
if (this.van.currentNode === this.map.destination && !this.program.isTerminated) {
console.debug('You win!');
window.alert('You win!');
}
}
};
function stepper(level){
return function(){
try {
if(level.program.canStep()) {
level.correct = level.correct + 1;
level.program.step(level);
} else {
if (level.van.currentNode === level.map.destination && !level.program.isTerminated) {
console.debug('You win!');
ocargo.sound.win();
window.alert('You win!');
}
}
} catch (error) {
level.program.terminate();
}
};
}
function InstructionHandler(level){
this.level = level;
}
InstructionHandler.prototype.handleInstruction = function(instruction, program){
console.debug('Calculating next node for instruction ' + instruction.name);
var nextNode = instruction.getNextNode(this.level.van.previousNode, this.level.van.currentNode);
if (!nextNode) {
var n = this.level.correct - 1;
var total = this.level.map.nodes.length - 2;
console.debug('Oh dear! :(');
ocargo.sound.failure();
ocargo.blocklyTest.blink();
window.alert("Oh dear! :( Your first " + n + " instructions were right."
+ " Click 'Clear Incorrect' to remove the incorrect blocks and try again!");
program.terminate();
return; //TODO: animate the crash
}
this.level.van.move(nextNode, instruction, program.stepCallback);
};
| JavaScript | 0.998117 | @@ -661,32 +661,110 @@
ated) %7B%0A
+ this.win();%0A %7D%0A %7D%0A%7D;%0A%0Aocargo.Level.prototype.win = function() %7B%0A
console.debu
@@ -778,28 +778,44 @@
win!');%0A
-
+ocargo.sound.win();%0A
window.a
@@ -832,31 +832,150 @@
win!');%0A
- %7D%0A %7D
+%7D;%0A%0Aocargo.Level.prototype.fail = function(msg) %7B%0A console.debug('Oh dear! :(');%0A ocargo.sound.failure();%0A window.alert(msg);
%0A%7D;%0A%0Afun
@@ -1177,14 +1177,20 @@
-%09
+
-%09
+
if (
@@ -1271,25 +1271,26 @@
ated) %7B%0A
-%09
+
@@ -1293,32 +1293,20 @@
-console.debug('You win!'
+ level.win(
);%0A
@@ -1324,36 +1324,94 @@
- ocargo.sound.win(
+%7D else %7B%0A level.fail(%22Oh dear! :( You ran out of instructions!%22
);%0A
+%0A
@@ -1430,39 +1430,37 @@
-window.alert('You win!'
+program.terminate(
);%0A
-%09
+
@@ -1469,17 +1469,21 @@
%7D%0A
-%09
+
%7D%0A
@@ -1999,78 +1999,8 @@
2;%0A
- console.debug('Oh dear! :(');%0A ocargo.sound.failure();%0A
@@ -2040,28 +2040,31 @@
-window.alert
+this.level.fail
(%22Oh dea
@@ -2115,17 +2115,16 @@
right.%22
-
%0A
|
9b1ff1cc48e86dde05ac4ced8f08502a4e484c1e | fix another typo from moses | mvp_apps/mvp_deaths/views/under5_deaths/map.js | mvp_apps/mvp_deaths/views/under5_deaths/map.js | function (doc) {
// !code util/mvp.js
if (isChildCloseForm(doc) ||
isPregnancyCloseForm(doc)) {
var indicators = get_indicators(doc),
closed_date = new Date(doc.form.meta.timeEnd),
indicator_keys = new Array(),
close_reason = "",
termination_reason = "";
if(indicators.date_of_death && indicators.date_of_death.value)
report_date = new Date(indicators.date_of_death.value);
}
else{
report_date = closed_date;
}
if (indicators.close_reason && indicators.close_reason.value) {
close_reason = indicators.close_reason.value;
}
if (indicators.termination_reason && indicators.termination_reason.value) {
termination_reason = indicators.termination_reason.value;
}
if (isChildCloseForm(doc)
&& close_reason === 'death'
&& (indicators.date_of_death && indicators.date_of_death.value)
&& (indicators.child_dob && indicators.child_dob.value)) {
var date_of_death = new Date(indicators.date_of_death.value),
child_dob = new Date(indicators.child_dob.value);
if (child_dob <= date_of_death) {
var difference = date_of_death.getTime() - child_dob.getTime();
if (difference <= 28*MS_IN_DAY) {
indicator_keys.push("neonatal_death");
}
if (difference < 330*MS_IN_DAY) {
indicator_keys.push("infant_death")
}
if (difference < 1825*MS_IN_DAY) {
indicator_keys.push("under5_death")
}
}
}
/*
if (isPregnancyCloseForm(doc)
&& termination_reason === 'stillbirth') {
indicator_keys.push("neonatal_death");
indicator_keys.push("infant_death");
indicator_keys.push("under5_death");
}
*/
emit_standard(doc, report_date, indicator_keys, []);
}
}
| JavaScript | 0.999933 | @@ -331,16 +331,17 @@
if
+
(indicat
@@ -384,32 +384,34 @@
_of_death.value)
+ %7B
%0A rep
|
bd16b0456bdc9e7ff61e7cebc3da197bbc5c0b04 | patch for issue #291 | content/overlays/calendar-event-dialog-attendees.js | content/overlays/calendar-event-dialog-attendees.js | /*
* This file is part of TbSync.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
"use strict";
var { TbSync } = ChromeUtils.import("chrome://tbsync/content/tbsync.jsm");
var tbSyncAttendeeEventDialog = {
onInject: function (window) {
// Add autoComplete for TbSync
if (window.document.getElementById("attendeeCol3#1")) {
let autocompletesearch = window.document.getElementById("attendeeCol3#1").getAttribute("autocompletesearch");
if (autocompletesearch.indexOf("tbSyncAutoCompleteSearch") == -1) {
window.document.getElementById("attendeeCol3#1").setAttribute("autocompletesearch", autocompletesearch + " tbSyncAutoCompleteSearch");
}
}
},
onRemove: function (window) {
// Remove autoComplete for TbSync
if (window.document.getElementById("attendeeCol3#1")) {
let autocompletesearch = window.document.getElementById("attendeeCol3#1").getAttribute("autocompletesearch").replace("tbSyncAutoCompleteSearch", "");
window.document.getElementById("attendeeCol3#1").setAttribute("autocompletesearch", autocompletesearch.trim());
}
}
}
| JavaScript | 0 | @@ -474,38 +474,38 @@
ntById(%22attendee
-Col3#1
+sInput
%22)) %7B%0A let
@@ -557,38 +557,38 @@
ntById(%22attendee
-Col3#1
+sInput
%22).getAttribute(
@@ -724,38 +724,38 @@
ntById(%22attendee
-Col3#1
+sInput
%22).setAttribute(
@@ -969,22 +969,22 @@
attendee
-Col3#1
+sInput
%22)) %7B%0A
@@ -1052,22 +1052,22 @@
attendee
-Col3#1
+sInput
%22).getAt
@@ -1187,14 +1187,14 @@
ndee
-Col3#1
+sInput
%22).s
|
50f7ed2188be840501c270d69fde38b0d47736ae | Set context menu & reattach right-click listener when recreating Tray | app/main.js | app/main.js | 'use strict'
const pjson = require('../package.json')
const store = require('./store')
const autolaunch = require('./autolaunch')
const electron = require('electron')
const applescript = require('applescript')
const { app, globalShortcut, Tray, Menu, BrowserWindow, shell, ipcMain } = electron
app.on('ready', () => {
let tray = new Tray(`${__dirname}/iconTemplate.png`)
let preferencesWindow = null
function createTrayMenu () {
let menuTemplate = [
{ label: `Start ${pjson.name}`, accelerator: store.get('hotkey'), click: onActivate },
{
label: 'Mode',
submenu: [{
label: 'Screensaver',
type: 'radio',
checked: store.get('mode') === 'Screensaver',
click: (radio) => { setMode(radio.label) }
}, {
label: 'Sleep',
type: 'radio',
checked: store.get('mode') === 'Sleep',
click: (radio) => { setMode(radio.label) }
}, {
label: 'Lock',
type: 'radio',
checked: store.get('mode') === 'Lock',
click: (radio) => { setMode(radio.label) }
}]
},
{ label: 'Preferences', accelerator: 'Cmd+,', click: createPreferencesWindow },
{ type: 'separator' },
{ label: `About ${pjson.name}...`, click: () => { shell.openExternal(pjson.homepage) } },
{ label: 'Feedback && Support...', click: () => { shell.openExternal(pjson.bugs.url) } },
{ type: 'separator' },
{ label: `Quit ${pjson.name}`, accelerator: 'Cmd+Q', click: () => { app.quit() } }
]
return Menu.buildFromTemplate(menuTemplate)
}
function createPreferencesWindow () {
if (preferencesWindow) return preferencesWindow.focus()
preferencesWindow = new BrowserWindow({
title: `${app.getName()} Preferences`,
titleBarStyle: 'hidden',
width: 325,
height: 178,
resizable: false,
maximizable: false,
show: false
})
preferencesWindow.loadURL(`file://${__dirname}/preferences.html`)
preferencesWindow.once('ready-to-show', () => {
let screen = electron.screen.getDisplayNearestPoint(electron.screen.getCursorScreenPoint())
preferencesWindow.setPosition(
Math.floor(screen.bounds.x + (screen.size.width / 2) - (preferencesWindow.getSize()[0] / 2)),
Math.floor(screen.bounds.y + (screen.size.height / 2) - (preferencesWindow.getSize()[1] / 2))
)
preferencesWindow.show()
app.dock.show()
})
preferencesWindow.on('closed', () => {
preferencesWindow = null
app.dock.hide()
})
}
function onActivate () {
let unpackedPath = __dirname.replace('app.asar', 'app.asar.unpacked')
let mode = store.get('mode')
if (!tray.isDestroyed()) tray.setHighlightMode('always')
setTimeout(() => {
applescript.execFile(`${unpackedPath}/applescript/${mode}.applescript`)
if (!tray.isDestroyed()) tray.setHighlightMode('selection')
}, 500)
}
function setAutoLaunch (value) {
store.set('autoLaunch', value)
value ? autolaunch.enable() : autolaunch.disable()
}
function setHideIcon (value) {
store.set('hideIcon', value)
if (value) {
tray.destroy()
} else {
tray = new Tray(`${__dirname}/iconTemplate.png`)
}
}
function setMode (mode, reloadPreferences) {
store.set('mode', mode)
tray.setContextMenu(createTrayMenu())
if (reloadPreferences && preferencesWindow) preferencesWindow.reload()
}
function setHotkey (hotkey) {
globalShortcut.unregister(store.get('hotkey'))
globalShortcut.register(hotkey, onActivate)
store.set('hotkey', hotkey)
}
globalShortcut.register(store.get('hotkey'), onActivate)
tray.setContextMenu(createTrayMenu())
tray.on('right-click', onActivate)
if (store.get('hideIcon')) tray.destroy()
app.dock.hide()
app.on('window-all-closed', () => {})
app.on('activate', createPreferencesWindow)
ipcMain.on('setAutoLaunch', (event, checked) => { setAutoLaunch(checked) })
ipcMain.on('setHideIcon', (event, checked) => { setHideIcon(checked) })
ipcMain.on('setMode', (event, mode) => { setMode(mode) })
ipcMain.on('setHotkey', (event, hotkey) => { setHotkey(hotkey) })
})
| JavaScript | 0 | @@ -3255,16 +3255,101 @@
e.png%60)%0A
+ tray.setContextMenu(createTrayMenu())%0A tray.on('right-click', onActivate)%0A
%7D%0A
|
6176cb55ebd73773d2572158a1ba73c2d1fd51dc | Fix config fetching for multi-activity packages | cli/activity-worker.js | cli/activity-worker.js | /**
* Default worker process for swf-activity
* This process is spawned for each new activity task received.
* It will look in the working directory for a Node.JS module that has the same name as the activity-type
*/
var path = require('path'),
swf = require('../index');
// The task is given to this process as a command line argument in JSON format :
var taskConfig = JSON.parse(process.argv[2]);
// AWS credentials
var accessKeyId = process.argv[3],
secretAccessKey = process.argv[4];
var swfClient = swf.createClient({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey
});
// Optional fetchConfigData
var fetchConfigData = (process.argv.length >= 5) ? process.argv[5] : null;
// Create the ActivityTask
var task = new swf.ActivityTask(swfClient, taskConfig);
function activityFailed(reason, details) {
task.respondFailed(reason, details, function (err) {
if (err) { console.error(err); return; }
console.log("respond failed !");
});
}
// Fetchconfigfile must be a js file exporting the 'fetch_config' method
// signature: function(workerName, fetchConfigData, function (err, config) {...})
var fetchconfigfile = process.argv[5],
fetch_config;
try {
fetch_config = require(fetchconfigfile).fetch_config;
} catch (ex) {
console.log(ex);
activityFailed("Unable to load for fetchconfigfile, or does not export fetch_config : " + fetchconfigfile, ex.message);
}
var workerName = taskConfig.activityType.name;
try {
// Load the worker module
// Simple module : 'soap' -> require('soap').worker
// or multiple activities package: 'ec2_runInstances' -> require('ec2').runInstances
console.log("Trying to load worker : " + workerName);
var split = workerName.split('_');
var packageName = split[0],
workerName = "worker";
if(split.length > 1) {
workerName = split[1];
}
var worker = require(path.join(process.cwd(), packageName))[workerName];
//var worker = require(path.join(process.cwd(), workerName)).worker;
console.log("module loaded !");
// Use the asynchronous method to get the config for this module
fetch_config(workerName, fetchConfigData, function (err, config) {
if (err) {
console.log(err);
activityFailed("Unable to get config for: " + workerName, "");
return;
}
try {
worker(task, config);
} catch (ex) {
console.log(ex);
activityFailed("Error executing " + workerName, "");
}
});
} catch (ex) {
console.log(ex);
activityFailed("Unable to load module " + workerName, "");
}
| JavaScript | 0.000001 | @@ -2166,22 +2166,23 @@
_config(
-worker
+package
Name, fe
|
27bf1aca66791c6a060f80e0620f56a9a1d649d1 | Update tcp.js | lib/adapter/tcp.js | lib/adapter/tcp.js | /**
* Licensed under the MIT License
*
* @author Kanstantsin A Kamkou (2ka.by)
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @link https://github.com/kkamkou/node-gelf-pro
*/
'use strict';
// required stuff
var path = require('path'),
abstract = require(path.join(__dirname, 'abstract')),
async = require('async'),
net = require('net');
// the class itself
var tcp = Object.create(abstract);
/**
* Sends a chunk to the server
* @param {Object} packet
* @param {Function} callback
* @returns {tcp}
*/
tcp.send = function (message, callback) {
var client, self = this;
async.waterfall(
[
function (cb) {
client = net.connect(self.options, cb);
client.on('error', function (err) {
client.destroy();
cb(err);
});
},
function (cb) {
if (!self.options.deflate) {
return cb(null, new Buffer(message));
}
self.deflate(message, cb);
},
function (buffer, cb) {
var packet = new Buffer(Array.prototype.slice.call(buffer, 0, buffer.length).concat(0x00));
client.end(packet, function () {
cb(null, packet.length);
});
}
],
function (err, result) {
return callback(err, result);
}
);
return this;
};
// exporting outside
module.exports = tcp;
| JavaScript | 0.000002 | @@ -461,13 +461,15 @@
s a
-chunk
+message
to
|
49484945a44b92a9eb003cacf9b4554aa1356bcd | implement filter by query parameter to include or exclude | main.js | main.js | var margin = {top: 10, right: 200, bottom: 10, left: 40},
width = 1400 - margin.left - margin.right,
height = 800 - margin.top - margin.bottom;
offset_right = 300;
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom + width/10);
var base = svg.append("g")
.attr("transform", "translate(" + margin.left + ", " + margin.top + ")");
var tree = d3.layout.tree()
.separation(function(a, b) { return (a.fname == b.fname) ? 1 : 0.8 })
.size([height, width + height/10 - offset_right]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x + d.y / 10]; });
var color = d3.scale.category20();
var rails_directory_hue = d3.scale.ordinal()
.domain([null, "controller", "model", "view", "helper", "lib", "vendor", "config", "js", "stylesheet", "db"])
.rangeBands([0, 360]);
// var gray_scale = d3.scale.linear().domain([0, 255]).range(["red", "blue"]);
d3.json("foo.json", function(json) {
var nodes = tree.nodes(json);
var links = tree.links(nodes);
var font_size = 9;
base.selectAll("path.link")
.data(links)
.enter()
.append("path")
.attr("class", "link")
.attr("d", function(d){
return diagonal(d);
});
base.selectAll("g.textnode")
.data(nodes)
.enter()
.append("g")
.each(function(d){
//var texts = [d.primary_word, d.fname + ":" + d.lnum, d.corners].filter(function(e){ return e });
var texts = [d.corners + " " + d.fname + ":" + d.lnum];
var offset_x = 0; //(-1) * d3.max(texts, function(t){ return font_size * (t || "").length }) / 4;
var offset_y = (-1) * (font_size * texts.length) / 2;
var text = d3.select(this).selectAll("text.label")
.data(texts)
.enter()
.append("text")
.attr("class", "label")
.attr("x", function(d){ return offset_x; })
.attr("y", function(d, i){ return offset_y + font_size*(i+1); })
.attr("fill", "#000")
.attr("font-family", "trebuchet ms, helvetica, sans-serif")
.attr("text-anchor", "start")
.attr("font-size", font_size)
.text(function(t){ return t });
var real_box_width = d3.max(text[0].map(function(e){ return e.getBBox().width; }));
var real_box_height = d3.sum(text[0].map(function(e){ return e.getBBox().height; }));
d3.select(this)
.insert("rect", "text")
.attr("width", function(e){ return real_box_width })
.attr("height", function(e){ return real_box_height })
.attr("rx", 3)
.attr("ry", 3)
//.style("fill", function(e){ return gray_scale(strToCode(d.search_word || "", 255)) })
.style("fill", function(e){ return d3.hsl(rails_directory_hue(d.rails_directory), 1, 0.5) })
.attr("x", function(e){ return offset_x })
.attr("y", function(e){ return offset_y })
.attr("fill-opacity", function(e){ return 0.3 })
.style("stroke-width", "0");
})
.attr("transform", function(d){ return "translate(" + d.y + ", " + (d.x + d.y / 10) + ")"; });
});
function getParam(){
var pairs = (location.href.split("?")[1] || "").split("&").map(function(pair){ return pair.split("=") });
return _.reduce(pairs, function(obj, e){
obj[e[0]] = e[1];
return obj
}, {});
}
function strToCode(str, max){
return +d3.range(str.length).map(function(i){ return str[i].charCodeAt().toString() }).join("") % max
}
| JavaScript | 0 | @@ -590,24 +590,487 @@
1 : 0.8 %7D)%0A
+ .children(function(a)%7B%0A return a.children.filter(function(e)%7B%0A var ex_pattern = getParam(%22exclude%22);%0A var in_pattern = getParam(%22include%22);%0A%0A function match(pattern)%7B%0A return (new RegExp(pattern, 'i')).test(e.fname);%0A %7D%0A%0A return (!in_pattern %7C%7C match(in_pattern)) && (!ex_pattern %7C%7C !match(ex_pattern));%0A %7D)%0A %7D)%0A
@@ -4043,16 +4043,19 @@
etParam(
+key
)%7B%0A var
@@ -4170,16 +4170,15 @@
urn
+(
_.
-reduce
+find
(pai
@@ -4194,62 +4194,49 @@
ion(
-obj, e)%7B%0A obj%5Be%5B0%5D%5D = e%5B1%5D;%0A return obj%0A %7D, %7B%7D)
+pair)%7B return pair%5B0%5D == key %7D) %7C%7C %5B%5D)%5B1%5D
;%0A%7D%0A
|
85a39ab14d4ecbe966da2a3c1327229efb505acc | Make lint happy | cli/wildcat-codemod.js | cli/wildcat-codemod.js | #! /usr/bin/env babel-node
import {echo, exit} from "shelljs";
import nomnom from "nomnom";
import fs from "fs";
import path from "path";
import {exec} from "child_process";
const transformBasePath = path.join(__dirname, "..", "transforms");
const runFirst = [
"resolve-relative-imports.js"
];
const runLast = [
"remove-stilr.js",
"convert-to-radium.js",
];
const {src, all, single} = nomnom.options({
src: {
position: 0,
help: "Source directory to run the transforms against"
},
all: {
flag: true,
abbr: "A",
help: "Run all transforms in transforms folder"
},
single: {
help: "Run single transform",
abbr: "S"
}
}).parse();
if (!src) {
echo("src option is required");
exit(1);
}
const buildCMD = (filePath, src) => {
return `jscodeshift -t ${filePath} ${src} --extensions "jsx,js"`;
};
const applyTransform = (transforms) => {
if (!transforms.length) {
return;
}
const transform = transforms.shift();
const transformFilePath = path.join(transformBasePath, transform);
const cmd = buildCMD(transformFilePath, src);
echo("Applying transform", transform);
exec(cmd, (err, stout) => {
echo(stout);
applyTransform(transforms);
});
};
if (all) {
const transforms = fs.readdirSync(transformBasePath)
.filter(fileName => fileName.match(".js$"))
.filter(filename => runFirst.indexOf(filename) === -1)
.filter(filename => runLast.indexOf(filename) === -1);
const orderedTransforms = [...runFirst, ...transforms, ...runLast];
applyTransform(orderedTransforms);
}
if (single) {
const transformFilePath = path.join(transformBasePath, single);
const cmd = buildCMD(transformFilePath, src);
exec(cmd, (err, stout) => {
echo(err);
echo(stout);
});
}
| JavaScript | 0.000047 | @@ -361,17 +361,16 @@
dium.js%22
-,
%0A%5D;%0A%0Acon
@@ -807,19 +807,20 @@
lePath,
-src
+file
) =%3E %7B%0A
@@ -859,19 +859,20 @@
Path%7D $%7B
-src
+file
%7D --exte
@@ -1918,12 +1918,8 @@
%7D);%0A%7D%0A
-%0A%0A%0A%0A
|
95cbf8bb1251f54a92018a803354d5277c9ff923 | Fix in data-hash. Go to #data-hash ONLY if it exists. If not, go to <a href='...'>. | main.js | main.js | "use strict";
define(["/jquery.js"], function () {
var self;
function init(config) {
self = this;
if(config.sample) {
buildSampleConfiguration(config);
}
if (typeof this.onload === 'function') {
this.onload();
}
var container = $(config.container, self.dom);
// On tab click
$(config.tabs, self.dom).on('click', function() {
// Change the hash in URL
if (config.options.hash) {
window.location.hash = $(this).attr('data-hash');
} else {
activateTab(config, $(this));
}
return false;
});
// hashchange handler
$(window).on('hashchange', function () {
var tab = $("[data-hash=" + window.location.hash.substring(1) + "]");
activateTab(config, tab);
})
// Load first content
if((config.options.first) && (!window.location.hash)) {
M(config.container, config.options.first);
return;
}
// Load the right content for hash
if((window.location.hash) && (config.options.hash)) {
var tab = $("[data-hash=" + window.location.hash.substring(1) + "]");
activateTab(config, tab);
return;
}
}
function activateTab(config, tab) {
if (!tab.length) {
return;
}
// TODO we cannot rely that the selected class exists and based on this
// to test the current tab. The current miid should be buffered
var active = $(config.tabs).parent().find("." + config.options.classes.selected);
if (tab.attr("data-miid") === active.attr("data-miid")) {
return;
}
// Removes the active class
$(config.tabs).removeClass(config.options.classes.selected);
// Removes the content of container
$(config.container).html("");
// Adds active class
tab.addClass(config.options.classes.selected);
// Sets the content in container
M(config.container, tab.attr("data-miid"));
}
function buildSampleConfiguration(config) {
config.container = "#content";
config.tabs = ".nav-tabs li";
config.options = {};
config.options.classes = { selected: "active" };
config.options.first = "tabContent1";
config.options.hash = true;
}
return init;
});
| JavaScript | 0.0006 | @@ -527,24 +527,137 @@
ons.hash) %7B%0A
+ if (!$(this).attr(%22data-hash%22)) %7B%0A return;%0A %7D%0A %0A
|
3a1ce583f4e45a3ca5760c1c8175124e9f7bb089 | Fix indent | lib/assets/Json.js | lib/assets/Json.js | const errors = require('../errors');
const Text = require('./Text');
class Json extends Text {
get parseTree() {
if (!this._parseTree) {
try {
this._parseTree = JSON.parse(this.text);
} catch (e) {
const err = new errors.ParseError({
message:
'Json parse error in ' + this.urlOrDescription + ': ' + e.message,
asset: this
});
if (this.assetGraph) {
this.assetGraph.warn(err);
} else {
throw err;
}
}
}
return this._parseTree;
}
set parseTree(parseTree) {
this.unload();
this._parseTree = parseTree;
this._lastKnownByteLength = undefined;
if (this.assetGraph) {
this.populate();
}
this.markDirty();
}
get text() {
if (typeof this._text !== 'string') {
if (this._parseTree) {
if (this.isPretty) {
this._text =
JSON.stringify(this._parseTree, undefined, ' ') + '\n';
} else {
this._text = JSON.stringify(this._parseTree);
}
} else {
this._text = this._getTextFromRawSrc();
}
}
return this._text;
}
set text(text) {
super.text = text;
}
prettyPrint() {
this.isPretty = true;
/*eslint-disable*/
const parseTree = this.parseTree; // So markDirty removes this._text
/*eslint-enable*/
this.markDirty();
return this;
}
minify() {
this.isPretty = false;
/*eslint-disable*/
const parseTree = this.parseTree; // So markDirty removes this._text
/*eslint-enable*/
this.markDirty();
return this;
}
}
Object.assign(Json.prototype, {
contentType: 'application/json',
supportedExtensions: ['.json', '.topojson'],
isPretty: false
});
module.exports = Json;
| JavaScript | 0.000854 | @@ -1267,36 +1267,32 @@
slint-disable*/%0A
-
const parseT
@@ -1340,36 +1340,32 @@
oves this._text%0A
-
/*eslint-ena
@@ -1477,20 +1477,16 @@
sable*/%0A
-
cons
@@ -1550,20 +1550,16 @@
s._text%0A
-
/*es
|
8409acdd8f235f6f621f296d733f6dc2b23e2bbe | Break misleading `config` object into 3 parts | main.js | main.js | (function(){
/* global VersalPlayerAPI */
// Declare a gadget class.
var Gadget = function(options) {
// versal interface
this.vi = new VersalPlayerAPI();
// the main DOM element for attaching
this.el = options.el;
// the selected word
this.wordEl = this.el.querySelector('span.adjective');
// the gadget's internal state, including the default values of all attributes and learner state.
this.config = {
isEditable: false,
authorState: {
chosenColor: 'green',
chosenWord: 'green'
},
learnerState: {
isBold: false // whether the learner has made the chosen word bold.
}
};
this.initialize();
};
// Need to configure the property sheet after attaching.
Gadget.prototype.setupPropertySheet = function() {
// set up a property sheet for word and color selection.
this.vi.setPropertySheetAttributes({
chosenColor: { type: 'Color' },
chosenWord: { type: 'Text' }
});
};
// Initialize: before the gadget is attached to the lesson's DOM.
Gadget.prototype.initialize = function() {
//
this.vi.on('attributesChanged', this.attributesChanged.bind(this));
this.vi.on('learnerStateChanged', this.learnerStateChanged.bind(this));
this.setupPropertySheet();
// subscribe to player events.
this.vi.startListening();
// add click listener to toggle bold font.
this.wordEl.onclick = this.toggleBoldWord.bind(this);
// for assets
this.vi.on('assetSelected', function(assetData){
var assetUrl = this.vi.assetUrl(assetData.asset.representations[0].id);
//change local image
this.setImagePath({
url: assetUrl
});
//persist
this.vi.setAttributes({
chosenImage : {
url: assetUrl,
assetObj: assetData
}
});
}.bind(this));
// add click listener to upload new asset.
this.el.querySelector('.button-upload-image').onclick = this.requestUpload.bind(this);
// set gadget height.
this.vi.setHeight(400);
// initially the gadget is already not empty (it has "green" set). If it were otherwise, we would have done this:
// this.vi.setEmpty();
};
Gadget.prototype.requestUpload = function() {
this.vi.requestAsset({
attribute: 'tmpImage',
type: 'image'
});
};
// Methods that respond to some player events. Other events will be ignored by this gadget.
Gadget.prototype.setEditable = function(jsonData) {
this.config.isEditable = jsonData.editable;
// some elements have class 'authoring-only' and need to be hidden when we are in non-editable mode.
var visibilityForAuthor = this.config.isEditable ? 'visible' : 'hidden';
// set visibility on all such elements.
var elementsAuthoringOnly = document.getElementsByClassName('authoring-only');
for (var i = 0; i < elementsAuthoringOnly.length; ++i) {
var item = elementsAuthoringOnly[i];
item.setAttribute('style', 'visibility: ' + visibilityForAuthor + ';');
}
};
Gadget.prototype.setImagePath = function(jsonData) {
var imageUrl = jsonData.url;
// now we set the image src attribute to this url.
this.el.querySelector('.sample-image').setAttribute('src', imageUrl);
};
Gadget.prototype.attributesChanged = function(jsonData) {
// we expect only the attributes 'chosenColor', 'chosenWord', 'chosenImage'.
if (jsonData.chosenColor) {
this.config.authorState.chosenColor = jsonData.chosenColor;
this.wordEl.setAttribute('style', 'color: ' + this.config.authorState.chosenColor);
}
if (jsonData.chosenWord) {
this.config.authorState.chosenWord = jsonData.chosenWord;
this.wordEl.innerHTML = this.config.authorState.chosenWord;
}
if (jsonData.chosenImage) {
this.config.authorState.asset = jsonData.chosenImage;
this.setImagePath(jsonData.chosenImage);
}
};
Gadget.prototype.learnerStateChanged = function(jsonData) {
// we expect only the attribute 'isBold'.
if (jsonData.isBold) {
this.config.learnerState.isBold = jsonData.isBold;
this.updateBoldWord();
}
};
Gadget.prototype.updateBoldWord = function() {
if (this.config.learnerState.isBold) {
addClassToElement(this.el, 'setBold');
} else {
removeClassFromElement(this.el, 'setBold');
}
};
Gadget.prototype.toggleBoldWord = function() {
this.config.learnerState.isBold = ! this.config.learnerState.isBold;
this.vi.setLearnerState({
isBold: this.config.learnerState.isBold
});
this.updateBoldWord();
};
// Finished with defining the gadget class.
// Instantiate the gadget, pass the DOM element, start listening to events.
new Gadget({ el: document.querySelector('body') });
// This gadget instance will remain active because it has added itself as a listener to the window.
})();
| JavaScript | 0.000948 | @@ -341,158 +341,102 @@
t's
-internal state, including the default values of all attributes and learner state.%0A this.config = %7B%0A isEditable: false,%0A authorState: %7B%0A
+configuration, consistent for anyone viewing each instance of this gadget%0A this.config = %7B%0A
@@ -461,26 +461,24 @@
een',%0A
-
-
chosenWord:
@@ -493,124 +493,316 @@
- %7D,
+%7D;%0A
%0A
- learnerState: %7B%0A isBold:
+// Internal state of the gadget. Only authors can edit gadgets%0A // - When editing, config can be changed by the author%0A this.isEditable =
false
+;%0A%0A
- // whether the learner has made the chosen word bold.%0A %7D
+// State of the gadget, unique to the gadget instance AND each specific learner using the gadget%0A this.learnerState = %7B%0A isBold: false
%0A
@@ -2707,31 +2707,24 @@
%7B%0A this.
-config.
isEditable =
@@ -2884,23 +2884,16 @@
= this.
-config.
isEditab
@@ -3651,36 +3651,24 @@
this.config.
-authorState.
chosenColor
@@ -3751,36 +3751,24 @@
this.config.
-authorState.
chosenColor)
@@ -3820,36 +3820,24 @@
this.config.
-authorState.
chosenWord =
@@ -3900,28 +3900,16 @@
.config.
-authorState.
chosenWo
@@ -3972,20 +3972,8 @@
fig.
-authorState.
asse
@@ -4196,39 +4196,32 @@
d) %7B%0A this.
-config.
learnerState.isB
@@ -4342,31 +4342,24 @@
if (this.
-config.
learnerState
@@ -4543,31 +4543,24 @@
%7B%0A this.
-config.
learnerState
@@ -4572,31 +4572,24 @@
ld = ! this.
-config.
learnerState
@@ -4646,23 +4646,16 @@
d: this.
-config.
learnerS
|
5725e1ea19d3e69580dd229aeacfe251a3cc624f | fix home IP address | client/www/js/index.js | client/www/js/index.js | var isBrowser = document.URL.indexOf( 'http://' ) !== -1 || document.URL.indexOf( 'https://' ) !== -1;
if ( !isBrowser ) {
document.addEventListener('deviceready', init, false);
} else {
init();
}
function init() {
var callerId;
// PeerJS server location
var SERVER_IP = '192.168.0.102'; //home
// var SERVER_IP = '192.168.1.227'; //office
var SERVER_PORT = 9000;
// DOM elements manipulated as user interacts with the app
var callButton = document.querySelector("#callButton");
var localVideo = document.querySelector("#localVideo");
var remoteVideo = document.querySelector("#remoteVideo");
// the ID set for this client
var callerId = null;
// PeerJS object, instantiated when this client connects with its
// caller ID
var peer = null;
// the local video stream captured with getUserMedia()
var localStream = null;
// get the local video and audio stream and show preview in the
// "LOCAL" video element
// successCb: has the signature successCb(stream); receives
// the local video stream as an argument
var getLocalStream = function(successCb) {
if (localStream && successCb) {
successCb(localStream);
} else {
navigator.webkitGetUserMedia({
audio: true,
video: true
},
function(stream) {
localStream = stream;
localVideo.src = window.URL.createObjectURL(stream);
if (successCb) {
successCb(stream);
}
},
function(err) {
alert('Failed to access local camera');
console.log(err);
}
);
}
};
// set the "REMOTE" video element source
var showRemoteStream = function(stream) {
remoteVideo.src = window.URL.createObjectURL(stream);
};
// set caller ID and connect to the PeerJS server
var connect = function() {
if (!callerId) {
alert('Please enter your name first');
setCallerId();
return;
}
try {
// create connection to the ID server
console.log('create connection to the ID server');
console.log('host: ' + SERVER_IP + ', port: ' + SERVER_PORT);
peer = new Peer(callerId, {
host: SERVER_IP,
port: SERVER_PORT
});
// hack to get around the fact that if a server connection cannot
// be established, the peer and its socket property both still have
// open === true; instead, listen to the wrapped WebSocket
// and show an error if its readyState becomes CLOSED
peer.socket._socket.onclose = function() {
alert('No connection to server');
peer = null;
};
// get local stream ready for incoming calls once the wrapped
// WebSocket is open
peer.socket._socket.onopen = function() {
getLocalStream(function() {
callButton.style.display = 'block';
});
};
// handle events representing incoming calls
peer.on('call', answer);
} catch (e) {
peer = null;
alert('Error while connecting to server');
}
};
// make an outgoing call
var dial = function() {
if (!peer) {
alert('Please connect first');
return;
}
if (!localStream) {
alert('Could not start call as there is no local camera');
return
}
var recipientId = prompt('Please enter recipient name');
if (!recipientId) {
alert('Could not start call as no recipient ID is set');
dial();
return;
}
getLocalStream(function(stream) {
console.log('Outgoing call initiated');
var call = peer.call(recipientId, stream);
call.on('stream', showRemoteStream);
call.on('error', function(e) {
alert('Error with call');
console.log(e.message);
});
});
};
// answer an incoming call
var answer = function(call) {
if (!peer) {
alert('Cannot answer a call without a connection');
return;
}
if (!localStream) {
alert('Could not answer call as there is no localStream ready');
return;
}
console.log('Incoming call answered');
call.on('stream', showRemoteStream);
call.answer(localStream);
};
var setCallerId = function () {
callerId = prompt('Please enter your name');
connect();
};
setCallerId();
// wire up button events
callButton.addEventListener('click', dial);
} | JavaScript | 0 | @@ -230,27 +230,8 @@
%7B%0A%0A
- var callerId;%0A%0A
@@ -289,17 +289,17 @@
168.0.10
-2
+1
'; //hom
|
f47c3f9884dad12959f1d1f70eef88ba9d1c4e88 | Update main.js | main.js | main.js | var rm = function() {
$('tr.plistitem td:contains("Keeper")').parent().remove();
$('span#posList a').click(rm);
};
window.onload = rm;
| JavaScript | 0.000069 | @@ -1,10 +1,17 @@
-var rm
+window.onload
= f
@@ -127,25 +127,4 @@
%0A%7D;%0A
-%0Awindow.onload = rm;%0A
|
bfb515d7b8b42601ba103d86982672ef0aab3738 | Add basic IPv6 support. | lib/builder/win.js | lib/builder/win.js | 'use strict';
/**
* A builder builds command line arguments for ping in window environment
* @module lib/builder/win
*/
var util = require('util');
var builder = {};
/**
* Cross platform config representation
* @typedef {Object} PingConfig
* @property {boolean} numeric - Map IP address to hostname or not
* @property {number} timeout - Time duration for ping command to exit
* @property {number} min_reply - Exit after sending number of ECHO_REQUEST
* @property {string[]} extra - Optional options does not provided
*/
var defaultConfig = {
numeric: true,
timeout: 5,
min_reply: 1,
extra: [],
};
/**
* Get the finalized array of command line arguments
* @param {string} target - hostname or ip address
* @param {PingConfig} [config] - Configuration object for cmd line argument
* @return {string[]} - Command line argument according to the configuration
*/
builder.getResult = function (target, config) {
var _config = config || {};
// Empty argument
var ret = [];
// Make every key in config has been setup properly
var keys = ['numeric', 'timeout', 'min_reply', 'extra'];
keys.forEach(function (k) {
// Falsy value will be overrided without below checking
if (typeof(_config[k]) !== 'boolean') {
_config[k] = _config[k] || defaultConfig[k];
}
});
if (!_config.numeric) {
ret.push('-a');
}
if (_config.timeout) {
// refs #56: Unit problem
// Our timeout is in second while timeout in window is in milliseconds
// so we need to convert our units accordingly
ret = ret.concat([
'-w',
util.format('%d', _config.timeout * 1000),
]);
}
if (_config.min_reply) {
ret = ret.concat([
'-n',
util.format('%d', _config.min_reply),
]);
}
if (_config.extra) {
ret = ret.concat(_config.extra);
}
ret.push(target);
return ret;
};
module.exports = builder;
| JavaScript | 0.998719 | @@ -1342,24 +1342,65 @@
%7D%0A %7D);%0A%0A
+ ret.push(_config.v6 ? '-6' : '-4');%0A%0A
if (!_co
|
bb05936ed0550faf4b4b9448fb6c94b0ea4b6a03 | Tweak buster object exposure | lib/buster-core.js | lib/buster-core.js | var buster = (function (setTimeout) {
var isNode = typeof require == "function" && typeof module == "object";
var div = typeof document != "undefined" && document.createElement("div");
var F = function () {};
var buster = {
bind: function bind(obj, methOrProp) {
var method = typeof methOrProp == "string" ? obj[methOrProp] : methOrProp;
var args = Array.prototype.slice.call(arguments, 2);
return function () {
var allArgs = args.concat(Array.prototype.slice.call(arguments));
return method.apply(obj, allArgs);
};
},
partial: function partial(fn) {
var args = [].slice.call(arguments, 1);
return function () {
return fn.apply(this, args.concat([].slice.call(arguments)));
};
},
create: function create(object) {
F.prototype = object;
return new F();
},
extend: function extend(target) {
if (!target) { return; }
for (var i = 1, l = arguments.length, prop; i < l; ++i) {
for (prop in arguments[i]) {
target[prop] = arguments[i][prop];
}
}
return target;
},
nextTick: function nextTick(callback) {
if (typeof process != "undefined" && process.nextTick) {
return process.nextTick(callback);
}
setTimeout(callback, 0);
},
functionName: function functionName(func) {
if (!func) return "";
if (func.displayName) return func.displayName;
if (func.name) return func.name;
var matches = func.toString().match(/function\s+([^\(]+)/m);
return matches && matches[1] || "";
},
isNode: function isNode(obj) {
if (!div) return false;
try {
obj.appendChild(div);
obj.removeChild(div);
} catch (e) {
return false;
}
return true;
},
isElement: function isElement(obj) {
return obj && buster.isNode(obj) && obj.nodeType === 1;
},
isArray: function isArray(arr) {
return Object.prototype.toString.call(arr) == "[object Array]";
},
flatten: function flatten(arr) {
var result = [], arr = arr || [];
for (var i = 0, l = arr.length; i < l; ++i) {
result = result.concat(buster.isArray(arr[i]) ? flatten(arr[i]) : arr[i]);
}
return result;
},
each: function each(arr, callback) {
for (var i = 0, l = arr.length; i < l; ++i) {
callback(arr[i]);
}
},
map: function map(arr, callback) {
var results = [];
for (var i = 0, l = arr.length; i < l; ++i) {
results.push(callback(arr[i]));
}
return results;
},
parallel: function parallel(fns, callback) {
function cb(err, res) {
if (typeof callback == "function") {
callback(err, res);
callback = null;
}
}
if (fns.length == 0) { return cb(null, []); }
var remaining = fns.length, results = [];
function makeDone(num) {
return function done(err, result) {
if (err) { return cb(err); }
results[num] = result;
if (--remaining == 0) { cb(null, results); }
};
}
for (var i = 0, l = fns.length; i < l; ++i) {
fns[i](makeDone(i));
}
},
series: function series(fns, callback) {
function cb(err, res) {
if (typeof callback == "function") {
callback(err, res);
}
}
var remaining = fns.slice();
var results = [];
function callNext() {
if (remaining.length == 0) return cb(null, results);
var promise = remaining.shift()(next);
if (promise && typeof promise.then == "function") {
promise.then(buster.partial(next, null), next);
}
}
function next(err, result) {
if (err) return cb(err);
results.push(result);
callNext();
}
callNext();
},
countdown: function countdown(num, done) {
return function () {
if (--num == 0) done();
};
}
};
if (isNode) {
module.exports = buster;
buster.eventEmitter = require("./buster-event-emitter");
Object.defineProperty(buster, "defineVersionGetter", {
get: function () {
return require("./define-version-getter");
}
});
}
return buster;
}(setTimeout));
| JavaScript | 0 | @@ -27,16 +27,19 @@
tTimeout
+, B
) %7B%0A
@@ -5108,16 +5108,40 @@
n buster
+.extend(B %7C%7C %7B%7D, buster)
;%0A%7D(setT
@@ -5146,12 +5146,20 @@
tTimeout
+, buster
));%0A
|
5bbace32086f827eef498d4dad3572191f6894f8 | Change ipc.on to ipc.once | main.js | main.js | var app = require('app'); // Module to control application life.
var request = require('request');
var BrowserWindow = require('browser-window'); // Module to create native browser window.
var Menu = require('menu');
var Dialog = require('dialog');
var Fs = require('fs');
var XLSX = require('xlsx');
var ipc = require('ipc');
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is GCed.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
var template = [
{
label: 'Electron',
submenu: [
{
label: 'About Electron',
selector: 'orderFrontStandardAboutPanel:'
},
{
type: 'separator'
},
{
label: 'Services',
submenu: []
},
{
type: 'separator'
},
{
label: 'Hide Electron',
accelerator: 'CmdOrCtrl+H',
selector: 'hide:'
},
{
label: 'Hide Others',
accelerator: 'CmdOrCtrl+Shift+H',
selector: 'hideOtherApplications:'
},
{
label: 'Show All',
selector: 'unhideAllApplications:'
},
{
type: 'separator'
},
{
label: 'Quit',
accelerator: 'CmdOrCtrl+Q',
selector: 'terminate:'
},
]
},
{
label: 'File',
submenu: [
{
label: 'New',
accelerator: 'CmdOrCtrl+N',
click: function() { createWindow(); }
},
{
label: 'Open..',
accelerator: 'CmdOrCtrl+O',
click: function() { openFile(); }
},
{
label: 'Import Excel file',
click: function() { importExcel(); }
},
{
label: 'Save As..',
accelerator: 'Shift+CmdOrCtrl+S',
click: function() { saveFile(); }
},
{
label: 'Validate',
accelerator: 'CmdOrCtrl+V',
click: function() { validateFile(); }
}
]
},
{
label: 'Edit',
submenu: [
{
label: 'Undo',
accelerator: 'CmdOrCtrl+Z',
selector: 'undo:'
},
{
label: 'Redo',
accelerator: 'Shift+CmdOrCtrl+Z',
selector: 'redo:'
},
{
type: 'separator'
},
{
label: 'Cut',
accelerator: 'CmdOrCtrl+X',
selector: 'cut:'
},
{
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: function() { BrowserWindow.getFocusedWindow().reload(); }
},
{
label: 'Toggle DevTools',
accelerator: 'Alt+CmdOrCtrl+I',
click: function() { BrowserWindow.getFocusedWindow().toggleDevTools(); }
},
]
},
{
label: 'Window',
submenu: [
{
label: 'Minimize',
accelerator: 'CmdOrCtrl+M',
selector: 'performMiniaturize:'
},
{
label: 'Close',
accelerator: 'CmdOrCtrl+W',
selector: 'performClose:'
},
{
type: 'separator'
},
{
label: 'Bring All to Front',
selector: 'arrangeInFront:'
}
]
},
{
label: 'Help',
submenu: []
}
];
menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
// Create the browser window.
createWindow();
});
function createWindow(data, title) {
data = typeof data !== 'undefined' ? data : '"","",""';
title = typeof title !== 'undefined' ? title : "Untitled.csv";
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Open the devtools.
mainWindow.openDevTools();
mainWindow.webContents.on('did-finish-load', function() {
mainWindow.setTitle(title);
mainWindow.webContents.send('loadData', data);
});
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
function openFile() {
Dialog.showOpenDialog(
{ filters: [
{ name: 'csv files', extensions: ['csv'] },
{ name: 'json schemas', extensions: ['json'] }
]}, function (fileNames) {
if (fileNames === undefined) {
return;
} else {
console.log("the file processed = "+JSON.stringify(fileNames));
var fileName = fileNames[0];
Fs.readFile(fileName, 'utf-8', function (err, data) {
createWindow(data, fileName);
});
}
});
}
function saveFile() {
window = BrowserWindow.getFocusedWindow();
Dialog.showSaveDialog({ filters: [
{ name: 'text', extensions: ['csv'] }
]}, function (fileName) {
if (fileName === undefined) return;
window.webContents.send('saveData', fileName);
});
}
function importExcel() {
Dialog.showOpenDialog({ filters: [
{ name: 'text', extensions: ['xlsx', 'xls'] }
]}, function (fileNames) {
if (fileNames === undefined) return;
var fileName = fileNames[0];
var workbook = XLSX.readFile(fileName);
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
popup = new BrowserWindow({width: 300, height: 150, 'always-on-top': true});
popup.loadUrl('file://' + __dirname + '/select_worksheet.html');
popup.webContents.on('did-finish-load', function() {
popup.webContents.send('loadSheets', workbook.SheetNames);
ipc.on('worksheetSelected', function(e, sheet_name) {
data = XLSX.utils.sheet_to_csv(workbook.Sheets[sheet_name]);
popup.close();
createWindow(data);
});
ipc.on('worksheetCanceled', function() {
popup.close();
});
});
popup.on('closed', function() {
popup = null;
});
});
}
function validateFile() {
window = BrowserWindow.getFocusedWindow();
window.webContents.send('validate');
}
| JavaScript | 0 | @@ -6759,32 +6759,34 @@
);%0A%0A ipc.on
+ce
('worksheetSelec
@@ -6960,16 +6960,18 @@
ipc.on
+ce
('worksh
|
2e7632ca63a003b2e228eafdc71181a1d273c09d | Update default User-Agent header to include package version. | lib/client/http.js | lib/client/http.js | 'use strict';
const http = require('http');
const url = require('url');
const utils = require('../utils');
const Client = require('../client');
/**
* Constructor for a Jayson HTTP Client
* @class ClientHttp
* @constructor
* @extends Client
* @param {Object|String} [options] String interpreted as a URL
* @param {String} [options.encoding="utf8"] Encoding to use
* @return {ClientHttp}
*/
const ClientHttp = function(options) {
// accept first parameter as a url string
if(typeof(options) === 'string') {
options = url.parse(options);
}
if(!(this instanceof ClientHttp)) {
return new ClientHttp(options);
}
Client.call(this, options);
const defaults = utils.merge(this.options, {
encoding: 'utf8'
});
this.options = utils.merge(defaults, options || {});
};
require('util').inherits(ClientHttp, Client);
module.exports = ClientHttp;
ClientHttp.prototype._request = function(request, callback) {
const self = this;
// copies options so object can be modified in this context
const options = utils.merge({}, this.options);
utils.JSON.stringify(request, options, function(err, body) {
if(err) {
return callback(err);
}
options.method = options.method || 'POST';
const headers = {
'Content-Length': Buffer.byteLength(body, options.encoding),
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json',
'User-Agent': 'jayson',
};
// let user override the headers
options.headers = utils.merge(headers, options.headers || {});
const req = self._getRequestStream(options);
self.emit('http request', req);
req.on('response', function(res) {
self.emit('http response', res, req);
res.setEncoding(options.encoding);
let data = '';
res.on('data', function(chunk) { data += chunk; });
res.on('end', function() {
// assume we have an error
if(res.statusCode < 200 || res.statusCode >= 300) {
// assume the server gave the reason in the body
const err = new Error(data);
err.code = res.statusCode;
callback(err);
} else {
// empty reply
if(!data || typeof(data) !== 'string') {
return callback();
}
utils.JSON.parse(data, options, callback);
}
});
});
// abort on timeout
req.on('timeout', function() {
req.abort(); // req.abort causes "error" event
});
// abort on error
req.on('error', function(err) {
self.emit('http error', err);
callback(err);
req.abort();
});
req.end(body);
});
};
/**
* Gets a stream interface to a http server
* @param {Object} options An options object
* @return {require('http').ClientRequest}
* @private
*/
ClientHttp.prototype._getRequestStream = function(options) {
return http.request(options || {});
};
| JavaScript | 0 | @@ -137,16 +137,67 @@
lient');
+%0Aconst %7B version %7D = require('../../package.json');
%0A%0A/**%0A *
@@ -1487,16 +1487,27 @@
t':
-'
+%60
jayson
-'
+-$%7Bversion%7D%60
,%0A
|
c4452923bc3f675d67e9e01e48356fde78a683db | switch to my local ubuntu mqtt server for testing instead | cms/webroot/js/base.js | cms/webroot/js/base.js | window.log = function() {
log.history = log.history || [];
log.history.push(arguments);
if(this.console){
console.log( Array.prototype.slice.call(arguments) );
}
};
function BaseChannelPath() {
var base_channel = "/helios/phoenix"
return base_channel;
}
function SubChannelPath(path) {
return BaseChannelPath() + "/" + path;
}
function AuthorizeMachine(info){
console.log(info);
$.post("/machines/authorize", info, function(data) {
log("Machine authorized: " + data);
});
}
function AddMachineEntry(payload, columns) {
try { var msg = $.parseJSON(payload); }
catch(e) { log("Failed to parse: " + payload); return; }
var row = $('<tr>');
columns.forEach(function(col) {
if (col == "is_authorized") {
row.append($('<td>').append(
$('<a>')
.click(function() { AuthorizeMachine(msg); return false; })
.text('authorize'))
);
} else {
row.append($('<td>').text((col in msg) ? msg[col] : ''));
}
});
$('.content table')
.find('tbody')
.append(row);
}
$(document).ready(function() {
var columns = [];
var thead = $('.content table thead tr th')
.each(function( index, value )
{
var header = $('a', value).length == 1 ? $('a', value).text() : $(value).text();
header = header.toLowerCase().replace(' ', '_');
columns.push(header);
});
var client = mqtt.connect("ws://test.mosquitto.org:8080/");
client.subscribe(SubChannelPath("machines"));
client.on("message", function(topic, payload) {
if (topic == SubChannelPath("machines"))
AddMachineEntry(payload, columns);
else
log([topic, payload].join(" : "));
client.end();
});
client.publish(BaseChannelPath(), "echo");
});
| JavaScript | 0 | @@ -1333,26 +1333,20 @@
s://
-test.mosquitto.org
+192.168.56.1
:808
|
012d6a1e5b173a24e7f6d99adddf4c8f1bf8d46b | remove token | main.js | main.js | var SlackClient = require("slack-client")
var shuffle = require("shuffle-array")
var token = "xoxb-14558007971-sBnunZdIb59EopEAKyIcLt57" // slackbot's integration token.
var autoReconnect = true // Automatically reconnect after an error response from Slack.
var autoMark = true // Automatically mark each message as read after it is processed.
var channels = {}
var slackbot = new SlackClient(token, autoReconnect, autoMark)
slackbot.on("open", slackopened)
slackbot.on("message", slackmessage)
function slackopened() {
console.log("I'm alive!")
}
function isMessageForMe(message) {
return (message.text && message.text.substr(0, 12) === `<@${slackbot.self.id}>`);
}
function startretro(channelID) {
channels[channelID] = {
plus: [],
minus: [],
question: []
users: []
}
var channel = slackbot.getChannelGroupOrDMByID(channelID)
console.log("Starting Retro")
channel.send("<!here|here>: Starting Retro Recording. \n Please use + for positive, - for negative, and ? for questions!")
}
function stopretro(channelID) {
if (channels[channelID] === undefined) { return }
// Shuffle Retro Feedback
shuffle(channels[channelID].plus)
shuffle(channels[channelID].minus)
shuffle(channels[channelID].question)
// Send the full retro to post
var channel = slackbot.getChannelGroupOrDMByID(channelID)
var summary = "```Randomized Summary of Inputs From This Retrospective \n\n"
summary += "# Positives: \n" + channels[channelID].plus.join("\n")
summary += "\n\n# Negatives: \n" + channels[channelID].minus.join("\n")
summary += "\n\n# Questions: \n" + channels[channelID].question.join("\n")
summary += "```"
channel.send(summary)
// Delete retro to reset
delete channels[channelID]
}
function addtoarray(channelID, line, type) {
if (line.length > 2) {
channels[channelID][type].push(line)
console.log(channels)
}
}
function adduser(channelID) {
}
function slackmessage(message) {
// console.log(message.text, message.channel, message.user)
if (! message.text) { return }
var channel = slackbot.getChannelGroupOrDMByID(message.channel)
if (isMessageForMe(message)) {
if (message.text.indexOf("start") >= 0) {
startretro(message.channel)
}
else if (message.text.indexOf("stop") >= 0) {
stopretro(message.channel)
}
else if (message.text.indexOf("help") >=0) {
channel.send("Let me help you make retrospectives great!\n"
+ "To start your retrospective type `@retrobot start`. "
+ "To end the retrospective and print out a randomized summary of feedback type `@retrobot stop`.\n\n"
+ "To make a positive remark, start your message with `+`. Negative or needs improvement, start with `-`. "
+ "For questions or ideas, start your messsage with a `?`\n\n"
+ "You can put multiple pieces of feedback in one message if you'd rather not print each thought on a new line.\n\n"
+ "I was made by @kat. Please direct questions or feedback to her.")
}
else {
channel.send("That is not a retro command! (Try @retrobot help)")
}
}
else if (channels[message.channel] !== undefined) {
var lines = message.text.split("\n")
console.log(lines)
for (i in lines) {
console.log(lines[i])
var char1 = lines[i].substr(0,1)
switch(char1) {
case "+":
addtoarray(message.channel, lines[i], "plus")
break
case "-":
addtoarray(message.channel, lines[i], "minus")
break
case "?":
addtoarray(message.channel, lines[i], "question")
break
}
}
}
}
slackbot.login()
| JavaScript | 0.000638 | @@ -1,12 +1,37 @@
+require(%22dotenv%22).load()%0A
var SlackCli
@@ -116,51 +116,31 @@
n =
-%22xoxb-14558007971-sBnunZdIb59EopEAKyIcLt57%22
+process.env.SLACK_TOKEN
//
@@ -776,20 +776,8 @@
%5B%5D%0A
-%09%09users: %5B%5D%0A
%09%7D%0A%09
@@ -1838,42 +1838,8 @@
%0A%7D%0A%0A
-function adduser(channelID) %7B%0A%0A%7D%0A%0A
func
|
b49b4076f4b4e471bd2cb6ac01ddc8dd48548db8 | Add title method | lib/controllers.js | lib/controllers.js | /* ================================================================
* macaca-ios by xdf(xudafeng[at]126.com)
*
* first created at : Tue Mar 17 2015 00:16:10 GMT+0800 (CST)
*
* ================================================================
* Copyright xdf
*
* Licensed under the MIT License
* You may not use this file except in compliance with the License.
*
* ================================================================ */
'use strict';
const co = require('co');
const errors = require('webdriver-dfn-error-code').errors;
const _ = require('./helper');
const ELEMENT_OFFSET = 1000;
const implicitWaitForCondition = function(func) {
return _.waitForCondition(func, this.implicitWaitMs);
};
const convertAtoms2Element = function(atoms) {
const atomsId = atoms && atoms.ELEMENT;
if (!atomsId) {
return null;
}
const index = this.atoms.push(atomsId) - 1;
return {
ELEMENT: index + ELEMENT_OFFSET
};
};
const convertElement2Atoms = function(elementId) {
let atomsId;
try {
atomsId = this.atoms[parseInt(elementId, 10) - ELEMENT_OFFSET];
} catch (e) {
return null;
}
return {
ELEMENT: atomsId
};
};
const findElementOrElements = function *(strategy, selector, ctx, many) {
let result;
const that = this;
// TODO const atoms = this.convertElement2Atoms(ctx);
function *search() {
result = yield that.sendCommand(`find_element${many ? 's' : ''}`, [strategy, selector, null]);
return _.size(result) > 0;
}
try {
yield implicitWaitForCondition.call(this, co.wrap(search));
} catch(err) {
result = [];
}
if (many) {
return result.map(convertAtoms2Element.call(this));
} else {
if (!result || _.size(result) === 0) {
throw new errors.NoSuchElement();
}
return convertAtoms2Element.call(this, result);
}
};
const sendCommand = function *(atom, args) {
let frames = [];
return yield this.remote.sendCommand(atom, args, frames);
};
const controllers = {};
controllers.getScreenshot = function *(context) {
const data = yield this.xctest.sendCommand(context.url, context.method, context.body);
const result = JSON.parse(data);
return result.value;
};
controllers.click = function *(elementId) {
const atomsElement = convertElement2Atoms.call(this, elementId);
return yield sendCommand.call(this, 'click', [atomsElement]);
};
controllers.findElement = function *(strategy, selector, ctx) {
return yield findElementOrElements.call(this, strategy, selector, ctx, false);
};
controllers.findElements = function *(strategy, selector, ctx) {
return yield findElementOrElements.call(this, strategy, selector, ctx, true);
};
controllers.getText = function *(elementId) {
const atomsElement = convertElement2Atoms.call(this, elementId);
return yield sendCommand.call(this, 'get_text', [atomsElement]);
};
controllers.setValue = function *(elementId, value) {
const atomsElement = convertElement2Atoms.call(this, elementId);
yield sendCommand.call(this, 'click', [atomsElement]);
return yield sendCommand.call(this, 'type', [atomsElement, value]);
};
controllers.title = function *() {
return yield sendCommand.call(this, 'title', [], true);
};
controllers.execute = function *(script, args) {
args = args.map(arg => {
if (arg.ELEMENT) {
return convertElement2Atoms(this, arg.ELEMENT);
}
});
return yield sendCommand.call(this, 'execute_script', [script, args]);
};
controllers.url = function *() {
const pages = yield this.remote.getPages();
if (pages.length === 0) {
throw errors.NoSuchWindow();
}
const latestPage = _.last(pages);
return latestPage.url;
};
controllers.get = function *(url) {
throw errors.NotImplementedError();
};
controllers.forward = function *() {
throw errors.NotImplementedError();
};
controllers.back = function *() {
throw errors.NotImplementedError();
};
controllers.refresh = function *() {
throw errors.NotImplementedError();
};
module.exports = controllers;
| JavaScript | 0.001495 | @@ -3133,62 +3133,178 @@
%7B%0A
-return yield sendCommand.call(this, 'title', %5B%5D, true)
+const pages = yield this.remote.getPages();%0A if (pages.length === 0) %7B%0A throw errors.NoSuchWindow();%0A %7D%0A const latestPage = _.last(pages);%0A return latestPage.title
;%0A%7D;
|
a235209ce151e7f22a339135934778a29dd03048 | print error message | main.js | main.js | import { perform } from "./tasks";
import fs from 'fs';
import config from "./config"
function setupGoCDAuth(config) {
if (config.gocd && config.gocd.auth) {
const auth = config.gocd.auth;
if (auth.username === "ENV_GOCD_USERNAME") {
auth.username = process.env.GOCD_USERNAME;
}
if (auth.password === "ENV_GOCD_PASSWORD") {
auth.password = process.env.GOCD_PASSWORD;
}
}
}
function setupCircleciToken(config) {
const circleci = config.circleci;
if (circleci && circleci.token) {
if (circleci.token === "ENV_CIRCLECI_TOKEN") {
circleci.token = process.env.CIRCLECI_TOKEN;
}
}
}
async function main() {
setupGoCDAuth(config);
setupCircleciToken(config);
var pipelines = await perform(config);
return new Promise((resolve, reject) => {
fs.writeFile("./pipelines.json", JSON.stringify(pipelines, null, 2), (error) => {
if(error) {
return reject(error);
}
return resolve(pipelines)
});
})
}
setInterval(async () => {
try {
await main();
} catch(e) {
console.log("[ERROR]" + new Date())
}
}, 30000);
| JavaScript | 0.000012 | @@ -1042,59 +1042,105 @@
;%0A
-%7D catch(e) %7B%0A console.log(%22%5BERROR%5D%22 + new Date()
+ console.log(new Date(), %22%5BOK%5D%22)%0A %7D catch(e) %7B%0A console.log(new Date(), %22%5BERROR%5D%22, e.message
)%0A
|
dc87771b99d31927c9e288e9c8f5a78f1a386adb | Fix font size, line height and selection background | main.js | main.js | define(function (require, exports, module) {
"use strict";
var ExtensionUtils = brackets.getModule("utils/ExtensionUtils");
ExtensionUtils.addEmbeddedStyleSheet("* { font-size: 22px !important; line-height: 25px !important; }");
});
| JavaScript | 0 | @@ -173,9 +173,253 @@
et(%22
-*
+#sidebar *, #main-toolbar *, #titlebar *, #problems-panel *,%22+%0A%09%22#find-in-files-results *, #e4b-main-panel *, #status-bar *,%22+%0A%09%22#main-toolbar *, #context-menu-bar *, #codehint-menu-bar *,%22+%0A%09%22#quick-view-container *, #function-hint-container *
%7B f
@@ -444,16 +444,21 @@
portant;
+%22+%0A%09%22
line-he
@@ -482,15 +482,163 @@
tant; %7D%22
++%0A%09%22.sidebar li %7B min-height: 25px !important;%7D%22+%0A%09%22.sidebar-selection, .filetree-selection %7B min-height: 30px !important; margin-top: 3px;%7D%22+%0A%09%22%22%0A%09
);%0A%7D);%0A
|
400325c87b9f17abfcbebf0cf8099a33df570e40 | Add some comments to the main functions | main.js | main.js | function main() {
gmail3AddMsgConsumers();
gmail3.main();
}
function enableDebugMode() {
PropertiesService.getUserProperties().setProperty("debugEnabled", "true");
Logger.log("Debugging enabled");
}
function disableDebugMode() {
PropertiesService.getUserProperties().setProperty("debugEnabled", "false");
Logger.log("Debugging disabled");
}
function resetScriptState() {
var userProperties = PropertiesService.getUserProperties();
userProperties.deleteAllProperties();
var projectTriggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < projectTriggers.length; i++) {
ScriptApp.deleteTrigger(projectTriggers[i]);
}
var files = DriveApp.searchFiles("title contains 'gmail3 Data'");
while (files.hasNext()) {
var file = files.next();
Logger.log("Trashing: " + file.getName());
file.setTrashed(true);
}
}
| JavaScript | 0 | @@ -1,68 +1,399 @@
-function main() %7B%0A gmail3AddMsgConsumers();%0A gmail3.main();%0A%7D%0A
+/**%0A * Used to start the script. Adds a daily trigger and then begins to process%0A * messages. Once it is through processing a batch of messages it will schedule%0A * the next trigger. %0A */%0Afunction main() %7B%0A gmail3AddMsgConsumers();%0A gmail3.main();%0A%7D%0A%0A/**%0A * Enables more verbose logging and only processes 20 messages per run. Also%0A * restricts the total messages processed per month to 40.%0A */
%0Afun
@@ -525,32 +525,59 @@
g enabled%22);%0A%7D%0A%0A
+/** Disables debug mode */%0A
function disable
@@ -707,16 +707,137 @@
d%22);%0A%7D%0A%0A
+/**%0A * Deletes all existing gmail3 Google sheets, and deletes all triggers. This%0A * effectively disables the script.%0A */%0A
function
|
7b5c13c5cbfd0d39c89d1af0913036a0999d4504 | Remove unused fs | lib/customUtils.js | lib/customUtils.js | var crypto = require('crypto')
, fs = require('fs')
;
/**
* Return a random alphanumerical string of length len
* There is a very small probability (less than 1/1,000,000) for the length to be less than len
* (il the base64 conversion yields too many pluses and slashes) but
* that's not an issue here
* The probability of a collision is extremely small (need 3*10^12 documents to have one chance in a million of a collision)
* See http://en.wikipedia.org/wiki/Birthday_problem
*/
function uid (len) {
return crypto.randomBytes(Math.ceil(Math.max(8, len * 2)))
.toString('base64')
.replace(/[+\/]/g, '')
.slice(0, len);
}
// Interface
module.exports.uid = uid;
| JavaScript | 0.000001 | @@ -28,31 +28,8 @@
o')%0A
- , fs = require('fs')%0A
;%0A
|
f03eb3d59d77748a8e44173460eadfbc1b91a0d6 | Fix file error call parameters | lib/data/Binary.js | lib/data/Binary.js | // Dependencies ---------------------------------------------------------------
// ----------------------------------------------------------------------------
var fs = require('fs'),
path = require('path');
// Binary Includes ------------------------------------------------------------
// ----------------------------------------------------------------------------
function Binary(file, src, section, line, col) {
this.file = file;
this.src = path.join(path.dirname(this.file.path), src);
this.section = section;
this.offset = -1;
try {
this.size = fs.lstatSync(this.src).size;
} catch(err) {
this.file.fileError(err, 'include binary data', line, col);
}
this.section.add(this);
}
Binary.prototype = {
getBuffer: function() {
return fs.readFileSync(this.src);
}
};
// Exports --------------------------------------------------------------------
module.exports = Binary;
| JavaScript | 0.000001 | @@ -439,16 +439,147 @@
= file;%0A
+%0A if (src.substring(0, 1) === '/') %7B%0A this.src = path.join(this.file.compiler.base, src.substring(1));%0A%0A %7D else %7B%0A
this
@@ -627,24 +627,31 @@
ath), src);%0A
+ %7D%0A%0A
this.sec
@@ -764,24 +764,24 @@
atch(err) %7B%0A
-
this
@@ -823,16 +823,26 @@
y data',
+ this.src,
line, c
|
de8c845d3eaf3a7722278b0843cc83d470f17715 | Update club endpoint for intake form | web/src/redux/modules/clubs.js | web/src/redux/modules/clubs.js | const LOAD = 'hackclub/clubs/LOAD'
const LOAD_SUCCESS = 'hackclub/clubs/LOAD_SUCCESS'
const LOAD_FAIL = 'hackclub/clubs/LOAD_FAIL'
const initialState = {
loaded: false
}
export default function reducer(state=initialState, action={}) {
switch (action.type) {
case LOAD:
return {
...state,
loading: true
}
case LOAD_SUCCESS:
return {
...state,
loading: false,
loaded: true,
data: action.result,
error: null
}
case LOAD_FAIL:
return {
...state,
loading: false,
loaded: false,
data: null,
error: action.error
}
default:
return state
}
}
export function isLoaded(globalState) {
return globalState.clubs && globalState.clubs.loaded
}
export function load() {
return {
types: [LOAD, LOAD_SUCCESS, LOAD_FAIL],
promise: client => client.get('/v1/clubs/to_be_onboarded')
}
}
| JavaScript | 0 | @@ -870,23 +870,14 @@
ubs/
-to_be_onboarded
+intake
')%0A
|
0417a5f3b476d2818d0d78230cedce78d61a7560 | Make sure appspec.yml is bundled | webapp/tasks/config/package.js | webapp/tasks/config/package.js | import path from 'path'
export default {
src: [
'{bin,rhizome,datapoints,templates,env_var}/**/*.*',
'webapp*/public*/**/*.*',
'docs*/_build/**/*.*',
'manage.py',
'requirements.txt',
'settings.py',
'initial_data.xlsx'
].map(file => {
return path.join(process.cwd(), '..') + '/' + file
}),
dest: path.join(process.cwd(), '../dist'),
options: {
filename: 'rhizome.zip'
}
}
| JavaScript | 0.000001 | @@ -171,24 +171,43 @@
manage.py',%0A
+ 'appspec.yml',%0A
'require
|
19b9642886a00ec8a3171ab3b7791c2385b8b546 | check mainWindow's existence before sending message | main.js | main.js | const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
// ipcMain module
const ipcMain = electron.ipcMain;
// file system module
const fs = require('fs');
const path = require('path');
const url = require('url');
// set up local express server for python data processing
var server = require('./server/express');
const isDevelopment = (process.env.NODE_ENV === 'development');
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
titleBarStyle: 'hidden',
frame: false,
show: false,
})
// and load the index.html of the app.
mainWindow.loadURL('file://' + path.join(__dirname, 'index.html'));
// Open the DevTools.
// mainWindow.webContents.openDevTools()
global.mainWindow = mainWindow;
// Require mainmenu from mainmenu.js
require('./menu/mainmenu');
// set window to show once renderer process has rendered the page
mainWindow.once('ready-to-show', () => {
mainWindow.show()
})
// Emitted when the window is closed
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
fs.writeFile(path.resolve(__dirname, 'src/components/temp/temp.html'), '//code here', (err) => {
if (err) throw err;
// console.log('The file has been emptied!');
})
mainWindow = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', () => {
// create initial main window
createWindow();
// let editorView = document.getElementById('editor');
// let webview = document.getElementById('render-window');
// pop out editor
ipcMain.on('popEditor', (event, arg) => {
if (!global.newEditor) {
if (global.newWebView) {
global.newWebView.destroy();
mainWindow.webContents.send('openWebView');
}
let newEditor = new BrowserWindow({ width: 800, height: 600 });
newEditor.loadURL(url.format({
pathname: path.join(__dirname, 'editor.html'),
protocol: 'file:',
slashes: true
}))
global.newEditor = newEditor;
setTimeout(() => {
newEditor.webContents.send('editorMsg', arg);
}, 1000);
newEditor.on('close', (event) => {
newEditor.webContents.send('editorClose');
mainWindow.webContents.send('resize');
});
newEditor.on('closed', (event) => {
if (mainWindow) {
mainWindow.webContents.send('updateMain');
global.newEditor = null;
}
});
}
});
ipcMain.on('fileUpload', (event, arg) => {
if (global.newEditor) {
global.newEditor.webContents.send('editorMsg', arg);
}
if (global.newWebView) {
global.newWebView.reload();
}
});
ipcMain.on('updateMain', (event) => {
mainWindow.webContents.send('updateMain');
if (global.newWebView) {
global.newWebView.reload();
}
});
ipcMain.on('updateAttr', (event) => {
mainWindow.webContents.send('updateAttr');
if (global.newWebView) {
global.newWebView.reload();
}
});
ipcMain.on('updateNewWebView', (event) => {
if (global.newWebView) {
global.newWebView.reload();
}
});
ipcMain.on('openDataWin', (event, arg) => {
if (!global.dataWin) {
let dataWin = new BrowserWindow({ width: 800, height: 600 });
dataWin.loadURL('file://' + path.join(__dirname, 'src/dataWindow/app/index.html'))
global.dataWin = dataWin;
dataWin.on('closed', () => {
global.dataWin = null;
})
}
});
// pop out live render window
ipcMain.on('popRender', (event, arg) => {
if (!global.newWebView) {
if (global.newEditor) {
global.newEditor.destroy();
mainWindow.webContents.send('openEditor');
}
let newWebView = new BrowserWindow({ width: 800, height: 600 });
newWebView.loadURL('file://' + path.resolve(__dirname, 'src/components/temp/temp.html'))
global.newWebView = newWebView;
newWebView.on('close', (event) => {
mainWindow.webContents.send('resize');
});
newWebView.on('closed', (event) => {
if (mainWindow) {
global.newWebView = null;
}
});
}
});
});
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit(() => {
var file = fs.readFileSync('./src/components/temp/onload.html');
fs.writeFileSync('./src/components/temp/temp.html', file);
})
}
})
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
| JavaScript | 0 | @@ -1297,24 +1297,71 @@
how()%0A %7D)%0A%0A
+ // mainWindow.on('close', () =%3E %7B%0A%0A // %7D);%0A%0A
// Emitted
@@ -1757,60 +1757,8 @@
rr;%0A
- // console.log('The file has been emptied!');%0A
@@ -2819,24 +2819,52 @@
torClose');%0A
+ if (mainWindow) %7B%0A
main
@@ -2890,32 +2890,42 @@
send('resize');%0A
+ %7D%0A
%7D);%0A%0A
@@ -4594,32 +4594,60 @@
', (event) =%3E %7B%0A
+ if (mainWindow) %7B%0A
mainWind
@@ -4673,24 +4673,34 @@
('resize');%0A
+ %7D%0A
%7D);%0A%0A
|
5a4ecc1dcfd8a00861f31ad926965788a0d067ef | Return support of old algorithm (changing document.location) | main.js | main.js | links = document.links;
for(var i = 0; i < links.length; ++i) {
href = links[i].href;
if(href) {
if(href.match(/http:\/\/vkontakte\.ru\/away\.php\?to=/)) {
links[i].href = unescape(href.substr(32));
}
if(href.match(/http:\/\/vk\.com\/away\.php\?to=/)) {
links[i].href = unescape(href.substr(26));
}
}
}
| JavaScript | 0 | @@ -1,112 +1,76 @@
-links = document.links;%0Afor(var i = 0; i %3C links.length; ++i) %7B%0A href = links%5Bi%5D.href;%0A if(href) %7B%0A
+function replace_away_link_at(obj) %7B%0A if(!obj.href) return;%0A%0A
if(
+ obj.
href
@@ -69,32 +69,33 @@
obj.href.match(/
+%5E
http:%5C/%5C/vkontak
@@ -107,39 +107,35 @@
u%5C/away%5C.php
-%5C?to=
/)
+
) %7B%0A
links%5Bi%5D.h
@@ -118,34 +118,27 @@
p/) ) %7B%0A
- links%5Bi%5D
+obj
.href = unes
@@ -134,32 +134,36 @@
href = unescape(
+obj.
href.substr(32))
@@ -168,21 +168,22 @@
));%0A
-
%7D%0A
-
if(
+ obj.
href
@@ -190,16 +190,17 @@
.match(/
+%5E
http:%5C/%5C
@@ -222,23 +222,19 @@
.php
-%5C?to=
/)
+
) %7B%0A
li
@@ -233,18 +233,11 @@
- links%5Bi%5D
+obj
.hre
@@ -249,16 +249,20 @@
nescape(
+obj.
href.sub
@@ -277,14 +277,151 @@
;%0A
- %7D%0A %7D
+%7D%0A%7D%0A%0Areplace_away_link_at(document.location);%0A%0Alinks = document.links;%0Afor(var i = 0; i %3C links.length; ++i) %7B%0A replace_away_link_at(links%5Bi%5D);
%0A%7D%0A
|
7dda8fe55cb3c05340d05cd2837e84023e7f509f | Add WebVTT subtitles drop on each browsers | main.js | main.js | function lg(s) { console.log(s); }
var
elBody = document.body,
elVideo = document.querySelector( "video" )
;
elBody.ondragover = function() {
lg("body:ondragover");
return false;
};
elBody.ondrop = function( e ) {
lg("body:ondrop");
elVideo.src = URL.createObjectURL( e.dataTransfer.files[ 0 ] );
elVideo.play();
return false;
};
| JavaScript | 0 | @@ -135,32 +135,33 @@
unction() %7B%0A%09lg(
+
%22body:ondragover
@@ -161,16 +161,17 @@
ragover%22
+
);%0A%09retu
@@ -220,16 +220,17 @@
) %7B%0A%09lg(
+
%22body:on
@@ -238,92 +238,1031 @@
rop%22
+
);%0A
-%09elVideo.src = URL.createObjectURL( e.dataTransfer.files%5B 0 %5D );%0A%09elVideo.play();
+%0A%09var%0A%09%09// Save file's informations%0A%09%09dropFile = e.dataTransfer.files%5B 0 %5D,%0A%09%09// Create a temporary fake absolute path to the dropped file%0A%09%09dropFileUrl = URL.createObjectURL( dropFile )%0A%09;%0A%0A%09// Check type file, eg : %22video/mp4%22 -%3E %22video%22%0A%09switch ( dropFile.type.substr( 0, dropFile.type.indexOf( %22/%22 ) ) ) %7B%0A%0A%09%09case %22video%22 :%0A%09%09%09elVideo.src = dropFileUrl;%0A%09%09%09elVideo.play();%0A%09%09break;%0A%0A%09%09default :%0A%09%09%09switch ( dropFile.name.substr( dropFile.name.lastIndexOf( %22.%22 ) + 1 ) ) %7B%0A%0A%09%09%09%09case %22vtt%22 :%0A%09%09%09%09%09var elTrack = document.createElement( %22track%22 );%0A%09%09%09%09%09elTrack.kind = %22subtitles%22;%0A%09%09%09%09%09elTrack.src = dropFileUrl;%0A%09%09%09%09%09elTrack.label = %22Subtitles %22 + ( elVideo.textTracks ? elVideo.textTracks.length + 1 : 1 );%0A%09%09%09%09%09elTrack.srclang = %22en%22; // TODO: We must find a way to made it generically%0A%09%09%09%09%09elVideo.appendChild( elTrack );%0A%09%09%09%09%09elTrack.addEventListener( %22load%22, function() %7B%0A%09%09%09%09%09%09// Set this track to be the active one%0A%09%09%09%09%09%09this.mode =%0A%09%09%09%09%09%09elVideo.textTracks%5B 0 %5D.mode = %22showing%22;%0A%09%09%09%09%09%7D); %0A%09%09%09%09break;%0A%09%09%09%7D%0A%09%7D%0A%09
%0A%09re
|
2590df1969601d12743fcc2fbc3dbd57c4ae453a | update version | main.js | main.js | // ==UserScript==
// @name Warcraft Logs Enhancement
// @namespace https://github.com/icyblade/warcraftlogs_enhancement
// @version 0.2
// @description Some Enhancement Scripts of Warcraft Logs
// @author swqsldz, kingofpowers, icyblade
// @match https://*.warcraftlogs.com/*
// @run-at document-idle
// ==/UserScript==
const attributes = ['critSpell', 'hasteSpell', 'mastery', 'versatilityDamageDone'];
const columnNames = ['Crit', 'Haste', 'Mastery', 'Versatility'];
const regex = /\/reports\/([\S\s]+?)#fight=([0-9]+)/;
const HOST = 'https://' + window.location.hostname;
var PlayerList = new Array();
function initialize() {
// initialize attribute columns
for (let i = 0; i < attributes.length; i++) {
$('<th class="sorting ui-state-default">' + columnNames[i] + '</th>').insertBefore('th.zmdi.zmdi-flag.sorting.ui-state-default');
}
for (let i = 0; i < attributes.length; i++) {
$('<td class="attr-' + attributes[i] + '"></td>').insertBefore('td.zmdi.zmdi-flag');
}
// extract fights from ranking page
$('td.unique-gear').parent().each(function() {
var player = new Object();
player.rowID = $(this).attr('id');
player.name = $(this).find('.players-table-name .main-table-player').text();
var href = $(this).find('.players-table-name .main-table-player').attr('href');
if (typeof(href) == 'undefined') {
return;
}
player.logID = href.match(regex)[1];
player.fightID = href.match(regex)[2];
PlayerList.push(player);
});
}
function loadFights(index) {
$.ajax({
type: 'GET',
url: HOST + '/reports/fights_and_participants/' + PlayerList[index].logID + '/0',
dataType: 'json',
success: function(data) {
console.log(index);
callback_fights(data, index);
}
});
}
function loadStats(rowID, logID, fightID, timestamp, sourceID) {
$.ajax({
type: 'GET',
url: HOST + '/reports/summary_events/' + logID + '/' + fightID + '/' + timestamp + '/' + (timestamp + 3000) + '/' + sourceID + '/0/Any/0/-1.0.-1/0',
dataType: 'json',
success: function(data) {
callback_stats(data, rowID, logID, fightID, timestamp, sourceID);
}
});
}
function callback_stats(data, rowID, logID, fightID, timestamp, sourceID) {
for (var key in attributes) {
try {
$('#' + rowID + ' .attr-' + attributes[key]).html(data.events[0][attributes[key]]);
} catch (e) {
console.error(e);
console.error(rowID);
console.error(data);
}
}
}
function callback_fights(data, idx) {
PlayerList[idx].fight = data;
for (let j in PlayerList[idx].fight.friendlies) {
if (PlayerList[idx].fight.friendlies[j].name == PlayerList[idx].name) {
PlayerList[idx].sourceID = PlayerList[idx].fight.friendlies[j].id;
break;
}
}
for (let j in PlayerList[idx].fight.fights) {
if (PlayerList[idx].fight.fights[j].id == PlayerList[idx].fightID) {
PlayerList[idx].timestamp = PlayerList[idx].fight.fights[j].start_time;
break;
}
}
loadStats(PlayerList[idx].rowID, PlayerList[idx].logID, PlayerList[idx].fightID, PlayerList[idx].timestamp, PlayerList[idx].sourceID);
idx++;
if (idx >= PlayerList.length) {
console.log(PlayerList);
return;
}
loadFights(idx);
}
function loadAttributes() {
initialize();
loadFights(0);
}
function delayLoadAttributes() {
if ($('.ranking-table tr:eq(1)').length === 0) {
console.log('delay');
setTimeout(delayLoadAttributes, 1000);
} else {
loadAttributes();
}
}
delayLoadAttributes();
| JavaScript | 0 | @@ -143,17 +143,17 @@
0.
-2
+3
%0A// @des
|
f8dfb59f53a9b4299c1899dff6303c8a10addd7b | add file->quit to non-mac | main.js | main.js | 'use strict';
const electron = require('electron');
const app = electron.app; // Module to control application life.
const Menu = electron.Menu;
const shell = electron.shell;
const core = require('./src/core/main-process');
const name = electron.app.getName();
const BrowserWindow = electron.BrowserWindow; // Module to create native browser window.
// Report crashes to our server.
electron.crashReporter.start();
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit();
}
});
app.on('before-quit', function() {
BrowserWindow.getAllWindows().forEach((win) => {
win.destroy();
})
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
core.init();
// Create the Application's main menu
let template = [{
label: "Edit",
submenu: [
{ label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
{ label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
{ type: "separator" },
{ label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
{ 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: function(item, focusedWindow) {
if (focusedWindow)
focusedWindow.reload();
}
},
{
label: 'Toggle Full Screen',
accelerator: (function() {
if (process.platform == 'darwin')
return 'Ctrl+Command+F';
else
return 'F11';
})(),
click: function(item, focusedWindow) {
if (focusedWindow)
focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
}
},
{
label: 'Toggle Developer Tools',
accelerator: (function() {
if (process.platform == 'darwin')
return 'Alt+Command+I';
else
return 'Ctrl+Shift+I';
})(),
click: function(item, focusedWindow) {
if (focusedWindow) {
focusedWindow.toggleDevTools();
focusedWindow.send('toggle-webview-inspector');
}
}
},
]
},
{
label: 'Window',
role: 'window',
submenu: [
{
label: 'Minimize',
accelerator: 'CmdOrCtrl+M',
role: 'minimize'
},
{
label: 'Close',
accelerator: 'CmdOrCtrl+W',
role: 'close'
},
]
},
{
label: 'Help',
role: 'help',
submenu: [
{
label: 'Github Repository',
click: function() { shell.openExternal('https://github.com/kfatehi/modmail') }
},
{
label: 'Search Issues',
click: function() { shell.openExternal('https://github.com/kfatehi/modmail/issues') }
}
]
},
];
if (process.platform == 'darwin') {
template.unshift({
label: name,
submenu: [
{
label: 'About ' + name,
role: 'about'
},
{
type: 'separator'
},
{
label: 'Services',
role: 'services',
submenu: []
},
{
type: 'separator'
},
{
label: 'Hide ' + name,
accelerator: 'Command+H',
role: 'hide'
},
{
label: 'Hide Others',
accelerator: 'Command+Shift+H',
role: 'hideothers'
},
{
label: 'Show All',
role: 'unhide'
},
{
type: 'separator'
},
{
label: 'Quit',
accelerator: 'Command+Q',
click: function() {
app.quit();
}
},
]
});
}
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
});
| JavaScript | 0 | @@ -4303,16 +4303,252 @@
%7D);%0A %7D
+ else %7B%0A template.unshift(%7B%0A label: %22File%22,%0A submenu: %5B%0A %7B%0A label: 'Quit',%0A accelerator: 'Command+Q',%0A click: function() %7B%0A app.quit();%0A %7D%0A %7D,%0A %5D%0A %7D);%0A %7D
%0A%0A Menu
|
001c85f7f6d05e7b5d84ed4db8ce122bf513f5c5 | Rename randomTip | main.js | main.js | fetch('tips.json')
.then(response => response.json())
.then(tips => {
let randomTip = tips[Math.floor(Math.random() * tips.length)];
let tipCategoryElem = document.getElementById('tip-category');
let tipTextElem = document.getElementById('tip-text');
// Update category text and class
tipCategoryElem.textContent = randomTip.tool;
tipCategoryElem.classList.add(randomTip.toolSlug);
// Update tip text and add source link if applicable
let tipText = randomTip.text.replace(/\[/g, '<code>').replace(/\]/g, '</code>');
tipTextElem.innerHTML = tipText;
if (randomTip.source) {
let learnMore = document.createElement('a');
learnMore.href = randomTip.source;
learnMore.classList.add('learn-more');
learnMore.textContent = 'Learn More';
tipTextElem.appendChild(learnMore);
}
})
.catch(error => console.log({ error })); | JavaScript | 0.001964 | @@ -75,25 +75,27 @@
let
-randomTip
+tipOfTheDay
= tips%5B
@@ -336,25 +336,27 @@
ntent =
-randomTip
+tipOfTheDay
.tool;%0A
@@ -388,25 +388,27 @@
ist.add(
-randomTip
+tipOfTheDay
.toolSlu
@@ -487,25 +487,27 @@
pText =
-randomTip
+tipOfTheDay
.text.re
@@ -602,25 +602,27 @@
if (
-randomTip
+tipOfTheDay
.source)
@@ -702,17 +702,19 @@
f =
-randomTip
+tipOfTheDay
.sou
|
db1474a05baf6ee21d729c25c13134259867c768 | update err path for mongoose 4.x | lib/entity-base.js | lib/entity-base.js | /**
* @fileOverview The entities base class.
*/
var __ = require('lodash');
var EntityCrudMongoose = require('node-entity').Mongoose;
var appError = require('nodeon-error');
var log = require('logg').getLogger('nodeON-base.EntityBase');
/**
* The base Entity Class all entities extend from.
*
* @constructor
* @extends {crude.Entity}
*/
var Entity = module.exports = EntityCrudMongoose.extend();
/**
* Wrap the default "create" method,
* taking care to normalize any error messages.
*
* @param {Object} itemData The data to use for creating.
* @param {Function(?app.error.Abstract, Mongoose.Model=)} done callback.
* @override
*/
Entity.prototype._create = function(itemData) {
// stub to default for now until Mongoose is normalized
return EntityCrudMongoose.prototype._create.call(this, itemData)
.bind(this)
.catch(this._normalizeError);
};
/**
* Wrap the default "update" method,
* taking care to normalize any error messages.
*
* @param {Object|string} query The query.
* @param {Object} itemData The data to use for updating.
* @param {Function(?app.error.Abstract, Mongoose.Model=)} done callback.
* @override
*/
Entity.prototype._update = function(query, itemData) {
// stub to default for now until Mongoose is normalized
return EntityCrudMongoose.prototype._update.call(this, query, itemData)
.bind(this)
.catch(this._normalizeError);
};
/**
* Normalize errors comming from the db
*
* @param {Object} err Error as provided by the orm.
* @return {Promise} A Promise.
* @private
* @throws {app.error.ErrorBase} always.
*/
Entity.prototype._normalizeError = function(err) {
log.fine('_normalizeError() :: Error intercepted, code:', err.code, err.message);
log.finest('_normalizeError() :: Error stack:', err.stack);
var error = new appError.Validation(err);
switch(err.code) {
case 11000:
var items = err.err.match(/key error index:\s(.+)\.(\w+)\.\$([\w\_]+)\s/);
// error.db = items[1];
// error.collection = items[2];
error.index = items[3];
error.message = 'Duplicate record found';
// now cleanup the error object
delete error.err;
delete error.code;
delete error.n;
delete error.connectionId;
delete error.ok;
break;
case 11001:
error.message = 'Duplicate record found';
break;
default:
if (err.message === 'record not found') {
error = new appError.Error('record not found');
}
if (err.type === 'ObjectId' && err.message.match(/Cast to ObjectId failed/)) {
error.message = 'Attribute requires a proper id value';
}
}
// check for mongoose specific validation errors
if (err.name === 'ValidationError') {
__.forOwn(err.errors, function(value) {
error.errors.push(value);
});
}
throw error;
};
| JavaScript | 0 | @@ -1880,16 +1880,19 @@
err.err
+msg
.match(/
@@ -2134,16 +2134,19 @@
rror.err
+msg
;%0A de
|
eece235c288329d48d5496e9bb9c9c6719bdd155 | Use portable $(window).innerHeight() for IE8. | src/pat/modal.js | src/pat/modal.js | define([
"jquery",
"../core/parser",
"../registry",
"./inject"
], function($, Parser, registry, inject) {
var parser = new Parser("modal");
parser.add_argument("class");
var modal = {
name: "modal",
jquery_plugin: true,
// div's are turned into modals
// links and forms inject modals
trigger: "div.pat-modal, a.pat-modal, form.pat-modal",
init: function($el, opts) {
return $el.each(function() {
var $el = $(this),
cfg = parser.parse($el, opts);
if ($el.is("div"))
modal._init_div1($el, cfg);
else
modal._init_inject1($el, cfg);
});
},
_init_inject1: function($el, cfg) {
var opts = {
target: "#pat-modal",
"class": "pat-modal" + (cfg["class"] ? " " + cfg["class"] : "")
};
// if $el is already inside a modal, do not detach #pat-modal,
// because this would unnecessarily close the modal itself
if (!$el.closest("#pat-modal")) {
$("#pat-modal").detach();
}
inject.init($el, opts);
},
_init_div1: function($el) {
var $header = $("<div class='header' />"),
activeElement = document.activeElement;
$("<button type='button' class='close-panel'>Close</button>").appendTo($header);
// We cannot handle text nodes here
$el.children(":last, :not(:first)")
.wrapAll("<div class='panel-content' />");
$(".panel-content", $el).before($header);
$el.children(":first:not(.header)").prependTo($header);
// Restore focus in case the active element was a child of $el and
// the focus was lost during the wrapping.
activeElement.focus();
// event handlers remove modal - first arg to bind is ``this``
$(document).on("click.pat-modal", ".close-panel",
modal.destroy.bind($el, $el));
// remove on ESC
$(document).on("keyup.pat-modal",
modal.destroy.bind($el, $el));
modal.setPosition();
},
setPosition: function() {
var $el = $('div.pat-modal,#pat-modal'),
maxHeight = window.innerHeight - $el.outerHeight(true) +
$el.outerHeight();
if ($el.length === 0) {
return;
}
// set max-height first, then measure and change if necessary
$el.css('max-height', maxHeight).css('height', '');
if (maxHeight - $el.outerHeight() < 0) {
$el.addClass('max-height')
.css('height', maxHeight).css('max-height', '');
} else {
$el.removeClass('max-height');
}
var top = (window.innerHeight - $el.outerHeight(true)) / 2;
$el.css('top', top);
},
destroy: function($el, ev) {
if (ev && ev.type === "keyup" && ev.which !== 27)
return;
$(document).off(".pat-modal");
$el.remove();
}
};
$(window).on('resize.pat-modal-position', modal.setPosition);
$(document).on('patterns-injected.pat-modal-position', '#pat-modal,div.pat-modal',
modal.setPosition);
registry.register(modal);
return modal;
});
// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab
| JavaScript | 0 | @@ -2427,22 +2427,25 @@
eight =
+$(
window
+)
.innerHe
@@ -2440,32 +2440,34 @@
dow).innerHeight
+()
- $el.outerHeig
@@ -3007,23 +3007,26 @@
r top =
+($
(window
+)
.innerHe
@@ -3025,24 +3025,26 @@
.innerHeight
+()
- $el.outer
|
0fd1571b82414faa2f0cae1c5619d480d72f4ab4 | Fix whitespace in grep finder. | lib/finder/grep.js | lib/finder/grep.js | // Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
var spawn = require('child_process').spawn;
var path = require('path');
var carrier = require('carrier');
var os = require('os'), isWin = (os.platform() === 'win32');
/**
* A regular expression for parsing goog.provide results from grep output.
* @type {RegExp}
*/
var PROVIDE_RE = /^(.+\.js):goog\.provide\(['"](\S+)['"]\);/;
/**
* A simple class for mapping class names to origin files which pre-populates a
* map of names to files by delegating to grep.
* @param {string} projectDir The Tern project directory.
* @param {{name: string, debug: boolean, dirs: Array.<string>}} options
* @constructor
*/
var GrepFileFinder = function(projectDir, options) {
/**
* A map of class names to canonical file paths.
* @type {Object.<string>}
* @private
*/
this.files_ = {};
/** @private {string} The project dir. */
this.projectDir_ = projectDir;
/** @private {{name: string, debug: boolean, dirs: Array.<string>}} */
this.options_ = options;
this.prepopulate_();
};
module.exports = GrepFileFinder;
/**
* Pre-populates the internal file map.
* @private
*/
GrepFileFinder.prototype.prepopulate_ = function() {
var dirs;
if (this.options_.dirs) {
dirs = this.options_.dirs;
} else {
dirs = ['.'];
}
for (var i = 0; i < dirs.length; i++) {
this.searchDir_(path.resolve(this.projectDir_, dirs[i]));
}
};
/**
* Search the given directory for goog.provide statements.
* @param {string} dir
* @private
*/
GrepFileFinder.prototype.searchDir_ = function(dir) {
// TODO: Track when done prepopulating, defer calls that come in before done.
if (this.options_.debug) {
console.log('grep: searching ' + dir);
}
var search = isWin ?
spawn('findstr', ['/S', '/R', '/D:' + dir, '/C:^goog.provide(', '*.js']) :
spawn('grep', ['-R', '--include=*.js', '^goog.provide(', dir]);
search.stdout.setEncoding('utf8');
carrier.carry(search.stdout, function(line) {
var match = line.match(PROVIDE_RE);
if (!match) {
// TODO: Deal with line-wrapped goog.provide statements #7.
if (this.options_.debug) {
console.log('grep: Failed to match line ' + line);
}
return;
}
var name = match[2];
// Use the absolute path, unless under the project dir.
var filePath = path.resolve(dir, match[1]);
if (filePath.indexOf(this.projectDir_) === 0) {
filePath = path.relative(this.projectDir_, filePath);
}
this.files_[name] = filePath;
}.bind(this));
};
/**
* @param {string} name
* @param {fn(string)} cb
*/
GrepFileFinder.prototype.findFile = function(name, cb) {
setTimeout(function() {
cb(this.files_[name]);
}.bind(this));
};
| JavaScript | 0.000017 | @@ -785,16 +785,17 @@
n32');%0A%0A
+%0A
/**%0A * A
@@ -2319,18 +2319,19 @@
isWin ?
-
%0A
+
spaw
@@ -2404,10 +2404,11 @@
%5D) :
-
%0A
+
|
cbed2b72e7a510d35069a6cc3b46c3f8d28d2932 | Update select.js | lib/form/select.js | lib/form/select.js | 'use strict'
var Element = require('vigour-element')
var Icon = require('../icon')
/**
* Select element
* @memberOf UIKit
*/
module.exports = new Element({
css: 'ui-select ui-atom ui-form-element',
node: 'label',
options: {
node: 'select',
ChildConstructor: new Element({
node: 'option'
}).Constructor,
placeholder: {
attributes: {
disabled: 'disabled',
selected: 'selected',
value: ''
},
text: 'Select your option'
},
on: {
change: {
dirty () {
this.parent.setKey('css', {
addClass: 'ui-dirty'
})
}
}
}
},
down: new Icon('bottom ui-additional')
}).Constructor
| JavaScript | 0.000001 | @@ -122,17 +122,16 @@
Kit%0A */%0A
-%0A
module.e
|
f330232ed5cd1384f1508bc62ac389795c7904d2 | Configure bluebird. | src/polyfills.js | src/polyfills.js | import 'dom4';
import Promise from 'bluebird';
import { polyfill as smoothscroll } from 'smoothscroll-polyfill';
smoothscroll();
window.Promise = Promise;
| JavaScript | 0 | @@ -111,46 +111,247 @@
';%0A%0A
-smoothscroll();%0Awindow.Promise = Promise
+// Smooth scroll polyfill%0Asmoothscroll();%0A%0A// Make bluebird global%0Awindow.Promise = Promise;%0A%0A// Improve debugging by enabling long stack traces.. it has minimal impact in production%0APromise.config(%7B longStackTraces: true, warnings: false %7D)
;%0A
|
eb161bbc94c9c53ef91fb1106dd1fc60175cff36 | rename vars | lib/get-loaders.js | lib/get-loaders.js | 'use strict';
const resultCache = {};
const cacheMap = new Map();
const stripOutputLoader = require.resolve('./strip-output-loader');
const formatLoaders = (source) => {
if (!source) return [];
if (source instanceof Array) return source;
return source.split('!');
};
module.exports = function getLoaders(context) {
let res = '';
const resourcePath = context.resourcePath;
if (resultCache[resourcePath]) return resultCache[resourcePath];
if (!cacheMap.size) {
context.options.module.loaders
.filter(config =>
formatLoaders(config.loaders).some(loader => loader.match('premodules'))
)
.forEach(config => {
const rules = {
test: config.test,
include: [],
};
if (config.include) {
if (config.include instanceof Array) {
config.include.forEach(path => {
rules.include.push(new RegExp(path));
});
} else {
rules.include.push(new RegExp(config.include));
}
}
// strip all loaders after premodules?restore
const loaders = formatLoaders(config.loaders)
.join('!')
.replace(/^.*?(?=premodules\?restore)/, '');
cacheMap.set(rules, `${stripOutputLoader}!${loaders}`);
});
}
cacheMap.forEach((loaders, rules) => {
if (res) return;
let matched = true;
matched &= rules.test.test(resourcePath);
if (rules.include.length) {
matched &= rules.include.some(r => {
return resourcePath.match(r);
});
}
if (matched) res = loaders;
});
resultCache[resultCache] = res;
return res;
};
| JavaScript | 0.000209 | @@ -38,21 +38,23 @@
;%0Aconst
-cache
+loaders
Map = ne
@@ -457,21 +457,23 @@
%0A if (!
-cache
+loaders
Map.size
@@ -1226,21 +1226,23 @@
-cache
+loaders
Map.set(
@@ -1305,13 +1305,15 @@
%0A%0A
-cache
+loaders
Map.
|
1f9b269a9afbc7d7c856b90f23bbe01dff4d5072 | Increase maximum git stdout buffer size | lib/git-process.js | lib/git-process.js | /** @babel */
import {EventEmitter} from 'events'
import path from 'path'
import cp from 'child_process'
function resolveGit () {
// return '/usr/bin/git' // TODO [mkt/ku] why do we need this for https endpoints?
if (process.platform === 'darwin') {
return path.join(__dirname, '../git-distributions/git-macos/git/bin/git')
// } else if (process.platform === 'win32') {
// return path.join(__dirname, 'git/cmd/git.exe')
} else {
throw new Error('Git not supported on platform: ' + process.platform)
}
}
export default class GitProcess extends EventEmitter {
constructor (args, options) {
super()
this.args = args
this.options = options
this.formatArgs = `git ${this.args.join(' ')} in ${this.options.cwd}`
this.label = `git ${this.args.join(' ')} (stdin length ${this.options.stdin && this.options.stdin.length})@${new Date().getTime()}`
}
exec () {
return new Promise(async (resolve, reject) => {
if (global.PRINT_GIT_TIMES) console.time(this.label)
const opts = {
cwd: this.options.cwd,
encoding: 'utf8',
env: {...process.env, ...this.options.env}
}
const child = cp.execFile(resolveGit(), this.args, opts, (...args) => {
this.onComplete(resolve, reject, ...args)
})
child.on('exit', (...args) => this.onChildExit(...args))
child.on('error', (...args) => this.onChildError(...args))
child.stdin.on('error', (...args) => this.onChildStdinError(...args))
if (this.options.stdin) {
child.stdin.end(this.options.stdin)
}
})
}
onComplete (resolve, reject, err, output, stdErr) {
if (err) {
err.command = this.formatArgs
err.stdErr = stdErr
return reject(err)
}
resolve(output)
}
onChildExit (code) {
if (global.PRINT_GIT_TIMES) console.timeEnd(this.label)
this.emit('exit', code)
}
onChildError (err) {
console.error('Error executing: ' + this.formatArgs)
console.error(err.stack)
this.emit('error', err)
}
onChildStdinError (err) {
console.error('Error writing to process: ' + this.formatArgs)
console.error(err.stack)
console.error('Tried to write: ' + this.options.stdin)
}
}
| JavaScript | 0.000005 | @@ -1134,16 +1134,53 @@
ons.env%7D
+,%0A maxBuffer: 10 * 1024 * 1024
%0A %7D
|
508e8435705dbdbe33e7cd1a62c24c4beb690778 | Use child_process.fork rather than exec when loading grunt. | lib/grunt/index.js | lib/grunt/index.js | module.exports = function (sails) {
return function load (taskName, cb) {
var environment = sails.config.environment;
var baseurl = 'http://' + sails.config.host + ':' + sails.config.port;
var signalpath = '/___signal';
var pathToSails = __dirname.replace(' ', '\\ ') + '/../..';
if (!taskName) {
taskName = '';
}
// Build command to run Gruntfile
var cmd = 'node ' + pathToSails + '/node_modules/grunt-cli/bin/grunt ' +
taskName +
' --gdsrc=' + pathToSails + '/node_modules' +
' --environment=' + environment +
' --baseurl=' + baseurl +
' --signalpath=' + signalpath;
// Spawn grunt process
var child = require('child_process').exec(cmd);
var errorMsg = '';
var stackTrace = '';
// Log output as it comes in to the appropriate log channel
child.stdout.on('data', function (consoleMsg) {
// store all the output
errorMsg += consoleMsg + '\n';
if( consoleMsg.match(/Warning:/)) {
// Find the Stack Trace related to this warning
stackTrace = errorMsg.substring(errorMsg.lastIndexOf('Running "'));
sails.log.error('Grunt :: ' + consoleMsg, stackTrace);
return;
}
// Throw an error
else if (consoleMsg.match(/Aborted due to warnings./)) {
sails.log.error('Grunt :: ', consoleMsg, stackTrace);
sails.log.error(
'*-> An error occurred-- please fix it, then stop ' +
'and restart Sails to continue watching assets.'
);
}
else if (consoleMsg.match(/ParseError/)) {
sails.log.error('Grunt :: ', consoleMsg, stackTrace);
}
else sails.log.verbose('Grunt :: ' + consoleMsg);
});
child.stdout.on('error', function (consoleErr) {
sails.log.error('Grunt :: ' + consoleErr);
});
child.stderr.on('data', function (consoleErr) {
sails.log.error('Grunt :: ' + consoleErr);
});
child.stderr.on('error', function (consoleErr) {
sails.log.error('Grunt :: ' + consoleErr);
});
sails.log.verbose('Tracking new grunt child process...');
sails.childProcesses.push(child);
// Go ahead and get out of here, since Grunt might sit there backgrounded
cb && cb();
};
};
| JavaScript | 0 | @@ -378,18 +378,8 @@
md =
- 'node ' +
pat
@@ -427,26 +427,35 @@
runt
- ' +
+',%0A%09%09%09args = %5B
%0A%09%09%09%09
-%09
taskName
+%0A%09
@@ -450,26 +450,23 @@
taskName
- +%0A%09
+,%0A
%09%09%09%09'
-
--gdsrc=
@@ -498,26 +498,23 @@
modules'
- +
+,
%0A%09%09%09%09
-%09'
+'
--enviro
@@ -534,26 +534,23 @@
ironment
- +%0A%09
+,%0A
%09%09%09%09'
-
--baseur
@@ -566,18 +566,15 @@
eurl
- +%0A%09
+,%0A
%09%09%09%09'
-
--si
@@ -596,16 +596,78 @@
gnalpath
+%0A%09%09%09%5D,%0A%09%09%09options = %7B%0A%09%09%09%09silent: true,%0A%09%09%09%09stdio: 'pipe'%0A%09%09%09%7D
;%0A%0A%09%09//
@@ -729,16 +729,31 @@
s').
-exec(cmd
+fork(cmd, args, options
);%0A%0A
@@ -910,16 +910,56 @@
Msg) %7B%0A%0A
+%09%09%09consoleMsg = consoleMsg.toString();%0A%0A
%09%09%09// st
|
52254b43e3111b6dc9bc82597debd8168943b17f | add escape ' | lib/html-escape.js | lib/html-escape.js | var check = [/</g,/>/g,/&/g,/"/g,/</g,/>/g,/&/g,/"/g];
exports.escape = function (str) {
str = str.replace(check[0], "<");
str = str.replace(check[1], ">");
str = str.replace(check[2], "&");
str = str.replace(check[3], """);
return str;
};
exports.unEscape = function (str) {
str = str.replace(check[4], "<");
str = str.replace(check[5], ">");
str = str.replace(check[6], "&");
str = str.replace(check[7], '"');
return str;
}; | JavaScript | 0.000038 | @@ -27,16 +27,21 @@
g,/%22/g,/
+'/g,/
</g,/
@@ -65,16 +65,26 @@
"/g
+,/'/g
%5D;%0Aexpor
@@ -104,32 +104,52 @@
unction (str) %7B%0A
+%09str = String(str);%0A
%09str = str.repla
@@ -287,16 +287,56 @@
uot;%22);%0A
+%09str = str.replace(check%5B4%5D, %22'%22);%0A
%09return
@@ -375,24 +375,44 @@
ion (str) %7B%0A
+%09str = String(str);%0A
%09str = str.r
@@ -420,25 +420,25 @@
place(check%5B
-4
+5
%5D, %22%3C%22);%0A%09st
@@ -455,25 +455,25 @@
place(check%5B
-5
+6
%5D, %22%3E%22);%0A%09st
@@ -490,25 +490,25 @@
place(check%5B
-6
+7
%5D, %22&%22);%0A%09st
@@ -529,17 +529,17 @@
e(check%5B
-7
+8
%5D, '%22');
@@ -539,16 +539,51 @@
, '%22');%0A
+%09str = str.replace(check%5B9%5D, %22'%22);%0A
%09return
|
beb09faf82fe0e48e8bbbecd7ec420a1fe8efbc9 | Fix to prevent interpolation from stomping on regex | lib/interpolate.js | lib/interpolate.js | var _ = require("underscore");
var moment = require("moment");
var named = require("named-regexp").named;
function interpolate_string(string, data) {
return string.replace(/<%(%?[#=+\-:\?@&\$]*)\s*(.+?)(\|(.*?))?\s*%>/g, function(match, options, key, ignore, parameters, offset, string) {
var url_encode_level = 0;
var optional = false;
var date_format = false;
var array_access = false;
var array_join = false;
var random_value = false;
var delimiter_quote = false;
if(options) {
for(var i=0;i<options.length;i++) {
switch(options[i]) {
case '%': // Literal escape, do not replace anything
return "<%" + match.substring(3);
case '+':
url_encode_level++;
break;
case '-':
url_encode_level--;
break;
case '?':
optional = true;
break;
case ':':
date_format = true;
break;
case "@":
array_access = true;
break;
case "&":
array_join = true;
break;
case "$":
random_value = true;
break;
case "#":
delimiter_quote = true;
break;
}
}
}
var value;
if(date_format) {
if(parameters) {
var object = data[key];
if(_.isUndefined(object)) {
throw new Error("Target of date-format must be a moment/date object - key:" + key + ", value:" + JSON.stringify(data[key]));
}
if(!object._isAMomentObject) {
if(isFinite(object) && _.isString(object)) {
object = moment(parseInt(object));
}
else {
object = moment(object);
}
if(!object.isValid()) {
throw new Error("Could not convert object to date - key:" + key);
}
}
value = object.format(parameters);
}
else { // Legacy fallback attempt to format the current date/time with the key
value = moment().format(key);
}
}
else if(array_join) {
if(parameters) {
parameters = parameters
.replace("\\t","\t")
.replace("\\n","\n")
.replace("\\s"," ");
}
if(_.isArray(data[key]))
value = data[key].join(parameters);
else
value = data[key];
}
else if(random_value) {
// <%$@ array %> - Random element from array
if(array_access) {
if(_.has(data, key)) {
if(_.isArray(data[key])) {
var random_index = Math.floor(Math.random() * data[key].length);
value = data[key][random_index];
}
else {
value = data[key];
}
}
else {
if(optional) {
value = parameters;
}
else {
throw new Error("Array not found for random selection");
}
}
}
else {
// <%$ 3000-5000 %> - Random number in range min to max-1
// <%$ 5000 %> - Random number from 0 to max-1
var re = named(/^\s*(?:(:<min>\d+)\s*-\s*)?(:<max>\d+)\s*$/);
var matches = re.exec(key);
if(matches) {
var min = parseInt(matches.captures["min"]) || 0;
var max = parseInt(matches.captures["max"]);
if(min>max) throw new Error("min value cannot be larger than max value - " + min + "," + max);
if(min==max) throw new Error("min value cannot be the same as max value - " + min + "," + max);
value = Math.floor(Math.random() * (max - min) + min);
return value;
}
else {
throw new Error("Could not parse value for format specifier, random - " + key);
}
}
}
else if(array_access && _.isArray(data[key])) {
if(parameters) {
if(parseInt(parameters)>=data[key].length) {
throw new Error("Array index out of bounds for " + key + ", index=" + parseInt(parameters));
}
else {
value = data[key][parseInt(parameters)];
}
}
else {
if(!_.has(data, key + ".index")) {
data[key + ".index"] = 0;
}
if(parseInt(data[key + ".index"])>=data[key].length) {
if(optional && data[key + ".index"] === 0) { // Special case for empty arrays while optional
value = "";
}
else {
throw new Error("Array index out of bounds for " + key + ", index=" + parseInt(data[key + ".index"]));
}
}
else {
value = data[key][data[key + ".index"]];
}
}
}
else {
if(_.has(data, key)) {
value = data[key];
}
else {
if(optional) {
value = parameters ? parameters : "";
}
else {
throw new Error("No value found for non-optional replacement - key:" + key);
}
}
}
if(delimiter_quote) {
// Right now, if you combine with other features that use parameters, we're gonna have issues
var delimiter = parameters || ",";
if(value && value.indexOf(delimiter)>=0) {
value = '"' + value + '"';
}
}
if(_.isObject(value)) {
value = JSON.stringify(value, null, 2);
}
while(url_encode_level>0) {
value = encodeURIComponent(value);
url_encode_level--;
}
while(url_encode_level<0) {
value = decodeURIComponent(value);
url_encode_level++;
}
return value;
});
}
module.exports = function(object, data) {
function interpolate_tree(object) {
if(_.isString(object)) {
return interpolate_string(object, data);
}
if(_.isArray(object)) {
return _.map(object, interpolate_tree);
}
if(_.isObject(object) && !_.isFunction(object)) {
var result = {};
for(var key in object) {
result[key] = interpolate_tree(object[key]);
}
return result;
}
return object;
};
return interpolate_tree(object);
}
| JavaScript | 0.000001 | @@ -5106,16 +5106,39 @@
ject) &&
+ !_.isRegExp(object) &&
!_.isFu
|
8b57e409403da757936e73b64c52c7e53507cb46 | Use async/await | lib/linter-reek.js | lib/linter-reek.js | 'use babel';
// eslint-disable-next-line import/no-extraneous-dependencies, import/extensions
import { CompositeDisposable } from 'atom';
let helpers;
let path;
// Local variables
const parseRegex = /\[(\d+)(?:, \d+)*\]:(.*) \[.+\/(.+).md\]/g;
const loadDeps = () => {
if (!helpers) {
helpers = require('atom-linter');
}
if (!path) {
path = require('path');
}
};
export default {
activate() {
this.idleCallbacks = new Set();
let depsCallbackID;
const installLinterReekDeps = () => {
this.idleCallbacks.delete(depsCallbackID);
if (!atom.inSpecMode()) {
require('atom-package-deps').install('linter-reek');
}
loadDeps();
if (atom.inDevMode()) {
// eslint-disable-next-line no-console
console.log('linter-reek: All dependencies installed.');
}
};
depsCallbackID = window.requestIdleCallback(installLinterReekDeps);
this.idleCallbacks.add(depsCallbackID);
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(
atom.config.observe('linter-reek.executablePath', (value) => {
this.executablePath = value;
}),
);
if (atom.inDevMode()) {
/* eslint-disable no-console */
console.log('linter-reek: Reek linter is now activated.');
console.log(`linter-reek: Command path: ${this.executablePath}`);
/* eslint-enable no-console */
}
},
deactivate() {
this.idleCallbacks.forEach(callbackID => window.cancelIdleCallback(callbackID));
this.idleCallbacks.clear();
this.subscriptions.dispose();
},
provideLinter() {
return {
name: 'reek',
grammarScopes: ['source.ruby', 'source.ruby.rails', 'source.ruby.rspec'],
scope: 'file',
lintOnFly: false,
lint: (TextEditor) => {
const filePath = TextEditor.getPath();
if (!filePath) {
// Somehow a TextEditor without a path was passed in
return null;
}
const fileText = TextEditor.getText();
loadDeps();
const execOpts = { cwd: path.dirname(filePath), ignoreExitCode: true };
return helpers.exec(this.executablePath, [filePath], execOpts).then((output) => {
if (TextEditor.getText() !== fileText) {
// Editor contents have changed, tell Linter not to update
return null;
}
const messages = [];
let match = parseRegex.exec(output);
while (match !== null) {
const line = Number.parseInt(match[1], 10) - 1;
const urlBase = 'https://github.com/troessner/reek/blob/master/docs/';
const ruleLink = `[<a href="${urlBase}${match[3]}.md">${match[3]}</a>]`;
messages.push({
filePath,
type: 'Warning',
severity: 'warning',
html: `${match[2]} ${ruleLink}`,
range: helpers.generateRange(TextEditor, line),
});
match = parseRegex.exec(output);
}
return messages;
});
},
};
},
};
| JavaScript | 0.000001 | @@ -1772,16 +1772,22 @@
lint:
+ async
(TextEd
@@ -2029,24 +2029,25 @@
loadDeps();%0A
+%0A
cons
@@ -2060,16 +2060,26 @@
Opts = %7B
+%0A
cwd: pa
@@ -2099,16 +2099,26 @@
lePath),
+%0A
ignoreE
@@ -2134,20 +2134,30 @@
true
+,%0A
%7D;%0A
+%0A
retu
@@ -2152,22 +2152,36 @@
-return
+const output = await
helpers
@@ -2232,30 +2232,11 @@
pts)
-.then((output) =%3E %7B%0A
+;%0A%0A
@@ -2276,26 +2276,24 @@
fileText) %7B%0A
-
//
@@ -2351,34 +2351,32 @@
pdate%0A
-
-
return null;%0A
@@ -2376,26 +2376,24 @@
ll;%0A
-
%7D%0A%0A
@@ -2387,26 +2387,24 @@
%7D%0A%0A
-
-
const messag
@@ -2413,18 +2413,16 @@
= %5B%5D;%0A%0A
-
@@ -2466,18 +2466,16 @@
-
-
while (m
@@ -2487,26 +2487,24 @@
!== null) %7B%0A
-
co
@@ -2555,26 +2555,24 @@
;%0A
-
-
const urlBas
@@ -2630,18 +2630,16 @@
docs/';%0A
-
@@ -2723,18 +2723,16 @@
-
-
messages
@@ -2751,18 +2751,16 @@
-
filePath
@@ -2773,18 +2773,16 @@
-
-
type: 'W
@@ -2782,34 +2782,32 @@
ype: 'Warning',%0A
-
seve
@@ -2835,18 +2835,16 @@
-
-
html: %60$
@@ -2868,18 +2868,16 @@
Link%7D%60,%0A
-
@@ -2934,32 +2934,28 @@
,%0A
-
-
%7D);%0A
-
ma
@@ -2989,30 +2989,26 @@
t);%0A
-
-
%7D%0A
-
retu
@@ -3020,28 +3020,16 @@
ssages;%0A
- %7D);%0A
%7D,
|
380b8b558c1f57e2ffa82682c7758ea01c81bedb | Fix broken link to Docs for Intelligent Code Autocompletion | lib/maintenance.js | lib/maintenance.js | 'use babel';
/**
* Copyright (C) 2016 Ivan Kravets. All rights reserved.
*
* This source file is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import fs from 'fs';
import path from 'path';
import child_process from 'child_process';
import {command as installPlatformIO} from './install/command';
import {getPythonExecutable, getIDEVersion, useBuiltinPlatformIO} from './utils';
import {ENV_BIN_DIR, WIN32, BASE_DIR} from './config';
import {command as donateCommand} from './donate/command';
import {runInTerminal} from './terminal';
export function onActivate() {
updateOSEnviron();
installPlatformIO()
.then(checkIfPlatformIOCanBeExecuted)
.then(() => donateCommand(true));
}
export function updateOSEnviron() {
if (useBuiltinPlatformIO()) { // Insert bin directory into PATH
if (process.env.PATH.indexOf(ENV_BIN_DIR) < 0) {
process.env.PATH = ENV_BIN_DIR + path.delimiter + process.env.PATH;
}
} else { // Remove bin directory from PATH
process.env.PATH = process.env.PATH.replace(ENV_BIN_DIR + path.delimiter, "");
process.env.PATH = process.env.PATH.replace(path.delimiter + ENV_BIN_DIR, "");
}
handleCustomPATH(atom.config.get('platformio-ide.customPATH'));
process.env.PLATFORMIO_CALLER = "atom";
process.env.PLATFORMIO_IDE = getIDEVersion();
}
export function installCommands() {
if (WIN32) {
const winCheckResult = child_process.spawnSync('platformio', ['--version']);
if (0 !== winCheckResult.status) {
const addResult = child_process.spawnSync(
getPythonExecutable(),
[path.join(BASE_DIR, 'misc', 'add_path_to_envpath.py'), ENV_BIN_DIR]);
if (0 !== addResult.status) {
atom.notifications.addError('Failed to install PlatformIO commands!', {
detail: addResult.stderr,
dismissable: true,
});
console.error('' + addResult.stderr);
} else {
atom.notifications.addSuccess(
'PlatformIO commands have been successfully installed',
{dismissable: true}
);
}
}
} else {
const args = ['-c', 'command -v platformio --version'];
// Passing empty env, because "process.env" may contain a path to the
// "penv/bin", which makes the check always pass.
const options = {env: {}};
const checkResult = child_process.spawnSync('/bin/sh', args, options);
if (0 !== checkResult.status) {
const map = [
[path.join(ENV_BIN_DIR, 'platformio'), '/usr/local/bin/platformio'],
[path.join(ENV_BIN_DIR, 'pio'), '/usr/local/bin/pio'],
];
try {
for (let item of map) {
fs.symlinkSync(item[0], item[1]);
}
} catch(e) {
let msg = 'Please install shell commands manually. Open system ' +
'Terminal and paste commands below:\n';
for (let item of map) {
msg += `\n$ sudo ln -s ${item[0]} ${item[1]}`;
}
atom.notifications.addError('PlaftormIO: Failed to install commands', {
detail: msg,
dismissable: true,
});
}
} else {
atom.notifications.addInfo('PlatformIO: Shell Commands installation skipped.', {
detail: 'Commands are already available in your shell.',
dismissable: true,
});
}
}
}
export function openTerminal(cmd) {
const status = runInTerminal([cmd]);
if (-1 === status) {
atom.notifications.addError('PlatformIO: Terminal service is not registered.', {
detail: 'Make sure that "platformio-ide-terminal" package is installed.',
dismissable: true,
});
}
}
export function checkClang() {
if (localStorage.getItem('platformio-ide:clang-checked')) {
return;
}
const result = child_process.spawnSync('clang', ['--version']);
if (result.status !== 0) {
atom.notifications.addWarning('Clang is not installed in your system!', {
detail: 'PlatformIO IDE uses "clang" for the code autocompletion.\n' +
'Please install it otherwise this feature will be disabled.\n' +
'Details: http://docs.platformio.org/en/latest/ide/atom.html##code-completion',
dismissable: true
});
}
localStorage.setItem('platformio-ide:clang-checked', 1);
}
export function setBuildPanelVisibility(visibility) {
atom.config.set('build.panelVisibility', visibility);
}
export function handleCustomPATH(newValue, oldValue) {
if (oldValue) {
process.env.PATH = process.env.PATH.replace(oldValue + path.delimiter, "");
process.env.PATH = process.env.PATH.replace(path.delimiter + oldValue, "");
}
if (newValue && process.env.PATH.indexOf(newValue) < 0) {
process.env.PATH = newValue + path.delimiter + process.env.PATH;
}
}
function checkIfPlatformIOCanBeExecuted() {
return new Promise((resolve, reject) => {
var pioVersionProcessStderr = '';
const pioVersionProcess = child_process.spawn("platformio");
pioVersionProcess.stderr.on('data', (chunk) => pioVersionProcessStderr += chunk);
pioVersionProcess.on('close', (code) => {
if (0 !== code) {
let title = 'PlaftormIO tool is not available.';
let msg = 'Can not find `platformio` command. Please install it' +
' using `pip install platformio` or enable built-in PlatformIO tool in' +
' `platformio-ide` package settings.\nDetails:\n' +
pioVersionProcessStderr;
atom.notifications.addError(title, {detail: msg, dismissable: true});
console.error(title);
console.error(pioVersionProcessStderr);
reject();
}
resolve();
});
});
}
| JavaScript | 0 | @@ -4503,14 +4503,26 @@
the
-c
+Intelligent C
ode
-a
+A
utoc
@@ -4675,17 +4675,16 @@
om.html#
-#
code-com
|
290310848277f4352354b44106dc68841ada20c5 | Fix Bug 910906 - Add contenturl to the publicFields exposed for Make schema | lib/models/make.js | lib/models/make.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
module.exports = function( environment, mongoInstance ) {
var mongoosastic = require( "mongoosastic" ),
mongooseValidator = require( "mongoose-validator" ),
validate = mongooseValidator.validate,
env = environment,
url = require( "url" ),
mongoose = mongoInstance,
elasticSearchURL = env.get( "FOUNDELASTICSEARCH_URL" ) ||
env.get( "BONSAI_URL" ) ||
env.get( "ELASTIC_SEARCH_URL" );
elasticSearchURL = url.parse( elasticSearchURL );
mongooseValidator.extend( "isURL", function() {
var str = this.str;
// This is a copy of https://github.com/chriso/node-validator/blob/master/lib/validators.js#L29-L32 which
// is used for "isUrl" with mongoose-validator. Modified to accept underscores in the hostname.
return str.length < 2083 && str.match(/^(?!mailto:)(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\_\u00a1-\uffff0-9]+-?)*[a-z\_\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))|localhost)(?::\d{2,5})?(?:\/[^\s]*)?$/i);
});
var Timestamp = {
type: Number,
es_type: "long",
es_indexed: true,
es_index: "not_analyzed"
};
// Schema
var schema = new mongoose.Schema({
url: {
type: String,
required: true,
es_indexed: true,
validate: validate( "isURL" ),
unique: true,
es_index: "not_analyzed"
},
contenturl: {
type: String,
es_indexed: false,
validate: validate( "isURL" ),
unique: true
},
contentType: {
type: String,
es_indexed: true,
required: true,
es_index: "not_analyzed"
},
locale: {
type: String,
"default": "en_us",
es_indexed: true,
es_index: "not_analyzed"
},
title: {
type: String,
es_indexed: true,
required: true
},
description: {
type: String,
es_indexed: true
},
thumbnail: {
type: String,
es_indexed: true,
es_index: "not_analyzed"
},
author: {
type: String,
required: false,
es_indexed: true,
es_index: "not_analyzed"
},
email: {
type: String,
required: true,
validate: validate( "isEmail" ),
es_indexed: true,
es_index: "not_analyzed"
},
published: {
type: Boolean,
"default": true,
es_index: "not_analyzed"
},
tags: {
type: [ String ],
es_indexed: true,
es_index: "not_analyzed",
es_type: "String"
},
remixedFrom: {
type: String,
"default": null,
es_indexed: true,
es_index: "not_analyzed"
},
createdAt: Timestamp,
updatedAt: Timestamp,
deletedAt: {
type: Number,
"default": null,
es_indexed: true,
es_type: "long"
}
});
schema.set( "toJSON", { virtuals: true } );
schema.virtual( "id" ).get(function() {
return this._id;
});
schema.plugin( mongoosastic, {
port: elasticSearchURL.port || 80,
host: ( elasticSearchURL.auth ? elasticSearchURL.auth + "@" : "" ) + elasticSearchURL.hostname,
hydrate: true
});
var Make = mongoose.model( "Make", schema );
Make.createMapping(function( err, mapping ) {
if ( err ) {
console.log( "failed to create mapping", err.toString() );
}
});
// Synchronize existing makes with Elastic Search
Make.synchronize();
Make.publicFields = [ "url", "contentType", "locale",
"title", "description", "author", "published", "tags",
"thumbnail", "remixedFrom" ];
return Make;
};
| JavaScript | 0 | @@ -3809,16 +3809,30 @@
ntType%22,
+ %22contenturl%22,
%22locale
|
81b82b05e318503935743272a3806db0627fcc07 | Fix user.getByCredential() | lib/models/user.js | lib/models/user.js | const utils = require('../utils');
const bcrypt = require('bcrypt');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
publicId: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true
},
password: {
type: String,
bcrypt: true
},
firstName: {
type: String,
require: true
},
lastName: {
type: String,
require: true
},
googleId: String,
facebookId: String,
organizations: [{
type: Schema.Types.ObjectId,
ref: 'Organization',
required: true
}]
}, {timestamps: true});
userSchema.virtual('fullName').get(function () { return this.firstName + ' ' + this.lastName; });
userSchema.statics.createPassword = function (email, password, firstName, lastName, cb) {
bcrypt.hash(password, 10, function (err, hash) {
if (err) {
cb(err);
} else {
userModel.create({
email: email,
password: hash,
firstName: firstName,
lastName: lastName,
publicId: utils.uidGen(25),
organizations: []
}, cb);
}
});
};
userSchema.statics.createFacebook = function (email, facebookId, firstName, lastName, cb) {
userModel.create({
email: email,
facebookId: facebookId,
firstName: firstName,
lastName: lastName,
publicId: utils.uidGen(25),
organizations: []
}, cb);
};
userSchema.statics.createGoogle = function (email, googleId, firstName, lastName, cb) {
userModel.create({
email: email,
googleId: googleId,
firstName: firstName,
lastName: lastName,
publicId: utils.uidGen(25),
organizations: []
}, cb);
};
userSchema.statics.getByPublicId = function (publicId, organization, cb) {
if (organization) {
userModel.findOne({ publicId: publicId })
.populate('organizations')
.exec(function (err, fUser) {
if (err) {
cb(err);
} else if (fUser != null && fUser.organizations.length > 0) {
fUser.organizations.forEach(function (org, i) {
org.populate('owner creator members', function (err, fOrg) {
if (err) {
cb(err);
} else {
fUser.organizations[i] = fOrg;
if (i === fUser.organizations.length - 1) {
cb(null, fUser);
}
}
});
});
} else {
cb(null, fUser);
}
});
} else {
userModel.findOne({publicId: publicId}, cb);
}
};
userSchema.statics.getByEmail = function (email, cb) {
userModel.findOne({ email: email }, cb);
};
userSchema.statics.getByPartialEmail = function (partialEmail, limit, cb) {
userModel.find({ email: new RegExp('^' + partialEmail, 'i') })
.limit(limit)
.exec(cb);
};
userSchema.statics.getByCredential = function (email, password, cb) {
userModel.findOne({ email: email }, function (err, fUser) {
if (err) {
cb(err);
} else {
bcrypt.compare(password, fUser.password, function (err, res) {
if (err) {
cb(err);
} else {
cb(null, res === true ? fUser : false);
}
});
}
});
};
userSchema.statics.getByFacebookId = function (facebookId, cb) {
userModel.findOne({ facebookId: facebookId }, cb);
};
userSchema.statics.getByGoogleId = function (googleId, cb) {
userModel.findOne({ googleId: googleId }, cb);
};
userSchema.methods.safePrint = function () {
var orgs = [];
this.organizations.forEach(function (organization) {
orgs.push(organization.safePrint(true));
});
const obj = this.toObject();
delete obj.password;
delete obj.googleId;
delete obj.facebookId;
delete obj.__v;
delete obj._id;
delete obj.updatedAt;
obj.organizations = orgs;
return obj;
};
userSchema.methods.safePrintMember = function () {
const obj = this.toObject();
delete obj.password;
delete obj.googleId;
delete obj.facebookId;
delete obj.__v;
delete obj._id;
delete obj.updatedAt;
delete obj.organizations;
return obj;
};
userSchema.methods.integrateOrganization = function (organization, cb) {
this.organizations.push(organization);
return this.save(cb);
};
userSchema.methods.leaveOrganization = function (organization, cb) {
this.organizations.splice(this.organizations.indexOf(organization), 1);
return this.save(cb);
};
const userModel = mongoose.model('User', userSchema);
module.exports = userModel;
| JavaScript | 0.000006 | @@ -2974,32 +2974,87 @@
%0A cb(err);%0A
+ %7D else if (fUser == null) %7B%0A cb(null, false);%0A
%7D else %7B%0A
|
15bade582026cb69c117110aef820bec112ade9b | add more annotations, trying to prevent improper changes about the logic of type detection | lib/neuron/seed.js | lib/neuron/seed.js | /**
* @preserve Neuron JavaScript Framework & Library
* author i@kael.me
*/
/**
* including sequence: see ../build.json
*/
/**
* module seed
*/
/**
* @param {undefined=} undef
*
* REMEMBER: NEVER use undefined, because writing 'undefined = true;' will bring mass catastrophe
*/
;(function(K, undef){
/**
* isXXX method - basic javascript type detecting
* NEVER use `NR._type` to test for a certain type in your javascript for business,
* since the returned string may be subject to change in a future version
* ALWAYS use `NR.isXXX` instead, because:
- `typeof` is unreliable and imprecise
- the best method to detect whether the passed object matches a specified type is ever changing
in the future, `NR.isXXX` method may support Object.is(obj, type) of ECMAScript6
* ------------------------------------------------------------------------------------ */
K._type = function(){
/**
* @param {all} obj
* @param {boolean=} strict,
if true, method _type will only return a certain type within the type_list
* NEVER use `K._type(undefined)`
* for undefined/null, use obj === undefined / obj === null instead
* for host objects, always return 'object'
*/
function _type(obj, strict){
return type_map[ toString.call(obj) ] || !strict && obj && 'object' || undef;
};
var toString = Object.prototype.toString,
_K = K,
// basic javascript types
// never include any host types or new types of javascript variables for compatibility
type_list = 'Boolean Number String Function Array Date RegExp Object'.split(' '),
i = type_list.length,
type_map = {},
name,
name_lower,
isObject;
while( i -- ){
name = type_list[i];
name_lower = name.toLowerCase();
type_map[ '[object ' + name + ']' ] = name_lower;
_K['is' + name] = name === 'Object' ?
// Object.prototype.toString in IE:
// undefined -> [object Object]
// null -> [object Object]
isObject = function(nl){
return function(o){
return !!o && _type(o) === nl;
}
}(name_lower)
:
function(nl){
return function(o){
return _type(o) === nl;
}
}(name_lower);
}
/**
* whether an object is created by '{}', new Object(), or new myClass() [1]
* to put the first priority on performance, just make a simple method to detect plainObject.
* so it's imprecise in many aspects, which might fail with:
* - location
* - other obtrusive changes of global objects which is forbidden
*/
_K.isPlainObject = function(obj){
// undefined -> false
// null -> false
return !!obj && toString.call(obj) === '[object Object]' && 'isPrototypeOf' in obj;
};
/**
* simple method to detect DOMWindow in a clean world that has not been destroyed
*/
_K.isWindow = function(obj){
// toString.call(window):
// [object Object] -> IE
// [object global] -> Chrome
// [object Window] -> Firefox
// isObject(window) -> 'object'
return isObject(obj) && 'setInterval' in obj;
};
/**
* never use isNaN function, use NR.isNaN instead. NaN === NaN // false
* @return {boolean}
true, if Number(obj) is NaN
* ref:
* http://es5.github.com/#x15.1.2.4
* https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN
*/
// TODO
// _K.isNaN = function(obj){
// return obj == null || !/\d/.test( obj ) || isNaN( obj );
// };
return _type;
}();
/**
* build time will be replaced when packaging and compressing
*/
K.build = '%buildtime%';
/**
* atom to identify the Neuron Object, will not be able to access after cleaning
* @temp
* @private
* @const
*/
K._ = {};
K._env = {};
// K.log = function(){};
// switch debug-mode on, and load 'log' module
// K._debugOn = function(){
// K.provide('log', function(K){ K.log('debug module attached') });
// K._env.debug = true;
// };
})(
typeof exports !== 'undefined' ?
// NodeJS:
// var NR = require('./seed');
exports
:
// other environment, usually on browsers
(function(host, K){
// exactly, K must be an object, or override it
K = host[K] = host && host[K] || {};
/**
* host of global runtime environment
* @type {Object}
exports, if NodeJS
DOMWindow, if browsers
*/
K.__HOST = host = K.__HOST || host;
return K;
})(this, 'NR')
);
/**
--------------------------------------------------
[1] NR.isPlainObject will accept instances created by new myClass, but some libs don't, such as jQuery of whose strategy is dangerous, I thought.
for example:
suppose somebody, a newbie, wrote something like this:
<code>
Object.prototype.destroyTheWorld = true;
NR.isPlainObject({}); // true
</code>
if use jQuery: (at least up to 1.6.4)
<code>
jQuery.isPlainObject({}); // false
</code>
milestone 2.0 ------------------------------------
2011-10-11 Kael:
- add NR.isWindow method
- add an atom to identify the Neuron Object
2011-10-04 Kael:
- fix a but that NR.isObject(undefined/null) -> true in IE
2011-09-04 Kael:
- add global support for CommonJS(NodeJS)
Global TODO:
A. make Slick Selector Engine slim
B. remove setAttribute opponent from Slick
C. [business] move inline script for header searching after the HTML structure of header
2011-09-02 Kael:
- rename core.js as seed.js
- remove everything unnecessary out of seed.js
- seed.js will only manage the NR namespace and provide support for type detection
milestone 1.0 ------------------------------------
2010-08-27 Kael:
- add global configuration: NR.__PARSER as DOM selector and parser
2010-08-16 Kael:
TODO:
√ GLOBAL: remove all native implements of non-ECMAScript5 standards
2011-03-19 Kael: move NR.type to lang.js
2011-03-01 Kael Zhang: add adapter for typeOf of mootools
2010-12-13 Kael Zhang: fix the getter of NR.data
2010-10-09 Kael Zhang: create file
*/ | JavaScript | 0 | @@ -210,16 +210,17 @@
VER use
+%60
undefine
@@ -220,16 +220,17 @@
ndefined
+%60
, becaus
@@ -239,17 +239,17 @@
writing
-'
+%60
undefine
@@ -257,17 +257,17 @@
= true;
-'
+%60
will br
@@ -2229,32 +2229,208 @@
rn function(o)%7B%0A
+ %0A // never use %60toString.call(obj) === '%5Bobject Object%5D'%60 here,%0A // because %60isObject%60 is a totally generic detection%0A
@@ -2473,32 +2473,50 @@
%7D
+;%0A
%0A %7D(n
|
a61487a6f5931dc3a080b8c4b13313147f0ab789 | Edit packageJson 기본갑 추가 | lib/packageJson.js | lib/packageJson.js | 'use strict';
var readline = require('readline');
var chalk = require('chalk');
var packageJson = {
'name': '',
'version': '0.0.0',
'description': 'Woowahan Cli App',
'main': './src/main.js',
'scripts': {
'dev': 'webpack-dev-server --config webpack.config.js --progress --inline',
'build': 'webpack --progress'
},
'author': '',
'license': 'MIT',
'repository': {
'type': 'git',
'url': ''
},
'dependencies': {
'woowahan': '^0.2.0',
'bootstrap-sass': '^3.3.7'
},
'devDependencies': {
'babel-core': '^6.14.0',
'babel-eslint': '^6.1.2',
'babel-loader': '^6.2.5',
'babel-preset-es2015': '^6.14.0',
'babel-preset-stage-2': '^6.13.0',
'bootstrap-loader': '^2.0.0-beta.20',
'css-loader': '^0.26.1',
'extract-text-webpack-plugin': '^2.0.0-beta',
'file-loader': '^0.10.0',
'handlebars': '^4.0.3',
'handlebars-loader': '^1.1.4',
'html-webpack-plugin': '^2.28.0',
'imports-loader': '^0.7.0',
'node-sass': '^4.3.0',
'resolve-url-loader': '^1.6.1',
'sass-loader': '^5.0.0',
'style-loader': '^0.13.1',
'url-loader': '^0.5.7',
'webpack': '^2.2.1',
'webpack-dev-server': '^2.3.0'
}
};
module.exports = function(projectName) {
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var questionsArr = [
{
question : 'Name? (' + projectName + ')',
type: 'name',
value: projectName || ''
},
{
question : 'Author? ',
type: 'author',
value: ''
},
{
question : 'License? (MIT) ',
type: 'license',
value: 'MIT'
}
];
return new Promise(function(resolve, reject) {
var askTimes = 0;
var question = questionsArr[askTimes]['question'];
var type = questionsArr[askTimes]['type'];
var value = questionsArr[askTimes]['value'];
rl.setPrompt(question);
rl.prompt();
rl.on('line', function(line) {
packageJson[type] = line !== '' ? line : value;
askTimes++;
if(askTimes > questionsArr.length - 1) {
rl.close();
return resolve(packageJson);
}
question = questionsArr[askTimes]['question'];
type = questionsArr[askTimes]['type'];
value = questionsArr[askTimes]['value'];
rl.setPrompt(question);
rl.prompt();
});
rl.on('SIGINT' , function() {
console.log();
console.log(chalk.red('Canceled.'));
rl.close();
});
});
}; | JavaScript | 0 | @@ -1444,32 +1444,190 @@
ue: ''%0A%09%09%7D,%0A%09%09%7B%0A
+%09%09%09question : 'Verson? (1.0.0) ',%0A%09%09%09type: 'version',%0A%09%09%09value: '1.0.0'%0A%09%09%7D,%0A%09%09%7B%0A%09%09%09question : 'Description? ',%0A%09%09%09type: 'description',%0A%09%09%09value: ''%0A%09%09%7D,%0A%09%09%7B%0A
%09%09%09question : 'L
|
bcf5f2e46f5033b274e7e8b37ca1548edd17d73c | remove Authentication + hook into new infrastructure | lib/pages/index.js | lib/pages/index.js | define(['angular', 'angular-route'],
function(angular) {
'use strict';
var $ = angular.element;
var pagesModule = angular.module('camunda.common.pages', [
'ngRoute'
]);
function setHeadTitle(url) {
var pageTitle = 'camunda Login';
if (url.indexOf('/cockpit/') !== -1) {
pageTitle = 'camunda Cockpit';
} else
if (url.indexOf('/tasklist/') !== -1) {
pageTitle = 'camunda Tasklist';
} else
if (url.indexOf('/admin/') !== -1) {
pageTitle = 'camunda Admin';
}
$('head title').text(pageTitle);
}
var ResponseErrorHandlerInitializer = [
'$rootScope', '$location', 'Notifications', 'Authentication',
function($rootScope, $location, Notifications, Authentication) {
function addError(error) {
error.http = true;
error.exclusive = [ 'http' ];
Notifications.addError(error);
}
/**
* A handler function that handles HTTP error responses,
* i.e. 4XX and 5XX responses by redirecting / notifying the user.
*/
function handleHttpError(event, error) {
var status = error.status,
data = error.data;
switch (status) {
case 500:
if (data && data.message) {
addError({
status: 'Server Error',
message: data.message,
exceptionType: data.exceptionType
});
} else {
addError({
status: 'Server Error',
message: 'The server reported an internal error. Try to refresh the page or login and out of the application.'
});
}
break;
case 0:
addError({ status: 'Request Timeout', message: 'Your request timed out. Try to refresh the page.' });
break;
case 401:
Authentication.clear();
if ($location.absUrl().indexOf('/setup/#') == -1) {
addError({ type: 'warning', status: 'Session ended', message: 'Your session timed out or was ended from another browser window. Please signin again.' });
setHeadTitle($location.absUrl());
$location
.search('destination', $location.search().destination || encodeURIComponent($location.url()))
.path('/login')
;
} else {
$location.path('/setup');
}
break;
case 403:
if (data.type == 'AuthorizationException') {
addError({
status: 'Access Denied',
message: 'You are unauthorized to ' +
data.permissionName.toLowerCase() + ' ' +
data.resourceName.toLowerCase() +
(data.resourceId ? ' ' + data.resourceId : 's') +
'.' });
} else {
addError({
status: 'Access Denied',
message: 'Executing an action has been denied by the server. Try to refresh the page.'
});
}
break;
case 404:
addError({ status: 'Not found', message: 'A resource you requested could not be found.' });
break;
default:
addError({
status: 'Communication Error',
message: 'The application received an unexpected ' + status + ' response from the server. Try to refresh the page or login and out of the application.'
});
}
}
// triggered by httpStatusInterceptor
$rootScope.$on('httpError', handleHttpError);
}];
var ProcessEngineSelectionController = [
'$scope', '$http', '$location', '$window', 'Uri', 'Notifications',
function($scope, $http, $location, $window, Uri, Notifications) {
var current = Uri.appUri(':engine');
var enginesByName = {};
$http.get(Uri.appUri('engine://engine/')).then(function(response) {
$scope.engines = response.data;
angular.forEach($scope.engines , function(engine) {
enginesByName[engine.name] = engine;
});
$scope.currentEngine = enginesByName[current];
if (!$scope.currentEngine) {
Notifications.addError({ status: 'Not found', message: 'The process engine you are trying to access does not exist' });
$location.path('/');
}
});
$scope.$watch('currentEngine', function(engine) {
if (engine && current !== engine.name) {
$window.location.href = Uri.appUri('app://../' + engine.name + '/');
}
});
}];
var NavigationController = [ '$scope', '$location', function($scope, $location) {
$scope.activeClass = function(link) {
var path = $location.absUrl();
return path.indexOf(link) != -1 ? 'active' : '';
};
}];
var AuthenticationController = [
'$scope', '$window', '$cacheFactory', '$location', 'Notifications', 'AuthenticationService', 'Uri',
function($scope, $window, $cacheFactory, $location, Notifications, AuthenticationService, Uri) {
$scope.logout = function() {
AuthenticationService.logout();
};
}];
return pagesModule
.run(ResponseErrorHandlerInitializer)
.controller('ProcessEngineSelectionController', ProcessEngineSelectionController)
.controller('AuthenticationController', AuthenticationController)
.controller('NavigationController', NavigationController);
});
| JavaScript | 0 | @@ -652,26 +652,8 @@
ns',
- 'Authentication',
%0A
@@ -698,32 +698,16 @@
ications
-, Authentication
) %7B%0A%0A
@@ -1722,40 +1722,8 @@
401:
-%0A Authentication.clear();
%0A%0A
@@ -1771,16 +1771,17 @@
tup/#')
+!
== -1) %7B
@@ -1777,24 +1777,77 @@
) !== -1) %7B%0A
+ $location.path('/setup');%0A %7D else %7B%0A
ad
@@ -2059,212 +2059,59 @@
$
-location%0A .search('destination', $location.search().destination %7C%7C encodeURIComponent($location.url()))%0A .path('/login')%0A ;%0A %7D else %7B%0A $location.path('/setup
+rootScope.$broadcast('authentication.login.required
');%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.