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
|
---|---|---|---|---|---|---|---|
6354ccd4dd9a7dda72affa665540ac6391314cf0 | Add more emoji | cd/src/pipeline-events-handler/etc/execution-emoji.js | cd/src/pipeline-events-handler/etc/execution-emoji.js | // These should be easily identifiable and both visually and conceptually unique
// Don't include symbols that could be misconstrued to have some actual meaning
// (like a warning sign)
const emojis = [
'🦊',
'🐸',
'🦉',
'🦄',
'🐙',
'🐳',
'🌵',
'🍀',
'🍁',
'🍄',
'🌍',
'⭐️',
'🔥',
'🌈',
'🍎',
'🥯',
'🌽',
'🥞',
'🥨',
'🍕',
'🌮',
'🍦',
'🎂',
'🍿',
'🏈',
'🛼',
'🏆',
'🎧',
'🎺',
'🎲',
'🚚',
'✈️',
'🚀',
'⛵️',
'⛺️',
'📻',
'💰',
'💎',
'🧲',
'🔭',
'🪣',
'🧸',
];
module.exports = {
emoji(executionId) {
// Create a simple hash of the execution ID
const hash = [...executionId].reduce(
(prev, curr) => prev + curr.charCodeAt(0),
0,
);
// Return an emoji based on the hash. This is hopefully significantly
// random that deploys near to each other in time don't get the same
// symbol
return emojis[hash % emojis.length];
},
};
| JavaScript | 0.000034 | @@ -239,16 +239,30 @@
%0A '%F0%9F%90%B3',%0A
+ '%F0%9F%90%9D',%0A '%F0%9F%A6%96',%0A
'%F0%9F%8C%B5',%0A
@@ -408,16 +408,23 @@
%0A '%F0%9F%8E%A7',%0A
+ '%F0%9F%91%91',%0A
'%F0%9F%8E%BA',%0A
@@ -467,16 +467,23 @@
'%E2%9B%BA%EF%B8%8F',%0A
+ '%F0%9F%8C%80',%0A
'%F0%9F%93%BB',%0A
@@ -523,16 +523,30 @@
%0A '%F0%9F%A7%B8',%0A
+ '%F0%9F%A6%BA',%0A '%F0%9F%91%96',%0A
%5D;%0A%0Amodu
|
a1267749cbb5a69000e9415b84c22c1427cb5599 | Fix value to 2 digit after comma | 723e_web/app/scripts/views/transactions/YearView.js | 723e_web/app/scripts/views/transactions/YearView.js | define([
'jquery',
'underscore',
'backbone',
'mustache',
'moment',
'initView',
'ws',
'storage',
'chartjs',
'text!templates/transactions/dateSelectPage.mustache'
], function(
$,
_,
Backbone,
Mustache,
moment,
InitView,
ws,
storage,
Chart,
DateSelectorPageTemplate) {
var arrayAbstract = [];
var nbSource = 0;
var DashboardView = Backbone.View.extend({
el: $("#content"),
render: function(year) {
var initView = new InitView();
if (initView.isLoaded() === false) {
initView.render();
}
initView.changeSelectedItem("nav_transactions");
var currentDate = new Date();
var calendar = {};
if (year === undefined || year === null) {
calendar.year = currentDate.getFullYear();
} else {
calendar.year = moment().year(year).year();
}
calendar.before = calendar.year - 1;
calendar.after = calendar.year + 1;
calendar.months = [];
ws.get({
"url": ws.v1.resume_year,
"data": {
year: calendar.year
},
success: function(json) {
var account_currency = storage.currencies.get(storage.user.currency());
var i, l;
// Generate statistiques
var stats = {
'global' : {
'counter': 0,
'sum': 0,
'credits': 0,
'debits': 0
},
'average' : {
'sum': 0,
'credits': 0,
'debits': 0
},
'changes': json.stats.changes,
'categories': json.categories.list
};
for (i = 1; i <= 12; i = i + 1) {
var sum = (json.months[i] ? json.months[i].sum : 0),
credits = (json.months[i] ? json.months[i].sum_credits : 0),
debits = (json.months[i] ? json.months[i].sum_debits : 0),
count = (json.months[i] ? json.months[i].count : 0);
calendar.months.push({
month : moment().month(i - 1).format("MM"),
year : year,
label : moment().month(i - 1).format("MMMM"),
exist : (json.months[i] ? true : false),
count : count,
sum : account_currency.toString(sum),
credits : account_currency.toString(credits),
debits : account_currency.toString(debits),
c : credits,
d : Math.abs(debits),
color : (sum >= 0) ? 'green' : 'red'
});
if(i <= currentDate.getMonth() && count !== 0){
stats.global.counter += 1;
stats.global.sum += sum;
stats.global.credits += credits;
stats.global.debits += debits;
}
}
stats.average.sum = stats.global.sum / stats.global.counter;
stats.average.credits = stats.global.credits / stats.global.counter;
stats.average.debits = stats.global.debits / stats.global.counter;
for(i = 0, l = stats.average.length; i < l; i=i+1){
var new_currency = storage.currencies.get(stats.average[i].currency);
stats.average[i].old = account_currency.toString(stats.average[i].old);
stats.average[i].new = new_currency.toString(stats.average[i].new);
stats.average[i].average = account_currency.toString(stats.average[i].average);
}
for(i = 0, l = stats.categories.length; i < l; i=i+1){
stats.categories[i].category = storage.categories.get(stats.categories[i].category).toJSON();
}
var template = Mustache.render(DateSelectorPageTemplate, {
calendar: calendar,
stats: stats
});
$("#content").html(template);
$("#content .fitText").fitText();
// Init graph
var ctx = document.getElementById("expenseYearLine").getContext("2d");
var data = {
labels: _.pluck(calendar.months, 'label'),
datasets: [
{
label: "Crédits",
fillColor: "rgba(0,150,0,0.2)",
strokeColor: "rgba(0,150,0,1)",
pointColor: "rgba(0,150,0,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(0,150,0,1)",
data: _.pluck(calendar.months, 'c')
},
{
label: "Débits",
fillColor: "rgba(151,0,0,0.2)",
strokeColor: "rgba(151,0,0,1)",
pointColor: "rgba(151,0,0,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,0,0,1)",
data: _.pluck(calendar.months, 'd')
}
]
};
var myNewChart = new Chart(ctx).Line(data, {
responsive: true
});
var ctx = document.getElementById("categorieYearPie").getContext("2d");
var data = [];
for(i = 0, l = stats.categories.length; i < l; i=i+1){
data.push({
value: Math.round(Math.abs(stats.categories[i].sum) * 100) / 100,
color: stats.categories[i].category.color,
highlight: stats.categories[i].category.color,
label: stats.categories[i].category.name
});
}
// {
// value: 300,
// color:"#F7464A",
// highlight: "#FF5A5E",
// label: "Red"
// },
// {
// value: 50,
// color: "#46BFBD",
// highlight: "#5AD3D1",
// label: "Green"
// },
// {
// value: 100,
// color: "#FDB45C",
// highlight: "#FFC870",
// label: "Yellow"
// }
var myNewChart = new Chart(ctx).Pie(data, {
responsive: true
});
}
});
}
});
return DashboardView;
});
| JavaScript | 0.999996 | @@ -3548,32 +3548,303 @@
%7D%0A%0A
+ // Round to 2 digit after comma%0A stats.global.sum = stats.global.sum.toFixed(2);%0A stats.global.debits = stats.global.debits.toFixed(2);%0A stats.global.credits = stats.global.credits.toFixed(2);%0A%0A
|
f92cba9a3c423e3cdf80a34385963a495a0acf1a | Arrange a code | beginning/Object/create/index.js | beginning/Object/create/index.js | #!/usr/bin/env node
//
// Object.create()
//
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
//
var assert = require('assert');
function Foo(val) {
this.notProtoProp = val;
}
Foo.prototype.protoProp = 10;
var foo = new Foo('a');
assert(foo.protoProp === 10);
assert(foo.notProtoProp === 'a');
assert(foo.__proto__.protoProp === 10);
// Foo.prototype を prototype にもつ bar オブジェクトを生成する
var bar = Object.create(Foo.prototype);
assert(bar.__proto__.protoProp === 10);
assert(bar.__proto__ === Foo.prototype);
// これはなんでだろう..?
assert(bar.prototype !== Foo.prototype);
// これもなんでだろう...?
assert(bar.prototype === foo.prototype);
// オマケだけど、Foo と同じ初期化をしたければこうする
Foo.call(bar, 'a');
assert(bar.notProtoProp === 'a');
| JavaScript | 0.999999 | @@ -520,87 +520,220 @@
0);%0A
-assert(bar.__proto__ === Foo.prototype);%0A// %E3%81%93%E3%82%8C%E3%81%AF%E3%81%AA%E3%82%93%E3%81%A7%E3%81%A0%E3%82%8D%E3%81%86..?%0Aassert(bar.prototype !
+%0A%0A// %E3%82%AA%E3%83%9E%E3%82%B1: Foo %E3%81%A8%E5%90%8C%E3%81%98%E5%88%9D%E6%9C%9F%E5%8C%96%E3%82%92%E3%81%97%E3%81%9F%E3%81%91%E3%82%8C%E3%81%B0%E3%81%93%E3%81%86%E3%81%99%E3%82%8B%0AFoo.call(bar, 'a');%0Aassert(bar.notProtoProp === 'a');%0A%0A%0A// %E3%82%AA%E3%83%9E%E3%82%B1: prototype %E3%82%84 __proto__ %E3%81%AE%E3%81%93%E3%81%A8%0Aassert(foo.prototype !== Foo.prototype);%0Aassert(foo instanceof Foo);%0Aassert(foo.__proto__ =
== F
@@ -750,25 +750,34 @@
pe);
-%0A// %E3%81%93%E3%82%8C%E3%82%82%E3%81%AA%E3%82%93%E3%81%A7%E3%81%A0%E3%82%8D%E3%81%86...?
+ // @TODO __proto__ %E3%81%A3%E3%81%A6%E4%BD%95%EF%BC%9F%0A
%0Aass
@@ -798,13 +798,13 @@
ype
-=== f
+!== F
oo.p
@@ -818,90 +818,128 @@
e);%0A
-%0A// %E3%82%AA%E3%83%9E%E3%82%B1%E3%81%A0%E3%81%91%E3%81%A9%E3%80%81Foo %E3%81%A8%E5%90%8C%E3%81%98%E5%88%9D%E6%9C%9F%E5%8C%96%E3%82%92%E3%81%97%E3%81%9F%E3%81%91%E3%82%8C%E3%81%B0%E3%81%93%E3%81%86%E3%81%99%E3%82%8B%0AFoo.call(bar, 'a');%0Aassert(bar.notProtoProp === 'a');
+assert(bar instanceof Foo);%0Aassert(bar.__proto__ === Foo.prototype);%0Aassert(bar.prototype === foo.prototype); // @TODO %E4%BD%95%E6%95%85%EF%BC%9F
%0A
|
1cd2d4d07e475c8a622a8d9de03f0b75f2a6a65f | edit boot file | back/app.js | back/app.js | /**
* APP
* Your amazing app
* http://www.app.app
*
* Copyright (c) 2014 Thanasis Polychronakis
* Licensed under the MIT OSS
*/
/**
* Module dependencies.
*/
var util = require('util');
var BPromise = require('bluebird');
var log = require('logg').getLogger('app.boot');
var globals = require('./core/globals');
var AppServices = require('./app-services');
var logger = require('./util/logger');
/**
* The master boot.
*
*/
var app = module.exports = {};
// define stand alone status
globals.isStandAlone = require.main === module;
var initialized = false;
/** @type {?app.boot.services} The services boot */
app.boot = null;
/**
* Master bootstrap module.
*
* Available options to pass on the first arg:
*
* @param {Object=} optOpts init params.
* @return {BPromise} A dissaster.
*/
app.init = function(optOpts) {
if (initialized) { return BPromise.resolve(); }
initialized = true;
app.boot = AppServices.getInstance();
app.boot.setup(optOpts);
// assign to globals the boot options
globals.bootOpts = app.boot.options;
// Initialize logging facilities
logger.init();
if (!app.boot.options.log || process.env.NODE_NOLOG) {
logger.removeConsole();
}
log.info('Initializing... standAlone:', globals.isStandAlone,
':: System NODE_ENV:', process.env.NODE_ENV, ':: App Environment:', globals.env,
':: Server ID:', globals.serverId, ':: On Heroku:', globals.isHeroku,
':: Security:', app.boot.options.security);
// Global exception handler
process.on('uncaughtException', app.onNodeFail);
return app.boot.initServices()
.catch(function(err){
log.error('Error on boot:', err);
process.exit(-1);
});
};
/**
* Catch-all for all unhandled exceptions
*
* @param {Error} err An error object.
*/
app.onNodeFail = function(err) {
log.error('onNodeFail() :: Unhandled Exception. Error:', util.inspect(err), err);
process.exit(1);
};
// ignition
if (globals.isStandAlone) {
app.init();
}
| JavaScript | 0.000001 | @@ -4,11 +4,20 @@
%0A *
-APP
+wearetech.io
%0A *
@@ -1178,16 +1178,46 @@
G) %7B%0A
+ // TODO figure out wtf%0A //
logger.
|
f55d8434c21767dcdc1445381d233c00e2a24384 | Update google signin | configure/GoogleAuth.js | configure/GoogleAuth.js | /**
* Created by thanhqhc on 3/9/17.
*/
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.use(new GoogleStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/callback"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
}
));
module.exports = passport; | JavaScript | 0 | @@ -43,357 +43,856 @@
var
-passport = require('passport')
+auth = new GoogleAuth
;%0A
+%0A
var
-GoogleStrategy = require('passport-google-oauth20').Strategy;%0A%0Apassport.use(new GoogleStrategy(%7B%0A clientID: GOOGLE_CLIENT_ID,%0A clientSecret: GOOGLE_CLIENT_SECRET,%0A callbackURL: %22http://localhost:3000/auth/google/callback%22%0A %7D,%0A function(accessToken, refreshToken, profile, cb) %7B%0A
+client = new auth.OAuth2('633133829509-91rk6671rtm60nqdg0tiqjvhuenme6no.apps.googleusercontent.com', '', '');%0A%0Afunction requestFacebookInfo(access_token) %7B%0A%0A var rxObject = Rx.Observable.create(function (observer) %7B%0A client.verifyIdToken(%0A req.body.token,%0A %5B%0A '799105536867-8tcdqtmv7krhgfh4tat9ch1b226t4kc7.apps.googleusercontent.com',%0A '799105536867-mb2kn9vvcvcs2qqf6q9qqmj2rhbus82b.apps.googleusercontent.com',%0A '633133829509-91rk6671rtm60nqdg0tiqjvhuenme6no.apps.googleusercontent.com',%0A '633133829509-ljhkn3tfe9iodo0e8vmqdkk9e0eju73f.apps.googleusercontent.com'%0A %5D,%0A function(error, login) %7B%0A if (error) %7B%0A observer.error(error);%0A %7D else %7B%0A
cons
@@ -887,16 +887,23 @@
+
console.
@@ -910,51 +910,144 @@
log(
-profile);%0A %7D%0A));%0A%0Amodule.exports = passport
+%22Login success: %22 + login);%0A %7D%0A %7D%0A )%0A %7D%0A%0A return rxObject;%0A%7D%0A%0A%0A%0Amodule.exports = requestFacebookInfo
;
|
62a8f9564fd5a4728d8fa32dd9d8b897a55447b0 | Fix problem causing console error | app/boot.js | app/boot.js | window.name = 'NG_DEFER_BOOTSTRAP!';
require.config({
waitSeconds: 120,
baseUrl : '/app',
paths: {
'authentication' : 'services/authentication',
'angular' : 'libs/angular-flex/angular-flex',
'ngRoute' : 'libs/angular-route/angular-route.min',
'ngSanitize' : 'libs/angular-sanitize/angular-sanitize.min',
'domReady' : 'libs/requirejs-domready/domReady',
'text' : 'libs/requirejs-text/text',
'bootstrap' : 'libs/bootstrap/dist/js/bootstrap.min',
'lodash' : 'libs/lodash/lodash.min',
'URIjs' : 'libs/uri.js/src',
'linqjs' : 'libs/linqjs/linq.min',
'leaflet' : 'libs/leaflet/dist/leaflet',
'jquery' : 'libs/jquery/dist/jquery.min',
'moment' : 'libs/moment/moment',
'leaflet-directive' : 'js/libs/leaflet/angular-leaflet-directive',
'ng-breadcrumbs' : 'js/libs/ng-breadcrumbs/dist/ng-breadcrumbs.min',
'bootstrap-datepicker': 'libs/bootstrap-datepicker/js/bootstrap-datepicker',
'ionsound' : 'libs/ionsound/js/ion.sound.min',
'jqvmap' : 'js/libs/jqvmap/jqvmap/jquery.vmap',
'jqvmapworld' : 'js/libs/jqvmap/jqvmap/maps/jquery.vmap.world',
'ngAnimate' : 'libs/angular-animate/angular-animate.min',
'ngAria' : 'libs/angular-aria/angular-aria.min',
'ngMaterial' : 'libs/angular-material/angular-material.min',
'ngSmoothScroll' : 'libs/ngSmoothScroll/angular-smooth-scroll.min',
'ammap3WorldHigh' : 'directives/reporting-display/worldEUHigh',
'ammap3' : 'libs/ammap3/ammap/ammap',
'ammap-theme' : 'libs/ammap3/ammap/themes/light',
'ammap-resp' : 'libs/ammap3/ammap/plugins/responsive/responsive',
'ammap-export' : 'libs/ammap3/ammap/plugins/export/export.min',
'ammap-ex-fabric' : 'libs/ammap3/ammap/plugins/export/libs/fabric.js/fabric.min',
'ammap-ex-filesaver' : 'libs/ammap3/ammap/plugins/export/libs/FileSaver.js/FileSaver.min',
'ammap-ex-pdfmake' : 'libs/ammap3/ammap/plugins/export/libs/pdfmake/pdfmake.min',
'ammap-ex-vfs-fonts' : 'libs/ammap3/ammap/plugins/export/libs/pdfmake/vfs_fonts',
'ammap-ex-jszip' : 'libs/ammap3/ammap/plugins/export/libs/jszip/jszip.min',
'ammap-ex-xlsx' : 'libs/ammap3/ammap/plugins/export/libs/xlsx/xlsx.min',
'amchart3' : 'libs/amcharts3/amcharts/amcharts',
'amchart3-serial' : 'libs/amcharts3/amcharts/serial',
'amchart3-pie' : 'libs/amcharts3/amcharts/pie',
'amchart3-theme-light': 'libs/amcharts3/amcharts/themes/light'
},
shim: {
'libs/angular/angular' : { deps: ['jquery'] },
'angular' : { deps: ['libs/angular/angular'] },
'ngRoute' : { deps: ['angular'] },
'ngSanitize' : { deps: ['angular'] },
'leaflet-directive' : { deps: ['angular', 'leaflet'], exports : 'L' },
'ng-breadcrumbs' : { deps: ['angular'] },
'bootstrap' : { deps: ['jquery'] },
'linqjs' : { deps: [], exports : 'Enumerable' },
'leaflet' : { deps: [], exports : 'L' },
'bootstrap-datepicker' : { deps: ['bootstrap'] },
'jqvmap' : { deps: ['jquery'] },
'jqvmapworld' : { deps: ['jqvmap'] },
'ionsound' : { deps: ['jquery'] },
'ngAnimate' : { deps: ['angular'] },
'ngAria' : { deps: ['angular'] },
'ngMaterial' : { deps: ['angular', 'ngAnimate', 'ngAria'] },
'ngSmoothScroll' : { deps: ['angular'] },
'ammap3WorldHigh' : { deps: ['ammap3'] },
'ammap-theme' : { deps: ['ammap3']},
'ammap-resp' : { deps: ['ammap3']},
'amchart3-serial' : { deps: ['amchart3']},
'amchart3-pie' : { deps: ['amchart3']},
'amchart3-theme-light' : { deps: ['amchart3']},
},
});
// BOOT
require(['angular', 'domReady!', 'bootstrap', 'app', 'routes', 'index'], function(ng, doc) {
//this is for spec tests with selenium as it starts angular first
// this tests if angualr has been bootstrapped and if it has it resumes
ng.bootstrap(doc, ['kmApp']);
try {
$(document.body).attr("ng-app", "kmApp"); //jshint ignore:line
} catch (e) {
ng.resumeBootstrap();
}
});
| JavaScript | 0.000029 | @@ -4220,24 +4220,76 @@
mchart3'%5D%7D,%0A
+ 'ammap-export' : %7B deps: %5B'ammap3'%5D%7D,%0A
%7D,%0A%7D);%0A%0A
|
3f6b6b1db300809bef2540df1c6f05d53e2482af | Remove city 'Other' using removeIfExists | seeds/cities.js | seeds/cities.js | var util = require('../src/util/seeds');
exports.seed = function(knex, Promise) {
return util.insertOrUpdate(knex, 'cities', {
id: 1,
name: 'Otaniemi',
})
.then(() => util.insertOrUpdate(knex, 'cities', {
id: 2,
name: 'Tampere',
}));
}
| JavaScript | 0.998837 | @@ -85,16 +85,103 @@
return
+ util.removeIfExists(knex, 'cities', %7B%0A id: 1,%0A name: 'Other',%0A %7D)%0A .then(() =%3E
util.in
@@ -211,33 +211,33 @@
ies', %7B%0A id:
-1
+2
,%0A name: 'Ota
@@ -244,24 +244,25 @@
niemi',%0A %7D)
+)
%0A .then(()
@@ -302,33 +302,33 @@
ies', %7B%0A id:
-2
+3
,%0A name: 'Tam
|
c81c4fe3a5668daedf03abcbc144e2e644281a06 | Update ColdHeartEfficiency.js | src/Parser/DeathKnight/Unholy/Modules/Items/ColdHeartEfficiency.js | src/Parser/DeathKnight/Unholy/Modules/Items/ColdHeartEfficiency.js | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import ITEMS from 'common/ITEMS';
import { formatPercentage } from 'common/format';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
class ColdHeartEfficiency extends Analyzer {
static dependencies = {
combatants: Combatants,
};
on_initialized() {
this.active = this.combatants.selected.hasChest(ITEMS.COLD_HEART.id);
}
totalColdHeartCasts = 0;
correctColdHeartCasts = 0;
buffColdHeart = 0;
on_byPlayer_applybuff(event){
this.addStack(event);
}
on_byPlayer_applybuffstack(event){
this.addStack(event);
}
addStack(event){
const spellID = event.ability.guid;
if(spellID === SPELLS.COLD_HEART_BUFF.id){
this.buffColdHeart+=1;
if(this.buffColdHeart > 20) {
this.buffColdHeart=20;
}
}
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId == SPELLS.CHAINS_OF_ICE.id) {
this.totalColdHeartCasts++;
if (this.combatants.selected.hasBuff(SPELLS.UNHOLY_STRENGTH.id)) {
if (this.buffColdHeart < 20) {
if (this.buffColdHeart > 16) {
this.correctColdHeartCasts++;
}
}
}
if (this.buffColdHeart == 20) {
this.correctColdHeartCasts++;
}
}
}
suggestions(when) {
const castEfficiency = this.correctColdHeartCasts/this.totalColdHeartCasts;
when(castEfficiency).isLessThan(0.8)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>You are casting <SpellLink id={SPELLS.CHAINS_OF_ICE.id}/> at the wrong times. You either want to cast <SpellLink id={SPELLS.CHAINS_OF_ICE.id}/> when at 20 stacks of <SpellLink id={SPELLS.COLD_HEART_BUFF.id}/> or when you are above 16 stacks and you have the buff <SpellLink id={SPELLS.UNHOLY_STRENGTH.id}/></span>)
.icon(SPELLS.CHAINS_OF_ICE.icon)
.actual(`${formatPercentage(actual)}% of Chains of Ice were cast correctly.`)
.recommended(`>${formatPercentage(recommended)}% is recommended`)
.regular(recommended - 0.30).major(recommended - 0.40);
});
}
statistic() {
const castEfficiency = this.correctColdHeartCasts/this.totalColdHeartCasts;
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.CHAINS_OF_ICE.id} />}
value={`${formatPercentage(castEfficiency)} %`}
label={'Cold Heart Efficiency'}
tooltip={`${formatPercentage(1-castEfficiency)}% of Cold Heart casts were made incorrectly. Either there wasn't 20 stacks of cold heart, or you didn't have the Unholy Strength buff up with more than 16 stacks of Cold Heart.`}
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(5);
}
export default ColdHeartEfficiency;
| JavaScript | 0 | @@ -945,16 +945,20 @@
rt+=1;%0A%09
+
if(this.
@@ -980,16 +980,22 @@
20) %7B%0A%09
+
this.buf
@@ -1010,16 +1010,20 @@
rt=20;%0A%09
+
%7D%0A %7D%0A
@@ -1113,16 +1113,17 @@
ellId ==
+=
SPELLS.
@@ -1183,19 +1183,16 @@
;%0A %09
-
if (thi
@@ -1253,16 +1253,22 @@
d)) %7B%0A%09%09
+
if (this
@@ -1293,16 +1293,22 @@
0) %7B%0A%09%09%09
+
if (this
@@ -1341,19 +1341,15 @@
-%09%09
-%09
this
@@ -1381,26 +1381,26 @@
%0A%09%09%09
-%09%7D%0A%09%09%09%7D%0A
+
+%7D%0A%09
+%09%7D%0A
@@ -1438,24 +1438,16 @@
t ==
+=
20) %7B%0A
-
@@ -1486,20 +1486,19 @@
;%0A
-
%7D%0A
+
%7D%0A%0A %7D
|
272157dff36618c244269a274a80fdc0fa9a45d2 | Fix bug in pam.js | auth/pam.js | auth/pam.js | // Dependencies
var auth = require('../lib/auth');
var config = require('../lib/config');
var fs = require('../lib/fs');
var rfs = require('fs');
var _ = require('lodash');
var pam = require('authenticate-pam');
// Variables
var users = {};
var groups = {};
// Parse and cache /etc/passwd
rfs.readFile('/etc/passwd', { encoding: 'UTF-8' }, function (err, data) {
if (!err) {
var _users = data.split('\n');
_.map(_users, function (userRow) {
var user = userRow.split(':');
if (user[0] !== '') {
users[user[0]] = user;
}
});
}
});
// Parse and cache /etc/group
rfs.readFile('/etc/group', { encoding: 'UTF-8' }, function (err, data) {
if (!err) {
var _groups = data.split('\n');
_.map(_groups, function (groupRow) {
var group = groupRow.split(':');
if (group[0] !== '') {
groups[group[0]] = group;
}
});
}
});
// Register our authentication mechanism
auth.register('pam', function (username, password, done) {
pam.authenticate(username, password, function (err) {
if (err) {
done(err, null);
} else {
// Get all of the groups the user is part of
var userGroups = [parseInt(users[username][3])];
_.map(groups, function (group) {
var usersInGroup = group[3].split(',');
if (usersInGroup.indexOf(username) !== -1) {
userGroups.push(parseInt(group[2]));
}
});
// Format and return the user data
var user = {
uid: parseInt(users[username][2]),
gid: parseInt(users[username][3]),
username: username,
password: password,
chroot: config.get('auth.chroot') === '~' ? users[username][5] : config.get('auth.chroot'),
home: users[username][5],
groups: userGroups
};
done(err, user);
}
});
});
| JavaScript | 0.000001 | @@ -1649,37 +1649,32 @@
chroot: config.
-get('
auth.chroot') ==
@@ -1668,18 +1668,16 @@
h.chroot
-')
=== '~'
@@ -1711,13 +1711,8 @@
fig.
-get('
auth
@@ -1718,18 +1718,16 @@
h.chroot
-')
,%0A
|
8f17a0d6c3047119e8ed99b5131aad364af421b5 | Add opbeat config | config/configuration.js | config/configuration.js | /**
* @file Defines the hydrater settings.
*/
// nodeEnv can either be "development" or "production"
var nodeEnv = process.env.NODE_ENV || "development";
var defaultPort = 8000;
// Number of instance to run simultaneously per cluster
var defaultConcurrency = 1;
if(nodeEnv === "production") {
defaultPort = 80;
}
// Exports configuration
module.exports = {
env: nodeEnv,
port: process.env.PORT || defaultPort,
concurrency: process.env.ICS_CONCURRENCY || defaultConcurrency,
appName: process.env.APP_NAME || "ics-hydrater",
redisUrl: process.env.REDIS_URL
};
| JavaScript | 0.000001 | @@ -567,12 +567,173 @@
EDIS_URL
+,%0A%0A opbeat: %7B%0A organizationId: process.env.OPBEAT_ORGANIZATION_ID,%0A appId: process.env.OPBEAT_APP_ID,%0A secretToken: process.env.OPBEAT_SECRET_TOKEN%0A %7D
%0A%7D;%0A
|
24c262442ce990e68ed6f7a8aa98a95fba83379b | Add optional custom log | packages/express/index.js | packages/express/index.js | const express = require('express');
module.exports = async init => {
const app = express();
app.disable('x-powered-by');
await init(app, express);
const port = process.env.PORT;
if (!port) {
throw new Error('missing port');
}
app.listen(port, () => {
console.log(`app listen on port ${port}`);
});
};
| JavaScript | 0 | @@ -53,20 +53,55 @@
= async
+(
init
+, %7B log: log = console.log %7D = %7B%7D)
=%3E %7B%0A
@@ -304,24 +304,16 @@
%3E %7B%0A
-console.
log(%60app
|
54ad5372e4a67a08ab683a068f8bf33de91a8a26 | Remove stray callback | html5/controllers/todo.ctrl.js | html5/controllers/todo.ctrl.js | module.exports = TodoCtrl;
var app = require('../app.html5');
var async = require('async');
function TodoCtrl($scope, $routeParams, $filter, Todo, $location, sync) {
var todos = $scope.todos = [];
$scope.newTodo = '';
$scope.editedTodo = null;
// sync the initial data
sync(onChange);
// the location service
$scope.loc = $location;
function onChange() {
Todo.stats(function(err, stats) {
if(err) return error(err);
$scope.stats = stats;
});
Todo.find({
where: $scope.statusFilter,
sort: 'order DESC'
}, function(err, todos) {
$scope.todos = todos;
$scope.$apply();
});
}
function error(err) {
//TODO error handling
throw err;
}
function errorCallback(err) {
if(err) error(err);
}
Todo.on('changed', onChange);
Todo.on('deleted', onChange);
// Monitor the current route for changes and adjust the filter accordingly.
$scope.$on('$routeChangeSuccess', function () {
var status = $scope.status = $routeParams.status || '';
$scope.statusFilter = (status === 'active') ?
{ completed: false } : (status === 'completed') ?
{ completed: true } : {};
});
$scope.addTodo = function () {
var todo = new Todo({title: $scope.newTodo});
todo.save();
$scope.newTodo = '';
};
$scope.editTodo = function (todo) {
$scope.editedTodo = todo;
};
$scope.todoCompleted = function(todo) {
todo.completed = true;
todo.save();
}
$scope.doneEditing = function (todo) {
$scope.editedTodo = null;
todo.title = todo.title.trim();
if (!todo.title) {
$scope.removeTodo(todo);
} else {
todo.save();
}
};
$scope.removeTodo = function (todo) {
todo.remove(errorCallback);
};
$scope.clearCompletedTodos = function () {
Todo.destroyAll({completed: true}, onChange);
};
$scope.markAll = function (completed) {
Todo.find(function(err, todos) {
if(err) return errorCallback(err);
todos.forEach(function(todo) {
todo.completed = completed;
todo.save(errorCallback);
});
});
};
$scope.sync = function() {
sync(diff);
};
$scope.connected = function() {
return window.connected();
};
$scope.connect = function() {
window.isConnected = true;
sync();
};
$scope.disconnect = function() {
window.isConnected = false;
};
Todo.on('conflicts', function(conflicts) {
$scope.localConflicts = conflicts;
conflicts.forEach(function(conflict) {
conflict.type(function(err, type) {
conflict.type = type;
conflict.models(function(err, source, target) {
conflict.source = source;
conflict.target = target;
conflict.manual = new conflict.SourceModel(source || target);
$scope.$apply();
});
conflict.changes(function(err, source, target) {
conflict.sourceChange = source;
conflict.targetChange = target;
$scope.$apply();
});
});
});
});
$scope.resolveUsingSource = function(conflict) {
conflict.resolve(refreshConflicts);
}
$scope.resolveUsingTarget = function(conflict) {
if(conflict.targetChange.type() === 'delete') {
conflict.SourceModel.deleteById(conflict.modelId, refreshConflicts);
} else {
var m = new conflict.SourceModel(conflict.target);
m.save(refreshConflicts);
}
}
$scope.resolveManually = function(conflict) {
conflict.manual.save(function(err) {
if(err) return errorCallback(err);
conflict.resolve(refreshConflicts);
});
}
function refreshConflicts() {
$scope.localConflicts = [];
$scope.$apply();
sync();
}
}
| JavaScript | 0.000001 | @@ -2104,12 +2104,8 @@
ync(
-diff
);%0A
|
f47ab15e347186bb9d37e96804ceb587f72c54a7 | allow to update client with empty ssn | imports/api/hmisApi/clientApi.js | imports/api/hmisApi/clientApi.js | import moment from 'moment';
import querystring from 'querystring';
import { removeEmpty } from '/imports/api/utils';
import { HmisApiRegistry } from './apiRegistry';
import { ApiEndpoint } from './apiEndpoint';
const BASE_URL = 'https://www.hmislynk.com/hmis-clientapi/rest';
const DEFAULT_PROJECT_SCHEMA = 'v2017';
export class ClientApi extends ApiEndpoint {
getClient(clientId, schema = DEFAULT_PROJECT_SCHEMA) {
const url = `${BASE_URL}/${schema}/clients/${clientId}`;
const client = this.doGet(url).client;
// TODO: remove .trim() when api returns the data without space-padding
return {
...client,
firstName: client.firstName ? client.firstName.trim() : '',
middleName: client.middleName ? client.middleName.trim() : '',
lastName: client.lastName ? client.lastName.trim() : '',
nameSuffix: client.nameSuffix ? client.nameSuffix.trim() : '',
};
}
getClients() {
const url = `${BASE_URL}/clients`;
return this.doGet(url).Clients.clients;
}
createClient(client, schema) {
const dob = moment(client.dob);
const body = {
client: removeEmpty({
firstName: client.firstName,
middleName: client.middleName,
lastName: client.lastName,
nameSuffix: client.suffix,
nameDataQuality: 1,
ssn: client.ssn,
ssnDataQuality: 1,
dob: dob.isValid() ? dob.format('x') : 0,
dobDataQuality: dob.isValid() ? 1 : 0,
race: client.race,
ethnicity: client.ethnicity,
gender: client.gender,
// Putting otherGender as null. Confirmed with Javier. Because it's of no use as of now.
otherGender: 'null',
veteranStatus: client.veteranStatus,
disablingConditions: client.disablingConditions,
sourceSystemId: client._id || '',
phoneNumber: client.phoneNumber,
emailAddress: client.emailAddress,
}),
};
const url = `${BASE_URL}/${schema}/clients`;
return {
clientId: this.doPost(url, body).client.clientId,
schema,
};
}
updateClient(clientId, client, schema) {
const dob = moment(client.dob);
const body = {
client: {
firstName: client.firstName,
middleName: client.middleName,
lastName: client.lastName,
nameSuffix: client.suffix,
nameDataQuality: 1,
ssn: client.ssn,
ssnDataQuality: 1,
dob: dob.isValid() ? dob.format('x') : 0,
dobDataQuality: dob.isValid() ? 1 : 0,
race: client.race,
ethnicity: client.ethnicity,
gender: client.gender,
// Putting otherGender as null. Confirmed with Javier. Because it's of no use as of now.
otherGender: 'null',
veteranStatus: client.veteranStatus,
disablingConditions: client.disablingConditions,
sourceSystemId: clientId,
// sourceSystemId: client._id,
phoneNumber: client.phoneNumber,
emailAddress: client.emailAddress,
},
};
const url = `${BASE_URL}/${schema}/clients/${clientId}`;
const result = this.doPut(url, body);
return result;
}
deleteClient(clientId, schema) {
const url = `${BASE_URL}/${schema}/clients/${clientId}`;
return this.doDel(url);
}
getClientFromUrl(apiUrl) {
return this.doGet(`https://www.hmislynk.com${apiUrl}`).client;
}
searchClient(query, limit = 10) {
const params = {
q: query,
maxItems: limit,
sort: 'firstName',
order: 'asc',
};
const url = `${BASE_URL}/search/client?${querystring.stringify(params)}`;
return this.doGet(url).searchResults.items;
}
getClientEnrollments(clientId, schema = DEFAULT_PROJECT_SCHEMA, start = 0, limit = 9999) {
const url = `${BASE_URL}/${schema}/clients/${clientId}/enrollments?startIndex=${start}&maxItems=${limit}`; // eslint-disable-line max-len
return this.doGet(url).enrollments.enrollments;
}
getClientsEnrollmentExits(clientId, enrollmentId, schema = DEFAULT_PROJECT_SCHEMA) {
const url = `${BASE_URL}/${schema}/clients/${clientId}/enrollments/${enrollmentId}/exits`; // eslint-disable-line max-len
return this.doGet(url).exits.exits;
}
createProjectSetup(projectName, projectCommonName, schema = DEFAULT_PROJECT_SCHEMA) {
const url = `${BASE_URL}/${schema}/projects`;
const body = {
project: {
projectName,
projectCommonName,
continuumProject: 0,
projectType: 14, // Coordinated Assessment
residentialAffiliation: 0,
targetPopulation: 4, // NA - Not Applicable
trackingMethod: 0,
},
};
return this.doPost(url, body).project.projectId;
}
getProjects(schema = DEFAULT_PROJECT_SCHEMA, start = 0, limit = 9999) {
const url = `${BASE_URL}/${schema}/projects?startIndex=${start}&maxItems=${limit}`;
return this.doGet(url).projects.projects;
}
getProject(projectId, schema = DEFAULT_PROJECT_SCHEMA) {
const url = `${BASE_URL}/${schema}/projects/${projectId}`;
return this.doGet(url).project;
}
createProject(project, schema = DEFAULT_PROJECT_SCHEMA) {
const url = `${BASE_URL}/${schema}/projects`;
return this.doPost(url, { project });
}
updateProject(projectId, project, schema = DEFAULT_PROJECT_SCHEMA) {
const url = `${BASE_URL}/${schema}/projects/${projectId}`;
return this.doPut(url, { project });
}
deleteProject(projectId, schema = DEFAULT_PROJECT_SCHEMA) {
const url = `${BASE_URL}/${schema}/projects/${projectId}`;
return this.doDel(url);
}
postQuestionAnswer(category, data) {
const url = `${BASE_URL}/${category}`;
return this.doPost(url, data);
}
}
HmisApiRegistry.addApi('client', ClientApi);
| JavaScript | 0 | @@ -65,58 +65,8 @@
g';%0A
-import %7B removeEmpty %7D from '/imports/api/utils';%0A
impo
@@ -1066,20 +1066,8 @@
nt:
-removeEmpty(
%7B%0A
@@ -1843,17 +1843,16 @@
%0A %7D
-)
,%0A %7D;
|
2be94fb107262c1606fb4c14bef721c240caf1c6 | Fix bootstrapping for protractor and selenium | app/boot.js | app/boot.js | window.name = 'NG_DEFER_BOOTSTRAP!';
require.config({
waitSeconds: 120,
baseUrl : '/app',
paths: {
'authentication' : 'services/authentication',
'angular' : 'libs/angular-flex/angular-flex',
'ngRoute' : 'libs/angular-route/angular-route.min',
'ngSanitize' : 'libs/angular-sanitize/angular-sanitize.min',
'domReady' : 'libs/requirejs-domready/domReady',
'text' : 'libs/requirejs-text/text',
'bootstrap' : 'libs/bootstrap/dist/js/bootstrap.min',
'lodash' : 'libs/lodash/lodash.min',
'URIjs' : 'libs/uri.js/src',
'linqjs' : 'libs/linqjs/linq.min',
'leaflet' : 'libs/leaflet/dist/leaflet',
'jquery' : 'libs/jquery/dist/jquery.min',
'moment' : 'libs/moment/moment',
'leaflet-directive' : 'js/libs/leaflet/angular-leaflet-directive',
'ng-breadcrumbs' : 'js/libs/ng-breadcrumbs/dist/ng-breadcrumbs.min',
'bootstrap-datepicker': 'libs/bootstrap-datepicker/js/bootstrap-datepicker',
'ionsound' : 'libs/ionsound/js/ion.sound.min',
'jqvmap' : 'js/libs/jqvmap/jqvmap/jquery.vmap',
'jqvmapworld' : 'js/libs/jqvmap/jqvmap/maps/jquery.vmap.world',
'ngAnimate' : 'libs/angular-animate/angular-animate.min',
'ngAria' : 'libs/angular-aria/angular-aria.min',
'ngMaterial' : 'libs/angular-material/angular-material.min',
'ngSmoothScroll' : 'libs/ngSmoothScroll/angular-smooth-scroll.min',
'ammap3WorldHigh' : 'directives/reporting-display/worldEUHigh',
'ammap3' : 'libs/ammap3/ammap/ammap',
'ammap-theme' : 'libs/ammap3/ammap/themes/light',
'ammap-resp' : 'libs/ammap3/ammap/plugins/responsive/responsive',
'ammap-export' : 'libs/ammap3/ammap/plugins/export/export.min',
'ammap-ex-fabric' : 'libs/ammap3/ammap/plugins/export/libs/fabric.js/fabric.min',
'ammap-ex-filesaver' : 'libs/ammap3/ammap/plugins/export/libs/FileSaver.js/FileSaver.min',
'ammap-ex-pdfmake' : 'libs/ammap3/ammap/plugins/export/libs/pdfmake/pdfmake.min',
'ammap-ex-vfs-fonts' : 'libs/ammap3/ammap/plugins/export/libs/pdfmake/vfs_fonts',
'ammap-ex-jszip' : 'libs/ammap3/ammap/plugins/export/libs/jszip/jszip.min',
'ammap-ex-xlsx' : 'libs/ammap3/ammap/plugins/export/libs/xlsx/xlsx.min',
'amchart3' : 'libs/amcharts3/amcharts/amcharts',
'amchart3-serial' : 'libs/amcharts3/amcharts/serial',
'amchart3-pie' : 'libs/amcharts3/amcharts/pie',
'amchart3-theme-light': 'libs/amcharts3/amcharts/themes/light'
},
shim: {
'libs/angular/angular' : { deps: ['jquery'] },
'angular' : { deps: ['libs/angular/angular'] },
'ngRoute' : { deps: ['angular'] },
'ngSanitize' : { deps: ['angular'] },
'leaflet-directive' : { deps: ['angular', 'leaflet'], exports : 'L' },
'ng-breadcrumbs' : { deps: ['angular'] },
'bootstrap' : { deps: ['jquery'] },
'linqjs' : { deps: [], exports : 'Enumerable' },
'leaflet' : { deps: [], exports : 'L' },
'bootstrap-datepicker' : { deps: ['bootstrap'] },
'jqvmap' : { deps: ['jquery'] },
'jqvmapworld' : { deps: ['jqvmap'] },
'ionsound' : { deps: ['jquery'] },
'ngAnimate' : { deps: ['angular'] },
'ngAria' : { deps: ['angular'] },
'ngMaterial' : { deps: ['angular', 'ngAnimate', 'ngAria'] },
'ngSmoothScroll' : { deps: ['angular'] },
'ammap3WorldHigh' : { deps: ['ammap3'] },
'ammap-theme' : { deps: ['ammap3']},
'ammap-resp' : { deps: ['ammap3']},
'amchart3-serial' : { deps: ['amchart3']},
'amchart3-pie' : { deps: ['amchart3']},
'amchart3-theme-light' : { deps: ['amchart3']},
},
});
// BOOT
require(['angular', 'domReady!', 'bootstrap', 'app', 'routes', 'index'], function(ng, doc){
ng.bootstrap(doc, ['kmApp']);
ng.resumeBootstrap();
});
| JavaScript | 0 | @@ -4244,17 +4244,16 @@
// BOOT%0A
-%0A
require(
@@ -4338,44 +4338,276 @@
doc)
+
%7B%0A
-%0A ng.bootstrap(doc, %5B'kmApp'%5D);
+ //this is for spec tests with selenium as it starts angular first%0A // this tests if angualr has been bootstrapped and if it has it resumes%0A ng.bootstrap(doc, %5B'kmApp'%5D);%0A try %7B%0A $(document.body).attr(%22ng-app%22, %22kmApp%22); //jshint ignore:line%0A %7D catch (e) %7B
%0A
@@ -4629,13 +4629,16 @@
trap();%0A
+ %7D
%0A%7D);%0A
|
926e2bc7cffe4a81cfede2dd658c3f4fa78ed56e | fix config | config/configuration.js | config/configuration.js | /**
* @file Defines the hydrater settings.
*/
// nodeEnv can either be "development" or "production"
var nodeEnv = process.env.NODE_ENV || "development";
var defaultPort = 8000;
// Number of instance to run simultaneously per cluster
var defaultConcurrency = 1;
if(nodeEnv === "production") {
defaultPort = 80;
}
// Exports configuration
module.exports = {
env: nodeEnv,
port: process.env.PORT || defaultPort,
concurrency: process.env.MARKDOWN_CONCURRENCY || defaultConcurrency
};
| JavaScript | 0.000006 | @@ -486,12 +486,103 @@
currency
+,%0A appName: process.env.APP_NAME %7C%7C %22markdown-hydrater%22,%0A redisURL: process.env.REDIS_URL
%0A%7D;%0A
|
77ee486d078ceabefbc945d26ee565a14564e1c5 | Clean up boot.js | app/boot.js | app/boot.js | "use strict";
var config = require("../config/config"),
elasticsearch = require("elasticsearch"),
fs = require("fs"),
yaml = require('js-yaml');
var featured_path = "config/featured.yaml";
var featured = yaml.safeLoad(fs.readFileSync(featured_path));
module.exports = {
es: new elasticsearch.Client({
apiVersion: "1.7",
host: {
host: config.elasticsearch.host,
port: config.elasticsearch.port
},
// log: 'debug'
}),
featured: featured
};
| JavaScript | 0.000002 | @@ -156,115 +156,8 @@
);%0A%0A
-var featured_path = %22config/featured.yaml%22;%0Avar featured = yaml.safeLoad(fs.readFileSync(featured_path));%0A%0A
modu
@@ -351,32 +351,8 @@
%7D)
-,%0A%0A featured: featured%0A
%0A%7D;%0A
|
41c9e019da86359a757fcf1ab0349379ba755381 | Add onEnter check to dashboard route | imports/startup/client/routes.js | imports/startup/client/routes.js | import React from 'react';
import { render } from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { Meteor } from 'meteor/meteor';
import { App } from '../../ui/layouts/app';
import { Documents } from '../../ui/pages/documents';
import { Index } from '../../ui/pages/index';
import { NotFound } from '../../ui/pages/not-found';
// Auth
import { RecoverPassword } from '../../ui/pages/recover-password';
import { ResetPassword } from '../../ui/pages/reset-password';
import { Signup } from '../../ui/pages/signup';
// Timeline
import { Timeline } from '../../ui/pages/timeline';
// Dashboard
import { Dashboard } from '../../ui/pages/dashboard';
const requireAuth = (nextState, replace) => {
if (!Meteor.loggingIn() && !Meteor.userId()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname },
});
}
};
Meteor.startup(() => {
render(
<Router history={ browserHistory }>
<Route path="/">
<IndexRoute component={ Index } />
<Route component={ App }>
<Route name="recover-password" path="/recover-password" component={ RecoverPassword } />
<Route name="reset-password" path="/reset-password/:token" component={ ResetPassword } />
<Route name="signup" path="/signup" component={ Signup } />
<Route name="timeline" path="/timeline" component={ Timeline } />
<Route name="dashboard" path="/dashboard" component={ Dashboard } />
<Route path="*" component={ NotFound } />
</Route>
</Route>
</Router>,
document.getElementById('react-root')
);
});
| JavaScript | 0 | @@ -367,16 +367,66 @@
-found';
+%0Aimport %7B Bert %7D from 'meteor/themeteorchef:bert';
%0A%0A// Aut
@@ -870,13 +870,8 @@
: '/
-login
',%0A
@@ -937,16 +937,300 @@
%7D);%0A
+ if(nextState.location.pathname === %22/dashboard%22)%7B%0A Meteor.setTimeout(function()%7B%0A Bert.alert(%7B%0A title: 'Log in to access the dashboard!',%0A type: 'danger',%0A style: 'growl-top-right',%0A icon: 'fa-user'%0A %7D);%0A %7D, 1000)%0A %7D%0A
%7D%0A%7D;%0A%0A
@@ -1744,24 +1744,24 @@
meline %7D /%3E%0A
-
%3CR
@@ -1819,24 +1819,48 @@
Dashboard %7D
+ onEnter=%7B requireAuth %7D
/%3E%0A%0A
|
27005c3bf9a2e8170336229fff4a108b1526bd13 | update server | example/server.js | example/server.js | 'use strict';
var http = require('http');
var WebSocket = require('../lib/websocket');
const chalk = require('chalk')
var socketPool = {};
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(3000, function() {
console.log((new Date()) + ' Server is listening on port 3000');
});
var ws = new WebSocket({http: server});
ws
.on('open', function (socket) {
})
.on('text', function (msg, socket) {
msg = JSON.parse(msg);
switch(msg.type) {
case 'register':
register(socket, msg);
break;
case "message":
notifyAll(makeMessage({
id: msg.id,
text: msg.text
}));
break;
case 'userlist':
notifyAll(makeMessage({
type: 'userlist',
id: msg.id,
data: Object.keys(socketPool)
}));
break;
}
})
.on('close', function (socket) {
var index;
for (var key in socketPool) {
if (socketPool[key] === socket) {
index = key;
};
};
notifyAll(makeMessage({
id: index,
type: 'system',
text: index+ ' has left'
}));
})
function register (socket, msg) {
if (socketPool[msg.id]) {
notify(socket, makeMessage({
id: msg.id,
type: 'rejectusername',
}));
} else {
socketPool[msg.id] = {socket};
notify(socket, makeMessage({
id: msg.id,
type: 'register',
}));
notifyAll(makeMessage({
id: msg.id,
type: 'system',
text: msg.id + ' has joined'
}));
notifyAll(makeMessage({
type: 'userlist',
id: msg.id,
data: Object.keys(socketPool)
}));
}
}
function makeMessage (options) {
var sendingMsg = {
type: options.type || 'message',
text: options.text,
id: options.id,
date: Date.now(),
data: options.data
};
return JSON.stringify(sendingMsg);
}
function notifyAll (msg) {
notifyAllBut(msg);
}
function notifyAllBut (msg, people) {
people = people || [];
for (var id in socketPool) {
if (people.indexOf(id) === -1) {
notify(socketPool[id].socket, msg);
}
}
}
function notify(socket, msg) {
ws.sendFrame(socket, msg);
} | JavaScript | 0.000001 | @@ -329,19 +329,17 @@
.listen(
-300
+8
0, funct
@@ -496,20 +496,16 @@
cket) %7B%0A
-
%0A %7D)%0A
@@ -1082,16 +1082,23 @@
ool%5Bkey%5D
+.socket
=== soc
@@ -1227,16 +1227,17 @@
t: index
+
+ ' has
|
e5091302eef0a49633378f6ef1c370a22a01e7dd | optimize DataStore | src/stores/DataStore.js | src/stores/DataStore.js |
import { observable, computed, toJS } from 'mobx';
import { omit, isString, isNumber } from 'lodash';
import getAsk from 'utils/getAsk';
import showError from 'utils/showError';
import jsxToPlainObject from 'utils/jsxToPlainObject';
const caches = {};
let appConfig = {};
let authStore = {};
export default class DataStore {
static get(table) {
const schema = appConfig.tables[table].data;
// console.log('schema', schema);
if (caches.hasOwnProperty(table)) { return caches[table]; }
const store = new DataStore(table, jsxToPlainObject(schema));
caches[table] = store;
return store;
}
static setup(config, auth) {
appConfig = config;
authStore = auth;
}
@observable total = 0;
@observable isFetching = false;
@observable search = '?';
@observable selectedKeys = [];
@computed get collection() {
return this.collections.get(this.search);
}
@computed get dataSource() {
return toJS(this.collection);
}
@computed get selection() {
const { selectedKeys, collection, _uniqueKey } = this;
if (!collection) { return []; }
return this.collection.filter((item, index) =>
selectedKeys.includes(_uniqueKey ? item[_uniqueKey] : index)
);
}
collections = observable.map();
size = appConfig.api.count;
_prevQuery = {};
_pervSearch = '?';
constructor(table, schema) {
this._table = table;
this._schema = schema;
this.columns = schema
.filter(({ shouldHideInTable }) => !shouldHideInTable)
.map(({ render, ...props }) => ({
title: props.label,
key: props.name,
dataIndex: props.name,
render: render ? (...args) => render(...args, props) : undefined,
}))
;
const unique = schema.find((s) => s.unique);
this._uniqueKey = unique && unique.name;
this._ask = getAsk(appConfig).clone({
url: table,
[appConfig.api.accessTokenLocation]: {
[appConfig.api.accessTokenName]({ remove }) {
const token = authStore.getAccessToken();
if (!token) { remove(); }
else { return token; }
},
}
});
}
async fetch(query = this._prevQuery, search = this._prevSearch) {
this._prevQuery = query;
this._prevSearch = search;
const page = (function () {
const p = query.page || 1;
return p < 1 ? 1 : p;
}());
query = {
count: this.size,
...omit(query, ['action']),
page,
};
if (this.collections.has(search)) {
this.search = search;
return this;
}
this.isFetching = true;
try {
const { total, list = [] } = await this._ask.fork({ query });
const collection = list.map((data, index) => {
data.key = this._uniqueKey ? data[this._uniqueKey] : index;
return data;
});
this.search = search;
this.total = total;
this.collections.set(search, collection);
}
catch (err) {
showError('请求失败:', err.message);
}
this.isFetching = false;
return this;
}
_sync() {
this.collections.clear();
this.fetch();
}
setSelectedKeys(selectedKeys) {
this.selectedKeys = selectedKeys;
}
findItemByKey(key) {
const { collection, _uniqueKey } = this;
if (!collection) { return []; }
return collection.find((item, index) =>
key === (_uniqueKey ? item[_uniqueKey] : index)
);
}
async create(body) {
try {
await this._ask.fork({
method: 'POST',
body,
});
this._sync();
}
catch (err) {
showError('创建失败:', err.message);
}
}
async update(body, keys) {
try {
await this._ask.fork({
url: keys,
method: 'PUT',
body,
});
this._sync();
}
catch (err) {
showError('修改失败:', err.message);
}
}
async remove(keys) {
try {
if (isNumber(keys) || isString(keys)) { keys = [keys]; }
if (!Array.isArray(keys)) { keys = this.selectedKeys; }
if (!keys.length) { return; }
await this._ask.fork({
url: keys.join(','),
method: 'DELETE',
});
this._sync();
this.selectedKeys = [];
}
catch (err) {
showError('删除失败:', err.message);
}
}
}
| JavaScript | 0.000477 | @@ -938,250 +938,8 @@
%09%7D%0A%0A
-%09@computed get selection() %7B%0A%09%09const %7B selectedKeys, collection, _uniqueKey %7D = this;%0A%09%09if (!collection) %7B return %5B%5D; %7D%0A%09%09return this.collection.filter((item, index) =%3E%0A%09%09%09selectedKeys.includes(_uniqueKey ? item%5B_uniqueKey%5D : index)%0A%09%09);%0A%09%7D%0A%0A
%09col
|
3c18e97198bb642a0514bac5143894fcf599a59f | Make all cells viewable | public/js/main.js | public/js/main.js | /* eslint-env browser, jquery */
/* global io */
const api = (method, endpoint, params = {}) => {
const url = `/api${endpoint}`;
if (method === 'GET') {
return fetch(`${url}?${$.param(params)}`, {
method: 'GET',
credentials: 'include',
}).then(res => res.json());
} else if (method === 'POST') {
const csrfToken = $('meta[name=csrf-token]').attr('content');
const form = new FormData();
Object.keys(params).forEach((param) => {
const value = params[param];
if (value instanceof HTMLInputElement) {
form.append(param, value.files[0]);
} else {
form.append(param, value);
}
});
form.append('_csrf', csrfToken);
return fetch(url, {
method: 'POST',
body: form,
credentials: 'include',
}).then(res => res.json());
}
return Promise.reject();
};
let languageData = [];
const updateLanguages = () => {
api.get('/languages').then((languages) => {
languageData = languages;
let red = 0;
let blue = 0;
$('.language').each((index, languageEl) => {
const $language = $(languageEl);
const language = languageData[parseInt($language.data('index'), 10)];
$language.find('.name').text('');
$language.find('.size').text('');
$language.attr('data-toggle', 'modal');
$language.removeClass('red blue white gray black');
if (language) {
if (language.type === 'unknown') {
$language.addClass('black');
} else if (language.type === 'language') {
$language.find('.name').text(language.name);
if (language.solved) {
$language.find('.size').text(language.solution.size);
}
if (typeof language.team === 'number') {
$language.addClass(language.team === 0 ? 'red' : 'blue');
} else {
$language.addClass(language.available ? 'white' : 'gray');
}
} else if (language.type === 'base') {
if (typeof language.team === 'number') {
$language.addClass(language.team === 0 ? 'red' : 'blue');
}
}
if (language.team === 0) {
red++;
} else if (language.team === 1) {
blue++;
}
}
});
$('.team-info.red > .score').text(red);
$('.team-info.red > .bar').css({ flexBasis: `${red / (red + blue) * 100}%` });
$('.team-info.blue > .score').text(blue);
$('.team-info.blue > .bar').css({ flexBasis: `${blue / (red + blue) * 100}%` });
});
};
api.get = api.bind(null, 'GET');
api.post = api.bind(null, 'POST');
$(document).ready(() => {
if (location.pathname !== '/') {
return;
}
const $modal = $('#language-modal');
let pendingSubmission = {};
$('.language').each((index, language) => {
const $language = $(language);
$language.click(() => {
const language = languageData[parseInt($language.data('index'), 10)];
if (!language.slug || !language.available) {
return true;
}
// Set title
$modal.find('.modal-title').text(language.name);
$modal.find('.code').val('').attr('readonly', true);
$modal.find('.submit-code').attr('disabled', true);
$modal.find('.result').removeClass('bg-warning bg-success').hide();
$modal.data('language', language.slug);
if (language.solved) {
const solutionURL = `${location.origin}/submissions/${language.solution._id}`;
$modal.find('.owner-name').text(`${language.solution.user} (${language.team === 0 ? 'Red' : 'Blue'})`);
$modal.find('.solution').text(language.solution._id).attr('href', solutionURL);
$modal.find('.solution-bytes').text(language.solution.size);
} else {
$modal.find('.owner-name').text('Not Solved');
$modal.find('.solution').text('N/A').attr('href', '');
$modal.find('.solution-bytes').text('N/A');
}
if (language.available) {
$modal.find('.code').attr('readonly', false);
$modal.find('.submit-code').attr('disabled', false);
}
return true;
});
});
$modal.find('.submit-code').click(() => {
const language = $modal.data('language');
$modal.find('.code').attr('readonly', true);
$modal.find('.submit-code').attr('disabled', true);
$modal.find('.result').removeClass('bg-warning bg-success').hide();
const params = { language };
const $file = $modal.find('.file');
if ($file.get(0).files.length === 1) {
params.file = $file.get(0);
} else {
params.code = $modal.find('.code').val();
}
api.post('/submission', params).then((submission) => {
if (submission.error) {
$modal.find('.result').addClass('bg-warning').text(submission.error).show();
$modal.find('.code').attr('readonly', true);
$modal.find('.submit-code').attr('disabled', false);
} else {
pendingSubmission = submission;
}
});
});
updateLanguages();
const socket = io.connect(window.location.href);
socket.on('update-submission', (data) => {
if (data._id === pendingSubmission._id) {
pendingSubmission = {};
const getSubmission = () => {
api.get('/submission', { _id: data._id }).then((submission) => {
// TODO: XSS
if (submission.status === 'failed') {
$modal.find('.result').addClass('bg-warning')
.html(`<strong>Submission failed.</strong> Check out the detail <a href="${location.origin}/submissions/${submission._id}" target="_blank">here</a>.`)
.show();
$modal.find('.submit-code').attr('disabled', false);
} else if (submission.status === 'success') {
$modal.find('.result').addClass('bg-success')
.html(`<strong>You won the language!</strong> Check out the detail <a href="${location.origin}/submissions/${submission._id}" target="_blank">here</a>.`)
.show();
} else if (submission.status === 'pending') {
setTimeout(getSubmission, 1000);
}
});
};
getSubmission();
}
});
socket.on('update-languages', () => {
updateLanguages();
});
});
| JavaScript | 0.000018 | @@ -2951,31 +2951,8 @@
slug
- %7C%7C !language.available
) %7B%0A
|
58c51a54adc171de13a6a8d0dbbb301425cb8b70 | split long string | public/js/main.js | public/js/main.js | $(document).ready(function(){
item = 0
$.getJSON("/list", function(data) {
items = data
$('#pair').removeAttr("disabled")
$('#rand').removeAttr("disabled")
$('.button_start').removeAttr("disabled")
})
// checkbox menu
$('#checkbox_menu_button_go').on('click', function () {
$(this).button('toggle');
});
$('#checkbox_menu_button_random ').on('click', function () {
$(this).button('toggle')
});
$('#checkbox_menu_button_category ').on('click', function () {
$(this).button('toggle')
});
$(".container_words").fadeIn([2000, ]);
$(".block_img").fadeIn([5000, ]);
$(".block_img").fadeOut([5000, ]);
})
$('#button_next').on('click', function(){
$('.button_start').addClass('hidden')
if ( $("#checkbox_menu_button_random").prop("checked") ) {
var randoms = Math.floor((Math.random() * items.length) + 1)
ShowAndSpeak(randoms) } else if ( $("#checkbox_menu_button_go").prop("checked") ) {
ShowAndSpeak(item++)
}else {
ShowAndSpeak(item++)
}
})
$('.button_start').on('click', function(){
ShowAndSpeak(item++)
$('#button_next').removeClass('hidden')
$('#button_next').show()
$('.button_start').addClass('hidden')
})
$('#pair').on('click', function(){
ShowAndSpeak(item++)
$('.button_start').addClass('hidden')
$('#button_next').removeClass('hidden')
$('#listWords').empty()
$('#button_next').show()
})
$('#rand').on('click', function(){
$('.button_start').addClass('hidden')
$('#button_next').removeClass('hidden')
$('#button_next').show()
var rand = Math.floor((Math.random() * items.length) + 1)
ShowAndSpeak(rand)
$('#listWords').empty()
})
$('#show-list').on('click', function(){
$('.button_start').addClass('hidden')
$('.container_words').empty()
$('#button_next').hide()
$.ajax({
url: "/listByCategory",
success: function(data) {
$('#listWords').empty()
$('#listWords').append(data)
}
})
})
$('#myModal').on('show.bs.modal', function (event) {
var modal = $(this)
$.ajax({
url: "/form",
success: function(data) {
modal.empty()
modal.append(data)
categories = []
$.getJSON("/categories")
.done(function(data) {
categories = data
$('#form_category').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'categories',
displayKey: 'value',
source: substringMatcher(categories)
})
})
}
})
})
$('#mySettings').on('show.bs.modal', function (event) {
var modal = $(this)
$.ajax({
url: "/settings",
success: function(data) {
modal.empty()
modal.append(data)
}
})
})
$(document).on('click', '.word', function(){
speak($(this).text())
return false
})
function speak(text) {
text = $.trim(text)
if (text == '') return false
var msg = new SpeechSynthesisUtterance()
msg.text = text
msg.volume = localStorage["volume"]
msg.rate = localStorage["rate"]
msg.lang = localStorage["lang"]
window.speechSynthesis.speak(msg)
}
function ShowAndSpeak(i) {
$('#show-pair').empty()
$('#show-pair').html('<p class="block_img"><img src="'+items[i].image+'" alt="'+items[i].russian + '"></p> <p class="word words_eng">'+items[i].english+'</p> <p class="words_rus"> '+items[i].russian + '</p> <p class="words_transcription"> '+items[i].transcription + '</p>')
speak(items[i].english)
}
function substringMatcher(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;
matches = [];
substrRegex = new RegExp(q, 'i');
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push({ value: str });
}
});
cb(matches);
}
}
| JavaScript | 0.999999 | @@ -3572,16 +3572,22 @@
ck_img%22%3E
+%5C%0A
%3Cimg src
@@ -3640,13 +3640,20 @@
+ '%22
+
%3E%3C/p%3E
+ %5C%0A
%3Cp
@@ -3695,24 +3695,30 @@
nglish+'%3C/p%3E
+ %5C%0A
%3Cp class=%22w
@@ -3755,17 +3755,26 @@
+ '%3C/p%3E
-%3C
+%5C%0A %3C!--
p class=
@@ -3827,16 +3827,19 @@
n + '%3C/p
+ --
%3E')%0A
|
f3651fbe2ab406197bc878c16357f78c9ec9138a | Check for path_translate and script_Filename | lib/requestHandler.js | lib/requestHandler.js | include('Jst.js');
include('session.js');
/**
* Concatenates the values of a variable into an easily readable string
* by Matt Hackett [scriptnode.com]
* @param {Object} x The variable to debug
* @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
* @param {String} sep The separator to use between [default: a single space ' ']
* @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
*/
function print_r(x, max, sep, l) {
l = l || 0;
max = max || 10;
sep = sep || ' ';
if (l > max) {
return "[WARNING: Too much recursion]\n";
}
var
i,
r = '',
t = typeof x,
tab = '';
// r += t + '\n';
if (x === null) {
r += "(null)\n";
} else if (t === 'function') {
r += '(function)\n';
x = 'function';
} else if (t === 'object') {
l++;
for (i = 0; i < l; i++) {
tab += sep;
}
if (x && x.length) {
t = 'array';
}
r += '(' + t + ") :\n";
for (i in x) {
if (i === 'class') continue;
try {
r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
} catch(e) {
return "[ERROR: " + e + "]\n";
}
}
} else {
if (t == 'string') {
if (x == '') {
x = '(empty)';
}
}
r += '(' + t + ') ' + x + "\n";
}
return r;
};
// Attempt to read in application's configuration
try {
include('./AppConfig.js');
}
catch (e) {
// do nothing
}
ob_end_clean = function() {
outputBuffers = [[]];
outputBufferIndex = 0;
};
ob_end_flush = function() {
while (outputBuffers.length) {
response.write(outputBuffers.pop().join(''));
}
ob_end_clean();
};
ob_get_contents = function() {
return outputBuffers[outputBufferIndex];
};
ob_end_clean();
onexit(ob_end_flush);
// mimicks console object in firefox/firebug.
// useful for server-side script debugging.
// output is written to a file, specified in AppConfig class.
// typically, I'd tail -f on the output file to see the messages as they occur
console = {
log: function(s) {
if (AppConfig.consoleFile) {
var f = new File(AppConfig.consoleFile);
if (f.open('a')) {
f.write(s + '\n');
f.close();
}
}
},
dir: function(o) {
console.log(print_r(o));
}
};
function print(s) {
for (var i=0,len=arguments.length; i<len; i++) {
outputBuffers[outputBufferIndex].push(arguments[i]);
// response.write(arguments[i]);
}
}
println = function(s) {
print(s + '\n');
};
printbr = function(s) {
print(s + '<br/>\n');
};
// Handy helper to dump (php var_dump style) an object to the
// web page for debugging.
dump = function(obj, name) {
if (name) {
print('<h1>'+name+'</h1>');
}
print('<pre>'+print_r(obj)+'</pre>');
};
errorHandler = function(e) {
response.status(500);
println("<h1>500 Error</h1>");
if (e.stack) {
println('<h2>Stack Trace</h2>');
var stack = e.stack.split('\n');
// println('<h2>' + stack[0] + '</h2>');
for (var i=0; i<stack.length; i++) {
print(' ' + stack[i] + '<br/>');
}
}
else {
printbr(e);
}
println('<hr>');
println("<h2>Dump of Exception Object:</h2>");
dump(e);
println("<h2>Server Environment:</h2>");
dump(system.env);
// system.exit();
};
file_get_contents = function(fn) {
var f = new File(fn);
f.open('r');
var contents = f.read();
f.close();
return contents;
};
readFile = function(fn) {
println(file_get_contents(fn));
};
try {
// (function() {
// try {
if (system.env.SCRIPT_FILENAME.match(/\.jst$/)) {
var tpl = file_get_contents(system.env.SCRIPT_FILENAME);
var parsed = Jst.parse(tpl);
println(Jst.executeParsed(parsed, { }));
}
else {
try {
include(system.env.SCRIPT_FILENAME);
}
catch (e) {
throw new Error(e);
}
}
//}
//catch (e) {
// throw new Error(e);
//}
//})();
// dump(Session);
}
catch (e) {
ob_end_clean();
errorHandler(e);
}
| JavaScript | 0.000003 | @@ -3469,20 +3469,58 @@
ry %7B%0A%09%09%09
-if (
+var script = system.env.PATH_TRANSLATE %7C%7C
system.e
@@ -3537,16 +3537,31 @@
FILENAME
+;%0A%09%09%09if (script
.match(/
@@ -3609,33 +3609,13 @@
ts(s
-ystem.env.SCRIPT_FILENAME
+cript
);%0A%09
@@ -3734,33 +3734,13 @@
de(s
-ystem.env.SCRIPT_FILENAME
+cript
);%0A%09
|
692aa1ca5d46206e7e8e360412b545f593e4d355 | Fix websocket URL from localhost to the real one | web/client/scripts/controllers/LoginCtrl.js | web/client/scripts/controllers/LoginCtrl.js | 'use strict';
angular.module('app').controller('LoginCtrl', function($scope, $uibModal, mafenSession, alertify, PATHS) {
'ngInject';
$scope.mafenSession = mafenSession;
$scope.user = {};
$scope.login = function() {
$scope.mafenSession.reset();
$scope.mafenSession.connect('ws://127.0.0.1:8000');
$scope.loginPromise = $scope.mafenSession.login($scope.user.username, $scope.user.password);
$scope.loginPromise.then(function() {
$uibModal.open({
ariaLabelledBy: 'charlist-modal-title',
ariaDescribedBy: 'charlist-modal-body',
templateUrl: PATHS.views + 'charlist.html',
controller: 'CharListCtrl'
});
}, function() {
alertify.error('Authentication failed');
});
};
});
| JavaScript | 0.00003 | @@ -295,17 +295,18 @@
s://
-127.0.0.1
+mafen.club
:800
|
f0a00f82522a991973dcd3f784162a8cba213f31 | remove title tag, as alt is what we want | public/js/main.js | public/js/main.js | /* global fetch, localStorage */
const form = document.getElementById('form')
const region = document.getElementById('region')
const summonerName = document.getElementById('summonerName')
const result = document.getElementById('result')
const savedName = localStorage.getItem('summonerName')
if (savedName) summonerName.value = savedName
const savedRegion = localStorage.getItem('region')
if (savedRegion) region.value = savedRegion
const sortChampions = (champions) => {
return champions.sort((championA, championB) => {
if (championA.name < championB.name) return -1
if (championA.name > championB.name) return 1
return 0
})
}
const checkStatus = (response) => {
if (response.status >= 200 && response.status < 300) {
return response
} else {
const error = new Error(response.statusText)
error.response = response
throw error
}
}
const spriteStyleForChampion = (champion, version) => {
const spriteUrl = `//ddragon.leagueoflegends.com/cdn/${version}/img/sprite/${champion.image.sprite}`
return `background: url(${spriteUrl}) -${champion.image.x}px -${champion.image.y}px`
}
form.addEventListener('submit', (event) => {
event.preventDefault()
if (region.value.length === 0 || summonerName.value.length === 0) {
result.innerHTML = 'Please enter both summonerName and region'
return
}
// spinner ¯\_(ツ)_/¯
result.innerHTML = '<marquee width=200>Loading</marquee>'
localStorage.setItem('summonerName', summonerName.value)
localStorage.setItem('region', region.value)
fetch(`/api/summoner?region=${region.value}&name=${summonerName.value}`)
.then(checkStatus)
.then(response => response.json())
.then((data) => {
const champions = sortChampions(data.champions)
const version = data.version
const list = champions.map((champion) => {
const className = champion.chestGranted ? 'chest-granted' : 'no-chest-granted'
return `
<li class="${className}">
<img
class="champion-sprite"
src="/img/spacer.gif"
style="${spriteStyleForChampion(champion, version)}"
alt="${champion.name} chest granted: ${champion.chestGranted ? 'Yes' : 'No'}"
title="${champion.name} chest granted: ${champion.chestGranted ? 'Yes' : 'No'}"
/>
${champion.name}
</li>
`
})
result.innerHTML = `<ul>${list.join('\n')}</ul>`
})
.catch((error) => {
result.innerHTML = 'Sorry, something went wrong :/ Check console output.'
console.error(error)
})
})
| JavaScript | 0 | @@ -2224,102 +2224,8 @@
'%7D%22%0A
- title=%22$%7Bchampion.name%7D chest granted: $%7Bchampion.chestGranted ? 'Yes' : 'No'%7D%22%0A
|
9a1de834165cf5c41922c49db54547328919ba63 | fix updater ? | app/main.js | app/main.js | const isDev = require('electron-is-dev');
const {autoUpdater} = require("electron-updater");
const log = require('electron-log');
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
log.info('App starting...');
const electron = require('electron');
const app = electron.app;
const ipc = electron.ipcMain;
let mainWindow;
// Adds debug features like hotkeys for triggering dev tools and reload
const Window = require('./class/Window').Window;
const File = require('./class/File').File;
const Tools = require('./class/Tools').Tools;
// Prevent window being garbage collected
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (!mainWindow) {
mainWindow = Window.create(800,750);
}
});
app.on('ready', () => {
if (!isDev) {
autoUpdater.checkForUpdates();
}
console.log('The application is ready.');
mainWindow = Window.create(800,800);
});
ipc.on('open-file', function (event) {
let file = File.open();
if (file != null)
{
event.sender.send('file-opened', {file: file.file, content: file.content,window: mainWindow});
}
console.log(event);
});
function sendStatusToWindow(text) {
log.info(text);
mainWindow.window.webContents.send('message', text);
}
autoUpdater.on('checking-for-update', () => {
sendStatusToWindow('Checking for update...');
})
autoUpdater.on('update-available', (info) => {
sendStatusToWindow('Update available.');
mainWindow.window.webContents.send('update-available');
})
autoUpdater.on('update-not-available', (info) => {
sendStatusToWindow('Update not available.');
})
autoUpdater.on('error', (err) => {
sendStatusToWindow('Error in auto-updater.'+err);
})
autoUpdater.on('download-progress', (progressObj) => {
sendStatusToWindow(Math.round(progressObj.percent)+'%');
mainWindow.window.webContents.send('download-progress', {
'bytesPerSecond': Tools.FileConvertSize(progressObj.bytesPerSecond),
'percentValue' : Math.round(progressObj.percent),
'percent' : Math.round(progressObj.percent)+'%',
'transferred' : Tools.FileConvertSize(progressObj.transferred),
'total' : Tools.FileConvertSize(progressObj.total)
});
})
autoUpdater.on('update-downloaded', (info) => {
setTimeout(function() {
autoUpdater.quitAndInstall();
}, 1000)
});
| JavaScript | 0 | @@ -841,71 +841,8 @@
%3E %7B%0A
- if (!isDev) %7B%0A autoUpdater.checkForUpdates();%0A %7D%0A
@@ -923,16 +923,79 @@
00,800);
+%0A if (!isDev) %7B%0A autoUpdater.checkForUpdates();%0A %7D
%0A%0A%7D);%0A%0Ai
|
e68b13c44366f066f7d175a30faa658dcb4e64d1 | remove unused import | src/playbacks/html5_audio/html5_audio.js | src/playbacks/html5_audio/html5_audio.js | // Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
import Playback from 'base/playback'
import Events from 'base/events'
import find from 'lodash.find'
import HTML5Video from 'playbacks/html5_video'
export default class HTML5Audio extends HTML5Video {
get name() { return 'html5_audio' }
get tagName() { return 'audio' }
durationChange() {
this.settings.left = ["playpause", "position", "duration"]
this.settings.seekEnabled = this.isSeekEnabled()
this.trigger(Events.PLAYBACK_SETTINGSUPDATE)
}
getPlaybackType() {
return 'aod'
}
stalled() {
if (this.el.readyState < this.el.HAVE_FUTURE_DATA) {
this.trigger(Events.PLAYBACK_BUFFERING, this.name)
}
}
timeUpdated() {
this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name)
}
}
HTML5Audio.canPlay = function(resource, mimeType) {
var mimetypes = {
'wav': ['audio/wav'],
'mp3': ['audio/mp3', 'audio/mpeg;codecs="mp3"'],
'aac': ['audio/mp4;codecs="mp4a.40.5"'],
'oga': ['audio/ogg']
}
var resourceParts = resource.split('?')[0].match(/.*\.(.*)$/) || []
if ((resourceParts.length > 1) && (mimetypes[resourceParts[1]] !== undefined)) {
var a = document.createElement('audio')
return !!find(mimetypes[resourceParts[1]], (ext) => { return !!a.canPlayType(ext).replace(/no/, '') })
} else if (mimeType && !/m3u8/.test(resourceParts[1])) {
var a = document.createElement('audio')
return !!a.canPlayType(mimeType).replace(/no/, '')
}
return false
}
| JavaScript | 0.000006 | @@ -167,45 +167,8 @@
e.%0A%0A
-import Playback from 'base/playback'%0A
impo
|
c972e32e75904bc830ffb978694583b82bea0eb1 | fix for CharField rdata | lib/resourcerecord.js | lib/resourcerecord.js | /*
Copyright 2011 Timothy J Fontaine <tjfontaine@gmail.com>
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
*/
"use strict";
require('bufferjs/concat');
var util = require('util'),
Message = require('./message'),
fields = require('./fields'),
name = require('./name');
var ResourceRecord = function (vals) {
this._fields = [
fields.Label('name'),
fields.Struct('type', 'H'),
fields.Struct('class', 'H'),
fields.Struct('ttl', 'I'),
fields.BufferField('rdata', 'H'),
];
Message.call(this);
this.class = 1;
this.initialize(vals);
};
util.inherits(ResourceRecord, Message);
ResourceRecord.prototype.initialize = function (vals) {
var k;
if (vals) {
for (k in vals) {
if (vals.hasOwnProperty(k)) {
this[k] = vals[k];
}
}
}
};
ResourceRecord.prototype.pack = function () {
this.rdata = this.packFields(this._rdata_fields);
var ret = Message.prototype.pack.call(this);
return ret;
};
ResourceRecord.prototype.unpackRData = function () {
this.unpackFields(this._rdata_fields,
this.raw_,
this._fields[4].position);
};
module.exports = ResourceRecord;
| JavaScript | 0 | @@ -1799,24 +1799,206 @@
nction () %7B%0A
+ /* XXX%0A * this presumes that the accessor takes care of packing%0A * could have interesting side effects if you're trying to%0A * reuse full packets%0A */%0A if (!this.rdata) %7B%0A
this.rdata
@@ -2037,16 +2037,20 @@
ields);%0A
+ %7D%0A
var re
|
faf30c9b3843610993a1400cdf6a3fa3111dd05e | Fix address not showing | src/frontend/components/survey-renderers/BSDPhonebankRSVPSurvey.js | src/frontend/components/survey-renderers/BSDPhonebankRSVPSurvey.js | import React from 'react';
import Relay from 'react-relay'
import BSDSurvey from './BSDSurvey'
import {BernieColors, BernieText} from '../styles/bernie-css'
import {GoogleMapLoader, GoogleMap, Marker} from 'react-google-maps';
import {FlatButton, Paper} from 'material-ui';
import moment from 'moment';
class BSDPhonebankRSVPSurvey extends React.Component {
static propTypes = {
onSubmitted : React.PropTypes.func,
initialValues: React.PropTypes.object,
survey: React.PropTypes.object
}
submit() {
this.refs.survey.refs.component.submit()
}
state = {
clickedMarker: null
}
handleMarkerClick(marker) {
this.setState({clickedMarker: marker})
}
renderMarkerDescription(marker) {
if (!marker)
return <div></div>;
if (marker.key === 'home')
return <div></div>
let button = <div></div>;
if (marker.key !== 'home')
button = (
<FlatButton label='Select' style={{
...BernieText.inputLabel,
backgroundColor: BernieColors.red,
marginTop: 10,
}}
onTouchTap={(event) => {
this.refs.survey.refs.component.setFieldValue('event_id', marker.eventId)
}}
/>
)
return (
<Paper zDepth={0} style={{
marginTop: 10,
padding: '10px 10px 10px 10px',
border: 'solid 1px ' + BernieColors.lightGray
}}>
<div style={{
...BernieText.secondaryTitle,
color: BernieColors.gray,
fontSize: '1.0em'
}}>
{moment(marker.startDate).format('h:mm A MMM D')}
</div>
<div style={{
...BernieText.default,
fontWeight: 600,
fontSize: '1.0em'
}}>
{marker.name}
</div>
<div style={{
...BernieText.default,
fontSize: '1.0em'
}}>
<div>{marker.venueName}</div>
<div>{marker.addr1}</div>
<div>{marker.addr2}</div>
<div>Capacity: {marker.capacity}</div>
<div>Attendees: {marker.attendeesCount}</div>
{button}
</div>
</Paper>
)
}
getEventAddr2(event) {
let desc = ''
if (event.venueAddr2)
desc = desc + ' ' + event.venueAddr2;
if (event.venueCity)
desc = desc + ' ' + event.venueCity;
if (event.venueState)
desc = desc + ', ' + event.venueState
return desc.trim();
}
renderMap() {
let center = {
lat: this.props.interviewee.address.latitude,
lng: this.props.interviewee.address.longitude
}
let markers = [
// {
// position: center,
// key: 'home',
// title: 'home',
// name: 'Interviewee home'
// }
];
this.props.interviewee.nearbyEvents.forEach((event) => {
markers.push({
position: {
lat: event.latitude,
lng: event.longitude
},
key: event.id,
title: event.name,
name: event.name,
startDate: event.startDate,
venueName: event.venueName,
addr1: event.addr1,
addr2: this.getEventAddr2(event),
eventId: event.eventIdObfuscated,
capacity: event.capacity,
attendeesCount: event.attendeesCount
})
})
return (
<div style={{height: '100%', width: '100%'}}>
<GoogleMapLoader
containerElement={
<div
style={{
height: '100%',
width: '100%'
}}
/>
}
googleMapElement={
<GoogleMap
ref='map'
defaultZoom={9}
defaultCenter={center}>
{markers.map((marker, index) => {
return (
<Marker
{...marker}
onClick={this.handleMarkerClick.bind(this, marker)}
/>
);
})}
</GoogleMap>
}
/>
</div>
)
}
render() {
return (
<div>
<div style={{width: '100%', height: 200}}>
{this.renderMap()}
</div>
{this.renderMarkerDescription(this.state.clickedMarker)}
<BSDSurvey
ref='survey'
survey={this.props.survey}
interviewee={this.props.interviewee}
onSubmitted={this.props.onSubmitted}
/>
</div>
)
}
}
export default Relay.createContainer(BSDPhonebankRSVPSurvey, {
initialVariables: {
type: 'phonebank'
},
fragments: {
survey: () => Relay.QL`
fragment on Survey {
${BSDSurvey.getFragment('survey')}
}
`,
interviewee: () => Relay.QL`
fragment on Person {
${BSDSurvey.getFragment('interviewee')}
email
address {
latitude
longitude
}
nearbyEvents(within:20, type:$type) {
id
eventIdObfuscated
name
startDate
venueName
venueAddr1
venueAddr2
venueCity
venueState
description
latitude
longitude
capacity
attendeesCount
}
}
`
}
})
| JavaScript | 0.000001 | @@ -3055,17 +3055,22 @@
: event.
-a
+venueA
ddr1,%0A
|
cff4aa66a50c1db8058a00aa7734e35393c6cc2b | call the api to push updates when user clicks something | web/static/js/components/coder_estimates.js | web/static/js/components/coder_estimates.js | import React from "react"
import CoderEstimateHidden from "./coder_estimate_hidden"
import CoderEstimateCompleted from "./coder_estimate_completed"
import CoderEstimatePending from "./coder_estimate_pending"
let CoderEstimates = React.createClass({
propTypes: {
ticketId: React.PropTypes.string
},
getInitialState() {
return {
url: "",
pointOptions: [],
estimates: {}
}
},
componentDidMount: function() {
let url = `/api/tickets/${this.props.ticketId}`
$.ajax({
url: url,
dataType: 'json',
success: (response) => {
var data = response.data
console.log('ajax response', response.data);
this.setState({
url: data.url,
pointOptions: data.point_options,
estimates: data.estimates
})
}
})
},
render() {
let estimateComplete = this.isEstimateComplete(this.state.estimates)
let estimateRows = Object.keys(this.state.estimates).sort().map((key) => {
return this.estimateRow(estimateComplete, key, this.state.estimates[key])
})
// TODO: remove the hr
return(
<div className="estimates">
{estimateRows}
<hr />
</div>
)
},
updateEstimate(coder, points) {
var clone = this.cloneEstimates()
clone[coder] = points
// TODO: push to server
this.setState({ estimates: clone })
},
cloneEstimates() {
var clone = {}
Object.keys(this.state.estimates).map((key) => {
clone[key] = this.state.estimates[key]
})
return clone
},
isEstimateComplete(estimates) {
return Object.values(estimates).indexOf(0) === -1
},
estimateRow(estimateComplete, coder, points) {
var rtn
if (points === 0) {
rtn = <CoderEstimatePending key={coder}
coder={coder}
pointOptions={this.state.pointOptions}
onEstimate={this.updateEstimate}
/>
} else {
rtn = (estimateComplete)
? <CoderEstimateCompleted key={coder}
coder={coder}
points={points}
onClick={this.updateEstimate}
/>
: <CoderEstimateHidden key={coder}
coder={coder}
onClick={this.updateEstimate}
/>
}
return rtn
}
})
module.exports = CoderEstimates
| JavaScript | 0 | @@ -452,414 +452,38 @@
ount
-: function() %7B%0A let url = %60/api/tickets/$%7Bthis.props.ticketId%7D%60%0A%0A $.ajax(%7B%0A url: url,%0A dataType: 'json',%0A success: (response) =%3E %7B%0A var data = response.data%0A console.log('ajax response', response.data);%0A this.setState(%7B%0A url: data.url,%0A pointOptions: data.point_options,%0A estimates: data.estimates%0A %7D)%0A %7D%0A %7D
+() %7B%0A this.fetchServerData(
)%0A
@@ -880,349 +880,8 @@
%7D,%0A%0A
- updateEstimate(coder, points) %7B%0A var clone = this.cloneEstimates()%0A clone%5Bcoder%5D = points%0A // TODO: push to server%0A this.setState(%7B estimates: clone %7D)%0A %7D,%0A%0A cloneEstimates() %7B%0A var clone = %7B%7D%0A Object.keys(this.state.estimates).map((key) =%3E %7B%0A clone%5Bkey%5D = this.state.estimates%5Bkey%5D%0A %7D)%0A return clone%0A %7D,%0A%0A%0A
is
@@ -970,16 +970,17 @@
1%0A %7D,%0A%0A
+%0A
estima
@@ -1291,28 +1291,16 @@
stimate%7D
-%0A
/%3E%0A%0A
@@ -1309,16 +1309,17 @@
else %7B%0A
+%0A
rt
@@ -1568,27 +1568,12 @@
ate%7D
-%0A
/%3E%0A
-%0A
@@ -1728,30 +1728,16 @@
stimate%7D
-%0A
/%3E%0A
@@ -1754,20 +1754,1136 @@
urn rtn%0A
+ %7D,%0A%0A%0A updateEstimate(coder, points) %7B%0A var estimates = this.cloneEstimates(this.state.estimates)%0A estimates%5Bcoder%5D = points%0A%0A var data = %7B%0A ticket: %7B%0A estimates: estimates%0A %7D%0A %7D%0A%0A this.pushDataToServer(data)%0A %7D,%0A%0A convertJsonData(data) %7B%0A return %7B%0A url: data.url,%0A pointOptions: data.point_options.map((i) =%3E %7B return parseInt(i) %7D),%0A estimates: this.cloneEstimates(data.estimates)%0A %7D%0A %7D,%0A%0A cloneEstimates(estimates) %7B%0A var clone = %7B%7D%0A Object.keys(estimates).map((key) =%3E %7B%0A clone%5Bkey%5D = parseInt(estimates%5Bkey%5D)%0A %7D)%0A return clone%0A %7D,%0A%0A dataUrl() %7B%0A return %60/api/tickets/$%7Bthis.props.ticketId%7D%60%0A %7D,%0A%0A fetchServerData() %7B%0A $.ajax(%7B%0A url: this.dataUrl(),%0A dataType: 'json',%0A success: (response) =%3E %7B%0A this.setState(this.convertJsonData(response.data))%0A %7D%0A %7D)%0A %7D,%0A%0A pushDataToServer(data) %7B%0A $.ajax(%7B%0A url: this.dataUrl(),%0A dataType: 'json',%0A method: 'PUT',%0A data: data,%0A success: (response) =%3E %7B%0A this.setState(this.convertJsonData(response.data))%0A %7D%0A %7D)%0A
%7D%0A
+%0A
%7D)%0A%0Amodu
@@ -2910,9 +2910,8 @@
timates%0A
-%0A
|
8491fc0ca81867e9567047b510a358a08165bd62 | use hash for filename saved | scripts/deepdream.js | scripts/deepdream.js | // var imgur = require('imgur')
var client = require('../lib/client.js')
// imgur.setClientId(process.env.IMGUR_ID);
// console.log(imgur.getClientId())
// var path = require('path')
// // A single image
// // imgur.uploadFile('../lib/assets/doge.jpg')
// // .then(function (json) {
// // console.log(json.data.link);
// // })
// // .catch(function (err) {
// // console.error(err.message);
// // });
// // var dogePic = 'wiSk6R8';
// // imgur.getInfo(dogePic)
// // .then(function(json) {
// // console.log(json);
// // })
// // .catch(function (err) {
// // console.error(err.message);
// // });
// var dogeLink = 'http://i.imgur.com/wiSk6R8.jpg'
var _ = require('lodash')
var Promise = require('bluebird')
var Download = require('download');
var message = {
photo:
[ { file_id: 'AgADAQADlKoxG4bPLgUEjh8GSkYg_EWe0i8ABL3IL5XU4MGjLF4BAAEC',
file_size: 1080,
file_path: 'photo/file_0.jpg',
width: 90,
height: 54 },
{ file_id: 'AgADAQADlKoxG4bPLgUEjh8GSkYg_EWe0i8ABFyV54EytlKaLV4BAAEC',
file_size: 18819,
width: 320,
height: 192 },
{ file_id: 'AgADAQADlKoxG4bPLgUEjh8GSkYg_EWe0i8ABBF5HveFrLVjK14BAAEC',
file_size: 52347,
width: 800,
height: 480 } ]
}
function image_url_telegram(message) {
if (_.has(message, 'photo')) {
var file_path = _.get(message, 'photo[0]file_path')
return file_path ? 'https://api.telegram.org/file/bot'+process.env.TELEGRAM_TOKEN+'/'+file_path : undefined
};
}
console.log(image_url_telegram(message))
function downloadFile(url, dest) {
return new Promise(function(resolve, reject) {
new Download({mode: '755'})
.get(url, dest)
.run(function(err, files) {
if (err) { reject(err) };
var name_path = _.get(files, '[0]history')
resolve(name_path)
});
})
}
// just make dest = deepdream/inputs
// make sure it exists of course
// then poll outputs/ for filename, if exists resolve promise with its path, upload image to user
// var dogeLink = image_url_telegram(message)
// downloadFile(dogeLink, '../lib/assets')
// .then(console.log)
// .then(function(res) {
// // console.log(process.env.TELEGRAM_TOKEN)
// })
const pathExists = require('path-exists');
const untildify = require('untildify');
pathExists(untildify('~/Desktop/doge.jpg')).then(exists => {
console.log(exists);
//=> true
});
// ok so once started, deepdream is automatic
// thus need to just poll the output directory for matching filename
// prepend filename of image with message.message_id
//
// // ok do telegram first
// // global.gPass = client.gPass
// // global.gPass({
// // input: "hola amigos",
// // to: 'ai.py',
// // intent: 'nlp.translate'
// // }).then(console.log)
// // hello friends
| JavaScript | 0.000001 | @@ -1509,16 +1509,22 @@
rl, dest
+, hash
) %7B%0A re
@@ -1620,16 +1620,59 @@
, dest)%0A
+ .rename(hash+'_'+url.split('/').pop())%0A
.run
@@ -1985,19 +1985,16 @@
to user%0A
-//
var doge
@@ -2028,19 +2028,16 @@
essage)%0A
-//
download
@@ -2066,21 +2066,38 @@
/assets'
-)%0A//
+, message.message_id)%0A
.then(co
@@ -2107,19 +2107,16 @@
le.log)%0A
-//
.then(fu
@@ -2129,21 +2129,18 @@
(res) %7B%0A
-//
-
// conso
@@ -2178,15 +2178,15 @@
EN)%0A
-//
%7D)%0A%0A
+//
cons
@@ -2224,16 +2224,19 @@
ists');%0A
+//
const un
@@ -2268,16 +2268,19 @@
ify');%0A%0A
+//
pathExis
@@ -2332,16 +2332,19 @@
ts =%3E %7B%0A
+//
consol
@@ -2358,16 +2358,19 @@
xists);%0A
+//
//=%3E t
@@ -2374,21 +2374,57 @@
%3E true %0A
+//
%7D);%0A%0A
+// deep dream need stronger acid%0A
// ok so
|
22314e5faf492de45b827ae4d3bae40659e26285 | Fix feed parser bug when parsing an episode item without an enclosures[0].url | src/tasks/feedParser.js | src/tasks/feedParser.js | const
FeedParser = require('feedparser'),
request = require('request'),
{locator} = require('locator.js'),
errors = require('feathers-errors');
function parseFeed (feedURL) {
return new Promise ((res, rej) => {
const feedParser = new FeedParser([]),
req = request(feedURL);
req.on('error', function (e) {
rej(e);
});
req.on('response', function (res) {
let stream = this;
if (res.statusCode != 200) {
return this.emit('error', new Error('Bad status code'));
}
stream.pipe(feedParser);
});
let jsonString = '',
episodeObjs = [],
podcastObj = {},
parsedFeedObj = {};
feedParser.on('meta', function (meta) {
podcastObj = meta;
});
feedParser.on('readable', function () {
let stream = this,
item;
while (item = stream.read()) {
episodeObjs.push(item);
}
});
feedParser.on('error', done);
feedParser.on('end', done);
function done (e) {
if (e) {
rej(e);
}
if (!podcastObj.xmlurl) {
podcastObj.xmlurl = feedURL;
}
parsedFeedObj.podcast = podcastObj;
parsedFeedObj.episodes = episodeObjs;
res(parsedFeedObj);
}
});
}
function saveParsedFeedToDatabase (parsedFeedObj) {
const Models = locator.get('Models');
const {Episode, Podcast} = Models;
let podcast = parsedFeedObj.podcast;
let episodes = parsedFeedObj.episodes;
return Podcast.findOrCreate({
where: {
feedURL: podcast.xmlurl
},
defaults: Object.assign({}, podcast, {
imageURL: podcast.image.url, // node-feedparser supports image, itunes:image media:image, etc.,
summary: podcast.description,
title: podcast.title,
author: podcast.author,
lastBuildDate: podcast.date,
lastPubDate: podcast.pubdate
})
})
.then(([podcast]) => {
this.podcast = podcast;
return promiseChain = episodes.reduce((promise, ep) => {
return promise.then(() => Episode.findOrCreate({
where: {
mediaURL: ep.enclosures[0].url
},
// TODO: Do we want the podcast.id to be === to podcast feedURL?
defaults: Object.assign({}, ep, {
podcastId: podcast.id,
imageURL: ep.image.url,
title: ep.title,
summary: ep.description,
// duration: TODO: does node-feedparser give us access to itunes:duration?
guid: ep.guid,
link: ep.link,
mediaBytes: ep.enclosures[0].length,
mediaType: ep.enclosures[0].type,
pubDate: ep.pubdate
})
})
.catch(e => {
throw new errors.GeneralError(e);
}));
}, Promise.resolve());
})
.then(() => {
return this.podcast.id;
})
.catch((e) => {
throw new errors.GeneralError(e);
});
}
module.exports = {
parseFeed,
saveParsedFeedToDatabase
}
| JavaScript | 0.000001 | @@ -1996,24 +1996,131 @@
e, ep) =%3E %7B%0A
+%0A if (!ep.enclosures %7C%7C !ep.enclosures%5B0%5D %7C%7C !ep.enclosures%5B0%5D.url) %7B%0A return promise%0A %7D%0A%0A
return
@@ -2393,379 +2393,8 @@
t.id
-,%0A imageURL: ep.image.url,%0A title: ep.title,%0A summary: ep.description,%0A // duration: TODO: does node-feedparser give us access to itunes:duration?%0A guid: ep.guid,%0A link: ep.link,%0A mediaBytes: ep.enclosures%5B0%5D.length,%0A mediaType: ep.enclosures%5B0%5D.type,%0A pubDate: ep.pubdate
%0A
@@ -2428,24 +2428,48 @@
atch(e =%3E %7B%0A
+ console.log(e);%0A
thro
@@ -2605,24 +2605,44 @@
ch((e) =%3E %7B%0A
+ console.log(e);%0A
throw ne
@@ -2677,16 +2677,767 @@
%7D);%0A%0A%7D%0A%0A
+function pruneEpisode(ep) %7B%0A let prunedEpisode = %7B%7D;%0A%0A if (ep.image && ep.image.url) %7B prunedEpisode.imageURL = ep.image.url %7D%0A if (ep.title) %7B prunedEpisode.title = ep.title %7D%0A if (ep.description) %7B prunedEpisode.summary = ep.description %7D%0A if (ep.duration) %7B prunedEpisode.duration %7D TODO: does node-feedparser give us access to itunes:duration?%0A if (ep.guid) %7B prunedEpisode.guid = ep.guid %7D%0A if (ep.link) %7B prunedEpisode.link = ep.link %7D%0A if (ep.enclosures && ep.enclosures%5B0%5D) %7B%0A if (ep.enclosures%5B0%5D.length) %7B prunedEpisode.mediaBytes = ep.enclosures%5B0%5D.length %7D%0A if (ep.enclosures%5B0%5D.type) %7B prunedEpisode.mediaType = ep.enclosures%5B0%5D.type %7D%0A %7D%0A if (ep.pubDate) %7B prunedEpisode.pubDate = ep.pubdate %7D%0A%0A return prunedEpisode%0A%7D%0A%0A
module.e
|
4e9bb42db5492dc50d9b832057dee1ac0cebaf8d | Fix typo | resources/assets/js/mixins/printme.js | resources/assets/js/mixins/printme.js | import { Hub } from '../lib.js'
export default {
data () {
return {
printme: false
}
},
methods: {
afterprint () {
window.onafterprint = null
$(window).off('mousemove', this.afterprint)
this.$calendar && this.$calendar.remove()
this.printme = false
$('#app').show()
}
},
mounted() {
const self = this
Hub.$on('printme', newRole => {
this.printme = true
this.$calendar = $('.calendar').clone()
this.$calendar.css('width', '750px')
$('#app').hide().before(this.$calendar)
window.print()
setTimeout(() => {
window.onafterprint = this.afterprint
$(window).on('mousemove', this.afterprint)
}, 100)
})
}
}
| JavaScript | 0.999999 | @@ -343,30 +343,8 @@
) %7B%0A
- const self = this%0A
|
24d0c3e7822165e860132d5bcdc1e9c2ed9d9a2e | Fix trailing slashes output app-wide | initializers/trailing-history.js | initializers/trailing-history.js | /*global Ember */
var trailingHistory = Ember.HistoryLocation.extend({
setURL: function (path) {
var state = this.getState();
path = this.formatURL(path);
path = path.replace(/\/?$/, '/');
if (state && state.path !== path) {
this.pushState(path);
}
}
});
var registerTrailingLocationHistory = {
name: 'registerTrailingLocationHistory',
initialize: function (container, application) {
application.register('location:trailing-history', trailingHistory);
}
};
export default registerTrailingLocationHistory; | JavaScript | 0 | @@ -73,10 +73,13 @@
-se
+forma
tURL
@@ -90,20 +90,16 @@
nction (
-path
) %7B%0A
@@ -106,204 +106,71 @@
-var state = this.getState();%0A path = this.formatURL(path);%0A path = path.replace(/%5C/?$/, '/');%0A%0A if (state && state.path !== path) %7B%0A this.pushState(path);%0A %7D
+return this._super.apply(this, arguments).replace(/%5C/?$/, '/');
%0A
|
b49af39fe41bd4dd972076e703ac739cb2d16bea | Add scan time to doc title in scan js | public/js/scan.js | public/js/scan.js |
var scan_timer = 0;
var scan_counter = 0;
function addTime(time)
{
scan_timer += parseFloat(time);
scan_counter++;
$(".time_debug").html("<div>Duration: "+scan_timer.toFixed(2)+"s</div>");
$(".time_debug").append("<div>Average: "+(scan_timer/scan_counter).toFixed(2)+"s</div>");
}
function checkStatusScan()
{
$.ajax({
method: "POST",
url: baseUrl+"admin/scan/status"
}).done(function(msg) {
try
{
var data = $.parseJSON(msg);
if (data.result != "done")
{
addTime(data.time);
for (var i = 0; i < data.warning.length; i++)
{
$(".warning_debug").append("<div><b>Warning: </b>"+data.warning[i]+"</div>");
}
checkStatusScan();
}
else
{
$(".loader").html("<h3>Scan Completed</h3>");
}
}
catch(err)
{
$(".loader").remove();
$(".info_debug").html("<div>"+msg+"</div>");
}
});
}
$(document).ready(function() {
if (!$(".scan_start").length)
{
checkStatusScan();
}
});
| JavaScript | 0 | @@ -35,16 +35,31 @@
ter = 0;
+%0Avar doc_title;
%0A%0Afuncti
@@ -133,16 +133,75 @@
nter++;%0A
+ document.title = scan_timer.toFixed(2)+%22s %22+doc_title;%0A
$(%22.
@@ -1185,24 +1185,56 @@
unction() %7B%0A
+ doc_title = document.title;%0A
if (!$(%22
|
548aff14542cc7e5e39d3d7ac2b36353f39b986a | Update example | examples/index.js | examples/index.js | 'use strict';
var MAX_SAFE_INTEGER = require( './../lib' );
var max = Math.pow( 2, 55 ),
len = 100,
val,
i;
for ( i = 0; i < len; i++ ) {
val = Math.round( Math.random() * max );
if ( val > MAX_SAFE_INTEGER ) {
console.log( 'Unsafe: %d', val );
} else {
console.log( 'Safe: %d', val );
}
}
| JavaScript | 0.000001 | @@ -8,16 +8,88 @@
rict';%0A%0A
+var round = require( 'math-round' );%0Avar pow = require( 'math-power' );%0A
var MAX_
@@ -138,52 +138,44 @@
max
- = Math.pow( 2, 55 ),%0A%09len = 100,%0A%09val,%0A%09i;%0A
+;%0Avar x;%0Avar i;%0A%0Amax = pow( 2, 55 );
%0Afor
@@ -192,11 +192,11 @@
i %3C
-len
+100
; i+
@@ -206,19 +206,12 @@
%7B%0A%09
-val = Math.
+x =
roun
@@ -242,19 +242,17 @@
;%0A%09if (
-val
+x
%3E MAX_S
@@ -292,27 +292,25 @@
nsafe: %25d',
-val
+x
);%0A%09%7D else
@@ -342,11 +342,9 @@
d',
-val
+x
);%0A
|
92350aa75f4550c443e6f1858cbc96a0b10e4e00 | Remove unneeded code. (#274) | components/frontend/src/fields/MultipleChoiceInput.js | components/frontend/src/fields/MultipleChoiceInput.js | import React, { Component } from 'react';
import { Form } from 'semantic-ui-react';
class MultipleChoiceInput extends Component {
constructor(props) {
super(props);
this.state = { value: props.value, options: this.options() }
}
componentDidUpdate(prevProps) {
if (prevProps.values !== this.props.values) {
this.setState({ options: this.options() })
}
if (prevProps.value !== this.props.value) {
this.setState({ value: this.props.value })
}
}
options() {
let options = new Set();
this.props.options.forEach((option) => {options.add({key: option, text: option, value: option})});
this.props.value.forEach((val) => {options.add({key: val, text: val, value: val})});
options = Array.from(options);
options.sort((a, b) => a.text.localeCompare(b.text));
return options;
}
handleAddition = (event, { value }) => {
event.preventDefault();
this.setState({
options: [{ key: value, text: value, value: value }, ...this.state.options],
})
}
onSubmit(event, value) {
event.preventDefault();
if (value !== this.props.value) {
this.props.set_value(value);
}
}
render() {
let { set_value, allowAdditions, ...otherProps } = this.props;
return (
<Form>
{this.props.readOnly ?
<Form.Input
{...otherProps}
/>
:
<Form.Dropdown
{...otherProps}
allowAdditions={allowAdditions}
fluid
multiple
onAddItem={this.handleAddition}
onChange={(e, { value }) => this.onSubmit(e, value)}
options={this.state.options}
search
selection
value={this.state.value || []}
/>
}
</Form>
)
}
}
export { MultipleChoiceInput };
| JavaScript | 0.000047 | @@ -630,97 +630,8 @@
%7D);%0A
- this.props.value.forEach((val) =%3E %7Boptions.add(%7Bkey: val, text: val, value: val%7D)%7D);%0A
|
1fe85f37fdc3fe7f7bec90c3553cbd3227ec3c70 | Correct AddressTile and ChatInviteDialog styling, and performance tweak to searching | src/components/views/dialogs/ChatInviteDialog.js | src/components/views/dialogs/ChatInviteDialog.js | /*
Copyright 2015, 2016 OpenMarket Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var React = require("react");
var sdk = require("../../../index");
var Invite = require("../../../Invite");
var createRoom = require("../../../createRoom");
var MatrixClientPeg = require("../../../MatrixClientPeg");
var rate_limited_func = require("../../../ratelimitedfunc");
var Modal = require('../../../Modal');
const TRUNCATE_QUERY_LIST = 4;
module.exports = React.createClass({
displayName: "ChatInviteDialog",
propTypes: {
title: React.PropTypes.string,
description: React.PropTypes.oneOfType([
React.PropTypes.element,
React.PropTypes.string,
]),
value: React.PropTypes.string,
placeholder: React.PropTypes.string,
button: React.PropTypes.string,
focus: React.PropTypes.bool,
onFinished: React.PropTypes.func.isRequired
},
getDefaultProps: function() {
return {
title: "Start a chat",
description: "Who would you like to communicate with?",
value: "",
placeholder: "User ID, Name or email",
button: "Start Chat",
focus: true
};
},
getInitialState: function() {
return {
query: "",
queryList: [],
addressSelected: false,
};
},
componentDidMount: function() {
if (this.props.focus) {
// Set the cursor at the end of the text input
this.refs.textinput.value = this.props.value;
}
this._updateUserList();
},
onStartChat: function() {
this._startChat(this.refs.textinput.value);
},
onCancel: function() {
this.props.onFinished(false);
},
onKeyDown: function(e) {
if (e.keyCode === 27) { // escape
e.stopPropagation();
e.preventDefault();
this.props.onFinished(false);
}
else if (e.keyCode === 13) { // enter
e.stopPropagation();
e.preventDefault();
//this._startChat(this.refs.textinput.value);
this.setState({ addressSelected: true });
}
},
onQueryChanged: function(ev) {
var query = ev.target.value;
var queryList = this._userList.filter((user) => {
return this._matches(query, user);
});
this.setState({ queryList: queryList });
},
onDismissed: function() {
this.setState({ addressSelected: false });
},
_startChat: function(addr) {
// Start the chat
createRoom().then(function(roomId) {
return Invite.inviteToRoom(roomId, addr);
})
.catch(function(err) {
var ErrorDialog = sdk.getComponent("dialogs.ErrorDialog");
Modal.createDialog(ErrorDialog, {
title: "Failure to invite user",
description: err.toString()
});
return null;
})
.done();
// Close - this will happen before the above, as that is async
this.props.onFinished(true, addr);
},
_updateUserList: new rate_limited_func(function() {
// Get all the users
this._userList = MatrixClientPeg.get().getUsers();
}, 500),
// This is the search algorithm for matching users
_matches: function(query, user) {
var name = user.displayName.toLowerCase();
var uid = user.userId.toLowerCase();
query = query.toLowerCase();
// direct prefix matches
if (name.indexOf(query) === 0 || uid.indexOf(query) === 0) {
return true;
}
// strip @ on uid and try matching again
if (uid.length > 1 && uid[0] === "@" && uid.substring(1).indexOf(query) === 0) {
return true;
}
// split spaces in name and try matching constituent parts
var parts = name.split(" ");
for (var i = 0; i < parts.length; i++) {
if (parts[i].indexOf(query) === 0) {
return true;
}
}
return false;
},
render: function() {
var TintableSvg = sdk.getComponent("elements.TintableSvg");
console.log("### D E B U G - queryList:");
console.log(this.state.queryList);
var query;
if (this.state.addressSelected) {
var AddressTile = sdk.getComponent("elements.AddressTile");
// NOTE: this.state.queryList[0] is just a place holder until the selection logic is completed
query = (
<AddressTile user={this.state.queryList[0]} canDismiss={true} onDismissed={this.onDismissed} />
);
} else {
query = (
<input type="text"
id="textinput"
ref="textinput"
className="mx_ChatInviteDialog_input"
onChange={this.onQueryChanged}
placeholder={this.props.placeholder}
defaultValue={this.props.value}
autoFocus={this.props.focus}
onKeyDown={this.onKeyDown}
autoComplete="off"
size="64"/>
);
}
return (
<div className="mx_ChatInviteDialog">
<div className="mx_Dialog_title">
{this.props.title}
</div>
<div className="mx_ChatInviteDialog_cancel" onClick={this.onCancel} >
<TintableSvg src="img/icons-close-button.svg" width="35" height="35" />
</div>
<div className="mx_ChatInviteDialog_label">
<label htmlFor="textinput"> {this.props.description} </label>
</div>
<div className="mx_Dialog_content">
<div>{ query }</div>
</div>
<div className="mx_Dialog_buttons">
<button className="mx_Dialog_primary" onClick={this.onStartChat}>
{this.props.button}
</button>
</div>
</div>
);
}
});
| JavaScript | 0 | @@ -2771,31 +2771,239 @@
var
-queryList = this._userL
+list;%0A // Use the already filtered list if it has been filtered%0A if (query.length %3E 1) %7B%0A list = this.state.queryList;%0A %7D else %7B%0A list = this._userList;%0A %7D%0A var queryList = l
ist.
@@ -6430,18 +6430,18 @@
tinput%22%3E
-
%7B
+
this.pro
@@ -6454,18 +6454,18 @@
cription
-%7D
+%7D
%3C/label%3E
@@ -6564,16 +6564,63 @@
%3Cdiv
+ className=%22mx_ChatInviteDialog_inputContainer%22
%3E%7B query
|
227ea5756de986cdc7253dbf8bbe2d118cf8aae9 | Change ncc taskr function name (#6471) | packages/next/taskfile.js | packages/next/taskfile.js | const notifier = require('node-notifier')
const relative = require('path').relative
const babelOpts = {
presets: [
['@babel/preset-env', {
modules: 'commonjs',
'targets': {
'browsers': ['IE 11']
}
}]
],
plugins: [
['@babel/plugin-transform-runtime', {
corejs: 2,
helpers: true,
regenerator: true,
useESModules: false
}]
]
}
export async function nccunistore (task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('unistore')))
.ncc({ packageName: 'unistore' })
.target('dist/compiled/unistore')
}
export async function precompile (task) {
await task.parallel(['nccunistore'])
}
export async function compile (task) {
await task.parallel(['cli', 'bin', 'server', 'nextbuild', 'nextbuildstatic', 'pages', 'lib', 'client'])
}
export async function bin (task, opts) {
await task.source(opts.src || 'bin/*').typescript({ module: 'commonjs', stripExtension: true }).target('dist/bin', { mode: '0755' })
notify('Compiled binaries')
}
export async function cli (task, opts) {
await task.source(opts.src || 'cli/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/cli')
notify('Compiled cli files')
}
export async function lib (task, opts) {
await task.source(opts.src || 'lib/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/lib')
notify('Compiled lib files')
}
export async function server (task, opts) {
await task.source(opts.src || 'server/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/server')
notify('Compiled server files')
}
export async function nextbuild (task, opts) {
await task.source(opts.src || 'build/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/build')
notify('Compiled build files')
}
export async function client (task, opts) {
await task.source(opts.src || 'client/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).babel(babelOpts).target('dist/client')
notify('Compiled client files')
}
// export is a reserved keyword for functions
export async function nextbuildstatic (task, opts) {
await task.source(opts.src || 'export/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/export')
notify('Compiled export files')
}
export async function pages (task, opts) {
await task.source(opts.src || 'pages/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).babel(babelOpts).target('dist/pages')
}
export async function build (task) {
await task.serial(['precompile', 'compile'])
}
export default async function (task) {
await task.clear('dist')
await task.start('build')
await task.watch('bin/*', 'bin')
await task.watch('pages/**/*.+(js|ts|tsx)', 'pages')
await task.watch('server/**/*.+(js|ts|tsx)', 'server')
await task.watch('build/**/*.+(js|ts|tsx)', 'nextbuild')
await task.watch('export/**/*.+(js|ts|tsx)', 'nextexport')
await task.watch('client/**/*.+(js|ts|tsx)', 'client')
await task.watch('lib/**/*.+(js|ts|tsx)', 'lib')
}
export async function release (task) {
await task.clear('dist').start('build')
}
// notification helper
function notify (msg) {
return notifier.notify({
title: '▲ Next',
message: msg,
icon: false
})
}
| JavaScript | 0.000001 | @@ -389,24 +389,62 @@
%7D%5D%0A %5D%0A%7D%0A%0A
+// eslint-disable-next-line camelcase%0A
export async
@@ -456,16 +456,17 @@
tion ncc
+_
unistore
@@ -716,16 +716,17 @@
el(%5B'ncc
+_
unistore
|
d8adfda022c3795706737771bfccd6a97f004c7c | remove duplicated default params | src/rough/object/RoughSpriteGenerator.js | src/rough/object/RoughSpriteGenerator.js | class RoughSpriteGenerator
{
constructor(game) {
this.game = game;
}
getRectangle(bmd, width, height, config, x = 0, y = 0) {
let rc = rough.canvas(bmd.canvas);
rc.rectangle(x, y, width, height, config);
}
getCircle(bmd, center, radius, config) {
let rc = rough.canvas(bmd.canvas);
rc.circle(center.x, center.y, radius * 2, config);
}
getLine(bmd, dist, config) {
this.getRectangle(bmd, dist, 2, config);
}
getPolygon(bmd, data, config) {
let rc = rough.canvas(bmd.canvas);
rc.path(data, config);
}
getCircleSprite(x, y, radius, config = {}) {
const defaultConfig = {
fill: "rgb(10,150,10)",
fillWeight: 5 // thicker lines for hachure
};
const configs = Object.assign({}, defaultConfig, config);
const realRadius = radius + (config.fillWeight|| 0);
let bmd = this.game.add.bitmapData(realRadius * 2, realRadius * 2);
this.getCircle(bmd, {x: realRadius, y: realRadius}, radius, configs);
return new Phaser.Sprite(this.game, x, y, bmd);
}
getRectangleSprite(x, y, width, height, config = {}) {
let bmd = this.game.add.bitmapData(width, height);
const defaultConfig = {
fill: 'black',
stroke: 'black',
hachureAngle: 60,
hachureGap: 10,
fillWeight: 5,
strokeWidth: 5
};
const configs = Object.assign({}, defaultConfig, config);
this.getRectangle(bmd, width, height, configs);
return new Phaser.Sprite(this.game, x, y, bmd);
}
getAnimatedRectangle(x,y, width, height, config, nbImages) {
let bmd = this.game.add.bitmapData(width * nbImages, height);
const defaultConfig = {
fill: 'orange',
stroke: 'black',
hachureAngle: 60,
hachureGap: 10,
fillWeight: 5,
strokeWidth: 5
};
const configs = Object.assign({}, defaultConfig, config);
for(let i = 0; i < nbImages; i++) {
this.getRectangle(bmd, width, height, configs, (i * width), 0);
}
const key = `${x}_${y}_${width}_${height}`;
this.game.cache.addSpriteSheet(key, null, bmd.canvas, width, height);
let sprite = new Phaser.Sprite(this.game, x, y, key);
const walk = sprite.animations.add('sketch');
walk.enableUpdate = true;
sprite.animations.play('sketch', 10, true);
return sprite;
}
getLineSprite(x, y, x1, y1, x2, y2, config = {}) {
const dist = this.lengthFromPoints(x1, y1, x2, y2);
let bmd = this.game.add.bitmapData(dist, 2);
this.getLine(bmd, dist, config);
const angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
let sprite = new Phaser.Sprite(this.game, x, y, bmd);
sprite.angle =- angle;
return sprite;
}
getPolygonSprite(x,y, data, width, height, config) {
let bmd = this.game.add.bitmapData(width, height);
this.getPolygon(bmd, data, config);
return new Phaser.Sprite(this.game, x, y, bmd);
}
lengthFromPoints(x1, y1, x2, y2) {
return Math.sqrt( ((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) );
}
}
export default RoughSpriteGenerator; | JavaScript | 0.000001 | @@ -1683,247 +1683,8 @@
);%0D%0A
- const defaultConfig = %7B%0D%0A fill: 'orange',%0D%0A stroke: 'black',%0D%0A hachureAngle: 60,%0D%0A hachureGap: 10,%0D%0A fillWeight: 5,%0D%0A strokeWidth: 5%0D%0A %7D;%0D%0A const configs = Object.assign(%7B%7D, defaultConfig, config);%0D%0A
@@ -1770,17 +1770,16 @@
, config
-s
, (i * w
|
02422c5036034ccee0d042eaee32e5b4728899a2 | update base diffractionplan with all new fields | client/js/modules/imaging/models/plan.js | client/js/modules/imaging/models/plan.js | define(['backbone'], function(Backbone) {
return Backbone.Model.extend({
idAttribute: 'DIFFRACTIONPLANID',
urlRoot: '/sample/plan',
validation: {
COMMENTS: {
required: true,
pattern: 'wwsdash',
},
EXPERIMENTKIND: {
required: true,
pattern: 'word',
},
REQUIREDRESOLUTION: {
required: true,
pattern: 'number',
},
EXPOSURETIME: {
required: true,
pattern: 'number',
},
PREFERREDBEAMSIZEX: {
required: true,
pattern: 'number',
},
PREFERREDBEAMSIZEY: {
required: true,
pattern: 'number',
},
BOXSIZEX: {
required: true,
pattern: 'digits',
},
BOXSIZEY: {
required: true,
pattern: 'digits',
},
AXISRANGE: {
required: true,
pattern: 'number',
},
AXISSTART: {
required: true,
pattern: 'number',
},
NUMBEROFIMAGES: {
required: true,
pattern: 'digits',
},
TRANSMISSION: {
required: true,
pattern: 'number',
},
WAVELENGTH: {
required: true,
pattern: 'digits',
},
MONOCHROMATOR: {
required: true,
pattern: 'word',
},
},
})
})
| JavaScript | 0 | @@ -672,35 +672,36 @@
required:
-tru
+fals
e,%0A
@@ -790,35 +790,36 @@
required:
-tru
+fals
e,%0A
@@ -898,35 +898,36 @@
required:
-tru
+fals
e,%0A
@@ -1006,35 +1006,36 @@
required:
-tru
+fals
e,%0A
@@ -1115,35 +1115,36 @@
required:
-tru
+fals
e,%0A
@@ -1224,35 +1224,36 @@
required:
-tru
+fals
e,%0A
@@ -1338,35 +1338,36 @@
required:
-tru
+fals
e,%0A
@@ -1450,35 +1450,36 @@
required:
-tru
+fals
e,%0A
@@ -1532,18 +1532,14 @@
-WAVELENGTH
+ENERGY
: %7B%0A
@@ -1556,35 +1556,36 @@
required:
-tru
+fals
e,%0A
@@ -1669,35 +1669,36 @@
required:
-tru
+fals
e,%0A
|
a904f9543d2161a8306157af35c362c38d590fe6 | Add function openPage() to add functionality to tabs. | portfolio/src/main/webapp/script.js | portfolio/src/main/webapp/script.js | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Fetches messages from the servers and adds them to the DOM.
*/
async function getComments() {
fetch('/data').then(response => response.json()).then((msgs) => {
const statsListElement = document.getElementById('comments-container');
statsListElement.innerHTML = '';
msgs.forEach((msg) => {
statsListElement.appendChild(
createListElement(msg.sender + ': ' + msg.message));
statsListElement.appendChild(
createImgElement(msg.imgUrl));
})
});
}
/** Creates an <li> element containing text. */
function createListElement(text) {
const liElement = document.createElement('li');
liElement.innerText = text;
return liElement;
}
/** Creates an <img> element containing text. */
function createImgElement(text) {
const imgElement = document.createElement('img');
imgElement.src = text;
return imgElement;
}
function deleteData(){
fetch('/delete-data', {method: 'POST'}).then(getComments());
}
function fetchBlobstoreUrlAndShowForm() {
fetch('/blobstore-upload-url')
.then((response) => {
return response.text();
})
.then((imageUploadUrl) => {
const messageForm = document.getElementById('my-form');
messageForm.action = imageUploadUrl;
messageForm.classList.remove('hidden');
});
} | JavaScript | 0 | @@ -581,17 +581,729 @@
icense.%0A
+ %0Afunction openPage(pageName, elmnt, color) %7B%0A // Hide all elements with class=%22tabcontent%22 by default */%0A var i, tabcontent, tablinks;%0A tabcontent = document.getElementsByClassName(%22tabcontent%22);%0A for (i = 0; i %3C tabcontent.length; i++) %7B%0A tabcontent%5Bi%5D.style.display = %22none%22;%0A %7D%0A %0A // Remove the background color of all tablinks/buttons%0A tablinks = document.getElementsByClassName(%22tablink%22);%0A for (i = 0; i %3C tablinks.length; i++) %7B%0A tablinks%5Bi%5D.style.backgroundColor = %22%22;%0A %7D%0A %0A // Show the specific tab content%0A document.getElementById(pageName).style.display = %22block%22;%0A %0A // Add the specific color to the button used to open the tab content%0A elmnt.style.backgroundColor = color;%0A %0A%7D%0A
%0A
-
/**%0A * F
@@ -1815,17 +1815,18 @@
%7D);%0A%7D%0A
+
%0A
-
/** Crea
@@ -2181,25 +2181,26 @@
gElement;%0A%7D%0A
+
%0A
-
function del
@@ -2277,16 +2277,17 @@
s());%0A%7D%0A
+
%0Afunctio
|
af35cb2656d4b8e8621c0d246a5a75ab02cf96bc | convert max_results to a number from the form before sending to server | client/components/QueryForm.js | client/components/QueryForm.js | "use strict";
var React = require('react');
var moment = require('moment');
var cleanupURLs = require('../../common/cleanupURLs');
var DeleteButton = React.createFactory(require('./DeleteButton'));
/*
interface QueryFormProps{
query: MyWIQuery
oracles: MyWIOracle[]
deleteQuery: (q: MyWIQuery) => void
}
*/
module.exports = React.createClass({
getInitialState: function(){
var props = this.props
return {
selectedOracleId: (props.query && props.query.oracle_id) || props.oracles[0].id
};
},
render: function(){
var self = this;
var props = this.props;
var state = this.state;
var editionMode = !!props.query; // by opposition to creationMode
var query = props.query || {};
var selectedOracle = props.oracles.find(function(o){
return o.id === state.selectedOracleId
});
var queryOracleOptions = query.oracle_options || {};
return React.DOM.div({className: "QueryForm-react-component"}, [
React.DOM.form({
className: "query",
onSubmit: function(e){
e.preventDefault();
var formData = Object.create(null);
formData.name = self.refs['form-name'].getDOMNode().value.trim();
if(!editionMode){
formData.q = self.refs['form-q'].getDOMNode().value;
formData.oracle_id = self.refs['form-oracle_id'].getDOMNode().value;
}
var oracleOptionsSection = self.refs['oracle-options'];
var oracleOptionElements = oracleOptionsSection.getDOMNode().querySelectorAll('*[data-oracle-option-id]');
var oracleOptions = Object.create(null);
Array.from(oracleOptionElements).forEach(function(el){
var oracleOptionId = el.getAttribute('data-oracle-option-id');
var value;
var type = selectedOracle.options.find(function(opt){
return opt.id === oracleOptionId;
}).type;
switch(type){
case 'list':
value = cleanupURLs(el.value.split('\n'));
break;
case 'boolean':
value = el.checked;
break;
case 'date range':
value = {};
var fromInput = el.querySelector('input[name="from"]');
var from = fromInput.value;
if(from)
value.from = from;
var toInput = el.querySelector('input[name="to"]');
var to = toInput.value;
if(to)
value.to = to;
break;
default:
// works for Array.isArray(type) (select/option)
value = el.value;
}
oracleOptions[oracleOptionId] = value;
});
formData.oracle_options = JSON.stringify(oracleOptions);
console.log('formData', formData);
props.onSubmit(formData);
}
}, [
React.DOM.section({className: "table-layout"}, [
React.DOM.h1({}, "Query settings"),
React.DOM.label({}, [
React.DOM.span({}, 'name'),
React.DOM.input({
ref: "form-name",
name: 'name',
type: 'text',
required: true,
pattern: '\\s*(\\S+\\s*)+',
// browsers auto-complete based on @name and here it's "name" which is common
// so autocompletion values aren't that useful. This isn't very autocompletable anyway
autoComplete: 'off',
defaultValue: query.name
})
]),
React.DOM.label({}, [
React.DOM.span({}, 'query string'),
editionMode ?
React.DOM.span({}, query.q) :
React.DOM.input({
ref: "form-q",
name: 'q',
required: true,
type: 'text'
})
]),
React.DOM.label({}, [
React.DOM.span({}, 'oracle'),
editionMode ?
React.DOM.span({}, selectedOracle.name) :
React.DOM.select({
ref: "form-oracle_id",
name: 'oracle_id',
defaultValue: state.selectedOracleId,
onChange: function(e){
self.setState({
selectedOracleId: e.target.value
})
}
}, props.oracles.map(function(o){
return React.DOM.option({
value: o.id
}, o.name)
}))
])
]),
selectedOracle.options ? React.DOM.section({ref: 'oracle-options', className: "table-layout"}, [
React.DOM.h1({}, "Oracle options"),
selectedOracle.options.map(function(opt){
var id = opt.id;
var input;
var defaultValue = queryOracleOptions[id];
if(selectedOracle.name === "Google Custom Search Engine" && opt.id === "lr" && !defaultValue){
defaultValue = 'lang_'+( (typeof navigator !== 'undefined' && navigator.language) || 'en');
}
if(Array.isArray(opt.type)){ // enum
input = React.DOM.select({
name: id,
"data-oracle-option-id": id,
defaultValue: defaultValue
}, opt.type.map(function(optOpt){
return React.DOM.option({
value: optOpt.value,
key: optOpt.value
}, optOpt.text)
}));
}
else{
switch(opt.type){
case 'list':
input = React.DOM.textarea({
"data-oracle-option-id": id,
name: id,
defaultValue: (queryOracleOptions[id] || []).join('\n'),
rows: 5
})
break;
case 'boolean':
input = React.DOM.input({
"data-oracle-option-id": id,
name: id,
defaultChecked: queryOracleOptions[id],
type: 'checkbox'
});
break;
case 'number':
input = React.DOM.input({
"data-oracle-option-id": id,
name: id,
defaultValue: queryOracleOptions[id] || opt.default,
min: opt.min,
max: opt.max,
step: opt.step,
type: 'number'
});
break;
case 'date range':
input = React.DOM.div(
{
"data-oracle-option-id": id,
className: 'date-range-input'
},
React.DOM.input({
name: 'from',
defaultValue: (queryOracleOptions[id] || {}).from ||
moment().subtract(2, 'years').format('YYYY-MM-DD'),
placeholder: 'YYYY-MM-DD',
type: 'date'
}),
React.DOM.input({
name: 'to',
defaultValue: (queryOracleOptions[id] || {}).to ||
moment().format('YYYY-MM-DD'),
placeholder: 'YYYY-MM-DD',
type: 'date'
})
);
break;
default:
console.error('unknown oracle option type', opt.type, selectedOracle.name, opt.name, opt.id);
}
}
return React.DOM.label({},
React.DOM.span({}, opt.name),
input
);
})
]) : undefined,
React.DOM.button({
type: "submit"
}, "ok")
]),
props.query ? new DeleteButton({
onDelete: function(){
props.deleteQuery(props.query);
}
}) : undefined
]);
}
});
| JavaScript | 0.000001 | @@ -3386,32 +3386,172 @@
break;%0A
+ case 'number':%0A value = Number(el.value);%0A break;%0A
|
1a94110f83797461340bf46c20638afb653be1bf | Remove StyledFlexContainer import | src/containers/profile/components/ProfileForm.js | src/containers/profile/components/ProfileForm.js | import React, { PropTypes } from 'react';
import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap';
import StyledFlexContainer from '../../../components/flex/StyledFlexContainer';
import styles from '../styles.module.css';
// TODO: Set label on left side
// TODO: Style Form
const getFormItems = (content, handleChange) => {
// TODO: Update key with item id
const formItems = content.map((item) => {
return (
<div className={styles.formRow} key={item.key}>
<ControlLabel className={styles.controlLabel}>
{item.label}
</ControlLabel>
<FormControl
className={styles.formControl}
type="text"
value={item.value}
disabled />
</div>
);
});
// TODO: Make input editable once changes are able to be saved
// <FormControl
// type="text"
// value={item.value}
// onChange={(e) => {
// return (handleChange(item.key, e.target.value));
// }} />
return formItems;
};
const ProfileForm = ({ header, content, handleChange }) => {
return (
<form className={styles.profileFormWrapper}>
<div className={styles.header}>
{header}
</div>
<FormGroup className={styles.formGroup}>
{getFormItems(content, handleChange)}
</FormGroup>
</form>
);
};
ProfileForm.propTypes = {
content: PropTypes.array.isRequired,
handleChange: PropTypes.func.isRequired
};
export default ProfileForm;
| JavaScript | 0 | @@ -111,88 +111,8 @@
p';%0A
-import StyledFlexContainer from '../../../components/flex/StyledFlexContainer';%0A
impo
|
4cd81ce798304d0b8dbefb395367e9be13fa47ac | update msg | server-pairs.js | server-pairs.js | /*
* Launcher file for nodeGame server with conf.
*/
var ServerNode = require('nodegame-server').ServerNode;
var options = {
confDir: './conf',
// logDir: './log', // not working at the moment
servernode: function (servernode) {
// TODO: check if the verbosity property here correctly affects the verbosity of the games in channels
servernode.verbosity = 100;
servernode.gamesDirs.push('./games_new');
return true;
},
http: function (http) {
// Special configuration here
return true;
},
sio: function (sio) {
// Special configuration here
return true;
}
};
// Start server
// Option parameter is optional
var sn = new ServerNode(options);
var pairs = sn.addChannel({
name: 'pairs',
admin: 'pairs/admin',
player: 'pairs',
verbosity: 100
});
// We can load a game here
var path = require('path');
var logicPath = path.resolve('./games/pairs/server/game.room.js');
var room = pairs.createWaitingRoom({
logicPath: logicPath
});
module.exports = sn;
| JavaScript | 0.000001 | @@ -897,16 +897,20 @@
'./games
+_new
/pairs/s
|
fa833524093c4b305e9b37cac97901b4ab71f046 | add test for Parser.postParse() | src/test/parser-test.js | src/test/parser-test.js | /* eslint-disable import/no-unresolved, spaced-comment, no-unused-expressions */
import { expect } from 'chai';
import { describe, it } from 'mocha';
import Parser from '../libs/parser';
describe('Parser', () => {
describe('#parseStatus', () => {
it('returns the unmodified command if command is falsy', () => {
const parsed = Parser.parseStatus(null, null);
//noinspection BadExpressionStatementJS
expect(parsed).to.not.be.ok;
});
it('returns the unmodified command if it is a vorpal command', () => {
const command = '/some_command arg1 arg2';
const parsed = Parser.parseStatus(command, null);
expect(parsed).to.equal(command);
});
it('correctly escapes single and double quotes', () => {
const command = 'This is a \'Test\' with "Quotes"';
//noinspection UnnecessaryLocalVariableJS
const args = command;
const parsed = Parser.parseStatus(command, args);
expect(parsed).to.equal('\'This is a &bquot;Test&bquot; with "Quotes"\'');
});
});
describe('#parseCommand', () => {
it('returns the unmodified command if command is falsy', () => {
const parsed = Parser.parseCommand(null, null);
//noinspection BadExpressionStatementJS
expect(parsed).to.not.be.ok;
});
it('returns the unmodified command if it is not a vorpal command', () => {
const command = 'some_command arg1 arg2';
const parsed = Parser.parseCommand(command, null);
expect(parsed).to.equal(command);
});
it('correctly escapes single and double quotes ignoring the vorpal command and the id argument', () => {
const command = '/reply a1 This is a \'Test\' reply with "Quotes"';
const args = 'a1 This is a \'Test\' reply with "Quotes"';
const parsed = Parser.parseCommand(command, args);
expect(parsed).to.equal('/reply a1 \'This is a &bquot;Test&bquot; reply with "Quotes"\'');
});
});
});
| JavaScript | 0 | @@ -2114,14 +2114,432 @@
%0A %7D);
+%0A%0A describe('#postParse', () =%3E %7B%0A it('should replace placeholders with their original value', () =%3E %7B%0A const parsed = '/reply a1 %5C'This is a &bquot;Test&bquot; reply with %22Quotes%22 and an &bequals; char.%5C'';%0A const postParsed = Parser.postParse(parsed);%0A%0A expect(postParsed).to.equal('/reply a1 %5C'This is a %5C'Test%5C' reply with %22Quotes%22 and an = char.%5C'');%0A %7D);%0A %7D);
%0A%7D);%0A%0A
|
f6a41116ece20362ff6614a51b7b4e7094d185ce | Set this.userId by default in publication | lib/server/publish.js | lib/server/publish.js | import userService from '../services/user'
import comment from '../services/comment'
/**
* Return user ids by the given comment.
*
* @param {Object} comment
*
* @returns {Array}
*/
function getUserIdsByComment(comment) {
var ids = []
ids.push(comment.userId)
if (comment.replies) {
_.each(comment.replies, function (reply) {
ids = _.union(ids, getUserIdsByComment(reply))
})
}
return ids
}
Meteor.publish('comments/anonymous', function (data) {
check(data, {
_id: String,
salt: String
})
return AnonymousUserCollection.find(data, {
fields: { salt: 0, anonIp: 0 }
})
})
const getCompositeCommentCursor = (rootCursor) => ({
find: () => rootCursor,
children: [
{
find(comment) {
const userIds = getUserIdsByComment(comment)
return Meteor.users.find(
{ _id: { $in: userIds } },
{ fields: Comments.config().publishUserFields }
)
}
},
{
find(comment) {
const userIds = getUserIdsByComment(comment)
return AnonymousUserCollection.find(
{ _id: { $in: userIds } },
{
fields: { salt: 0, email: 0, anonIp: 0 }
}
)
}
}
]
})
Meteor.publishComposite('comments/reference', function (id, anonUserData, sorting, limit, skip = 0) {
check(id, String)
check(sorting, String)
check(limit, Number)
check(skip, Number)
let userId = ''
try {
userService.verifyAnonUserData(anonUserData, id)
userId = this.userId || anonUserData._id
} catch(e) {}
const canSeePending = Comments.config()
.canSeePendingComments(id, userId)
const selector = comment.getCommentsSelector(
id,
userId,
canSeePending,
)
return getCompositeCommentCursor(Comments._collection.find(
selector,
{
limit,
skip,
sort: Comments.getSortOption(sorting),
transform: d => canSeePending ? d : comment.commentTransform(d, userId),
}
))
})
Meteor.publishComposite('comments/single', function (commentOrReplyId, anonUserData) {
check(commentOrReplyId, String)
let userId = ''
try {
userService.verifyAnonUserData(anonUserData, null, true)
userId = this.userId || anonUserData._id
} catch(e) {}
const canSeePending = Comments.config()
.canSeePendingComments(null, userId)
return getCompositeCommentCursor(
Comments._collection.find({
$and: ([
comment.commentOrReplySelector(commentOrReplyId),
(canSeePending
? null
: comment.commentStatusSelector(userId)),
]).filter(selector => !!selector),
}, {
transform: d => canSeePending ? d : comment.commentTransform(d, userId),
})
)
})
| JavaScript | 0 | @@ -1421,34 +1421,43 @@
%0A let userId =
-''
+this.userId
%0A%0A try %7B%0A us
@@ -1507,35 +1507,62 @@
id)%0A
+%0A
+if (!
userId
-= this.
+&& anonUserData._id) %7B%0A
userId
-%7C%7C
+=
ano
@@ -1567,32 +1567,38 @@
nonUserData._id%0A
+ %7D%0A
%7D catch(e) %7B%7D%0A
|
c268d91b4e85df9c25869a852e3de9390638abcb | Access new nick attribute in user object | client/js/socket-events/msg.js | client/js/socket-events/msg.js | "use strict";
const $ = require("jquery");
const socket = require("../socket");
const render = require("../render");
const utils = require("../utils");
const options = require("../options");
const helpers_roundBadgeNumber = require("../libs/handlebars/roundBadgeNumber");
const cleanIrcMessage = require("../libs/handlebars/ircmessageparser/cleanIrcMessage");
const webpush = require("../webpush");
const chat = $("#chat");
const sidebar = $("#sidebar");
let pop;
try {
pop = new Audio();
pop.src = "audio/pop.ogg";
} catch (e) {
pop = {
play: $.noop,
};
}
socket.on("msg", function(data) {
// We set a maximum timeout of 2 seconds so that messages don't take too long to appear.
utils.requestIdleCallback(() => processReceivedMessage(data), 2000);
});
function processReceivedMessage(data) {
const targetId = data.chan;
const target = "#chan-" + targetId;
const channel = chat.find(target);
const container = channel.find(".messages");
const activeChannelId = chat.find(".chan.active").data("id");
if (data.msg.type === "channel_list" || data.msg.type === "ban_list") {
$(container).empty();
}
// Add message to the container
render.appendMessage(
container,
targetId,
channel.attr("data-type"),
data.msg
);
container.trigger("keepToBottom");
notifyMessage(targetId, channel, data);
var lastVisible = container.find("div:visible").last();
if (data.msg.self
|| lastVisible.hasClass("unread-marker")
|| (lastVisible.hasClass("date-marker")
&& lastVisible.prev().hasClass("unread-marker"))) {
container
.find(".unread-marker")
.data("unread-id", 0)
.appendTo(container);
}
// Clear unread/highlight counter if self-message
if (data.msg.self) {
sidebar.find("[data-target='" + target + "'] .badge").removeClass("highlight").empty();
}
// Message arrived in a non active channel, trim it to 100 messages
if (activeChannelId !== targetId && container.find(".msg").slice(0, -100).remove().length) {
channel.find(".show-more").addClass("show");
// Remove date-separators that would otherwise
// be "stuck" at the top of the channel
channel.find(".date-marker-container").each(function() {
if ($(this).next().hasClass("date-marker-container")) {
$(this).remove();
}
});
}
if ((data.msg.type === "message" || data.msg.type === "action" || data.msg.type === "notice") && channel.hasClass("channel")) {
const nicks = channel.find(".users").data("nicks");
if (nicks) {
const find = nicks.indexOf(data.msg.from);
if (find !== -1) {
nicks.splice(find, 1);
nicks.unshift(data.msg.from);
}
}
}
}
function notifyMessage(targetId, channel, msg) {
const unread = msg.unread;
msg = msg.msg;
if (msg.self) {
return;
}
const button = sidebar.find(".chan[data-id='" + targetId + "']");
if (msg.highlight || (options.notifyAllMessages && msg.type === "message")) {
if (!document.hasFocus() || !channel.hasClass("active")) {
if (options.notification) {
try {
pop.play();
} catch (exception) {
// On mobile, sounds can not be played without user interaction.
}
}
utils.toggleNotificationMarkers(true);
if (options.desktopNotifications && Notification.permission === "granted") {
let title;
let body;
if (msg.type === "invite") {
title = "New channel invite:";
body = msg.from + " invited you to " + msg.channel;
} else {
title = msg.from;
if (!button.hasClass("query")) {
title += " (" + button.data("title").trim() + ")";
}
if (msg.type === "message") {
title += " says:";
}
body = cleanIrcMessage(msg.text);
}
try {
if (webpush.hasServiceWorker) {
navigator.serviceWorker.ready.then((registration) => {
registration.active.postMessage({
type: "notification",
chanId: targetId,
timestamp: msg.time,
title: title,
body: body,
});
});
} else {
const notify = new Notification(title, {
tag: `chan-${targetId}`,
badge: "img/logo-64.png",
icon: "img/touch-icon-192x192.png",
body: body,
timestamp: msg.time,
});
notify.addEventListener("click", function() {
window.focus();
button.click();
this.close();
});
}
} catch (exception) {
// `new Notification(...)` is not supported and should be silenced.
}
}
}
}
if (!unread || button.hasClass("active")) {
return;
}
const badge = button.find(".badge").html(helpers_roundBadgeNumber(unread));
if (msg.highlight) {
badge.addClass("highlight");
}
}
| JavaScript | 0 | @@ -2486,24 +2486,29 @@
ata.msg.from
+.nick
);%0A%09%09%09if (fi
@@ -2578,16 +2578,21 @@
msg.from
+.nick
);%0A%09%09%09%7D%0A
@@ -3341,16 +3341,21 @@
msg.from
+.nick
+ %22 inv
@@ -3417,16 +3417,21 @@
msg.from
+.nick
;%0A%09%09%09%09%09i
|
36fc32fe8b1589c1009999252ae45564dae2ff2d | Clean up code | client/src/components/Profile/Profile.js | client/src/components/Profile/Profile.js | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Grid } from 'semantic-ui-react';
import { push } from 'react-router-redux';
import ProfileDashboard from './ProfileDashboard';
import Inbox from './Inbox/Inbox';
import ProfileSettings from './profileSettings';
import ProfileNavbar from './profileNavbar';
import { updateFormField, getCurrentProfile, updateProfile, deleteProfile, changeDisplay, getUserProfileListings } from '../../actions/profileActions';
import { getUserDetails } from '../UserDetails/actions';
class Profile extends Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
// this.componentDidMount = this.componentDidMount.bind(this);
this.onUpdateClick = this.onUpdateClick.bind(this);
this.onDeleteClick = this.onDeleteClick.bind(this);
this.onListingClick = this.onListingClick.bind(this);
this.changeDisplay = this.changeDisplay.bind(this);
}
onChange(e) {
this.props.dispatch(updateFormField(e.target.name, e.target.value));
this.props.profileForm.profileUpdated = false;
}
componentWillMount() {
if (this.props.loggedInUser.id !== this.props.userId) {
this.props.dispatch(getUserDetails(this.props.userId));
this.props.dispatch(getUserProfileListings(this.props.userId));
}
}
onUpdateClick() {
this.props.dispatch(updateProfile(this.props.profileForm));
}
onDeleteClick() {
this.props.dispatch(deleteProfile(this.props.loggedInUser));
}
onListingClick(listingId) {
this.props.dispatch(push(`/listings/${listingId}`));
}
changeDisplay(route) {
this.props.dispatch(changeDisplay(route));
}
render() {
const {
firstName,
lastName,
email,
businessName,
address,
city,
zip,
state,
role,
profileUpdated,
business,
profile_img_path,
} = this.props.profileForm;
const display = this.props.display;
const loggedInUser = this.props.loggedInUser;
let thisUser;
let userListings;
let isLoggedInUser = false;
if (this.props.userId !== loggedInUser.id) {
thisUser = this.props.currentUserDetails;
userListings = this.props.profileUserListings;
} else {
thisUser = loggedInUser;
userListings = this.props.userListings;
isLoggedInUser = true;
}
return (
<Container textAlign="center">
{ this.props.userId === loggedInUser.id && this.props.path && (<ProfileNavbar current={this.props.path} userId={this.props.userId} />)}
{ this.props.path === 'dashboard' || !this.props.path ? <ProfileDashboard isLoggedInUser={isLoggedInUser} user={thisUser} userListings={userListings} onListingClick={this.onListingClick} /> : '' }
{ this.props.path === 'inbox' && <Inbox userId={this.props.userId}/> }
{ this.props.path === 'settings' ?
<ProfileSettings
firstName={firstName}
lastName={lastName}
email={email}
businessName={businessName}
address={address}
city={city}
zip={zip}
state={state}
profile_img_path={profile_img_path}
role={role}
profileUpdated={profileUpdated}
business={business}
onUpdateClick={this.onUpdateClick}
onDeleteClick={this.onDeleteClick}
onChange={this.onChange}
/>
: ''
}
</Container>
);
}
}
const mapStateToProps = (state) => {
const { profileForm, profileUserListings } = state.profile;
const { loggedInUser } = state.auth;
const { userListings } = state.listing;
const display = state.profile.display;
const { pathname } = state.routing.locationBeforeTransitions;
const { currentUserDetails } = state.userDetails;
let userId;
pathname !== '/profile' ? userId = parseInt(pathname.split('/')[2]) : userId = false;
const path = pathname.split('/')[3]
return {
profileForm,
loggedInUser,
display,
userId,
currentUserDetails,
userListings,
profileUserListings,
path,
};
};
export default connect(mapStateToProps)(Profile);
| JavaScript | 0.000004 | @@ -685,75 +685,8 @@
s);%0A
- // this.componentDidMount = this.componentDidMount.bind(this);%0A
|
e9de3d6da5e3cfc03b6d5e39fe92ede9c110d712 | Revert "style(webpack_config/server): rewrite prod conf in functional style" | webpack_config/server/webpack.prod.babel.js | webpack_config/server/webpack.prod.babel.js | import webpack from 'webpack'
import baseWebpackConfig from './webpack.base'
import UglifyJSPlugin from 'uglifyjs-webpack-plugin'
import {BundleAnalyzerPlugin} from 'webpack-bundle-analyzer'
import {Plugin as ShakePlugin} from 'webpack-common-shake'
import OptimizeJsPlugin from 'optimize-js-plugin'
const analyzePlugins = process.env.ANALYZE_BUNDLE
? [new BundleAnalyzerPlugin({analyzerMode: 'static'})]
: []
const plugins = [
new webpack.ProgressPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new ShakePlugin(),
// NOTE: you can use BabiliPlugin as an alternative to UglifyJSPlugin
// new BabiliPlugin(),
new UglifyJSPlugin({
sourceMap: true,
compress: {
warnings: false,
unused: true,
dead_code: true
// This option removes console.log in production
// drop_console: true
},
output: {
comments: false
}
}),
new OptimizeJsPlugin({
sourceMap: true
}),
...analyzePlugins
]
export default Object.assign({}, baseWebpackConfig, {
plugins: baseWebpackConfig.plugins.concat(plugins)
})
| JavaScript | 0 | @@ -298,120 +298,8 @@
n'%0A%0A
-const analyzePlugins = process.env.ANALYZE_BUNDLE%0A%09? %5Bnew BundleAnalyzerPlugin(%7BanalyzerMode: 'static'%7D)%5D%0A%09: %5B%5D%0A
cons
@@ -791,30 +791,152 @@
%0A%09%7D)
-,%0A%09...a
+%0A%5D%0A%0A// Do you want to use bundle analyzer?%0Aif (process.env.ANALYZE_BUNDLE) %7B%0A%09plugins.push(new BundleA
nalyze
+r
Plugin
-s%0A%5D
+(%7BanalyzerMode: 'static'%7D))%0A%7D
%0A%0Aex
|
48f6834b5de3f0f0169b1a855bd60136d51b5764 | update project | auto.js | auto.js | // var cron = require('node-cron');
const git = require('simple-git');
const firebase = require('firebase')
const config = require('./config')
// const path = __dirname + '/iotos';
// git(path).then etc..
firebase.initializeApp(config);
var ref = firebase.database().ref().child("servers")
ref.on('value', function (data) {
if (data.val(config.device) == "pull") {
deploy();
} else {
console.log('normal')
}
})
function deploy () {
console.log('Starting Deploying aplication ... :-)');
// git(path).pull('origin', 'master')
git()
.then(function() {
console.log('Starting pull ...');
})
.pull(function(err, update) {
if(update && update.summary.changes) {
console.log('processing and restarting app ...');
require('child_process').exec('npm restart app');
}
})
.then(function() {
console.log('pull done.');
});
}
// var task = cron.schedule('*/1 * * * *', function() {
// console.log('running a task every minute');
// deploy ()
// // task.stop();
// }); | JavaScript | 0 | @@ -326,35 +326,46 @@
%7B%0A%09
-if (data.val(config.device)
+console.log(data)%0A%09if (data.val().rpi1
==
@@ -728,17 +728,16 @@
ting app
-
...');%0A%09
|
6e115b7623ca8992cffe1d45a9a31630ff2a266e | Use sub-destructible to create sender. | factory/socket.js | factory/socket.js | var Conduit = require('conduit')
var Destructible = require('destructible')
var cadence = require('cadence')
var util = require('util')
var Signal = require('signal')
var stream = require('stream')
var Staccato = require('staccato')
var http = require('http')
var Downgrader = require('downgrader')
var delta = require('delta')
var interrupt = require('interrupt').createInterrupter('olio')
var coalesce = require('extant')
var noop = require('nop')
function SocketFactory () {
}
SocketFactory.prototype.createReceiver = cadence(function (async, olio, message, socket) {
var receiver = olio._receiver.call(null, message.argv)
var destructible = olio._destructible.destructible([ 'receiver', message.from ])
async(function () {
var conduit = new Conduit(socket, socket, receiver)
conduit.ready.wait(async())
destructible.destruct.wait(conduit, 'destroy')
destructible.destruct.wait(socket, 'destroy')
conduit.listen(null, olio._destructible.monitor([ 'receiver', message.from ]))
}, function () {
socket.write(new Buffer([ 0xaa, 0xaa, 0xaa, 0xaa ]), async())
})
})
SocketFactory.prototype.createSender = cadence(function (async, from, sender, message, handle, index, initializer) {
var receiver = sender.builder.call(null, message.argv, index, message.count)
var through = new stream.PassThrough
var readable = new Staccato.Readable(through)
var cookie = initializer.destructor(readable, 'destroy')
async(function () {
var request = http.request({
socketPath: message.socketPath,
url: 'http://olio',
headers: Downgrader.headers({
'x-olio-to-index': index,
'x-olio-to-argv': JSON.stringify(message.argv),
'x-olio-from-index': from.index,
'x-olio-from-argv': JSON.stringify(from.argv)
})
})
delta(async()).ee(request).on('upgrade')
request.end()
}, function (request, socket, head) {
async(function () {
readable.read(4, async())
through.write(head)
socket.pipe(through)
}, function (buffer) {
interrupt.assert(buffer != null && buffer.length == 4, 'closed before start')
interrupt.assert(buffer.toString('hex'), 'aaaaaaaa', 'failed to start middleware')
socket.unpipe(through)
coalesce(initializer.cancel(cookie), noop)()
readable.destroy()
var conduit = new Conduit(socket, socket, receiver)
initializer.destructor(conduit, 'destroy')
initializer.destructor(socket, 'destroy')
sender.receivers[index] = { conduit: conduit, receiver: receiver }
conduit.listen(null, async())
initializer.ready()
})
})
})
module.exports = SocketFactory
| JavaScript | 0.000001 | @@ -1416,24 +1416,115 @@
le(through)%0A
+ var destructible = initializer.destructible(%5B 'sender', message.argv, message.count %5D)%0A
var cook
@@ -2866,16 +2866,89 @@
n(null,
+destructible.monitor('conduit'))%0A destructible.completed.wait(
async())
|
de57d8ca1e5fe596a559ae79cb1757d94dc373e9 | Fix testcode | src/parser/core/modules/items/bfa/crafted/DarkmoonDeckBlockades.js | src/parser/core/modules/items/bfa/crafted/DarkmoonDeckBlockades.js | import React from 'react';
import ITEMS from 'common/ITEMS';
import Analyzer from 'parser/core/Analyzer';
import { calculatePrimaryStat } from 'common/stats';
import ExpandableStatisticBox from 'interface/others/ExpandableStatisticBox';
import ItemIcon from 'common/ItemIcon';
import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY';
import { formatDuration, formatNumber, formatPercentage } from 'common/format';
const DARKMOON_DECK_BLOCKADES_CARDS = {
276204: {
name: "Ace",
staminaIncrease: 72,
},
276205: {
name: "Two",
staminaIncrease: 146,
},
276206: {
name: "Three",
staminaIncrease: 218,
},
276207: {
name: "Four",
staminaIncrease: 291,
},
276208: {
name: "Five",
staminaIncrease: 364,
},
276209: {
name: "Six",
staminaIncrease: 437,
},
276210: {
name: "Seven",
staminaIncrease: 510,
},
276211: {
name: "Eight",
staminaIncrease: 583,
},
};
/**
* Darkmoon Deck: Blockades
* Equip: Whenever the deck is shuffled, heal a small amount of health and gain additional stamina. Amount of both stamina and healing depends on the topmost card of the deck.
* Equip: Periodically shuffle the deck while in combat.
*
* Example: https://www.warcraftlogs.com/reports/j7XQrN8LcJKw1qM3#fight=29&source=1&type=healing&view=timeline
*/
class DarkmoonDeckBlockades extends Analyzer {
healing = 0;
actualStaminaIncreasePerCard = {};
cardTracker = {};
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrinket(ITEMS.DARKMOON_DECK_BLOCKADES.id);
if (this.active) {
Object.keys(DARKMOON_DECK_BLOCKADES_CARDS).forEach((buffId) => {
const defaultCard = DARKMOON_DECK_BLOCKADES_CARDS[buffId];
const actualStaminaIncrease = calculatePrimaryStat(355, defaultCard.staminaIncrease, this.selectedCombatant.getItem(ITEMS.DARKMOON_DECK_BLOCKADES.id).itemLevel);
this.actualStaminaIncreasePerCard[buffId] = actualStaminaIncrease;
});
}
}
_isBlockadesCard(spellId) {
const cardId = '' + spellId;
const darkmoonSpells = Object.keys(DARKMOON_DECK_BLOCKADES_CARDS);
return darkmoonSpells.includes(cardId);
}
on_byPlayer_heal(event) {
if (!this._isBlockadesCard(event.ability.guid)) {
return;
}
this.healing += (event.amount || 0) + (event.absorbed || 0);
}
on_toPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (!this._isBlockadesCard(spellId)) {
return;
}
if (!this.cardTracker.hasOwnProperty(spellId)) {
this.cardTracker[spellId] = [];
}
this.cardTracker[spellId].push({
start: event.timestamp,
end: this.owner.fight.end_time,
});
}
on_toPlayer_removebuff(event) {
const spellId = event.ability.guid;
if (!this._isBlockadesCard(spellId)) {
return;
}
if (!this.cardTracker.hasOwnProperty(spellId)) {
return;
}
const lastOccurrenceOfThisCard = this.cardTracker[spellId][this.cardTracker[spellId].length -1];
console.log(lastOccurrenceOfThisCard);
lastOccurrenceOfThisCard.end = event.timestamp;
}
get staminaSummary() {
const summary = {};
Object.keys(this.cardTracker).forEach((cardId) => {
const card = this.cardTracker[cardId];
let duration = 0;
card.forEach((occurrence) => {
duration += occurrence.end - occurrence.start;
});
summary[cardId] = {
name: DARKMOON_DECK_BLOCKADES_CARDS[cardId].name,
occurrences: card.length,
duration: duration,
staminaIncrease: this.actualStaminaIncreasePerCard[cardId],
};
});
return summary;
}
_getSummaryTotals(summary) {
let totalDuration = 0;
let totaloccurrences = 0;
let totalStaminaIncrease = 0;
Object.keys(summary).forEach((cardId) => {
const entry = summary[cardId];
totalDuration += entry.duration;
totaloccurrences += entry.occurrences;
totalStaminaIncrease += entry.staminaIncrease * entry.duration;
});
return {
totalDuration: totalDuration,
totaloccurrences: totaloccurrences,
averageStaminaIncrease: totalStaminaIncrease / totalDuration,
};
}
item() {
const summary = this.staminaSummary;
const totals = this._getSummaryTotals(summary);
const tooltipData = (
<ExpandableStatisticBox
icon={<ItemIcon id={ITEMS.DARKMOON_DECK_BLOCKADES.id} />}
value={this.owner.formatItemHealingDone(this.healing)}
label="Darkmoon Deck: Blockades"
category={STATISTIC_CATEGORY.ITEMS}
>
<table className="table table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Stamina</th>
<th>Time (s)</th>
<th>Time (%)</th>
</tr>
</thead>
<tbody>
{Object.values(summary).map((card, index) => (
<tr key={index}>
<td>{card.name}</td>
<th>{card.staminaIncrease}</th>
<td>{formatDuration(card.duration / 1000)}</td>
<td>{formatPercentage(card.duration / this.owner.fightDuration)}%</td>
</tr>
))}
<tr key="total">
<th>Total</th>
<th>{formatNumber(totals.averageStaminaIncrease)}</th>
<td>{formatDuration(totals.totalDuration / 1000)}</td>
<td>{formatPercentage(totals.totalDuration / this.owner.fightDuration)}%</td>
</tr>
</tbody>
</table>
</ExpandableStatisticBox>
);
return tooltipData;
}
}
export default DarkmoonDeckBlockades;
| JavaScript | 0.003677 | @@ -3037,51 +3037,8 @@
1%5D;%0A
- console.log(lastOccurrenceOfThisCard);%0A
|
8bcad0c360284ffd1eba71d9af1ee1a6b31c35ae | Sanitize IDs on Windows | bake.js | bake.js | var fs = require('fs');
var path = require('path');
var props = require('props');
var dive = require('dive');
var ejs = require('ejs');
var async = require('async');
var clone = require('clone');
var append = require('append');
// Main function
var bake = function(conf, hooks, cb) {
// File counter
var todo = 0;
if (typeof conf != 'object')
return cb(new Error('parameter conf must be a valid configuration object'));
// Set values for `inputDir`, `outputDir` and `tplDir`
var root = conf.root || process.cwd();
var inputDir = conf.directories.input || 'pub';
var outputDir = conf.directories.output || 'pub';
var tplDir = conf.directories.templates || 'tpl';
inputDir = path.resolve(root, inputDir);
outputDir = path.resolve(root, outputDir);
tplDir = path.resolve(root, tplDir);
// Set values for `fileExt`
var fileExt = conf.fileExtensions || { txt: 'html' };
var fileExtPattern
= new RegExp('\.(' + Object.keys(fileExt).join('|') + ')$', 'i');
// Status log
console.log('Beginning to bake ' + inputDir + '.');
// Dive into the public directory
dive(inputDir, function(err, master) {
// Throw errors
if (err)
return cb(err);
// Matching variable
var match;
// Match the master-file's name against enabled file extensions
if (match = master.match(fileExtPattern)) {
// Get the file extension of the master file
var masterExt = match[1];
// Increase file counter
++todo;
// Read the master-file's contents
fs.readFile(master, 'utf8', function(err, data) {
// Throw errors
if (err)
return cb(err);
// Get the properties
// `prop` is the file specific property object
var prop = props(data);
// Amend `prop` by properties in `conf.properties` if defined
if (conf.properties)
prop = append(clone(conf.properties), prop);
// Assert that `prop.template` is set
if (typeof prop.template == 'undefined')
prop.template = 'default.tpl';
// `__propBefore` hook
if (hooks.__propBefore)
hooks.__propBefore(master, prop, propBeforeCB);
else
propBeforeCB(null, prop);
function propBeforeCB(err, prop) {
if (err)
return cb(err);
// tasks for async
var tasks = {};
// Various property hooks
for (var key in prop) {(function (prop, key) {
if (hooks[key])
tasks[key] = function (callback) {
return hooks[key](master, prop, callback);
};
else
tasks[key] = function (callback) {
return callback(null, prop[key]);
};
})(prop, key);}
// run tasks in parallel
async.parallel(tasks, function (err, prop) {
if (err)
return cb(err);
// `__propAfter` hook
if (hooks.__propAfter)
hooks.__propAfter(master, prop, propAfterCB);
else
propAfterCB(null, prop);
function propAfterCB(err, prop) {
if (err)
return cb(err);
// Read the template file
fs.readFile(path.resolve(tplDir, prop.template), 'utf8',
function(err, result) {
// Throw errors
if (err)
return cb(err);
// (Pre-)Insert the content (so ejs-tags in
// `prop.__content` are parsed, too.
result = result.replace(/<%=\s+__content\s+%>/g,
prop.__content);
// Result's filename
var resName = master.replace(fileExtPattern,
'.' + fileExt[masterExt]);
// New file's path
if (typeof prop._id == 'undefined')
prop._id = resName.replace(inputDir, '');
// Remove first slash
if (/^\//, prop._id)
prop._id = prop._id.substring(1);
// Add output dir
resName = path.resolve(outputDir, prop._id);
// Render ejs-template
result = ejs.render(result, { locals: prop });
// Write contents
fs.writeFile(resName, result, function(err) {
// Throw errors
if (err)
return cb(err);
// `__written` hook
if (hooks.__writeAfter)
hooks.__writeAfter(master, prop, writeAfterCB);
else
writeAfterCB(null);
function writeAfterCB(err) {
if (err)
return cb(err);
// Log status on success
console.log(' * ' + resName + ' written.');
// When file counter is zero
if (!--todo) {
// `__complete` hook
if (hooks.__complete)
hooks.__complete(master, prop, cb);
else
return cb(null);
}
}
});
});
}
});
}
});
}
});
};
module.exports = bake;
| JavaScript | 0.999208 | @@ -3894,32 +3894,34 @@
== 'undefined')
+ %7B
%0A
@@ -3964,16 +3964,91 @@
ir, '');
+%0A prop._id = prop._id.replace(/%5C/, '/');%0A %7D
%0A%0A
|
69664eb7d582ec2a1315d5ddad7fe8200ee9ab1f | Move ajax csrf setup into hq.helpers.js | corehq/apps/hqwebapp/static/hqwebapp/js/hq.helpers.js | corehq/apps/hqwebapp/static/hqwebapp/js/hq.helpers.js | hqDefine("hqwebapp/js/hq.helpers", ['jquery', 'knockout', 'underscore'], function($, ko, _) {
var clearAnnouncement = function (announcementID) {
$.ajax({
url: '/announcements/clear/' + announcementID
});
};
$('.page-level-alert').on('closed', function () {
var announcement_id = $('.page-level-alert').find('.announcement-control').data('announcementid');
if (announcement_id) {
clearAnnouncement(announcement_id);
}
});
// disable-on-submit is a class for form submit buttons so they're automatically disabled when the form is submitted
$(document).on('submit', 'form', function(ev) {
var form = $(ev.target);
form.find('.disable-on-submit').disableButton();
form.find('.disable-on-submit-no-spinner').disableButtonNoSpinner();
});
$(document).on('submit', 'form.disable-on-submit', function (ev) {
$(ev.target).find('[type="submit"]').disableButton();
});
$(document).on('click', '.add-spinner-on-click', function(ev) {
$(ev.target).addSpinnerToButton();
});
$(document).on('click', '.notification-close-btn', function() {
var note_id = $(this).data('note-id');
var post_url = $(this).data('url');
$.post(post_url, {note_id: note_id});
$(this).parents('.alert').hide(150);
});
// Initialize common widgets
$(function() {
_.each($(".ko-select2"), function(element) {
$(element).select2();
});
});
if ($.timeago) {
$.timeago.settings.allowFuture = true;
$(".timeago").timeago();
}
window.onerror = function(message, file, line, col, error) {
$.post('/jserror/', {
message: message,
page: window.location.href,
file: file,
line: line,
stack: error ? error.stack : null
});
return false; // let default handler run
};
var oldHide = $.fn.popover.Constructor.prototype.hide;
$.fn.popover.Constructor.prototype.hide = function() {
if (this.options.trigger === "hover" && this.tip().is(":hover")) {
var that = this;
setTimeout(function() {
return that.hide.apply(that, arguments);
}, that.options.delay.hide);
return;
}
oldHide.apply(this, arguments);
};
$.fn.hqHelp = function () {
var self = this;
self.each(function(i) {
var $self = $(self),
$helpElem = $($self.get(i)),
$link = $helpElem.find('a');
var options = {
html: true,
trigger: 'focus',
container: 'body',
};
if (!$link.data('content')) {
options.content = function() {
return $('#popover_content_wrapper').html();
};
}
if (!$link.data("title")) {
options.template = '<div class="popover"><div class="arrow"></div><div class="popover-inner"><div class="popover-content"><p></p></div></div></div>';
}
$link.popover(options);
// Prevent jumping to the top of the page when link is clicked
$helpElem.find('a').click(function(event) {
hqImport('analytix/js/google').track.event("Clicked Help Bubble", $(this).data('title'), '-');
event.preventDefault();
});
});
};
$.showMessage = function (message, level) {
var $notice = $('<div />').addClass("alert fade in alert-block alert-full page-level-alert")
.addClass("alert-" + level);
var $closeIcon = $('<a />').addClass("close").attr("data-dismiss", "alert");
$closeIcon.attr("href", "#").html("×");
$notice.append($closeIcon);
$notice.append(message);
$(".hq-page-header-container").prepend($notice);
};
$.fn.addSpinnerToButton = function () {
$(this).prepend('<i class="fa fa-refresh fa-spin icon-refresh icon-spin"></i> ');
};
$.fn.removeSpinnerFromButton = function () {
$(this).find('i').remove();
};
$.fn.disableButtonNoSpinner = function () {
$(this).prop('disabled', 'disabled')
.addClass('disabled');
};
$.fn.disableButton = function () {
$(this).disableButtonNoSpinner();
$(this).addSpinnerToButton();
};
$.fn.enableButton = function () {
$(this).removeSpinnerFromButton();
$(this).removeClass('disabled')
.prop('disabled', false);
};
$.fn.koApplyBindings = function (context) {
if (!this.length) {
throw new Error("No element passed to koApplyBindings");
}
if (this.length > 1) {
throw new Error("Multiple elements passed to koApplyBindings");
}
ko.applyBindings(context, this.get(0));
this.removeClass('ko-template');
};
$.ajaxSetup({
beforeSend: function(xhr, settings) {
// Don't pass csrftoken cross domain
// Ignore HTTP methods that do not require CSRF protection
if (!/^(GET|HEAD|OPTIONS|TRACE)$/.test(settings.type) && !this.crossDomain) {
var $csrf_token = $("#csrfTokenContainer").val();
xhr.setRequestHeader("X-CSRFToken", $csrf_token);
}
},
// Return something so that hqModules understands that the module has been defined
return 1;
});
| JavaScript | 0.000001 | @@ -5070,16 +5070,20 @@
%7D%0A %7D,
+%0A%7D);
%0A%0A //
|
5f0b9239d560b5fb3ef93f15780a40a4722c0a7f | add optional code to constructor | base.js | base.js | var util = require('util');
module.exports = function (name, defaultMessage, status) {
util.inherits(Constructor, Error);
return Constructor;
function Constructor (message) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = name;
this.message = message || defaultMessage;
this.status = status;
}
}; | JavaScript | 0.000001 | @@ -174,16 +174,22 @@
(message
+, code
) %7B%0A
@@ -353,15 +353,61 @@
status;%0A
+ if (code !== undefined) this.code = code;%0A
%7D%0A%0A%7D;
|
37cf17eeb8853241001ea63aca172a847b99c7e3 | Make link to Github source code more prominant (#1210) | www/src/templates/template-docs-packages.js | www/src/templates/template-docs-packages.js | import React from "react"
import { rhythm, scale } from "../utils/typography"
import presets from "../utils/presets"
import Container from "../components/container"
const DocsTemplate = React.createClass({
render() {
const packageName = this.props.data.markdownRemark.fields.title
return (
<Container>
<a
href={`https://github.com/gatsbyjs/gatsby/tree/1.0/packages/${packageName}`}
css={{
...scale(-1 / 5),
position: `absolute`,
}}
>
Github
</a>
<div
css={{
position: `relative`,
top: rhythm(-1 / 2),
}}
dangerouslySetInnerHTML={{
__html: this.props.data.markdownRemark.html,
}}
/>
</Container>
)
},
})
export default DocsTemplate
export const pageQuery = graphql`
query TemplateDocsQuery($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug }}) {
fields {
title
}
html
}
}
`
| JavaScript | 0 | @@ -326,10 +326,31 @@
%3C
-a%0A
+strong%3E%0A %3Ca%0A
@@ -434,32 +434,34 @@
me%7D%60%7D%0A
+
css=%7B%7B%0A
@@ -457,36 +457,8 @@
%7B%0A
- ...scale(-1 / 5),%0A
@@ -489,32 +489,34 @@
ute%60,%0A
+
%7D%7D%0A %3E%0A
@@ -510,16 +510,18 @@
+
+
%3E%0A
@@ -524,16 +524,52 @@
+ Browse source code for package on
Github%0A
@@ -579,13 +579,33 @@
+
+
%3C/a%3E%0A
+ %3C/strong%3E%0A
@@ -668,41 +668,8 @@
e%60,%0A
- top: rhythm(-1 / 2),%0A
|
5e9b9677c20a0b80566599d5cb967f1a5df3e932 | add sequelize.sync to server start | server/index.js | server/index.js | import express from 'express';
import bodyParser from 'body-parser';
import logger from 'morgan';
import passport from 'passport';
import group from './routes/group';
// Get the content of the ./auth/passport file
import './auth/passport';
const app = express();
// Middlewares
app.use(logger('dev'));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.status(200).send({ message: 'Api up and running' });
});
// User routes
app.post('/api/user/signin', passport.authenticate('local.signin'), (req, res) => {
res.send({ message: 'Signed in successfully' });
});
app.post('/api/user/signup', passport.authenticate('local.signup'), (req, res) => {
res.send({ message: 'Signed up successfully' });
});
// Create a group
app.post('/api/group', group.create);
// Add a user to the group
app.post('/api/group/:id/user', group.adduser);
// Post a message to the group
app.post('/api/group/:id/message', group.postmessage);
// Get messasges belonging to a particular group
app.get('/api/group/:id/messages', group.getmessages);
// Get all members of a particular group
app.get('/api/group/:id/members', group.getmembers);
const port = process.env.PORT || 8000;
const server = app.listen(port, () => {
console.log(`Listening at port ${port}`);
});
// Export server for use in unit tests
export default server;
| JavaScript | 0 | @@ -160,16 +160,48 @@
group';%0A
+import models from './models';%0A%0A
// Get t
@@ -1311,21 +1311,71 @@
%7C 8000;%0A
-const
+let server = %7B%7D;%0Amodels.sequelize.sync().then(() =%3E %7B%0A
server
@@ -1403,16 +1403,18 @@
=%3E %7B%0A
+
+
console.
@@ -1447,21 +1447,28 @@
ort%7D%60);%0A
+ %7D);%0A
%7D);%0A%0A
+%0A
// Expor
@@ -1498,16 +1498,19 @@
t tests%0A
+//
export d
|
13e827be4ba1384431e62014393d3d74862207ad | remove `Percentile 95` column | lib/ui/profiler-ui.js | lib/ui/profiler-ui.js | var _ = require('lodash');
var prettyMs = require('pretty-ms');
var Table = require('cli-table');
module.exports = {
printTechTable: function (printData) {
var printTable = new Table({
head: ['Tech', 'Number of calls', 'Time spend (%)', 'Percentile 95']
});
_.map(printData, function (techInfo) {
printTable.push([
techInfo.tech,
techInfo.callNumber,
techInfo.buildTimePercent,
prettyMs(techInfo.percentile95)
]);
});
console.log(printTable.toString());
},
printTargetTable: function (printData) {
var printTable = new Table({
head: ['Target', 'Self time', 'Wating time', 'Total time']
});
_.map(printData, function (targetInfo) {
printTable.push([
targetInfo.target,
prettyMs(targetInfo.selfTime),
prettyMs(targetInfo.watingTime),
prettyMs(targetInfo.totalTime)
]);
});
console.log(printTable.toString());
}
};
| JavaScript | 0.000001 | @@ -257,25 +257,8 @@
(%25)'
-, 'Percentile 95'
%5D%0A
@@ -458,57 +458,8 @@
cent
-,%0A prettyMs(techInfo.percentile95)
%0A
|
39b1d6f49ac4436fa32974e10c033649996b9aec | resolve lint error | lib/validators/kml.js | lib/validators/kml.js | var gdal = require('gdal');
module.exports = function (infile) {
var ds_kml = '';
var lyr_cnt = '';
function layername_count(ds) {
var lyr_name_cnt = {};
ds.layers.forEach(function(lyr) {
var lyr_name = lyr.name;
if (lyr_name in lyr_name_cnt) {
lyr_name_cnt[lyr_name]++;
} else {
lyr_name_cnt[lyr_name] = 1;
}
});
};
try {
ds_kml = gdal.open(infile);
lyr_cnt = ds_kml.layers.count();
} catch (err) {
return err.message;
}
if (lyr_cnt < 1) {
ds_kml.close();
return 'KML does not contain any layers.';
}
if (lyr_cnt > module.exports.max_layer_count) {
ds_kml.close();
return lyr_cnt + ' layers found. Maximum of ' + module.exports.max_layer_count + ' layers allowed.';
}
var duplicate_lyr_msg = layername_count(ds_kml);
if (duplicate_lyr_msg) {
ds_kml.close();
return 'No duplicate layers allowed.';
}
return true;
};
module.exports.max_layer_count = 15;
| JavaScript | 0.000003 | @@ -371,17 +371,16 @@
%7D);%0A %7D
-;
%0A%0A try
|
83afe27ec2f3c5532a8821d630f9f96a8f5f45ad | Fix test intermittent | src/test/unit/profile-conversion.test.js | src/test/unit/profile-conversion.test.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/. */
// @flow
import { unserializeProfileOfArbitraryFormat } from '../../profile-logic/process-profile';
import { CURRENT_VERSION as CURRENT_GECKO_VERSION } from '../../profile-logic/gecko-profile-versioning';
describe('converting Linux perf profile', function() {
it('should import a perf profile', async function() {
let version = -1;
try {
const fs = require('fs');
const zlib = require('zlib');
const buffer = fs.readFileSync('src/test/fixtures/upgrades/test.perf.gz');
const decompressedArrayBuffer = zlib.gunzipSync(buffer);
const text = decompressedArrayBuffer.toString('utf8');
const profile = await unserializeProfileOfArbitraryFormat(text);
if (profile === undefined) {
throw new Error('Unable to parse the profile.');
}
version = profile.meta.version;
expect(profile).toMatchSnapshot();
} catch (e) {
console.log(e);
// probably file not found
}
expect(version).toEqual(CURRENT_GECKO_VERSION);
});
});
describe('converting Google Chrome profile', function() {
it('successfully imports', async function() {
// Mock out image loading behavior as the screenshots rely on the Image loading
// behavior.
jest
.spyOn(Image.prototype, 'addEventListener')
.mockImplementation((name: string, callback: Function) => {
if (name === 'load') {
callback();
}
});
const fs = require('fs');
const zlib = require('zlib');
const buffer = fs.readFileSync('src/test/fixtures/upgrades/test.chrome.gz');
const decompressedArrayBuffer = zlib.gunzipSync(buffer);
const text = decompressedArrayBuffer.toString('utf8');
const profile = await unserializeProfileOfArbitraryFormat(text);
if (profile === undefined) {
throw new Error('Unable to parse the profile.');
}
expect(profile).toMatchSnapshot();
});
});
| JavaScript | 0.000001 | @@ -1423,16 +1423,28 @@
ior.%0A
+ const spy =
jest%0A
@@ -2097,16 +2097,398 @@
pshot();
+%0A%0A // This is really odd behavior, but this spy was showing up in stack traces in%0A // an intermittent test failure. Adding this manually mock restore made the error%0A // go away. Generally spies should be removed with automatically because of the%0A // %22resetMocks%22 configuration option.%0A //%0A // See https://github.com/facebook/jest/issues/7654%0A spy.mockRestore();
%0A %7D);%0A%7D
|
09757bcd9f341a6934c3b8cb8e56a22c7c35df35 | Update Pointwise.js | CNN/Conv/Pointwise.js | CNN/Conv/Pointwise.js | export { PassThrough, AllZeros, ValueBounds } from "./Pointwise/Pointwise_PassThrough.js";
export { Base } from "./Pointwise/Pointwise_Base.js";
| JavaScript | 0 | @@ -23,17 +23,72 @@
AllZeros
-,
+ %7D from %22./Pointwise/Pointwise_PassThrough.js%22;%0Aexport %7B
ValueBo
@@ -118,35 +118,35 @@
e/Pointwise_
-PassThrough
+ValueBounds
.js%22;%0Aexport
|
0d8221abca2a3c429cc5d3208370a4067bd18526 | Update node.js | node_modules/mquery/test/collection/node.js | node_modules/mquery/test/collection/node.js |
var assert = require('assert')
var slice = require('sliced')
var mongo = require('mongodb')
var utils = require('../../').utils;
var uri = process.env.MQUERY_URI || 'mongodb://localhost/mquery';
var db;
exports.getCollection = function (cb) {
mongo.Db.connect(uri, function (err, db_) {
assert.ifError(err);
db = db_;
var collection = db.collection('stuff');
collection.opts.safe = true;
// clean test db before starting
db.dropDatabase(function () {
cb(null, collection);
});
})
}
exports.dropCollection = function (cb) {
db.dropDatabase(function () {
db.close(cb);
})
}
| JavaScript | 0.000005 | @@ -122,16 +122,83 @@
).utils;
+%0Avar client = require('redis').createClient(process.env.REDIS_URL);
%0A%0Avar ur
|
4d06ec4b715845cb986e9d166849bdbef910b9b0 | use strict AND remove ValidationUtils | balances.js | balances.js | var db = require('./db');
var ValidationUtils = require("./validation_utils.js");
function readBalance(wallet, handleBalance){
var walletIsAddress = ValidationUtils.isValidAddress(wallet);
var join_my_addresses = walletIsAddress ? "" : "JOIN my_addresses USING(address)";
var where_condition = walletIsAddress ? "address=?" : "wallet=?";
var assocBalances = {base: {stable: 0, pending: 0}};
db.query(
"SELECT asset, is_stable, SUM(amount) AS balance \n\
FROM outputs "+join_my_addresses+" CROSS JOIN units USING(unit) \n\
WHERE is_spent=0 AND "+where_condition+" AND sequence='good' \n\
GROUP BY asset, is_stable",
[wallet],
function(rows){
for (var i=0; i<rows.length; i++){
var row = rows[i];
var asset = row.asset || "base";
if (!assocBalances[asset])
assocBalances[asset] = {stable: 0, pending: 0};
assocBalances[asset][row.is_stable ? 'stable' : 'pending'] = row.balance;
}
var my_addresses_join = walletIsAddress ? "" : "my_addresses CROSS JOIN";
var using = walletIsAddress ? "" : "USING(address)";
db.query(
"SELECT SUM(total) AS total FROM ( \n\
SELECT SUM(amount) AS total FROM "+my_addresses_join+" witnessing_outputs "+using+" WHERE is_spent=0 AND "+where_condition+" \n\
UNION ALL \n\
SELECT SUM(amount) AS total FROM "+my_addresses_join+" headers_commission_outputs "+using+" WHERE is_spent=0 AND "+where_condition+" ) AS t",
[wallet,wallet],
function(rows) {
if(rows.length){
assocBalances["base"]["stable"] += rows[0].total;
}
// add 0-balance assets
db.query(
"SELECT DISTINCT outputs.asset, is_private \n\
FROM outputs "+join_my_addresses+" CROSS JOIN units USING(unit) LEFT JOIN assets ON asset=assets.unit \n\
WHERE "+where_condition+" AND sequence='good'",
[wallet],
function(rows){
for (var i=0; i<rows.length; i++){
var row = rows[i];
var asset = row.asset || "base";
if (!assocBalances[asset])
assocBalances[asset] = {stable: 0, pending: 0};
assocBalances[asset].is_private = row.is_private;
}
handleBalance(assocBalances);
}
);
}
);
}
);
}
function readSharedAddressesOnWallet(wallet, handleSharedAddresses){
db.query("SELECT DISTINCT shared_address FROM my_addresses JOIN shared_address_signing_paths USING(address) WHERE wallet=?", [wallet], function(rows){
handleSharedAddresses(rows.map(function(row){ return row.shared_address; }));
});
}
function readSharedBalance(wallet, handleBalance){
var assocBalances = {};
readSharedAddressesOnWallet(wallet, function(arrSharedAddresses){
if (arrSharedAddresses.length === 0)
return handleBalance(assocBalances);
db.query(
"SELECT asset, address, is_stable, SUM(amount) AS balance \n\
FROM outputs CROSS JOIN units USING(unit) \n\
WHERE is_spent=0 AND sequence='good' AND address IN(?) \n\
GROUP BY asset, address, is_stable \n\
UNION ALL \n\
SELECT NULL AS asset, address, 1 AS is_stable, SUM(amount) AS balance FROM witnessing_outputs \n\
WHERE is_spent=0 AND address IN(?) GROUP BY address \n\
UNION ALL \n\
SELECT NULL AS asset, address, 1 AS is_stable, SUM(amount) AS balance FROM headers_commission_outputs \n\
WHERE is_spent=0 AND address IN(?) GROUP BY address",
[arrSharedAddresses, arrSharedAddresses, arrSharedAddresses],
function(rows){
for (var i=0; i<rows.length; i++){
var row = rows[i];
var asset = row.asset || "base";
if (!assocBalances[asset])
assocBalances[asset] = {};
if (!assocBalances[asset][row.address])
assocBalances[asset][row.address] = {stable: 0, pending: 0};
assocBalances[asset][row.address][row.is_stable ? 'stable' : 'pending'] += row.balance;
}
handleBalance(assocBalances);
}
);
});
}
exports.readBalance = readBalance;
exports.readSharedBalance = readSharedBalance; | JavaScript | 0 | @@ -1,49 +1,47 @@
-var db = require('./db');%0Avar ValidationUtils
+/*jslint node: true */%0A%22use strict%22;%0Avar db
= r
@@ -51,31 +51,14 @@
ire(
-%22./validation_utils.js%22
+'./db'
);%0A%0A
@@ -124,16 +124,71 @@
ddress =
+ typeof wallet === 'string' && wallet.length === 32; //
Validat
@@ -214,17 +214,8 @@
ress
-(wallet);
%0A%09va
|
489def4403955165dd0efefca6b83d0a8f94e4e8 | Fix app modal test | src/test/units/AppModalComponent.test.js | src/test/units/AppModalComponent.test.js | import {expect} from "chai";
import {shallow} from "enzyme";
import React from "react/addons";
import AppModalComponent from "../../js/components/modals/AppModalComponent";
describe("App Modal", function () {
describe("default mode", function () {
before(function () {
this.component = shallow(<AppModalComponent />);
this.nodes = {
title: this.component.find(".modal-title"),
submitBtn: this.component.find(".btn-success")
};
});
after(function () {
this.component.instance().componentWillUnmount();
});
it("shows the creation title", function () {
expect(this.nodes.title.text()).to.equal("New Application");
});
it("shows the creation button text", function () {
expect(this.nodes.submitBtn.text()).to.equal("+ Create");
});
});
describe("edit mode", function () {
before(function () {
this.component = shallow(
<AppModalComponent
app={{id: "/some-app", cmd: "sleep 100"}}
editMode={true} />
);
this.nodes = {
title: this.component.find(".modal-title"),
submitBtn: this.component.find(".btn-success")
};
});
after(function () {
this.component.instance().componentWillUnmount();
});
it("shows the edit application title", function () {
expect(this.nodes.title.text()).to.equal("Edit Application");
});
it("shows the change/deploy button text", function () {
expect(this.nodes.submitBtn.text())
.to.equal("Change and deploy configuration");
});
});
});
| JavaScript | 0.000001 | @@ -798,16 +798,26 @@
al(%22
-+
Create
+ Application
%22);%0A
|
454caf4d2d7a138957f9f741d56b2b7c4cba6a9b | Make AppHeader more usable in mobile by shortening it | components/AppHeader.js | components/AppHeader.js | import React from 'react';
import { connect } from 'react-redux';
import Link from 'next/link';
import {
showDialog,
logout,
} from '../redux/auth';
export default connect(({auth}) => ({
user: auth.get('user'),
}), {
showDialog,
logout,
})( function AppHeader({
user,
showDialog,
logout,
}) {
return (
<header className="root">
<Link href="/"><a><h1>真的假的</h1></a></Link>
{
user ? (
<div className="user">
<img src={user.get('avatarUrl')} alt="avatar"/>
<span className="user-name">{user.get('name')}</span>
<button type="button" onClick={logout}>Logout</button>
</div>
) : (
<button type="button" onClick={showDialog}>Login</button>
)
}
<style jsx>{`
.root {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 40px;
}
.user {
display: flex;
align-items: center;
}
.user-name {
margin: 0 16px;
}
`}</style>
</header>
)
});
| JavaScript | 0 | @@ -1050,23 +1050,138 @@
-margin: 0 16px;
+display: none;%0A margin: 0 16px;%0A @media screen and (min-width: 1024px) %7B%0A display: block;%0A %7D
%0A
|
cebd203204ec1bf474c350333c369656ca93fd79 | add about button to plugin | saiku-ui/js/saiku/views/AboutModal.js | saiku-ui/js/saiku/views/AboutModal.js | /*
* Copyright 2012 OSBI Ltd
*
* 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.
*/
/**
* The "about us" dialog
*/
var AboutModal = Modal.extend({
type: 'info',
events: {
'click a' : 'close'
},
message: Settings.VERSION + '<br>' +
'<a href="http://saiku.meteorite.bi" target="_blank">http://saiku.meteorite.bi</a><br><br>' +
'<h2>License Type</h2>'+
'<span class="licensetype"/> - Expires: <span class="licenseexpr"/><br/>'+
'Number of users: <span class="licenseuserlimit"/><br/>'+
'Licensed to: <span class="licensename"/> - <span class="licenseemail"/>'+
'<div id="licensetable">'+
'<h2>Unlicenced User Quota</h2><br/>'+
'<div class="table-wrapper">'+
'<div class="table-scroll">'+
'<table>'+
'<thead>'+
'<tr>'+
'<th><span class="text">Username</span></th>'+
'<th><span class="text">Logins Remaining</span></th>'+
'</tr>'+
'</thead>'+
'<tbody>'+
'<tr id="quotareplace"/>'+
'</tbody>'+
'</table>'+
'</div>'+
'</div>'+
'</div>'+
'<strong><a href="http://sites.fastspring.com/meteoriteconsulting/product/saikusilver" target="_blank">Order more licenses' +
' here</a></strong><br/>'+
'Powered by <img src="images/src/meteorite_free.png" width="20px"> <a href="http://www.meteorite.bi/consulting/" target="_blank">www.meteorite.bi</a><br/>',
initialize: function() {
this.options.title = 'About ' + Settings.VERSION;
},
render: function() {
$(this.el).html(this.template())
.addClass("dialog_" + this.type)
.dialog(this.options);
var uiDialogTitle = $('.ui-dialog-title');
uiDialogTitle.html(this.options.title);
uiDialogTitle.addClass('i18n');
Saiku.i18n.translate();
license = new License();
if(Settings.LICENSE.expiration != undefined) {
yourEpoch = parseFloat(Settings.LICENSE.expiration);
var yourDate = new Date(yourEpoch);
$(this.el).find(".licenseexpr").text(yourDate.toLocaleDateString());
}
if(Settings.LICENSE.licenseType != undefined) {
$(this.el).find(".licensetype").text(Settings.LICENSE.licenseType);
$(this.el).find(".licensename").text(Settings.LICENSE.name);
$(this.el).find(".licenseuserlimit").text(Settings.LICENSE.userLimit);
$(this.el).find(".licenseemail").text(Settings.LICENSE.email);
}
else{
$(this.el).find(".licensetype").text("Open Source License");
}
if(Settings.LICENSEQUOTA != undefined) {
var tbl_body = "";
var odd_even = false;
$.each(Settings.LICENSEQUOTA, function () {
var tbl_row = "";
$.each(this, function (k, v) {
tbl_row += "<td>" + v + "</td>";
});
tbl_body += "<tr class=\"" + ( odd_even ? "odd" : "even") + "\">" + tbl_row + "</tr>";
odd_even = !odd_even;
});
$(this.el).find("#quotareplace").replaceWith(tbl_body);
}
else{
$(this.el).find("#licensetable").hide();
}
return this;
},
close: function(event) {
if (event.target.hash === '#close') {
event.preventDefault();
}
this.$el.dialog('destroy').remove();
}
});
| JavaScript | 0 | @@ -1694,75 +1694,38 @@
ef=%22
-http://sites.fastspring.com/meteoriteconsulting/product/saikusilver
+www.meteorite.bi/saiku-pricing
%22 ta
|
3dca90fc60f64a6e92c3616b8e34faa4155284cc | Improve the check for array instance | src/universal/apivis.js | src/universal/apivis.js | import {
name as LIB_NAME,
version as LIB_VERSION
} from '../../package.json';
const {
toString
} = Object.prototype;
function _isBasicObject(val) {
return typeof val === 'object' &&
val !== null &&
val.__proto__ === undefined;
}
function _argsStr(count, name = 'arg') {
let names = [];
for (let i = 0; i < count; i++) {
names.push(`${name}${i + 1}`);
}
return names.join(', ');
}
function typeStr(val, k = undefined) {
let t = (_isBasicObject(val)) ?
'BasicObject' :
toString.call(val).match(/^\[object ([^\]]*)\]$/)[1];
if (t === 'Object') {
if (val.constructor && (
(val.constructor.name && val.constructor.name !== t)
)) {
t = val.constructor.name;
}
}
if (val instanceof Error) {
// name might be a getter that throws
try {
let name = val.name;
if (name && name !== t) {
t = name;
}
} catch (err) {}
}
if (val instanceof Function) {
if (val.name && val.name !== t && (
val.name.match(/^[A-Z]/) ||
(k &&
['__apivis__chain_link',
'constructor',
'prototype',
'__proto__'
].includes(k)
)
)) {
t = val.name;
}
t = `${t}(${_argsStr(val.length)})`;
}
if (val && (
(val.hasOwnProperty && val.hasOwnProperty('constructor'))
)) {
if (!t.endsWith('Prototype') && (
(t !== 'Object' || val === Object.prototype)
)) {
t = `${t}.prototype`;
}
}
return t;
}
function descStr(val, k) {
if (val === undefined || val === null) {
return 'n/a';
}
let desc = Object.getOwnPropertyDescriptor(val, k);
let d1 = '';
let d2 = '';
if (desc === undefined) {
return 'n/a';
}
if (desc.hasOwnProperty('value')) { d1 += 'v'; }
if (desc.writable) { d1 += 'w'; }
if (desc.get) { d1 += 'g'; }
if (desc.set) { d1 += 's'; }
if (desc.enumerable) { d2 += 'e'; }
if (desc.configurable) { d2 += 'c'; }
return (d2) ? `${d1} ${d2}` : d1;
}
const _compare = (a, b) => {
let sa = String(a);
let sb = String(b);
let na;
let nb;
if (Number.isNaN(na = Number(sa)) || Number.isNaN(nb = Number(sb))) {
return (sa < sb) ? -1 : (sa > sb) ? 1 : 0;
}
return na - nb;
};
const _keys = (val, kind) =>
(val === undefined || val === null) ?
[] :
Object[`getOwnProperty${kind}`](val).sort(_compare);
const _symbols = val => _keys(val, 'Symbols');
const _names = val => _keys(val, 'Names');
const members = val => _symbols(val).concat(_names(val));
function membersStr(val, indent = ' ', level = 0, leaf = val) {
return members(val).
map(k => {
// Do not attempt to resolve these
let skip = [
'arguments',
'callee',
'caller'
];
// Only resolve these in the context of leaf
let leafOnly = [
'__proto__'
];
let v;
let sv = '';
// First resolve k in the context of leaf (like it would be normally)
try {
if (!skip.includes(k)) {
v = leaf[k];
}
} catch (err) {
v = err; // Make the error visible in the dump
}
// Then try resolving k in the context of val (reached through
// following __proto__) to eventually get a shadowed value (some
// props only make sense when resolved in the context of leaf
// and an exception will be thrown upon trying to access them through val)
try {
if ( !(val === leaf || leafOnly.includes(k) || skip.includes(k)) ) {
let shv = val[k];
if (shv !== undefined && shv !== null) {
v = shv;
}
}
} catch (err) {
// Leave v as set by trying to resolve k in the context of leaf
}
// Show select values
switch (typeof v) {
case 'boolean':
case 'number':
sv = `:${v}`;
break;
case 'string':
sv = `:${JSON.stringify(v)}`;
break;
case 'object':
if (Array.isArray(v)) {
sv = `:${v.length}`;
} else if (v instanceof Date) {
sv = `:${JSON.stringify(v)}`;
} else if (v instanceof Error && v.message) {
sv = `:${JSON.stringify(v.message)}`;
}
break;
}
return `${indent.repeat(level)}${String(k)}{${descStr(val, k)}}: ${typeStr(v, k)}${sv}`;
}).
join('\n');
}
function chain(val) {
let links = [val];
for (let link = Object.getPrototypeOf(val);
link;
link = Object.getPrototypeOf(link)
) {
links.push(link);
}
return links;
}
function chainStr(val, indent = ' ') {
return chain(val).
reverse().
map((v, i) => `${indent.repeat(i)}[${typeStr(v, '__apivis__chain_link')}]`).
join('\n');
}
function apiStr(val, indent = ' ') {
return chain(val).
reverse().
map((v, i) => `${indent.repeat(i)}[${typeStr(v, '__apivis__chain_link')}]\n${membersStr(v, indent, i + 1, val)}`).
join('\n');
}
// peek42 plugin
function peek42(fnOutput, fnComment) {
return {
type(val, comment = undefined, opts = undefined) {
fnOutput(
typeStr(val),
fnComment(comment, val, 'type'),
opts
);
},
desc(val, k, comment = undefined, opts = undefined) {
fnOutput(
descStr(val, k),
fnComment(comment, `${String(k)} in ${typeStr(val)}`, 'desc'),
opts
);
},
members(val, comment = undefined, opts = undefined) {
fnOutput(
membersStr(val,
(opts && typeof opts.indent === 'string') ?
opts.indent :
undefined,
(opts && typeof opts.indentLevel === 'number') ?
opts.indentLevel :
undefined
),
fnComment(comment, typeStr(val), 'members'),
opts
);
},
chain(val, comment = undefined, opts = undefined) {
fnOutput(
chainStr(val,
(opts && typeof opts.indent === 'string') ?
opts.indent :
undefined
),
fnComment(comment, typeStr(val), 'chain'),
opts
);
},
api(val, comment = undefined, opts = undefined) {
fnOutput(
apiStr(val,
(opts && typeof opts.indent === 'string') ?
opts.indent :
undefined
),
fnComment(comment, typeStr(val), 'api'),
opts
);
}
};
}
const apivis = {
get [Symbol.toStringTag]() {
return LIB_NAME;
},
version: LIB_VERSION,
typeStr,
descStr,
members,
membersStr,
chain,
chainStr,
apiStr,
peek42
};
export {typeStr, descStr, members, membersStr, chain, chainStr, apiStr};
export default apivis;
| JavaScript | 0.000016 | @@ -3977,16 +3977,41 @@
Array(v)
+ && v !== Array.prototype
) %7B%0A
|
09cafc4c81b5453eab52b45578689b15648ccdd0 | update throng | server/index.js | server/index.js | import './env';
import os from 'os';
import config from 'config';
import express from 'express';
import throng from 'throng';
import expressLib from './lib/express';
import logger from './lib/logger';
import routes from './routes';
async function start(i) {
const expressApp = express();
await expressLib(expressApp);
/**
* Routes.
*/
routes(expressApp);
/**
* Start server
*/
const server = expressApp.listen(config.port, () => {
const host = os.hostname();
logger.info(
'Open Collective API listening at http://%s:%s in %s environment. Worker #%s',
host,
server.address().port,
config.env,
i,
);
if (config.maildev.server) {
const maildev = require('./maildev'); // eslint-disable-line @typescript-eslint/no-var-requires
maildev.listen();
}
});
server.timeout = 25000; // sets timeout to 25 seconds
return expressApp;
}
let app;
if (['production', 'staging'].includes(config.env)) {
const workers = process.env.WEB_CONCURRENCY || 1;
throng({ workers, lifetime: Infinity }, start);
} else {
app = start(1);
}
// This is used by tests
export default async function () {
return app ? app : start(1);
}
| JavaScript | 0.000001 | @@ -229,16 +229,67 @@
utes';%0A%0A
+const workers = process.env.WEB_CONCURRENCY %7C%7C 1;%0A%0A
async fu
@@ -1032,111 +1032,80 @@
env)
-) %7B%0A const workers = process.env.WEB_CONCURRENCY %7C%7C 1;%0A throng(%7B workers, lifetime: Infinity %7D, start
+ && workers && workers %3E 1) %7B%0A throng(%7B worker: start, count: workers %7D
);%0A%7D
|
b0bcc3b12bc97ec041b510f429c16b0f6605979e | Fix setLastResponse out of a command | src/util/CommandUtil.js | src/util/CommandUtil.js | /**
* Extra properties applied to the Discord.js message object.
* @typedef {Object} Message
* @prop {?CommandUtil} util - Utilities for command responding.
* Available on all messages after 'all' inhibitors and built-in inhibitors (bot, client, notSelf).
* Not all properties of the util are available, depending on the input.
*/
class CommandUtil {
/**
* Command utilies.
* @param {AkairoClient} client - The Akairo client.
* @param {Message} message - Message that triggered the command.
* @param {Command} command - Command triggered.
* @param {string} prefix - Prefix used to trigger.
* @param {string} alias - Alias used to trigger.
*/
constructor(client, message, command, prefix, alias) {
/**
* The Akairo client.
* @readonly
* @name CommandUtil#client
* @type {AkairoClient}
*/
Object.defineProperties(this, {
client: {
value: client
}
});
/**
* Message that triggered the command.
* @type {Message}
*/
this.message = message;
/**
* Command used.
* @type {Command}
*/
this.command = command;
/**
* The prefix used.
* @type {?string}
*/
this.prefix = prefix;
/**
* The alias used.
* @type {?string}
*/
this.alias = alias;
/**
* Whether or not the last response should be edited.
* @type {boolean}
*/
this.shouldEdit = false;
/**
* The last response sent.
* @type {?Message}
*/
this.lastResponse = null;
}
/**
* Sets the last repsonse.
* @param {Message|Message[]} message - Message to set.
* @returns {void}
*/
setLastResponse(message) {
if (!this.command.handler.handleEdits || !this.command.editable) return;
if (Array.isArray(message)) {
this.lastResponse = message.slice(-1)[0];
} else {
this.lastResponse = message;
}
}
/**
* Sends a response or edits an old response if available.
* @param {string|MessageOptions} content - Content to send.
* @param {MessageOptions} [options] - Options to use.
* @returns {Promise<Message|Message[]>}
*/
send(content, options) {
[content, options] = this.constructor.swapOptions(content, options);
if (this.shouldEdit && (this.command ? this.command.editable : true) && (!options.file || this.lastResponse.attachments.size)) {
return this.lastResponse.edit(content, options);
}
return this.message.channel.send(content, options).then(sent => {
if (options.file) return sent;
if (this.lastResponse && this.lastResponse.attachments.size) return sent;
this.shouldEdit = true;
this.setLastResponse(sent);
return sent;
});
}
/**
* Sends a response with a mention concantenated to it.
* @param {string|MessageOptions} content - Content to send.
* @param {MessageOptions} [options] - Options to use.
* @returns {Promise<Message|Message[]>}
*/
reply(content, options) {
if (this.message.channel.type !== 'dm') content = `${this.message.author}, ${content}`;
return this.send(content, options);
}
/**
* Swaps and cleans up content and options.
* @param {string|MessageOptions} content - Content to send.
* @param {MessageOptions} [options] - Options to use.
* @returns {Array}
*/
static swapOptions(content, options) {
if (!options && typeof content === 'object' && !(content instanceof Array)) {
options = content;
content = '';
} else if (!options) {
options = {};
}
if (!options.embed) options.embed = null;
return [content, options];
}
}
module.exports = CommandUtil;
| JavaScript | 0.000017 | @@ -1894,24 +1894,59 @@
(message) %7B%0A
+ if (message.command) %7B%0A
if (
@@ -2013,16 +2013,26 @@
return;
+%0A %7D
%0A%0A
|
82c2dfc427ad48ccd2672ff2ab5495a6527d7eb8 | Add top-level error handling | server/index.js | server/index.js | var app = require('express')(),
env = app.get('env'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
logger = require('morgan'),
getConfigurationValue = require('./config').getValueForEnvironment
// TODO: Connect to database here
mongoose.connect(getConfigurationValue('/database', env))
// TODO: Setup express application here
app.set('port', getConfigurationValue('/app/port', env))
app.use(bodyParser.json())
if (env === 'development') {
app.use(logger('dev'))
}
app.use(require('./routes'))
function start() {
app.listen(app.get('port'))
}
module.exports = {
start: start,
app: app
} | JavaScript | 0.000006 | @@ -539,16 +539,394 @@
tes'))%0A%0A
+// Error middleware%0Aapp.use(function(err, req, res, next)%7B%0A%09// Handles not found errors from all routes%0A%09// Maybe this should be used only on API calls and views should serve a 404 page%0A%09if(err.status !== 404)%0A%09%09return next()%0A%09res.status(404).json(err)%0A%09%0A%7D)%0A%0Aapp.use(function(err, req, res, next)%7B%0A%09// TODO: log error and request and submit a bug%0A%09res.status(500).json(err)%0A%7D)%0A%0A
function
|
ccdaab7c54fdb0da4057eeaa2648f8fa2feb7199 | Fix cover image url | components/Html/Html.js | components/Html/Html.js | /**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import React, { PropTypes } from 'react';
import GoogleAnalytics from '../GoogleAnalytics';
import config from '../../config';
function Html({ title, description, body, debug }) {
return (
<html className="no-js" lang="">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<title>{title || config.title}</title>
<meta name="description" content={description || config.description} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="Takuya Matsuyama" />
<meta name="author" content="craftzdog" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@craftzdog" />
<meta name="twitter:creator" content="@craftzdog" />
<meta name="twitter:title" content={title || config.title} />
<meta name="twitter:description" content={description || config.description} />
<meta name="twitter:image" content="/cover.jpg" />
<meta property="og:site_name" content="Takuya Matsuyama's Homepage" />
<meta property="og:title" content={title || config.title} />
<meta property="og:description" content={description || config.description} />
<meta property="og:type" content="website" />
<meta property="og:image" content="/cover.jpg" />
<link rel="apple-touch-icon" href="apple-touch-icon.png" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Merriweather:300,400,700|Lato:300,400" />
<link rel="stylesheet" href="//fonts.googleapis.com/earlyaccess/notosansjapanese.css" />
<script src={'/app.js?' + new Date().getTime()} />
</head>
<body>
<div id="app" className="container" dangerouslySetInnerHTML={{ __html: body }} />
<GoogleAnalytics />
</body>
</html>
);
}
Html.propTypes = {
title: PropTypes.string,
description: PropTypes.string,
body: PropTypes.string.isRequired,
debug: PropTypes.bool.isRequired,
};
export default Html;
| JavaScript | 0.000548 | @@ -1527,32 +1527,54 @@
image%22 content=%22
+https://www.craftz.dog
/cover.jpg%22 /%3E%0A%0A
|
d7eda5f2b069c0faaf36f4155c90507c04dc03d4 | check resource folders exist during build | dev/webpack.config.js | dev/webpack.config.js | const path = require('path'),
copyPlugin = require('copy-webpack-plugin'),
glob = require('glob'),
del = require('del');
module.exports = env => {
// Set up
let project;
const projectPath = `./projects/${env.fdk_project || 'project'}`;
try {
project = require(projectPath);
} catch (ex) {
console.error(`Error loading project settings file at '${projectPath}'`);
process.exit(1);
}
const resourceTypes = Object.keys(project.resources),
configList = [],
copyList = [],
wpContentPath = 'www/wp-content/',
ignores = [
'node_modules/**',
'.git/**',
'src/**',
'.gitignore',
'.gitmodules',
'webpack.config.js',
'package.json',
'package-lock.json',
'.DS_Store',
];
// Compile resource configs
const defaultEntryIndex = path.resolve(__dirname, 'src/index.js'),
defaultOutputPath = path.resolve(__dirname, 'build');
resourceTypes.forEach(resourceType => {
// Process each resource config
project.resources[resourceType].forEach(resourcePath => {
let resourceName = resourcePath.split('/').pop();
console.log('FDK: processing ' + resourceType + ': ' + resourceName);
const sourcePath = path.resolve(__dirname, resourcePath);
// If this resource has a webpack config, use it to build
// Change default relative paths to absolute ones where necessary
try {
const config = require(path.resolve(sourcePath, 'webpack.config.js'));
if (config.entry.index == defaultEntryIndex) {
config.entry.index = path.resolve(sourcePath, 'src/index.js');
}
if (config.output.path == defaultOutputPath) {
config.output.path = path.resolve(sourcePath, 'build');
}
config.resolve = { modules: [path.resolve(sourcePath, 'node_modules')] };
config.resolveLoader = { modules: [path.resolve(sourcePath, 'node_modules')] };
configList.push(config);
} catch (e) { // No webpack config
console.log('FDK: ' + resourceName + ' does not have a webpack config, copying anyway');
}
// Assemble list of files to copy, pre-filtered for ignores
// (the `ignores` setting slows down the copy plugin/watch immensely)
const destPath = path.resolve(resourceType, resourceName);
glob('*', { cwd: sourcePath, ignore: ignores }, (er, files) => {
files.forEach(file => {
copyList.push({ from: path.resolve(sourcePath, file), to: path.resolve(destPath, file) });
});
});
// Empty resource folder ready for fresh version
console.log('FDK: emptying ' + path.resolve(wpContentPath, destPath));
del([path.resolve(wpContentPath, destPath)], { force: true });
});
});
// Add extra config to copy all compiled files into active WP installation
configList.push({
entry: path.resolve(__dirname, 'projects', project.entry || 'index.js'),
output: { path: path.resolve(__dirname, wpContentPath) },
plugins: [new copyPlugin(copyList)],
});
return configList;
}
| JavaScript | 0 | @@ -115,16 +115,37 @@
e('del')
+,%0A%09fs = require('fs')
;%0A%0Amodul
@@ -1203,16 +1203,121 @@
cePath);
+%0A%09%09%09if (!fs.existsSync(sourcePath)) %7B%0A%09%09%09%09console.log('FDK: cannot find source folder');%0A%09%09%09%09return;%0A%09%09%09%7D
%0A%0A%09%09%09//
|
becf9db404692122fd1cba24f3db8632e278ddb9 | Update 3d object color for design | src/js/graphic/background/geometric/geometric.js | src/js/graphic/background/geometric/geometric.js | export default class Geometric
{
static draw(p)
{
Geometric.translateByMouse(p)
Geometric.generateGeometric(p)
}
static generateGeometric(p)
{
let xMax = 17
let yMax = 17
let geometricSizeMulti = 1
let radius = p.width * 1
let rotateX = p.frameCount * -0.0005 + 1000
let rotateY = p.frameCount * 0.0010
let rotateZ = p.frameCount * 0.0010
if (window.screen.width < 600) {
radius *= 2
xMax = 10
yMax = 10
geometricSizeMulti = 0.5
rotateX *= 3
rotateY *= 3
rotateZ *= 3
}
for (let x = 0; x <= xMax; ++x) {
p.push()
for (let y = 0; y <= yMax; ++y) {
const xMapped1 = x / xMax
const yMapped1 = y / yMax
const xRadian = xMapped1 * p.TWO_PI
const yRadian = yMapped1
const xSine = p.sin(xRadian)
const ySine = p.sin(yRadian)
const xCos = p.cos(xRadian)
const yCos = p.cos(yRadian)
const xTranslate = radius * xSine * ySine
const yTranslate = radius * xCos * yCos
const zTranslate = radius * xSine * ySine
p.push()
p.translate(xTranslate, yTranslate, zTranslate)
Geometric.addGeometric(p, x, geometricSizeMulti)
p.pop()
p.rotateX(rotateX)
p.rotateY(rotateY)
p.rotateZ(rotateZ)
Geometric.moveLightByMouse(p)
}
p.pop()
}
}
static addGeometric(p, unique, multi)
{
const type = unique % 6
if (type === 0) {
p.plane(16 * multi)
} else if (type === 1) {
p.box(8 * multi, 8 * multi, 8 * multi)
} else if (type === 2) {
p.cylinder(8 * multi, 16 * multi)
} else if (type === 3) {
p.cone(8 * multi, 16 * multi)
} else if (type === 4) {
p.torus(16 * multi, 4 * multi)
} else if (type === 5) {
p.sphere(8 * multi)
} else if (type === 6) {
p.ellipsoid(8 * multi, 16, 2)
}
}
static moveLightByMouse(p)
{
const y = ((p.mouseY / p.height) - 0.5) * 2
const x = ((p.mouseX / p.width) - 0.5) * 2
p.directionalLight(160, 160, 180, x, -y, 0.25)
p.specularMaterial(50)
}
static translateByMouse(p)
{
p.orbitControl()
}
}
| JavaScript | 0 | @@ -2320,10 +2320,26 @@
ial(
+255, 255, 255, 23
5
-0
)%0A
|
e382c03e6dd543a910105a098876e3f35e177fb0 | use server time for messages | src/webapp/js/services/messageService.js | src/webapp/js/services/messageService.js | angular.module('j.point.me').factory('MessageService', ['$firebase', 'AuthenticationService',
function ($firebase, AuthenticationService) {
var ref = new Firebase("https://jpointme.firebaseio.com/");
return {
/**
* Returns all the sessions that are stored in firebase.
*/
getMessages: function () {
return $firebase(ref.child("messages")).$asArray();
},
/**
* Returns all the messages for a specific session.
*/
getMessagesForSession: function(sessionId) {
var allMessagesPerSession = $firebase(ref.child("messages").child(sessionId)).$asArray();
return allMessagesPerSession;
},
/**
* Posts a message to the specified session.
*/
postMessageToSession: function(sessionId, text) {
var messages = this.getMessagesForSession(sessionId);
messages.$add({
sender: AuthenticationService.getUser().username,
text: text,
time: new Date().getTime()
});
}
}
}
]);
| JavaScript | 0.000001 | @@ -1157,28 +1157,38 @@
me:
-new Date().getTime()
+Firebase.ServerValue.TIMESTAMP
%0A
|
e85b0d407adcb44df8eaa0223fbf5dbae4b02997 | allow indent attributor to take +1/-1 | formats/indent.js | formats/indent.js | import Parchment from 'parchment';
let IndentClass = new Parchment.Attributor.Class('indent', 'ql-indent', {
scope: Parchment.Scope.BLOCK,
whitelist: [1, 2, 3, 4, 5, 6, 7, 8]
});
export { IndentClass };
| JavaScript | 0.00037 | @@ -33,40 +33,319 @@
';%0A%0A
-let IndentClass = new Parchment.
+class IdentAttributor extends Parchment.Attributor.Class %7B%0A add(node, value) %7B%0A if (value === '+1' %7C%7C value === '-1') %7B%0A let indent = parseInt(this.value(node) %7C%7C 0);%0A value = value === '+1' ? (indent + 1) : (indent - 1);%0A %7D%0A return super.add(node, value);%0A %7D%0A%7D%0A%0Alet IndentClass = new Ident
Attr
@@ -350,22 +350,16 @@
tributor
-.Class
('indent
|
a02a6aa4104acd2901fa124363208eac970cbb74 | Simplify server bootstrap | server/index.js | server/index.js | #!/usr/bin/env node -r bshed-requires
import Koa from 'koa'
import debug from 'debug'
import convert from 'koa-convert'
import session from 'koa-session'
// import DataLoader from 'dataloader'
const log = debug('server:loader')
// Server libraries
import assets from './lib/assets'
import graphiql from './lib/graphiql'
import graphqlHTTP from './lib/graphql'
import imageProxy from './lib/imageProxy'
import requestId from './lib/requestId'
import Router from './lib/router'
// import setCsrfToken from './lib/setCsrfToken'
import setUser from './lib/setUser'
import uploader from './lib/uploader'
// Config, models, schema, queue
import * as config from '../config'
import createModels from './models'
import createSchema from './schema'
import Queue from 'bull'
// Build models
const { database } = config
const models = createModels({ database })
// Build queues
const { PROCESS_IMAGE_WORKER_QUEUE, redis } = config
const { port, host, ...redisConfig } = redis
const processImageQueue = new Queue(PROCESS_IMAGE_WORKER_QUEUE, port, host, redisConfig)
const queues = {
processImageQueue
}
// Build schema
const schema = createSchema({
// models,
// queues
})
// Create and configure server
const app = new Koa()
app.keys = config.keys
app.env = config.env
Object.assign(app.context, {
models,
schema,
queues
})
/**
* Global middleware
*/
// Log requests in development
if (config.env === 'development') {
const logger = require('koa-logger')
app.use(logger())
}
// Expose errors outside of production
if (config.env !== 'production') {
const { exposeError } = require('./lib/exposeError')
app.use(exposeError(config.env))
}
// Add unique id to each request
app.use(requestId())
// Cookie sessions
app.use(convert(session({ key: 'bshed' }, app)))
// Set session userId
app.use(setUser())
// Set csrf token cookie
// @TODO: Add csrf token validator
// @TODO: Enable csrf cookie setter
// app.use(setCsrfToken())
// Routes
// @TODO: Clean this up
const router = new Router()
.addRoute({
methods: ['GET'],
path: '/images/:bikeshedId/:bikeKey/:size',
middleware: imageProxy(config.aws)
})
.addRoute({
methods: ['GET'],
path: '/graphiql',
middleware: graphiql({
enabled: true
})
})
.addRoute({
methods: ['GET', 'POST'],
path: '/graphql',
middleware: [
uploader(config.aws),
graphqlHTTP(getGraphqlOptions)
]
})
function getGraphqlOptions (ctx) {
const rootValue = {
files: ctx.request.files || {},
// loaders: {
// Bikeshed: new DataLoader(models.Bikeshed.batchLoad),
// User: new DataLoader(models.User.batchLoad),
// Vote: new DataLoader(models.Vote.batchLoad)
// },
models: models,
queues: queues,
requestId: ctx.request.requestId,
userId: ctx.session.userId
}
return {
rootValue,
schema
}
}
app.use(router.middleware())
// Serve everything in assets folder, falling back to index.html
// This will catch any request that's not handled by the router
app.use(assets(config.ASSETS_PATH))
app.init = function init (port = Number(process.env.PORT) || 3000) {
return new Promise(resolve => {
const instance = app.listen(port, () => {
log(`listening on port "${port}"`)
resolve(instance)
})
})
}
export default app
// Initialize server if called directly
if (require.main === module) {
log('auto-initializing')
app.init()
}
| JavaScript | 0.000009 | @@ -264,19 +264,26 @@
from './
-lib
+middleware
/assets'
@@ -303,27 +303,34 @@
iql from './
-lib
+middleware
/graphiql'%0Ai
@@ -355,19 +355,26 @@
from './
-lib
+middleware
/graphql
@@ -401,19 +401,26 @@
from './
-lib
+middleware
/imagePr
@@ -449,19 +449,26 @@
from './
-lib
+middleware
/request
@@ -493,19 +493,26 @@
from './
-lib
+middleware
/router'
@@ -539,27 +539,34 @@
ken from './
-lib
+middleware
/setCsrfToke
@@ -591,19 +591,26 @@
from './
-lib
+middleware
/setUser
@@ -682,16 +682,17 @@
a, queue
+s
%0Aimport
@@ -727,23 +727,17 @@
%0Aimport
-createM
+m
odels fr
@@ -761,466 +761,104 @@
ort
-createSchema from './schema'%0Aimport Queue from 'bull'%0A%0A// Build models%0Aconst %7B database %7D = config%0Aconst models = createModels(%7B database %7D)%0A%0A// Build queues%0Aconst %7B PROCESS_IMAGE_WORKER_QUEUE, redis %7D = config%0Aconst %7B port, host, ...redisConfig %7D = redis%0Aconst processImageQueue = new Queue(PROCESS_IMAGE_WORKER_QUEUE, port, host, redisConfig)%0Aconst queues = %7B%0A processImageQueue%0A%7D%0A%0A// Build schema%0Aconst schema = createSchema(%7B%0A // models,%0A // queues%0A%7D)
+queues from './services/queues'%0Aimport s3fs from './services/s3fs'%0Aimport schema from './schema'
%0A%0A//
@@ -1284,19 +1284,26 @@
uire('./
-lib
+middleware
/exposeE
@@ -1802,25 +1802,19 @@
geProxy(
-config.aw
+s3f
s)%0A%7D)%0A.a
|
5e901fb1fcdbf269af37d2184ddf93f10651c991 | Fix QueryParamsMixin linting errors | src/js/mixins/__tests__/QueryParamsMixin-test.js | src/js/mixins/__tests__/QueryParamsMixin-test.js | jest.dontMock('../QueryParamsMixin');
var QueryParamsMixin = require('../QueryParamsMixin');
describe('QueryParamsMixin', function () {
beforeEach(function () {
this.instance = QueryParamsMixin;
this.instance.context = {
router: {
getCurrentPathname: function () {
return '/pathname';
},
getCurrentQuery: function () {
return {
stringValue: 'string',
arrayValue: [
'value1',
'value2'
]
};
},
transitionTo: jasmine.createSpy()
}
};
});
it('returns the current pathname', function () {
expect(this.instance.getCurrentPathname()).toEqual('/pathname');
});
it('returns an Object built from the query params', function () {
let queryParamObject = {
stringValue: 'string',
arrayValue: [
'value1',
'value2'
]
};
expect(this.instance.getQueryParamObject()).toEqual(queryParamObject);
});
it('returns a specific value from the query params object', function () {
expect(this.instance.getQueryParamObject()['stringValue'])
.toEqual('string');
});
it('should transition to the right path with the given query params',
function () {
let queryObject = {
arrayValue: [
'value1',
'value2'
],
paramKey: 'paramValue',
stringValue: 'string'
};
this.instance.setQueryParam('paramKey', 'paramValue');
let transitionTo = this.instance.context.router.transitionTo;
expect(transitionTo.calls.count()).toEqual(1);
let [pathname, route, queryParams] = transitionTo.calls.first().args;
expect(pathname).toEqual('/pathname');
expect(route).toEqual({});
expect(queryParams).toEqual(queryObject);
});
it('decodes an arrayString given in the query params', function () {
let decodedArrayString = this.instance.decodeQueryParamArray('a;b;c');
expect(decodedArrayString).toEqual(['a', 'b', 'c']);
});
it('should encode nested arrays in query params',
function () {
let queryObject = {
arrayValue: [
'value1',
'value2'
],
nestedArray: [
'1;2;3',
'4;5;6',
'',
'7;;8',
'non-array'
],
stringValue: 'string'
};
this.instance.setQueryParam('nestedArray', [
[1, 2, 3],
[4, 5, 6],
[],
['7', null, '8'],
'non-array'
]);
let transitionTo = this.instance.context.router.transitionTo;
expect(transitionTo.calls.count()).toEqual(1);
let [pathname, route, queryParams] = transitionTo.calls.first().args;
expect(pathname).toEqual('/pathname');
expect(route).toEqual({});
expect(queryParams).toEqual(queryObject);
});
});
| JavaScript | 0 | @@ -2056,20 +2056,16 @@
params',
-%0A
functio
|
e3cea9c521cca26ff27392d7786cfc0fe8f67f23 | remove spellchecker(scayt) from ckeditor toolbar (#4539) | public/assets/js/ckeditor/config.js | public/assets/js/ckeditor/config.js | /**
* @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here.
// For complete reference see:
// https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html
// The toolbar groups arrangement, optimized for two toolbar rows.
config.toolbarGroups = [
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
{ name: 'links' },
{ name: 'insert' },
{ name: 'forms' },
{ name: 'tools' },
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'others' },
'/',
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
{ name: 'styles' },
{ name: 'colors' },
{ name: 'about' }
];
// Remove some buttons provided by the standard plugins, which are
// not needed in the Standard(s) toolbar.
// config.removeButtons = 'Underline,Subscript,Superscript';
// Set the most common block elements.
config.format_tags = 'p;h1;h2;h3;h4;pre';
// Simplify the dialog windows.
config.removeDialogTabs = 'image:advanced;link:advanced';
config.image_previewText = ' ';
config.removePlugins = 'iframe';
// config.fontSize_style = {
// element: 'style',
// styles: { 'font-size': '#(size)' },
// overrides: [ { element: 'font', attributes: { 'size': null } } ]
// };
// config.colorButton_foreStyle = {
// element: 'style',
// styles: { color: '#(color)' }
// };
config.templates_replaceContent = false;
};
| JavaScript | 0 | @@ -572,24 +572,8 @@
ion'
-, 'spellchecker'
%5D %7D
|
b796134536e8eca6514ef6ba6199d0d1894b6e7d | Add group member count | client/src/components/group.js | client/src/components/group.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ContentClear from 'material-ui/svg-icons/content/clear';
import Chip from 'material-ui/Chip';
import IconButton from 'material-ui/IconButton';
import { Card, CardHeader, CardActions } from 'material-ui/Card';
import { ListItem } from 'material-ui/List';
import PersonAdd from 'material-ui/svg-icons/social/person-add';
import TextField from 'material-ui/TextField';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import Member from './member';
class Group extends Component {
handleUpdateAddMemberName(e) {
this.props.handleUpdateAddMemberName(e.target.value, this.props.idx);
}
handleAddMemberClick(e) {
this.props.handleAddMemberClick(this.props.idx);
}
handleRemoveMemberClick(e, member) {
this.props.handleRemoveMemberClick(this.props.idx, member);
}
renderRemoveGroupButton() {
return this.props.idx === 0 ? '' : (
<FloatingActionButton onTouchTap={(e) =>
this.props.handleRemoveGroupClick(this.props.idx)}>
<ContentClear />
</FloatingActionButton>);
};
render() {
const members = this.props.members.map((member, idx) => {
return (
<Chip
key={idx}
onRequestDelete={(e) => {this.handleRemoveMemberClick(e, member);}}>
<Member name={member.name}/>
</Chip>
);
});
const groupName =
this.props.idx === 0 ? 'Unassigned Group' : `Group ${this.props.idx}`;
const addMemberButton =
(<IconButton
className={"group__add-member-button"}
style={{top: 15}}
onTouchTap={(e) => {this.handleAddMemberClick(e)}}>
<PersonAdd />
</IconButton>);
return (
<Card zDepth={5}>
<CardHeader
title={`${groupName}:`} />
{members}
<CardActions>
<ListItem
rightIconButton={addMemberButton}>
<TextField
hintText="Type in member name"
value={this.props.addMemberName}
onChange={(e) => {this.handleUpdateAddMemberName(e)}} />
</ListItem>
{this.renderRemoveGroupButton()}
</CardActions>
</Card>);
}
}
Group.propTypes = {
idx: PropTypes.number,
members: PropTypes.arrayOf(
PropTypes.shape({name: PropTypes.string}),
),
addMemberName: PropTypes.string,
handleUpdateAddMemberName: PropTypes.func,
handleAddMemberClick: PropTypes.func,
handleRemoveMemberClick: PropTypes.func,
handleRemoveGroupClick: PropTypes.func,
};
Group.defaultProps = {
addMemberName: '',
}
export default Group;
| JavaScript | 0.000001 | @@ -1529,16 +1529,67 @@
.idx%7D%60;%0A
+ const memberCount = this.props.members.length;%0A
cons
@@ -1907,12 +1907,57 @@
ame%7D
-:%60%7D
+%60%7D%0A subtitle=%7B%60$%7BmemberCount%7D people%60%7D
/%3E%0A
|
6bf45d425a47caa83eae07113249c414df6c32c4 | Fix deprecated warning for ts-jest | jest.config.js | jest.config.js | var semver = require('semver');
function getSupportedTypescriptTarget() {
var nodeVersion = process.versions.node;
if (semver.gt(nodeVersion, '7.6.0')) {
return 'es2017'
} else if (semver.gt(nodeVersion, '7.0.0')) {
return 'es2016';
} else if (semver.gt(nodeVersion, '6.0.0')) {
return 'es2015';
} else if (semver.gt(nodeVersion, '4.0.0')) {
return 'es5';
} else {
return 'es3';
}
}
module.exports = {
mapCoverage: true,
testEnvironment: 'node',
moduleFileExtensions: ['js', 'json', 'ts'],
transform: {
'.ts': '<rootDir>/node_modules/ts-jest/preprocessor.js'
},
testMatch: [
'**/__tests__/**/*.ts'
],
testPathIgnorePatterns: [
'<rootDir>/(node_modules|dist)',
'_\\w*.\\w+$'
],
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.d.ts'
],
globals: {
__TS_CONFIG__: {
target: getSupportedTypescriptTarget(),
module: 'commonjs'
}
}
};
| JavaScript | 0 | @@ -832,25 +832,45 @@
-__TS_CONFIG__
+'ts-jest': %7B%0A tsConfigFile
: %7B%0A
+
@@ -917,16 +917,18 @@
,%0A
+
module:
@@ -938,16 +938,24 @@
mmonjs'%0A
+ %7D%0A
%7D%0A
|
03ed1776047ebe316fef8e077a0d62d6b5587da6 | Remove unused template helper; add comments | client/views/home/edit/edit.js | client/views/home/edit/edit.js | Template.editHome.helpers({
'home': function () {
// Get Home ID from template data context
// convert the 'String' object to a string for the DB query
var homeId = this._id;
// Get home document
var home = Homes.findOne(homeId);
return home;
}
});
Template.editHome.created = function () {
var instance = this;
var router = Router.current();
var homeId = router.params.homeId;
instance.subscribe('singleHome', homeId);
instance.subscribe('allGroups');
};
AutoForm.addHooks(['editHomeForm'], {
'onSuccess': function () {
// Hide the modal dialogue
Modal.hide('editHome');
}
});
| JavaScript | 0 | @@ -15,27 +15,17 @@
ome.
-helpers(%7B%0A 'home':
+created =
fun
@@ -31,26 +31,24 @@
nction () %7B%0A
-
// Get Hom
@@ -48,406 +48,354 @@
Get
-Home ID from template data context%0A // convert the 'String' object to a string for the DB query%0A var homeId
+reference to template instance%0A var instance
= this
-._id
;%0A%0A
-
-
// Get
-home document%0A var home = Homes.findOne(homeId);%0A%0A return home;%0A %7D%0A%7D);%0A%0ATemplate.editHome.created = function () %7B%0A var instance = this;%0A%0A var router = Router.current();%0A%0A var homeId = router.params.homeId;%0A%0A instance.subscribe('singleHome', homeId);
+reference to router%0A var router = Router.current();%0A%0A // Get Home ID from router parameter%0A var homeId = router.params.homeId;%0A%0A // Subscribe to single home, based on Home ID%0A instance.subscribe('singleHome', homeId);%0A%0A // Subscribe to all groups, for the group select options
%0A i
|
d67246fcadac96e79335c82af765b67d980183be | make it obvious if you forgot to add to assets.yml | public/javascripts/requireConfig.js | public/javascripts/requireConfig.js | require = {
baseUrl: '/public/javascripts'
};
| JavaScript | 0 | @@ -22,26 +22,44 @@
: '/
-public/javascripts
+you_forgot_to_add_this_to_assets_yml
'%0A%7D;
|
375fd5de13d927060b3905be2a99669e15518e7f | Increase max name length to 50 | src/validation/index.js | src/validation/index.js | var _ = require('lodash');
var Joi = require('joi');
var common = {
team: Joi.number().integer().min(0),
userUuid: Joi.string().regex(/^[A-Za-z0-9_-]+$/).min(1, 'utf8').max(128, 'utf8'),
primaryKeyId: Joi.number().integer().min(0)
};
const schemas = {
common: common,
action: {
user: common.userUuid.required(),
type: Joi.string().uppercase().required(),
imageData: Joi.string().when('type', { is: 'IMAGE', then: Joi.required() }),
text: Joi.string().when('type', { is: 'TEXT', then: Joi.required() }),
location: Joi.object({
latitude: Joi.number(),
longitude: Joi.number()
})
},
user: {
uuid: common.userUuid.required(),
name: Joi.string().min(1, 'utf8').max(30, 'utf8').required(),
team: common.team.required()
},
feedParams: {
beforeId: Joi.number().integer().min(0).optional(),
limit: Joi.number().integer().min(1).max(100).optional()
}
};
const conversions = {};
function assert(obj, schemaName) {
var joiObj = _getSchema(schemaName);
// All this hassle to get joi to format nice error messages
var content = {};
content[schemaName] = obj;
var expected = {};
expected[schemaName] = joiObj;
try {
Joi.assert(content, expected);
} catch (err) {
if (!err.isJoi) {
throw err;
}
_throwJoiError(err);
};
// Return for convenience
return obj;
}
// Converts string `value` to a correct js object.
// `schemaName` refers to key in `conversion` object. It defines all
// conversion functions.
function convert(obj, schemaName) {
return _.reduce(obj, (memo, val, key) => {
var func = _getConversion(schemaName)
if (_.isFunction(func)) {
memo[key] = func(val);
} else {
memo[key] = val;
}
return memo;
}, {});
}
function _getConversion(name) {
var conversion = _.get(conversions, name);
if (!conversion) {
throw new Error('Conversion with name ' + name + ' was not found');
}
return conversion;
}
function _getSchema(name) {
var joiObj = _.get(schemas, name);
if (!joiObj) {
throw new Error('Schema with name ' + name + ' was not found');
}
return joiObj;
}
function _throwJoiError(err) {
// See https://github.com/hapijs/joi/blob/v7.2.3/API.md#errors
var msg = _.get(err, 'details.0.message') || 'Validation error';
var newErr = new Error(msg);
newErr.status = 400;
throw newErr;
}
export {
assert,
convert,
common,
schemas
};
| JavaScript | 0.999999 | @@ -715,17 +715,17 @@
8').max(
-3
+5
0, 'utf8
|
abe3c582db2d9e25d3812e2ce81c6e22380c4eba | fix test | client_test/stats/statsSpec.js | client_test/stats/statsSpec.js | define(["../DataHelper.js","stats/stats"], function(DataHelper) {
describe("stats", function() {
beforeEach(function() {
//Mock google maps modules
var dummy1 = angular.module('google-maps', []);
var placesDummy = angular.module('ngGPlaces', []);
placesDummy.factory("ngGPlacesAPI", function() {
return {};
});
});
beforeEach(angular.mock.module('dl.stats'));
it("Should load stats", inject(function($controller, $rootScope, Cache, Brewery, Rating, $filter) {
//Mocks
// spyOn(Cache, 'styles').andReturn([{_id:'style1', name:'Style 1'}]);
spyOn(Cache, 'styles').andCallFake(function(cb) {
cb([{_id:'style1', name:'Style 1'}]);
});
// spyOn(Cache, 'categories').andReturn([{_id:'cat1', name:'Cat 1'}]);
spyOn(Cache, 'categories').andCallFake(function(cb) {
cb([{_id:'cat1', name:'Cat 1'}]);
});
// spyOn(Brewery, 'query').andReturn([{_id:'brew1', name:'Brewery 1'}]);
spyOn(Brewery, 'query').andCallFake(function(cb) {
// cb([{_id:'brew1', name:'Brewery 1'},
// {
// _id: 'AndersonValleyBrewingCompany',
// name: "Anderson Valley Brewing Company",
// country: "Estados Unidos"
// },{
// "_id": "BrewDog",
// "name": "BrewDog",
// "country": "Reino Unido"
// }]);
cb(DataHelper.breweries);
});
// spyOn(Rating, 'query').andReturn([{_id:'rating1'}]);
spyOn(Rating, 'query').andCallFake(function(cb) {
cb(DataHelper.ratings);
});
var $scope = $rootScope.$new();
var statsController = $controller("StatsController", {$scope: $scope});
$rootScope.user = {name: "jose", _id:'User_ID'};
$rootScope.$digest();
expect($scope.styles['style1'].name).toBe('Style 1');
expect($scope.categories['cat1'].name).toBe('Cat 1');
expect($scope.breweries['Mikkeller'].name).toBe('Mikkeller');
expect($scope.myStats).toBeDefined();
expect($scope.myStats.maxABV.name).toBe('Schloss Eggenberg Samichlaus Classic');
expect($scope.myStats.minABV.name).toBe('Lindemans Pêcheresse');
expect($scope.myStats.maxScore.finalScore).toBe(49);
expect($scope.myStats.maxScore.beer.name).toBe('Cocoa Psycho');
expect($scope.myStats.minScore.finalScore).toBe(1);
expect($scope.myStats.minScore.beer.name).toBe('Bischofshof Hefe-Weissbier Dunkel');
var notNull = $filter("notNull");
expect(notNull).toBeDefined();
//Tables
expect($scope.styleTBConfig.rows).toBe($scope.myStats.styles);
expect($scope.styleAvgTBConfig.rows).toEqual(notNull($scope.myStats.styles,'avg.value'));
expect($scope.catTBConfig.rows).toBe($scope.myStats.categories);
expect($scope.catAvgTBConfig.rows).toEqual(notNull($scope.myStats.categories,'avg.value'));
expect($scope.breweriesTBConfig.rows).toBe($scope.myStats.breweries);
expect($scope.breweriesAvgTBConfig.rows).toEqual(notNull($scope.myStats.breweries,'avg.value'));
expect($scope.countryTBConfig.rows).toBe($scope.myStats.countries);
expect($scope.countryAvgTBConfig.rows).toEqual(notNull($scope.myStats.countries,'avg.value'));
//Charts
//Cantidad por estilo
expect($scope.styleChartConfig.series[0].data.length).toBe(10);
expect($scope.styleChartConfig.series[0].data[0]).toEqual(['18e',19]);
expect($scope.styleChartConfig.series[0].data[8]).toEqual(['14a',8]);
expect($scope.styleChartConfig.series[0].data[9]).toEqual(['stats.others',122]);
//Cantidad por categoria
expect($scope.categoryChartConfig.series[0].data.length).toBe(10);
expect($scope.categoryChartConfig.series[0].data[0]).toEqual(['18',66]);
expect($scope.categoryChartConfig.series[0].data[8]).toEqual(['05',7]);
expect($scope.categoryChartConfig.series[0].data[9]).toEqual(['stats.others',52]);
//Cantidad por pais
expect($scope.countryChartConfig.series[0].data.length).toBe(2);
expect($scope.countryChartConfig.series[0].data[0]).toEqual(['España',2]);
//Cantidad por location (google)
expect($scope.locationChartConfig.series[0].data.length).toBe(1);
expect($scope.locationChartConfig.series[0].data[0]).toEqual(['Plaça de Sant Pere, 9',2]);
//Cantidad por origen de la cerveza
expect($scope.originChartConfig.series[0].data.length).toBe(14);
expect($scope.originChartConfig.series[0].data[0]).toEqual(['Bélgica',89]);
//Cervezas por mes
expect($scope.beersPerMonth.xAxis.categories.length).toEqual(11);
expect($scope.beersPerMonth.series[0].data.length).toEqual(11);
expect($scope.beersPerMonth.series[0].data[0]).toEqual(1);
expect($scope.beersPerMonth.series[0].data[1]).toEqual(36);
}));
});
}); | JavaScript | 0.000002 | @@ -5002,17 +5002,17 @@
).toBe(1
-4
+0
);%0A
|
8c6f5c59220e6da56f7e62d73374ccee64c0f634 | Update lead styling | src/views/ClientCard.js | src/views/ClientCard.js | import React from 'react'
import { Link } from 'react-router-dom'
import styled from 'styled-components'
import numeral from 'numeral'
const StyledLead = styled.div`
width: 31%;
text-align: center;
padding: 20px;
border: 1px solid black;
border-radius: 5px;
margin: 10px;
`
const ClientCard = ({ id, name, address, monthly_rate }) => {
return (
<StyledLead>
<Link to={`/households/clients/${id}`}>
{name}
</Link>
<h3>
{address}
</h3>
<h3>
{numeral(monthly_rate).format('$0,0.00')}
</h3>
</StyledLead>
)
}
export default ClientCard
| JavaScript | 0 | @@ -278,16 +278,32 @@
: 10px;%0A
+ color: green;%0A
%60%0A%0Aconst
@@ -398,16 +398,43 @@
%3CLink
+ style=%7B%7B color: 'green' %7D%7D
to=%7B%60/h
@@ -472,14 +472,43 @@
-%7Bname%7D
+%3Ch2%3E%0A %7Bname%7D%0A %3C/h2%3E
%0A
|
7c7d533c56393e7d1b895b5d23bc0888050fa629 | Use while in CentsGauge.browse. | src/views/centsgauge.js | src/views/centsgauge.js | var CentsGauge = (function (containerID) {
function CentsGauge() {
ViewContextAndStyle.apply(this,arguments);
var _width = 400
, _height = 200
, twoPI = 2 * Math.PI
;
this.cvs.width = 400;
this.cvs.height = 200;
var centerX = this.cvs.width / 2
, centerY = this.cvs.height
, radius = 160
, circumference = twoPI * radius
, quadrantArc = circumference / 4
, dotRadius = 3
, zeroDotRadius = 5
, markStep = 50
;
Object.defineProperties(this, {
"width" : {
enumerable : true
, configurable : false
, get : function () {
return _width;
}
, set : function (val) {
_width = val;
this.cvs.width = _width;
centerX = this.cvs.width / 2;
}
}
, "height" : {
enumerable : true
, configurable : false
, get : function () {
return _height;
}
, set : function (val) {
_height = val;
this.cvs.height = _height;
centerY = this.cvs.height;
}
}
, "dotRadius" : {
value : dotRadius
, configurable : false
, enumerable : true
, writable : true
}
, "zeroDotRadius" : {
value : zeroDotRadius
, configurable : false
, enumerable : true
, writable : true
}
, "markStep" : {
value : markStep
, configurable : false
, enumerable : true
, writable : true
}
, "radius" : {
enumerable : true
, configurable : false
, get : function () {
return radius;
}
, set : function (r) {
radius = r;
circumference = twoPI * radius;
quadrantArc = circumference / 4;
}
}
});
Object.defineProperties(CentsGauge.prototype, {
"background" : {
value : function() {
var arc
, alfa
, x
, xs
, y
;
this.ctx.beginPath();
this.ctx.arc(centerX,centerY,10,0,twoPI,false);
this.ctx.arc(centerX,centerY - radius,zeroDotRadius,0,twoPI,true);
this.ctx.fillStyle = this.color;
this.ctx.fill();
for (arc = quadrantArc - markStep ; arc > 0 ; arc -= markStep) {
alfa = arc / radius;
x = centerX - radius * Math.cos(alfa);
xs = centerX + radius * Math.cos(alfa);
y = centerY - radius * Math.sin(alfa);
this.ctx.beginPath();
this.ctx.arc(x,y,dotRadius,0,twoPI,true);
this.ctx.arc(xs,y,dotRadius,0,twoPI,true);
this.ctx.fillStyle = this.color;
this.ctx.fill();
}
}
, enumerable : false
, configurable : false
, writable : false
}
, "run" : {
value : function() {
var arc = quadrantArc - (this.peek.cents * quadrantArc / 50)
, alfa = arc / radius
, x = centerX + radius * Math.cos(alfa)
, y = centerY - radius * Math.sin(alfa)
;
this.ctx.clearRect(0,0,this.cvs.width,this.cvs.height);
this.background();
this.ctx.font = this.noteFont;
this.ctx.fillStyle = this.color;
this.ctx.fillText(this.peek.note.name,20,50);
this.ctx.font = this.freqFont;
this.ctx.fillText(this.peek.frequency.toFixed(2) + " Hz",this.cvs.width-110,40);
this.ctx.beginPath();
this.ctx.moveTo(centerX,centerY);
this.ctx.lineTo(x,y);
this.ctx.strokeStyle = this.color;
this.ctx.stroke();
window.requestAnimationFrame(this.run.bind(this));
}
, enumerable : false
, configurable : false
, writable : false
}
, "update" : {
value : function (element) {
this.peek = element.peek;
}
, enumerable : false
, configurable : false
, writable : false
}
}
);
};
if (!this.instance) {
this.instance = new CentsGauge(containerID);
} else {
console.log("An instance of CentsGauge already exists.");
}
return this.instance;
}); | JavaScript | 0 | @@ -2154,16 +2154,41 @@
var arc
+ = quadrantArc - markStep
%0A
@@ -2537,69 +2537,22 @@
-for
+while
(arc
-= quadrantArc - markStep ; arc %3E 0 ; arc -= markStep
+%3E 0
) %7B%0A
@@ -2979,16 +2979,48 @@
.fill();
+%0A%0A arc -= markStep;
%0A
|
63c76144abfeeaaebc8757b7c8a5f3319704e383 | Update config | config/configuration.js | config/configuration.js | /**
* @file Defines the provider settings.
*
* Will set the path to Mongo, and applications id
* Most of the configuration can be done using system environment variables.
*/
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();
// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
default_port = 80;
}
// Exports configuration for use by app.js
module.exports = {
env: node_env,
port: process.env.PORT || default_port,
maxSize: process.env.MAX_SIZE || 50,
mongoUrl: process.env.MONGO_URL || process.env.MONGOLAB_URI,
redisUrl: process.env.REDIS_URL || process.env.REDISCLOUD_URL,
dropboxId: process.env.DROPBOX_API_ID,
dropboxSecret: process.env.DROPBOX_API_SECRET,
providerUrl: process.env.PROVIDER_URL,
appId: process.env.ANYFETCH_API_ID,
appSecret: process.env.ANYFETCH_API_SECRET,
concurrency: process.env.DROPBOX_CONCURRENCY || 5,
testTokens: {
oauth_token_secret: process.env.DROPBOX_TEST_OAUTH_TOKEN_SECRET,
oauth_token: process.env.DROPBOX_TEST_OAUTH_TOKEN,
uid: process.env.DROPBOX_TEST_UID,
},
testImagePath: process.env.DROPBOX_TEST_IMAGE_PATH, // Path to an image in the dropbox test account
testCursor: process.env.DROPBOX_TEST_CURSOR,
kue: {
attempts: 2,
backoff: {delay: 20 * 1000, type: 'fixed'}
},
opbeat: {
organizationId: process.env.OPBEAT_ORGANIZATION_ID,
appId: process.env.OPBEAT_APP_ID,
secretToken: process.env.OPBEAT_SECRET_TOKEN
}
};
| JavaScript | 0.000001 | @@ -1458,82 +1458,41 @@
%0A%0A
-kue: %7B%0A attempts: 2,%0A backoff: %7Bdelay: 20 * 1000, type: 'fixed'%7D%0A %7D
+retry: 2,%0A retryDelay: 20 * 1000
,%0A%0A
|
890659ee3ce3bd1ee5a270642b4521aee4699b46 | Update concurrency params | config/configuration.js | config/configuration.js | /**
* @file Defines the provider settings.
*
* Will set the path to Mongo, and applications id
* Most of the configuration can be done using system environment variables.
*/
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();
// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
default_port = 80;
}
// Exports configuration for use by app.js
module.exports = {
env: node_env,
port: process.env.PORT || default_port,
mongoUrl: process.env.MONGO_URL || process.env.MONGOLAB_URI,
redisUrl: process.env.REDIS_URL || process.env.REDISCLOUD_URL,
concurrency: process.env.GCONTACTS_CONCURRENCY || 1,
googleId: process.env.GCONTACTS_API_ID,
googleSecret: process.env.GCONTACTS_API_SECRET,
appId: process.env.ANYFETCH_API_ID,
appSecret: process.env.ANYFETCH_API_SECRET,
providerUrl: process.env.PROVIDER_URL,
testRefreshToken: process.env.GCONTACTS_TEST_REFRESH_TOKEN,
retry: 2,
retryDelay: 20 * 1000,
opbeat: {
organizationId: process.env.OPBEAT_ORGANIZATION_ID,
appId: process.env.OPBEAT_APP_ID,
secretToken: process.env.OPBEAT_SECRET_TOKEN
}
};
| JavaScript | 0.000001 | @@ -806,16 +806,82 @@
D_URL,%0A%0A
+ usersConcurrency: process.env.GCONTACTS_USERS_CONCURRENCY %7C%7C 1,%0A
concur
|
0104689c83cfd192c6eec767f674817d28572394 | Remove unnecessary style information to fix rendering issues in Firefox | js/containers/bottom-controls.js | js/containers/bottom-controls.js | import React, { Component } from 'react'
import pureRender from 'pure-render-decorator'
import { connect } from 'react-redux'
import * as actions from '../actions'
import AnimationButton from '../components/animation-button'
import Slider from 'rc-slider'
import ccLogoSrc from '../../images/cc-logo.png'
import screenfull from 'screenfull'
import { layerInfo } from '../map-layer-tiles'
import '../../css/bottom-controls.less'
import '../../css/settings-controls.less'
import 'rc-slider/assets/index.css'
import '../../css/slider.less'
function sliderDateFormatter(value) {
const date = new Date(value)
// .getMoth() returns [0, 11] range.
return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`
}
function sliderTickFormatter(valueMin, valueMax) {
const minDate = new Date(valueMin)
const maxDate = new Date(valueMax)
const minDecadeString = minDate.getFullYear().toString().substr(0, 2) + minDate.getFullYear().toString().substr(2, 1) + '0'
let minDecade = new Date(minDecadeString)
minDecade.setFullYear(minDecade.getUTCFullYear() + 10, 0, 1)
let tickMarks = {}
let decade = minDecade
while (decade <= maxDate) {
tickMarks[decade.getTime()] = { style: "tickMark", label: decade.getUTCFullYear() }
// increment decade by 10 years
decade.setFullYear(decade.getUTCFullYear() + 10, 0, 1)
}
return tickMarks
}
function toggleFullscreen() {
if (!screenfull.isFullscreen) {
screenfull.request()
} else {
screenfull.exit()
}
}
@pureRender
class BottomControls extends Component {
constructor(props) {
super(props)
this.state = {
fullscreen: false
}
this.handleTimeRange = this.handleTimeRange.bind(this)
this.handleMagRange = this.handleMagRange.bind(this)
this.handleBaseLayerChange = this.handleBaseLayerChange.bind(this)
this.handlePlateLayerChange = this.handlePlateLayerChange.bind(this)
this.handleAnimStep = this.handleAnimStep.bind(this)
this.handleAnimBtnClick = this.handleAnimBtnClick.bind(this)
}
componentDidMount() {
if (screenfull.enabled) {
document.addEventListener(screenfull.raw.fullscreenchange, () => {
this.setState({fullscreen: screenfull.isFullscreen})
})
}
}
handleTimeRange(value) {
const { setFilter } = this.props
setFilter('minTime', value[0])
setFilter('maxTime', value[1])
}
handleMagRange(value) {
const { setFilter } = this.props
setFilter('minMag', value[0])
setFilter('maxMag', value[1])
}
handleBaseLayerChange(event) {
const { setBaseLayer } = this.props
setBaseLayer(event.target.value)
}
handlePlateLayerChange(event) {
const { setPlatesVisible } = this.props
setPlatesVisible(event.target.checked)
}
handleAnimStep(newValue) {
const { filters, setFilter, setAnimationEnabled } = this.props
if (newValue > filters.get('maxTimeLimit')) {
newValue = filters.get('maxTimeLimit')
setAnimationEnabled(false)
}
setFilter('maxTime', newValue)
}
handleAnimBtnClick() {
const { animationEnabled, setAnimationEnabled } = this.props
setAnimationEnabled(!animationEnabled)
}
get dateMarks() {
const { filters } = this.props
const min = filters.get('minTimeLimit')
const max = filters.get('maxTimeLimit')
let marks = {
[min]: { style: "dateMarker", label: sliderDateFormatter(min) },
[max]: { style: "dateMarker", label: sliderDateFormatter(max) }
}
if (min != 0 && max != 0) {
// add tick marks for each decade between min and max
Object.assign(marks, sliderTickFormatter(min, max))
}
return marks
}
get mapLayerOptions() {
return layerInfo.map((m, idx) => <option key={idx} value={m.type}>{m.name}</option>)
}
get animSpeed() {
const { filters } = this.props
return (filters.get('maxTimeLimit') - filters.get('minTimeLimit')) / 15000
}
render() {
const { animationEnabled, filters, layers, mode } = this.props
const { fullscreen } = this.state
return (
<div>
<div className='bottom-controls'>
<img src={ccLogoSrc}/>
<AnimationButton ref='playButton' animationEnabled={animationEnabled} speed={this.animSpeed} value={filters.get('maxTime')}
onClick={this.handleAnimBtnClick} onAnimationStep={this.handleAnimStep}/>
<div className='center'>
<Slider className='slider-big' range min={filters.get('minTimeLimit')} max={filters.get('maxTimeLimit')} step={86400}
value={[filters.get('minTime'), filters.get('maxTime')]} onChange={this.handleTimeRange}
tipFormatter={sliderDateFormatter} marks={this.dateMarks}/>
</div>
{screenfull.enabled &&
<div className='fullscreen-icon' onClick={toggleFullscreen}>
</div>
}
</div>
<div className={'settings'}>
<i className='fa fa-gear'/>
<h2>Map Settings</h2>
<div className={'map-type-label'}>
Displayed map type
</div>
<div>
<select value={layers.get('base') } onChange={this.handleBaseLayerChange}>
{this.mapLayerOptions}
</select>
</div>
{mode !== '3d' &&
<div>
<label htmlFor='plate-border-box'>Show plate boundaries</label>
<input type='checkbox' checked={layers.get('plates') } onChange={this.handlePlateLayerChange} id='plate-border-box'/>
</div>
}
<div>
Show earthquakes with magnitude between <strong>{filters.get('minMag').toFixed(1)}</strong> and <strong>{filters.get('maxMag').toFixed(1)}</strong>
</div>
<div className={'mag-slider'}>
<Slider range min={0} max={10} step={0.1} value={[filters.get('minMag'), filters.get('maxMag')]}
onChange={this.handleMagRange} marks={{ 0: 0, 10: 10 }}/>
</div>
</div>
</div>
)
}
}
function mapStateToProps(state) {
return {
filters: state.get('filters'),
layers: state.get('layers'),
mode: state.get('mode'),
animationEnabled: state.get('animationEnabled')
}
}
export default connect(mapStateToProps, actions)(BottomControls)
| JavaScript | 0 | @@ -1193,27 +1193,8 @@
= %7B
- style: %22tickMark%22,
lab
@@ -3309,37 +3309,16 @@
%5Bmin%5D: %7B
- style: %22dateMarker%22,
label:
@@ -3363,29 +3363,8 @@
%5D: %7B
- style: %22dateMarker%22,
lab
|
faa0958623896b41df370c18e957a422618ddefb | Fix config | config/configuration.js | config/configuration.js | /**
* @file Defines the provider settings.
*
* Will set the path to Mongo, and applications id
* Most of the configuration can be done using system environment variables.
*/
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();
// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
default_port = 80;
}
// Exports configuration for use by app.js
module.exports = {
env: node_env,
port: process.env.PORT || default_port,
// Optional params
providerUrl: process.env.PROVIDER_URL,
appId: process.env.ANYFETCH_API_ID,
appSecret: process.env.ANYFETCH_API_SECRET,
opbeat: {
organization_id: process.env.OPBEAT_ORGANIZATION_ID,
app_id: process.env.OPBEAT_APP_ID,
secret_token: process.env.OPBEAT_SECRET_TOKEN,
silent: true
}
};
| JavaScript | 0.000007 | @@ -700,16 +700,118 @@
params%0A%0A
+ usersConcurrency: process.env.USERS_CONCURRENCY %7C%7C 1,%0A concurrency: process.env.CONCURRENCY %7C%7C 1,%0A%0A
provid
@@ -956,18 +956,17 @@
nization
-_i
+I
d: proce
@@ -1007,10 +1007,9 @@
app
-_i
+I
d: p
@@ -1048,10 +1048,9 @@
cret
-_t
+T
oken
@@ -1086,26 +1086,8 @@
OKEN
-,%0A silent: true
%0A %7D
|
39111728dba35a4788213680b6ce15614e8a1cd4 | add tests for the signup stage | test/acceptance/test.js | test/acceptance/test.js | var tape = require('tape')
var async = require('async')
var request = require('request')
var routerPort = null
function get(host, url, done){
request(host + url, function (error, response, body) {
if (!error) {
done(null, body, response)
}
else{
done(error)
}
})
}
function k8surl(path){
return 'http://127.0.0.1:8080' + path
}
function routerurl(path){
return 'http://127.0.0.1:' + routerPort + path
}
tape('can connect to the k8s api', function (t) {
request({
url:k8surl('/version'),
method: 'GET',
json: true
}, function(err, res, body){
if(err){
t.error(err)
return t.end()
}
t.equal(res.body.major, "1", "the major version is equal")
t.end()
})
})
tape('can read the exposed port for the route', function (t) {
request({
url:k8surl('/api/v1/namespaces/default/services/jenca-router-public'),
method:'GET',
json:true
}, function(err, res){
if(err){
t.error(err)
return t.end()
}
t.equal(typeof(res.body.spec.ports[0].nodePort), 'number', 'the node port is a number')
routerPort = res.body.spec.ports[0].nodePort
console.log('router port: ' + routerPort)
t.end()
})
})
tape('can read /v1/projects/version', function (t) {
request({
url:routerurl('/v1/projects/version'),
method:'GET'
}, function(err, res){
if(err){
t.error(err)
return t.end()
}
console.log('-------------------------------------------');
console.log(res.body)
t.equal(res.body.match(/^\d+\.\d+\.\d+$/) ? true : false, true, 'the version is a semver')
t.end()
})
})
tape('can read /v1/projects/version via the k8s proxy', function (t) {
request({
url:k8surl('/api/v1/proxy/namespaces/default/services/projects/v1/projects/version'),
method:'GET'
}, function(err, res){
if(err){
t.error(err)
return t.end()
}
t.equal(res.body.match(/^\d+\.\d+\.\d+$/) ? true : false, true, 'the version is a semver')
t.end()
})
})
tape('can signup to /v1/auth/signup', function (t) {
request({
url:routerurl('/v1/auth/signup'),
method:'POST',
json:true,
body:{
email:'bob@bob.com',
password:'apples'
}
}, function(err, res){
if(err){
t.error(err)
return t.end()
}
console.log('-------------------------------------------');
console.log(res.statusCode)
console.dir(res.body)
//t.equal(res.body.match(/^\d+\.\d+\.\d+$/) ? true : false, true, 'the version is a semver')
t.end()
})
})
| JavaScript | 0 | @@ -2080,32 +2080,98 @@
, function (t) %7B
+%0A%0A var emailaddress = 'bob' + (new Date().getTime()) + '@bob.com'
%0A request(%7B%0A
@@ -2266,21 +2266,20 @@
ail:
-'bob@bob.com'
+emailaddress
,%0A
@@ -2487,16 +2487,16 @@
usCode)%0A
-
cons
@@ -2510,24 +2510,220 @@
(res.body)%0A%0A
+ t.equal(res.statusCode, 201, 'the status code is 201')%0A t.equal(res.body.email, emailaddress, 'the email is the same')%0A t.equal(res.body.password, 'apples', 'the password is the same')%0A%0A
//t.equa
|
bb39f4059d5af4e46eb1d679f4797feb80330cc5 | move function off of scope | js/controllers/MainController.js | js/controllers/MainController.js | app.controller('MainController', ['$scope', function($scope) {
//CONTAINERS
$scope.creatures = [{
name: 'Player #1',
initiativeModifier: 0,
rolledInitiative: 0,
category: 'player',
},
{
name: 'Monster #1',
initiativeModifier: 0,
rolledInitiative: 0,
category: 'monster'
}
];
var numPlayers = 1;
var numNPCs = 0;
var numMonsters = 1;
$scope.showMoreInfo = false;
$scope.showTooltip = false;
//FUNCTIONS
$scope.addNew = function(typeIn) {
//Makes sure that added name has a proper number
var newName = "";
if (typeIn === "Player") {
numPlayers += 1;
newName = typeIn + " #" + numPlayers.toString();
}
else if (typeIn === "NPC") {
numNPCs += 1;
newName = typeIn + " #" + numNPCs.toString();
}
else {
numMonsters += 1;
newName = typeIn + " #" + numMonsters.toString();
}
$scope.creatures.push({
name: newName,
initiativeModifier: 0,
rolledInitiative: 0,
category: typeIn.toLowerCase()
});
}
//Returns number between 1 and 20, as though rolling 1d20. Using
//window.crypto because Math.random() seed may not have
//been random enough
$scope.roll1D20 = function() {
var array = new Uint32Array(1);
window.crypto.getRandomValues(array);
return 1 + (array[0] % 20);
}
//Sort the list of creatures
$scope.sortCreatures = function(creaturesIn) {
creaturesIn.sort(function(creature1, creature2) {
return creature2.rolledInitiative - creature1.rolledInitiative;
});
}
//Roll initiative, then reorder the creatures by their rolled value
$scope.rollInitiative = function() {
for (var i = 0; i < $scope.creatures.length; i++) {
var d20 = $scope.roll1D20();
$scope.creatures[i].rolledInitiative =
d20 + $scope.creatures[i].initiativeModifier;
}
$scope.sortCreatures($scope.creatures);
}
//Removes the creature from the list and decriments the number of that
//type of creature
$scope.removeCreature = function(creature) {
var index = $scope.creatures.indexOf(creature);
if (creature.category === "player") {
numPlayers -= 1;
}
else if (creature.category === "npc") {
numNPCs -= 1;
}
else {
numMonsters -= 1;
}
$scope.creatures.splice(index, 1);
}
}]); | JavaScript | 0.000001 | @@ -461,18 +461,16 @@
CTIONS%0D%0A
-%0D%0A
%09$scope.
@@ -1183,34 +1183,25 @@
h%0D%0A%09
-$scope.roll1D20 = function
+function roll1D20
() %7B
@@ -1708,23 +1708,16 @@
r d20 =
-$scope.
roll1D20
|
0f35317651df2bf3e6d4f666a65ffc5dff33d4ac | Update index.js | test/assets/js/index.js | test/assets/js/index.js | var accessToken = "db6b486f323c410a82d597f2e1ad6a5c",
subscriptionKey = "878cd060684e45099834389e8de74e63",
baseUrl = "https://api.api.ai/v1/",
$speechInput, // The input element, the speech box
$recBtn, // Toggled recording button value
recognition, // Used for accessing the HTML5 Speech Recognition API
messageRecording = " я слушаю...",
messageCouldntHear = "я не слышу",
messageInternalError = "пока я немогу говорить, сначала надо набратся ума",
messageSorry = "даже и сказать нечего";
$(document).ready(function() {
$speechInput = $("#speech");
$recBtn = $("#rec");
$speechInput.keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
send();
}
});
$recBtn.on("click", function(event) {
switchRecognition();
});
$(".debug__btn").on("click", function() {
$(this).next().toggleClass("is-active");
return false;
});
});
function switchRecognition() {
if (recognition) {
stopRecognition();
} else {
startRecognition();
}
}
function startRecognition() {
recognition = new webkitSpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.onstart = function(event) {
respond(messageRecording);
updateRec();
};
recognition.onresult = function(event) {
recognition.onend = null;
var text = "";
for (var i = event.resultIndex; i < event.results.length; ++i) {
text += event.results[i][0].transcript;
}
setInput(text);
stopRecognition();
};
recognition.onend = function() {
respond(messageCouldntHear);
stopRecognition();
};
recognition.lang = "ru-RUS";
recognition.start();
}
function stopRecognition() {
if (recognition) {
recognition.stop();
recognition = null;
}
updateRec();
}
function setInput(text) {
$speechInput.val(text);
send();
}
function updateRec() {
$recBtn.html(recognition ? "<i class='fa fa-square'>" : "<i class='fa fa-circle'>");
}
function send() {
var text = $speechInput.val();
$.ajax({
type: "POST",
url: baseUrl + "query/",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken,
"ocp-apim-subscription-key": subscriptionKey
},
data: JSON.stringify({q: text, lang: "en", sessionId: "somerandomthing"}),
success: function(data) {
prepareResponse(data);
},
error: function() {
respond(messageInternalError);
}
});
}
function prepareResponse(val) {
var spokenResponse = val.result.speech;
// actionResponse = val.result.action;
// respond()
respond(spokenResponse);
var debugJSON = JSON.stringify(val, undefined, 2);
debugRespond(debugJSON); // Print JSON to Debug window
}
function debugRespond(val) {
$("#response").text(val);
}
function respond(val) {
if (val == "") {
val = messageSorry;
}
if (val !== messageRecording) {
var msg = new SpeechSynthesisUtterance();
msg.voiceURI = "native";
msg.text = val;
msg.lang = "en-US";
window.speechSynthesis.speak(msg);
}
$("#spokenResponse").addClass("is-active").find(".spoken-response__text").html(val);
}
$("#bu2") function r() {
document.getElementById("demo").innerHTML = "";
}
| JavaScript | 0.000002 | @@ -3249,16 +3249,25 @@
%0A%0A$(
-%22#bu2%22)
+document).ready (
func
@@ -3330,9 +3330,10 @@
= %22%22;%0A%7D
+)
%0A
|
80d07f7e009e3068ca594da40b9d745ad2b5fdac | Update link in comment (#215) | test/automated-suite.js | test/automated-suite.js | /*
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict';
/* eslint-disable max-len, no-console, padded-blocks, no-multiple-empty-lines */
/* eslint-env node,mocha */
// These tests make use of selenium-webdriver. You can find the relevant
// documentation here: http://selenium.googlecode.com/git/docs/api/javascript/index.html
const path = require('path');
const seleniumAssistant = require('selenium-assistant');
const mochaUtils = require('sw-testing-helpers').mochaUtils;
require('geckodriver');
require('chromedriver');
require('chai').should();
const testServer = require('./server/index.js');
describe('Test SW-Toolbox', function() {
// Browser tests can be slow
this.timeout(100000);
// Selenium Tests are Flakey
this.retries(3);
// Driver is initialised to `null` to handle scenarios
// where the desired browser isn't installed / fails to load
// `null` allows afterEach a safe way to skip quiting the driver
let globalDriverReference = null;
let testServerURL;
before(function() {
return testServer.startServer(path.join(__dirname, '..'))
.then(portNumber => {
testServerURL = `http://localhost:${portNumber}`;
});
});
after(function() {
testServer.killServer();
});
afterEach(function() {
this.timeout(2 * 60 * 1000);
return seleniumAssistant.killWebDriver(globalDriverReference)
.then(() => {
globalDriverReference = null;
});
});
const queueUnitTest = browserInfo => {
it(`should pass all tests in ${browserInfo.getPrettyName()}`, () => {
return browserInfo.getSeleniumDriver()
.then(driver => {
globalDriverReference = driver;
return mochaUtils.startWebDriverMochaTests(
browserInfo.getPrettyName(),
globalDriverReference,
`${testServerURL}/test/browser-tests/`
);
})
.then(testResults => {
mochaUtils.prettyPrintResults(testResults);
if (testResults.failed.length > 0) {
throw new Error('Tests Failed');
}
});
});
};
const automatedBrowsers = seleniumAssistant.getLocalBrowsers();
automatedBrowsers.forEach(browserInfo => {
// Firefox before version 50 have issues that can't be duplicated outside
// of the selenium test runner.
if (browserInfo.getId() === 'firefox' &&
browserInfo.getVersionNumber() < 50) {
console.log(`Skipping ${browserInfo.getId()}: ${browserInfo.getRawVersionString()}`);
return;
}
// Opera has bad unregister API and it's driver is far from happy
// with latest builds.
if (browserInfo.getId() === 'opera') {
console.log(`Skipping ${browserInfo.getId()}: ${browserInfo.getRawVersionString()}`);
return;
}
// Block browsers w/o Service Worker support from being included in the
// tests on Travis
if (browserInfo.getId() !== 'firefox' &&
browserInfo.getId() !== 'chrome') {
console.log(`Skipping ${browserInfo.getId()}: ${browserInfo.getRawVersionString()}`);
return;
}
queueUnitTest(browserInfo);
});
});
| JavaScript | 0 | @@ -822,69 +822,42 @@
http
+s
://
-selenium.googlecode.com/git/docs/api/javascript/index.html
+github.com/SeleniumHQ/selenium
%0A%0Aco
|
377d2326e9b16a82edc80d9ce76902c659281e60 | Fix lint issues for strings in tests. | test/aws-credentials.js | test/aws-credentials.js | 'use strict';
const AwsCredentials = require('../lib/aws-credentials');
const should = require('should');
describe('AwsCredentials#saveAsIniFile', function () {
it("returns an error if credentials aren't given", function (done) {
const aws = new AwsCredentials();
aws.saveAsIniFile(null, 'profile', (error, data) => {
should(data).be.undefined();
error.toString().should.not.eql('');
done();
});
});
it("returns an error if a profile isn't given", function (done) {
const aws = new AwsCredentials();
aws.saveAsIniFile({}, null, (error, data) => {
should(data).be.undefined();
error.toString().should.not.eql('');
done();
});
});
it("returns an error if a $HOME path isn't resolved", function (done) {
const aws = new AwsCredentials();
delete process.env.HOME;
delete process.env.USERPROFILE;
delete process.env.HOMEPATH;
delete process.env.HOMEDRIVE;
aws.saveAsIniFile({}, 'profile', (error, data) => {
should(data).be.undefined();
error.toString().should.not.eql('');
done();
});
});
});
describe('AwsCredentials#resolveHomePath', function () {
beforeEach(function () {
delete process.env.HOME;
delete process.env.USERPROFILE;
delete process.env.HOMEPATH;
delete process.env.HOMEDRIVE;
});
it('returns null if $HOME, $USERPROFILE, and $HOMEPATH are undefined', function () {
should(AwsCredentials.resolveHomePath()).be.null();
});
it('uses $HOME if defined', function () {
process.env.HOME = 'HOME';
should(AwsCredentials.resolveHomePath()).eql('HOME');
});
it('uses $USERPROFILE if $HOME is undefined', function () {
process.env.USERPROFILE = 'USERPROFILE';
should(AwsCredentials.resolveHomePath()).eql('USERPROFILE');
});
it('uses $HOMEPATH if $HOME and $USERPROFILE are undefined', function () {
process.env.HOMEPATH = 'HOMEPATH';
should(AwsCredentials.resolveHomePath()).eql('C:/HOMEPATH');
});
it('uses $HOMEDRIVE with $HOMEPATH if defined', function () {
process.env.HOMEPATH = 'HOMEPATH';
process.env.HOMEDRIVE = 'D:/';
should(AwsCredentials.resolveHomePath()).eql('D:/HOMEPATH');
});
});
| JavaScript | 0 | @@ -157,25 +157,25 @@
n () %7B%0A it(
-%22
+'
returns an e
@@ -179,18 +179,20 @@
n error
-if
+when
credent
@@ -199,26 +199,22 @@
ials are
-n't given%22
+ null'
, functi
@@ -426,33 +426,33 @@
%7D);%0A %7D);%0A%0A it(
-%22
+'
returns an error
@@ -452,20 +452,20 @@
n error
-if a
+when
profile
@@ -471,18 +471,14 @@
e is
-n't given%22
+ null'
, fu
@@ -695,17 +695,17 @@
;%0A%0A it(
-%22
+'
returns
@@ -717,12 +717,12 @@
ror
-if a
+when
$HO
@@ -735,20 +735,19 @@
h is
-n't
+ un
resolved
%22, f
@@ -746,9 +746,9 @@
lved
-%22
+'
, fu
|
4e7b838cd06c445b99380fb80cb2b3e4d4c18762 | Order groups of user by desc created datetime | server/users.js | server/users.js | var express = require('express')
var router = express.Router()
var helper = require('./helper')
var parser = require('./parser')
/* GET get groups of user
* response -> [groups]/error
*/
//order: [['updatedAt', 'DESC']]
router.get('/groups', helper.isAuthenticated, function(req, res) {
var source = '[GET /users/groups]'
var models = req.app.get('models')
models.User.findOne({
where: {facebookId: req.session.facebookId},
attributes: {exclude: ['lastName','createdAt','updatedAt']},
include: [{
model: models.Group,
as: 'Groupings',
attributes: {exclude: ['createdAt','updatedAt']},
through: {attributes:[]},
include: [{
model: models.User,
as: 'Members',
attributes: {exclude: ['lastName','createdAt','updatedAt']},
through: {attributes:[]}
}]
}]
})
.then(info => {
info = info.toJSON()['Groupings']
Promise.all(
info.map(grouping => {
return models.Photo
.findOne({
attributes: ['link'],
where: {
groupId: grouping.id
}
})
.then(photo => {
if (photo) {
grouping.link = photo.link
} else {
grouping.link = ""
}
})
})
).then(() => {
helper.log(source, 'Success: Got groups of user with facebookId:' + req.session.facebookId)
res.send(info)
})
})
})
/* POST set session.facebookId. create user if user does not exist
* body -> {facebookId: facebookId of user, name: firstName of user}
* response -> success/error
*/
router.post('/', function(req, res) {
var source = '[POST /users/]'
var models = req.app.get('models')
var facebookId = req.body.facebookId
helper.getUser(models, facebookId)
.then(user => {
req.session.facebookId = facebookId
helper.log(source, 'Success: userId:' + user.id + ' logged in')
res.send(helper.success())
})
.catch(e => {
models.User.create({
firstName: req.body.name,
lastName: 'null',
facebookId: facebookId,
})
.then(user => {
req.session.facebookId = facebookId
helper.log(source, 'Success: userId:' + user.id + ' signed up')
res.send(helper.success())
})
.catch(e => {
helper.log(source, e)
res.status(500).send(helper.error(e))
})
})
})
/* POST set session.facebookId. create user if user does not exist
* body -> signed request from facebook
* response -> success/error
*/
router.post('/delete', function(req, res) {
var source = '[POST /users/delete]'
var models = req.app.get('models')
var data = parser(req.body.signed_request, process.env.PIXELECT_APP_SECRET)
helper.getUser(models, data.user_id)
.then(user => {
var userId = user.id
user.destroy()
.then(function(){
helper.log(source, 'Success: userId:' + user.id + '\'s account deleted')
res.send(helper.success())
})
.catch(e => {
helper.log(source, e)
res.send('Error deleting user account')
})
models.Group.destroy({
where:{
owner: userId
}
})
.then(function(){
helper.log(source, 'Success: userId:' + user.id + '\'s groups deleted')
})
.catch(e => {
helper.log(source, e)
res.send('Error deleting user\'s groups')
})
models.Photo.destroy({
where:{
userId: userId
}
})
.then(function(){
helper.log(source, 'Success: userId:' + user.id + '\'s photos deleted')
})
.catch(e => {
helper.log(source, e)
res.send('Error deleting user\'s photos')
})
models.Vote.destroy({
where:{
userId: userId
}
})
.then(function(){
helper.log(source, 'Success: userId:' + user.id + '\'s votes deleted')
})
.catch(e => {
helper.log(source, e)
res.send('Error deleting user\'s votes')
})
})
.catch(e => {
helper.log(source, e)
res.status(500).send(helper.error(e))
})
})
module.exports = router
| JavaScript | 0 | @@ -187,41 +187,8 @@
*/%0A
-//order: %5B%5B'updatedAt', 'DESC'%5D%5D%0A
rout
@@ -803,16 +803,92 @@
%5D%0A %7D%5D
+,%0A order: %5B%5B%7Bmodel: models.Group, as: 'Groupings'%7D, 'createdAt', 'DESC'%5D%5D
%0A %7D)%0A
|
41ecb8af7006508f299b42ba7b2f48699b5957df | fix getSequenceKey when there isn't a key | htdocs/components/15_TextSequence.js | htdocs/components/15_TextSequence.js | // $Revision$
Ensembl.Panel.TextSequence = Ensembl.Panel.Content.extend({
constructor: function () {
this.base.apply(this, arguments);
Ensembl.EventManager.register('dataTableRedraw', this, this.initPopups);
Ensembl.EventManager.register('ajaxComplete', this, this.sequenceKey);
Ensembl.EventManager.register('getSequenceKey', this, this.getSequenceKey);
},
init: function () {
var panel = this;
this.popups = {};
this.base();
this.initPopups();
this.elLk.popup = $([
'<div class="info_popup floating_popup">',
' <span class="close"></span>',
' <table cellspacing="0"></table>',
'</div>'
].join(''));
this.el.on('mousedown', '.info_popup', function () {
$(this).css('zIndex', ++Ensembl.PanelManager.zIndex);
}).on('click', '.info_popup .close', function () {
$(this).parent().hide();
}).on('click', 'pre a.sequence_info', function (e) {
var el = $(this);
var data = el.data();
var popup = data.link.data('popup');
var position, maxLeft, scrollLeft;
if (!data.position) {
data.position = el.position();
data.position.top += 0.75 * el.height();
data.position.left += 0.25 * el.width();
el.data('position', data.position);
}
if (popup) {
position = $.extend({}, data.position); // modifying data.position changes the stored value too, so make a fresh copy
maxLeft = $(window).width() - popup.width() - 20;
scrollLeft = $(window).scrollLeft();
if (position.left > maxLeft + scrollLeft) {
position.left = maxLeft + scrollLeft;
}
popup.show().css(position);
} else if (!data.processing) {
el.data('processing', true);
panel.getPopup(el);
}
el = null;
popup = null;
return false;
});
},
initPopups: function () {
var panel = this;
$('.info_popup', this.el).hide();
$('pre a.sequence_info', this.el).each(function () {
if (!panel.popups[this.href]) {
panel.popups[this.href] = $(this);
}
$(this).data('link', panel.popups[this.href]); // Store a single reference <a> for all identical hrefs - don't duplicate the popups
$(this).data('position', null); // Clear the position data
}).css('cursor', 'pointer');
},
getPopup: function (el) {
var data = el.data();
var popup = this.elLk.popup.clone().appendTo(this.el).draggable({ handle: 'tr:first' }).css(data.position);
function toggle(e) {
if (e.target.nodeName !== 'A') {
var tr = $(this).parent();
tr.siblings('.' + tr.attr('class')).toggle();
$(this).toggleClass('closed opened');
tr = null;
}
}
$.ajax({
url: el.attr('href'),
dataType: 'json',
context: this,
success: function (json) {
if (json.length) {
var classes = {};
var i, j, tbody, feature, caption, entry, childOf, cls, css, tag, row, maxLeft, scrollLeft;
for (i = 0; i < json.length; i++) {
tbody = $('<tbody>').appendTo(popup.children('table'));
feature = json[i];
for (j = 0; j < feature.length; j++) {
entry = feature[j].entry || [];
childOf = feature[j].childOf || '';
cls = (feature[j].cls || childOf).replace(/\W/g, '_');
css = childOf ? { paddingLeft: '12px' } : {};
tag = 'td';
if (typeof entry !== 'object') {
entry = [ entry ];
}
caption = typeof feature[j].caption === 'undefined' ? entry.shift() : feature[j].caption;
if (cls) {
classes[cls] = 1;
}
if (caption && entry.length) {
caption += ':';
}
if (j === 0) {
tag = 'th';
cls = 'header';
}
row = $('<tr>', { 'class': cls }).appendTo(tbody);
if (typeof caption !== 'undefined' && entry.length) {
row.append($('<' + tag + '>', { html: caption, css: css })).append($('<' + tag + '>', { html: entry.join(' ') }));
} else {
row.append($('<' + tag + '>', { html: (caption || entry.join(' ')), colspan: 2 }));
}
}
tbody.append('<tr style="display:block;padding-bottom:3px;">'); // Add padding to the bottom of the tbody
}
$('tbody', popup).each(function () {
var rows = $('tr', this);
var trs;
for (var c in classes) {
trs = rows.filter('.' + c);
if (trs.length > 2) {
$(':first', trs[0]).addClass('closed').on('click', toggle);
trs.not(':first').hide();
}
}
trs = null;
rows = null;
});
popup.css('zIndex', ++Ensembl.PanelManager.zIndex).show();
maxLeft = $(window).width() - popup.width() - 20;
scrollLeft = $(window).scrollLeft();
if (data.position.left > maxLeft + scrollLeft) {
popup.css('left', maxLeft + scrollLeft);
}
data.link.data('popup', popup); // Store the popup on the reference <a>
}
},
complete: function () {
el.data('processing', false);
popup = null;
}
});
},
sequenceKey: function () {
if (!$('.sequence_key', this.el).length) {
var key = Ensembl.EventManager.trigger('getSequenceKey');
if (!key) {
return;
}
var params = {};
$.each(key, function (id, k) {
$.extend(true, params, k);
});
var urlParams = $.extend({}, params, { variations: [], exons: [] });
$.each([ 'variations', 'exons' ], function () {
for (var p in params[this]) {
urlParams[this].push(p);
}
});
this.getContent(this.params.updateURL.replace(/sub_slice\?/, 'key?') + ';' + $.param(urlParams, true), this.el.parent().siblings('.sequence_key'));
}
},
getSequenceKey: function () {
Ensembl.EventManager.unregister('ajaxComplete', this);
return JSON.parse($('.sequence_key_json', this.el).html());
}
});
| JavaScript | 0.000003 | @@ -6780,16 +6780,25 @@
).html()
+ %7C%7C false
);%0A %7D%0A%7D
|
11b8f35728a139031af88a642a19fd517430d0eb | Fix a failing test due to random channel name collision | static/js/containers/ChannelPage_test.js | static/js/containers/ChannelPage_test.js | // @flow
import { assert } from "chai"
import PostList from "../components/PostList"
import { makeChannel } from "../factories/channels"
import { makeChannelPostList } from "../factories/posts"
import { actions } from "../actions"
import { SET_POST_DATA } from "../actions/post"
import IntegrationTestHelper from "../util/integration_test_helper"
import { channelURL } from "../lib/url"
describe("ChannelPage", () => {
let helper, renderComponent, channel, postList
beforeEach(() => {
channel = makeChannel()
postList = makeChannelPostList()
helper = new IntegrationTestHelper()
helper.getChannelStub.returns(Promise.resolve(channel))
helper.getPostsForChannelStub.returns(Promise.resolve(postList))
renderComponent = helper.renderComponent.bind(helper)
})
afterEach(() => {
helper.cleanup()
})
const renderPage = channel =>
renderComponent(channelURL(channel.name), [
actions.channels.get.requestType,
actions.channels.get.successType,
actions.postsForChannel.get.requestType,
actions.postsForChannel.get.successType,
SET_POST_DATA
])
it("should fetch postsForChannel, set post data, and render", async () => {
let [wrapper] = await renderPage(channel)
assert.deepEqual(wrapper.find(PostList).props().posts, postList)
})
it("should handle missing data gracefully", async () => {
let otherChannel = makeChannel()
let [wrapper] = await renderPage(otherChannel)
assert.equal(wrapper.text(), "")
})
})
| JavaScript | 0.00001 | @@ -1406,24 +1406,113 @@
keChannel()%0A
+ otherChannel.name = 'somenamethatshouldnevercollidebecauseitsaridiculouslylongvalue'%0A
let %5Bwra
|
f925d3cf6bfe66e2f925786d524ccd2a4a31431b | update test use the same template file | tests/func/applications/frameworkapp/common/mojits/ACMojit/controller.common.js | tests/func/applications/frameworkapp/common/mojits/ACMojit/controller.common.js | YUI.add('ActionContextMojit', function(Y, NAME) {
Y.namespace('mojito.controllers')[NAME] = {
/**
* Method corresponding to the 'index' action.
*
* @param ac {Object} The action context that provides access
* to the Mojito API.
*/
index: function(ac){
ac.done();
},
acMojit: function(ac) {
var test = ac.params.getFromUrl('test');
var greetingstring = "Hello Action Context Testing";
var data1 = {
greeting:greetingstring
}
var myCars=new Array("Saab","Volvo","BMW");
var data2 = {
mycars:myCars
}
if(test=="done1"){
ac.done(data1);
}else if(test=="flush1"){
ac.flush(data1);
ac.done();
}else if(test=="done2"){
ac.done(data1, 'json');
}else if(test=="flush2"){
ac.flush(data1, 'json');
ac.done();
}else if(test=="done3"){
ac.done(data1, {name: "json"});
}else if(test=="flush3"){
ac.flush(data1, {name: "json"});
ac.done();
}else if(test=="done4"){
ac.done(data2);
}else if(test=="flush4"){
ac.flush(data2);
ac.done();
}else if(test=="done5"){
ac.done(data2, 'json');
}else if(test=="flush5"){
ac.flush(data2, 'json');
ac.done();
}else if(test=="done6"){
ac.done({data:"Hello, world!--from done"});
}else if(test=="flush6"){
ac.flush({data:"Hello, world!--from flush"});
ac.done();
}else if(test=="done7"){
ac.done({data:"Hello, world!"}, 'json');
}else if(test=="flush7"){
ac.flush({data:"Hello, world!"}, 'json');
ac.done();
}else if(test=="done8"){
ac.done({data:"Hello, world!--from done"}, {view: {name: "mytemplate"}});
}else if(test=="done9"){
ac.done({ foo: null }, {view: {name: "mytemplate1"}});
}else if(test=="done10"){
ac.done({ foo: [ 1, 2, null, 4 ]}, {view: {name: "testdir/mytemplate1"}} );
}else if(test=="flush8"){
ac.flush({data:"Hello, world!--from flush"}, {view: {name: "mytemplate"}});
ac.done();
}else{
ac.flush("Hello, world!--from flush,");
ac.done("Hello, world!--from done");
}
}
};
}, '0.0.1', {requires: ['mojito', 'mojito-params-addon']});
| JavaScript | 0 | @@ -2244,32 +2244,40 @@
%7Bview: %7Bname: %22
+testdir/
mytemplate1%22%7D%7D);
|
6c93a40e7704f4837887d8a08ccfec8041ea19ae | Add the callback when stop_all() is call | soundbox.js | soundbox.js | /**
* SoundBox
* By Starbeamrainbowlabs
* License: MIT License
* A super simple JS library for playing sound effects and other audio.
*
* Note to self: When making a release, remember to update the version number at the bottom of the file!
*/
"use strict";
class SoundBox {
constructor() {
this.sounds = {}; // The loaded sounds and their instances
this.instances = []; // Sounds that are currently playing
this.default_volume = 1;
}
load(sound_name, path, callback) {
this.sounds[sound_name] = new Audio(path);
if(typeof callback == "function")
this.sounds[sound_name].addEventListener("canplaythrough", callback);
else
return new Promise((resolve, reject) => {
this.sounds[sound_name].addEventListener("canplaythrough", resolve);
this.sounds[sound_name].addEventListener("error", reject);
});
};
remove(sound_name) {
if(typeof this.sounds != "undefined")
delete this.sounds[sound_name];
};
play(sound_name, callback, volume = null) {
if(typeof this.sounds[sound_name] == "undefined") {
console.error("Can't find sound called '" + sound_name + "'.");
return false;
}
var soundInstance = this.sounds[sound_name].cloneNode(true);
soundInstance.volume = volume || this.default_volume;
soundInstance.play();
this.instances.push(soundInstance);
// Don't forget to remove the instance from the instances array
soundInstance.addEventListener("ended", () => {
let index = this.instances.indexOf(soundInstance, 1);
if(index != -1) this.instances.splice(index, 1);
});
// Attach the callback / promise
if(typeof callback == "function") {
soundInstance.addEventListener("ended", callback);
return true;
}
return new Promise((resolve, reject) => soundInstance.addEventListener("ended", resolve));
};
stop_all() {
// Pause all currently playing sounds
for (let instance of this.instances)
instance.pause();
this.instances = []; // Empty the instances array
}
}
SoundBox.version = "0.3.2";
| JavaScript | 0.001637 | @@ -1889,16 +1889,69 @@
tances)%0A
+%09%09 %09instance.dispatchEvent((new Event('ended')));%0A
%09%09%09insta
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.