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
|
---|---|---|---|---|---|---|---|
3fa74dd9b111660fab73bf35f6e66855fa5c01a9
|
Change PAGE_SIZE to 7
|
Resources/ui/common/responses/ResponseViewHelper.js
|
Resources/ui/common/responses/ResponseViewHelper.js
|
function ResponseViewHelper() {
var _ = require('lib/underscore')._;
var Question = require('models/question');
var QuestionView = require('ui/common/questions/QuestionView');
var PAGE_SIZE = 6;
var generateLabelTextForQuestion = function(question, errorText) {
text = '';
text += question.number() + ') ';
text += question['content'];
text += question.mandatory ? ' *' : '';
text += question.max_length ? ' [' + question.max_length + ']' : '';
text += question.max_value ? ' (<' + question.max_value + ')' : '';
text += question.min_value ? ' (>' + question.min_value + ')' : '';
text += errorText ? '\n' + errorText : '';
return text;
};
var resetErrors = function(questionViews) {
_(questionViews).each(function(fields, questionID) {
var question = Question.findOneById(questionID);
var labelText = generateLabelTextForQuestion(question);
fields.label.setText(labelText);
fields.label.setColor('#000000');
});
};
var displayErrors = function(responseErrors, questionViews) {
resetErrors(questionViews);
Ti.API.info("All the errors:" + responseErrors);
for (var answerErrors in responseErrors) {
Ti.API.info("Answer errors for:" + answerErrors);
for (var field in responseErrors[answerErrors]) {
var question_id = answerErrors;
var question = Question.findOneById(question_id);
var label = questionViews[question_id].label;
var labelText = generateLabelTextForQuestion(question, responseErrors[question_id][field]);
label.setText(labelText);
label.setColor("red");
Ti.API.info(responseErrors[question_id][field]);
}
}
};
var getQuestionViews = function(parent) {
var foo = {};
if(_(parent).isArray()) {
var views = _.chain(parent).map(function(scrollView) { return scrollView.children; }).flatten().value();
} else {
var views = parent.getChildren() || [];
}
_(views).each(function(view) {
if (view.type == 'question') {
foo[view.id] = {
'label' : _(view.children).first(),
'valueField' : _(view.children).last(),
'answerID' : view.answerID
};
Ti.API.info("label and value" + _(view.children).first() + _(view.children).last());
}
_(foo).extend(getQuestionViews(view));
});
return foo;
};
var paginate = function(questions, scrollableView, buttons, response) {
var pagedQuestions = _.chain(questions).groupBy(function(a, b) {
return Math.floor(b / PAGE_SIZE);
}).toArray().value();
_(pagedQuestions).each(function(questions, pageNumber) {
var questionsView = Ti.UI.createScrollView({
layout : 'vertical'
});
_(questions).each(function(question) {
var answer = response ? response.answerForQuestion(question.id) : undefined;
var questionView = new QuestionView(question, answer);
questionsView.add(questionView);
})
if (pageNumber + 1 === pagedQuestions.length) {
_(buttons).each(function(button){ questionsView.add(button); });
}
scrollableView.addView(questionsView);
});
};
var scrollToFirstErrorPage = function(scrollableView, errors){
var views = scrollableView.getViews();
scrollableView.scrollToView(views[0]);
};
var self = {
getQuestionViews : getQuestionViews,
displayErrors : displayErrors,
resetErrors : resetErrors,
generateLabelTextForQuestion : generateLabelTextForQuestion,
paginate : paginate,
scrollToFirstErrorPage : scrollToFirstErrorPage
};
return self;
}
module.exports = ResponseViewHelper;
|
JavaScript
| 0.99867 |
@@ -195,9 +195,9 @@
E =
-6
+7
;%0A%0A%09
|
42d0c757755297757f55873ab4bbb28775008395
|
add relevant files to the Grunt release task
|
Gruntfile.js
|
Gruntfile.js
|
module.exports = function (grunt) {
'use strict';
require('time-grunt')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ''
},
library: {
src: [
'bower/fold-to-ascii-js/fold-to-ascii.js',
'src/eHealth.couchQuery/eHealth.couchQuery.prefix',
'src/eHealth.couchQuery/eHealth.couchQuery.js',
'src/eHealth.couchQuery/directives/**/*.js',
'src/eHealth.couchQuery/filters/**/*.js',
'src/eHealth.couchQuery/services/**/*.js',
'src/eHealth.couchQuery/eHealth.couchQuery.suffix'
],
dest: 'dist/ehealth-couch-query.js'
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
jid: {
files: {
'dist/ehealth-couch-query.min.js': ['<%= concat.library.dest %>']
}
}
},
jshint: {
beforeConcat: {
options: {
// allow to have global 'use stricts'
// statements. strict statements will be removed
// anyway from the `remove_usestrict` task below
globalstrict: true,
globals: {
'angular': false,
'foldToASCII': false
}
},
src: ['gruntfile.js', 'src/eHealth.couchQuery/**/*.js']
},
afterConcat: {
src: [
'<%= concat.library.dest %>'
]
},
options: {
// options here to override JSHint defaults
globals: {
jQuery: true,
console: true,
module: true,
document: true,
angular: true
},
globalstrict: false
}
},
watch: {
options: {
livereload: true
},
files: [
'Gruntfile.js',
'src/**/*'
],
tasks: ['default']
},
remove_usestrict: {
dist: {
files: [{
expand: true,
src: 'dist/ehealth-couch-query.js'
}]
}
},
karma: {
unit: {
configFile: 'karma-unit.conf.js',
singleRun: true
}
},
bump: {
options: {
files: ['package.json', 'bower.json'],
tagName: '%VERSION%'
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-remove-usestrict');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-bump');
grunt.registerTask('default', [
'jshint:beforeConcat',
'concat',
'remove_usestrict',
'jshint:afterConcat',
'uglify',
'karma'
]);
grunt.registerTask('livereload', ['default', 'watch']);
};
|
JavaScript
| 0 |
@@ -2247,16 +2247,85 @@
json'%5D,%0A
+ commitFiles: %5B'package.json', 'bower.json', 'CHANGELOG.md'%5D,%0A
|
32c48d151b1abccd5aeaa7894987550bc3f48b6e
|
fix deltion of regimens
|
BetterMeService/models/regimen/regimen.model.server.js
|
BetterMeService/models/regimen/regimen.model.server.js
|
module.exports = function () {
var api = {
createRegimen: createRegimen,
findRegimenById: findRegimenById,
findAllRegimens: findAllRegimens,
getRegimensForCoach: getRegimensForCoach,
updateRegimen: updateRegimen,
addCadetteToRegimen: addCadetteToRegimen,
deleteRegimen: deleteRegimen,
removeCadetteFromRegimen: removeCadetteFromRegimen
};
var q = require('q');
var mongoose = require('mongoose');
var RegimenSchema = require('./regimen.schema.server')();
var RegimenModel = mongoose.model('RegimenModel', RegimenSchema);
return api;
function createRegimen(regimen) {
return RegimenModel.create(regimen);
}
function findRegimenById(regimenId) {
var d = q.defer();
RegimenModel
.findById(regimenId, function (err, regimen) {
if(err) {
d.reject(err);
} else {
d.resolve(regimen);
}
});
return d.promise;
}
function findAllRegimens() {
var d = q.defer();
RegimenModel.find({}).populate('_coach').exec(function (err, regimens) {
if(err) {
d.reject(err);
} else {
d.resolve(regimens);
}
});
return d.promise;
}
function getRegimensForCoach(coachId) {
var d = q.defer();
RegimenModel
.find({ _coach: coachId }, function (err, regimens) {
if(err) {
d.reject(err);
} else {
d.resolve(regimens);
}
});
return d.promise;
}
function updateRegimen(regimenId, regimen) {
var d = q.defer();
RegimenModel
.findOneAndUpdate({'_id': regimenId}, regimen, {new: true}, function (err, regimen) {
if(err) {
d.reject(err);
} else {
d.resolve(regimen);
}
});
return d.promise;
}
function addCadetteToRegimen(regimenId, userId) {
var d = q.defer();
RegimenModel
.findById(regimenId, function (err, regimen) {
if(err) {
d.reject(err);
} else {
regimen.cadettes.push(userId);
regimen.save();
d.resolve(regimen);
}
});
return d.promise;
}
function deleteRegimen(regimenId) {
var d = q.defer();
RegimenModel
.findOneAndRemove(regimenId, function (err, regimen) {
if(err) {
d.reject(err);
} else {
d.resolve(regimen);
}
});
return d.promise;
}
function removeCadetteFromRegimen(userId, regimenId) {
var d = q.defer();
RegimenModel
.findById(regimenId, function (err, regimen) {
if(err) {
d.reject(err);
} else {
var index = regimen.cadettes.indexOf(userId);
regimen.cadettes.splice(index, 1);
regimen.save();
d.resolve(regimen);
}
});
return d.promise;
}
};
|
JavaScript
| 0.000001 |
@@ -2248,16 +2248,22 @@
dRemove(
+%7B_id:
regimenI
@@ -2255,32 +2255,33 @@
(%7B_id: regimenId
+%7D
, function (err,
|
a651911af82521af4b9b3f4bb555087823b0e7bd
|
Change tips
|
assets/js/func.js
|
assets/js/func.js
|
const randomBackground = () => {
let bgImg = document.getElementById('bg')
let baseURL = 'https://source.unsplash.com/random/'
let resolution = `${screen.width}x${screen.height}`
let imageURL = baseURL.concat(resolution)
caches.match(imageURL).then(response => {
bgImg.src = response.url
}).catch(() => {
fetch(imageURL).then(response => {
if (response.ok) {
bgImg.src = response.url
caches.open('bg-next').then(cache => {
cache.put(imageURL, response)
})
}
})
})
fetch(imageURL).then(response => {
caches.open('bg-next').then(cache => {
cache.put(imageURL, response)
})
})
}
const vimLike = () => {
let home = document.getElementById('logo')
if (window.location.pathname == '/') { // In post list
let sections = document.getElementsByName('focusable')
let i = -1
window.addEventListener('keypress', event => {
if (event.key == 'j' && i < sections.length - 1) {
sections[++i].focus()
} else if (event.key == 'k') {
if (i == -1 || i == 0) {
i = 1
}
sections[--i].focus()
} else if (event.key == 'G') {
i = sections.length - 1
sections[i].focus()
} else if (event.key == 'o') {
sections[i].click()
} else if (event.key == 'u') {
home.click()
}
})
} else { // In article
let article = document.getElementById('article')
window.addEventListener('keypress', event => {
if (event.key == 'j') {
scrollBy(0, 27)
} else if (event.key == 'k') {
scrollBy(0, -27)
} else if (event.key == 'J') {
scrollBy({
top: 240,
behavior: "smooth"
})
} else if (event.key == 'K') {
scrollBy({
top: -240,
behavior: "smooth"
})
} else if (event.key == 'G') {
scroll({
top: article.offsetHeight,
behavior: "smooth"
})
} else if (event.key == 'u') {
home.click()
}
})
}
}
const lightUp = () => {
let bg = document.getElementById('bg')
bg.style.animation = "fadein 4s"
bg.style.opacity = 1
let article = document.getElementById('article')
if (article) {
article.classList.add('light')
}
greeting.style.color = "#eeeeee"
greeting.style.transition = "opacity 1.5s"
greeting.style.opacity = 0
}
window.desktopInit = () => {
randomBackground()
vimLike()
let inners = [
"It's my personal blog",
"Anyway..",
"Have a good time!!"
]
let greeting = document.getElementById('greeting')
greeting.style.transition = "color 1s"
let i = 0
if (sessionStorage.getItem('light')) {
lightUp()
} else {
greeting.addEventListener('click', () => {
if (i < inners.length) {
greeting.innerHTML = inners[i++]
}
if (i == inners.length) {
lightUp()
sessionStorage.setItem('light', true)
}
})
}
}
if (screen.width > 480) {
window.desktopInit()
}
// Register Service Worker
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js').then(registration => {
console.log('ServiceWorker registration successful.')
}).catch(error => {
console.log('ServiceWorker registration failed: ', error)
})
})
}
// Tips
console.log(
'If you are a loyal vimer, tell you a good news!\n' +
'You can actually use vim-like shortcuts to control this web page.\n\n' +
'j Scroll down / Select below\n' +
'k Scroll up / Select above\n' +
'o Open the selected post\n' +
'u Up to the home URL\n\n' +
'And in article pages, you can also:\n\n' +
'J Scroll down faster\n' +
'K Scroll up faster\n\n' +
'Happy Viming :)'
)
|
JavaScript
| 0 |
@@ -1678,17 +1678,17 @@
top: 2
-4
+5
0,%0A
@@ -1795,17 +1795,17 @@
top: -2
-4
+5
0,%0A
@@ -3510,16 +3510,17 @@
+%0A 'j
+-
Scroll
@@ -3549,16 +3549,17 @@
+%0A 'k
+-
Scroll
@@ -3586,16 +3586,17 @@
+%0A 'o
+-
Open th
@@ -3621,16 +3621,17 @@
+%0A 'u
+-
Up to t
@@ -3690,71 +3690,36 @@
also
-:%5Cn%5Cn' +%0A 'J Scroll down faster%5Cn' +%0A 'K S
+ press J/K to s
croll
-up
faster
-%5Cn
+.
%5Cn'
@@ -3733,14 +3733,19 @@
ppy
-Viming
+a good day!
:)'
|
18e60b178d92e3f17ee38ff07874b1d61f66e8ef
|
Improve documentation
|
cangraph.js
|
cangraph.js
|
/**
* Cangraph
*
* Graphing and function plotting for the HTML5 canvas. Main function plotting
* engine was taken from the link below and modified.
*
* @link http://www.javascripter.net/faq/plotafunctiongraph.htm
*/
(function ($) {
/**
* Constructor and initialization
*
* @class Cangraph
*
* @param {String} canvasId The canvas element to draw on
*/
function Cangraph(canvasId, options) {
var defaults = {
axes: {
xOffset: 0,
yOffset: 0,
scale: 40,
showNegativeX: true
}
};
var canvas;
this.set('canvasId', canvasId);
canvas = document.getElementById(this.canvasId);
this.set('canvas', canvas);
this.setContext();
// Merge defaults with passed in options
this.options = options || {};
this.options = $.extend(true, {}, defaults, this.options);
}
Cangraph.prototype.set = function (name, value) {
if (value === null || typeof value === 'undefined') {
console.log(name, 'is undefined or null!');
return false;
}
this[name] = value;
};
Cangraph.prototype.setContext = function () {
var context = this.canvas.getContext('2d');
this.set('context', context);
};
Cangraph.prototype.draw = function (fx) {
var axes={};
axes.x0 = .5 + .5*this.canvas.width; // x0 pixels from left to x=0
axes.y0 = .5 + .5*this.canvas.height; // y0 pixels from top to y=0
axes.scale = 40; // 40 pixels from x=0 to x=1
axes.doNegativeX = true;
this.showAxes(this.context, axes);
this.funGraph(this.context, axes, fx, "rgb(11,153,11)", 1);
};
Cangraph.prototype.funGraph = function (ctx,axes,func,color,thick) {
var xx, yy, dx=4, x0=axes.x0, y0=axes.y0, scale=axes.scale;
var iMax = Math.round((ctx.canvas.width-x0)/dx);
var iMin = axes.doNegativeX ? Math.round(-x0/dx) : 0;
ctx.beginPath();
ctx.lineWidth = thick;
ctx.strokeStyle = color;
for (var i=iMin;i<=iMax;i++) {
xx = dx*i; yy = scale*func(xx/scale);
if (i==iMin) ctx.moveTo(x0+xx,y0-yy);
else ctx.lineTo(x0+xx,y0-yy);
}
ctx.stroke();
};
Cangraph.prototype.showAxes = function (ctx,axes) {
var x0=axes.x0, w=ctx.canvas.width;
var y0=axes.y0, h=ctx.canvas.height;
var xmin = axes.doNegativeX ? 0 : x0;
ctx.beginPath();
ctx.strokeStyle = "rgb(128,128,128)";
ctx.moveTo(xmin,y0); ctx.lineTo(w,y0); // X axis
ctx.moveTo(x0,0); ctx.lineTo(x0,h); // Y axis
ctx.stroke();
};
// Attach object to global namespace
this.Cangraph = Cangraph;
}).call(this, $);
|
JavaScript
| 0.000004 |
@@ -378,16 +378,95 @@
draw on%0A
+ * @param %7BObject%7D options Allows us to change defaults upon instantiation%0A
*/%0A
@@ -718,16 +718,50 @@
anvas;%0A%0A
+ // Set canvas and context%0A
@@ -792,17 +792,16 @@
vasId);%0A
-%0A
@@ -885,17 +885,16 @@
anvas);%0A
-%0A
|
ed2248756a134e3a63e2b2562969428d2ed1dd44
|
Remove debug info from demo
|
demo/basics/app.js
|
demo/basics/app.js
|
window = self;
importScripts("https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js");
importScripts("https://cdn.rawgit.com/jashkenas/dbmonster/gh-pages/junkola-copied-from-ember.js");
importScripts("../../dist/global/vdom.js");
importScripts("../../dist/global/worker.js");
workerRender.ready(render);
function render() {
var TIMEOUT = 0;
ROWS = 100;
var body = document.getElementsByTagName('body')[0];
var table;
function redraw() {
var dbs = getDatabases();
var drawBefore = new Date();
newTable = template(dbs);
console.log("took", new Date() - drawBefore);
if(table) {
body.removeChild(table);
}
body.appendChild(newTable);
table = newTable;
setTimeout(redraw, TIMEOUT);
}
redraw();
}
function template(dbs) {
// <table>
var table = document.createElement("table");
table.className = "table table-striped latest-data";
// <tbody>
var tbody = document.createElement("tbody");
var i = 0, len = dbs.length;
for(; i < len; i++) {
var db = dbs[i];
var tr = document.createElement("tr");
// <td dbname>
var dbname = document.createElement("td");
dbname.className = "dbname";
dbname.appendChild(document.createTextNode(db.name));
tr.appendChild(dbname);
// <td query-count>
var queryCount = document.createElement("td");
queryCount.className = "query-count";
var queryCountSpan = document.createElement("span");
queryCountSpan.className = db.countClassName;
queryCountSpan.appendChild(document.createTextNode(db.queries.length));
queryCount.appendChild(queryCountSpan);
tr.appendChild(queryCount);
// <td Query >
for(var j = 0, jLen = db.topFiveQueries.length; j < jLen; j++) {
var query = db.topFiveQueries[j];
var queryTd = document.createElement("td");
queryTd.className = "Query " + query.className;
queryTd.appendChild(document.createTextNode(query.elapsed));
var popover = document.createElement("div");
popover.className = "popover left";
var popoverContent = document.createElement("div");
popoverContent.className = "popover-content";
popoverContent.appendChild(document.createTextNode(query.query));
popover.appendChild(popoverContent);
var arrow = document.createElement("div");
arrow.className = "arrow";
popover.appendChild(arrow);
queryTd.appendChild(popover);
tr.appendChild(queryTd);
}
tbody.appendChild(tr);
}
table.appendChild(tbody);
return table;
}
|
JavaScript
| 0 |
@@ -497,110 +497,31 @@
%0A%0A%09%09
-var drawBefore = new Date();%0A%09%09newTable = template(dbs);%0A%09%09console.log(%22took%22, new Date() - drawBefore
+newTable = template(dbs
);%0A%09
|
885e8deaafa22d9932ca9e77d5836dbb46aeee40
|
Correct path for toolkit node module
|
Gruntfile.js
|
Gruntfile.js
|
module.exports = function (grunt) {
grunt.initConfig({
// Builds Sass
sass: {
dev: {
files: {
'public/stylesheets/main.css': 'public/sass/main.scss',
'public/stylesheets/main-ie6.css': 'public/sass/main-ie6.scss',
'public/stylesheets/main-ie7.css': 'public/sass/main-ie7.scss',
'public/stylesheets/main-ie8.css': 'public/sass/main-ie8.scss',
'public/stylesheets/elements-page.css': 'public/sass/elements-page.scss',
'public/stylesheets/elements-page-ie6.css': 'public/sass/elements-page-ie6.scss',
'public/stylesheets/elements-page-ie7.css': 'public/sass/elements-page-ie7.scss',
'public/stylesheets/elements-page-ie8.css': 'public/sass/elements-page-ie8.scss',
'public/stylesheets/prism.css': 'public/sass/prism.scss',
},
options: {
includePaths: [
'govuk_modules/govuk_template/assets/stylesheets',
'govuk_modules/govuk_frontend_toolkit/stylesheets'
],
outputStyle: 'expanded',
imagePath: '../images'
}
}
},
// Copies templates and assets from external modules and dirs
copy: {
assets: {
files: [{
expand: true,
cwd: 'app/assets/',
src: ['**/*', '!sass/**'],
dest: 'public/'
}]
},
govuk: {
files: [{
expand: true,
cwd: 'node_modules/govuk_frontend_toolkit/govuk_frontend_toolkit',
src: '**',
dest: 'govuk_modules/govuk_frontend_toolkit/'
},
{
expand: true,
cwd: 'node_modules/govuk_template_mustache/',
src: '**',
dest: 'govuk_modules/govuk_template/'
}]
},
},
// workaround for libsass
replace: {
fixSass: {
src: ['govuk_modules/public/sass/**/*.scss'],
overwrite: true,
replacements: [{
from: /filter:chroma(.*);/g,
to: 'filter:unquote("chroma$1");'
}]
}
},
// Watches styles and specs for changes
watch: {
css: {
files: ['public/sass/**/*.scss'],
tasks: ['sass'],
options: { nospawn: true }
}
},
// nodemon watches for changes and restarts app
nodemon: {
dev: {
script: 'server.js',
options: {
ext: 'html, js'
}
}
},
concurrent: {
target: {
tasks: ['watch', 'nodemon'],
options: {
logConcurrentOutput: true
}
}
},
// Lint scss files
shell: {
multiple: {
command: [
'bundle',
'bundle exec govuk-lint-sass public/sass/elements/'
].join('&&')
}
}
});
[
'grunt-contrib-copy',
'grunt-contrib-watch',
'grunt-sass',
'grunt-nodemon',
'grunt-text-replace',
'grunt-concurrent',
'grunt-shell'
].forEach(function (task) {
grunt.loadNpmTasks(task);
});
grunt.registerTask(
'convert_template',
'Converts the govuk_template to use mustache inheritance',
function () {
var script = require(__dirname + '/lib/template-conversion.js');
script.convert();
grunt.log.writeln('govuk_template converted');
}
);
grunt.registerTask('default', [
'copy',
'convert_template',
'replace',
'sass',
'concurrent:target'
]);
grunt.registerTask(
'test_default',
'Test that the default task runs the app',
[
'copy',
'convert_template',
'replace',
'sass'
]
);
grunt.registerTask(
'lint',
'Use govuk-scss-lint to lint the sass files',
function() {
grunt.task.run('shell', 'lint_message');
}
);
grunt.registerTask(
'lint_message',
'Output a message once linting is complete',
function() {
grunt.log.write("scss lint is complete, without errors.");
}
);
grunt.registerTask(
'test',
'Lint the Sass files, then check the app runs',
function() {
grunt.task.run('lint', 'test_default', 'test_message');
}
);
grunt.registerTask(
'test_message',
'Output a message once the tests are complete',
function() {
grunt.log.write("scss lint is complete and the app runs, without errors.");
}
);
};
|
JavaScript
| 0 |
@@ -1476,38 +1476,16 @@
toolkit/
-govuk_frontend_toolkit
',%0A
|
3bb636df90ae7bbe5de640c30bd91a1a4b15fda5
|
Remove unnecessary if(1) from tester.js
|
test/utils/tester.js
|
test/utils/tester.js
|
const fs = require('fs');
const binarystream = require('binary');
const EventEmitter = require('events').EventEmitter;
const message = require('./lib/message');
const hexy = require('hexy').hexy;
const packets = fs.readFileSync('./packets.bin');
function nextPacketPos(b) {
console.log(hexy(b, { prefix: 'SEARCHING : ' }));
if (b.length < 10) {
console.log('TOO SHORT');
return -1;
}
for (i = 1; i < b.length; ++i) {
if (b.get(i) == 0x6c) {
console.log(
'possible match at ' + i,
b.get(i + 3),
b.get(i + 1),
b.get(i + 2),
b.get(i + 8)
);
if (
b.get(i + 3) == 1 &&
b.get(i + 1) < 5 &&
b.get(i + 2) < 4 &&
b.get(i + 8) < 9
)
return i;
}
}
return -1;
}
if (1) {
function readPacket(offset, data) {
if (offset > data.length) return;
console.log(' ======********====== START : ', offset, data.length);
console.log(
hexy(data.slice(offset, offset + 48 * 8), { prefix: 'BODY BODY: ' })
);
console.log(nextPacketPos(data.slice(offset, offset + 400)));
process.exit(0);
var len = data.readUInt32LE(offset);
var packet;
if (len > 100000) {
packet = data.slice(offset, data.length);
console.log(hexy(packet, { prefix: 'packet: ' }));
} else {
console.log('SLICING:', len, offset + 4, offset + len + 4);
packet = data.slice(offset + 4, offset + len + 4);
console.log(hexy(packet, { prefix: 'packet: ' }));
}
var dbus = new EventEmitter();
var stream = binarystream.parse(packet);
dbus.on('message', function(msg) {
console.log(msg);
console.log(
'==================== ',
data.length,
offset,
4 + packet.length
);
readPacket(offset + 4 + packet.length, data);
});
dbus.on('header', function(msg) {
console.log('header: ', msg);
if (msg.signature.length > 1) {
}
});
message.read.call(stream, dbus);
}
readPacket(0x02e0 + 15 * 9 - 1, packets);
}
|
JavaScript
| 0.000013 |
@@ -782,19 +782,8 @@
%0A%7D%0A%0A
-if (1) %7B%0A
func
@@ -810,26 +810,24 @@
et, data) %7B%0A
-
if (offset
@@ -850,18 +850,16 @@
return;%0A
-
consol
@@ -920,18 +920,16 @@
ength);%0A
-
consol
@@ -939,18 +939,16 @@
og(%0A
-
hexy(dat
@@ -1008,27 +1008,23 @@
Y: ' %7D)%0A
-
);%0A
-
-
console.
@@ -1077,18 +1077,16 @@
400)));%0A
-
proces
@@ -1096,18 +1096,16 @@
xit(0);%0A
-
var le
@@ -1133,26 +1133,24 @@
(offset);%0A
-
-
var packet;%0A
@@ -1149,18 +1149,16 @@
packet;%0A
-
if (le
@@ -1167,26 +1167,24 @@
%3E 100000) %7B%0A
-
packet =
@@ -1217,26 +1217,24 @@
ength);%0A
-
console.log(
@@ -1272,18 +1272,16 @@
' %7D));%0A
-
%7D else
@@ -1283,18 +1283,16 @@
else %7B%0A
-
cons
@@ -1351,18 +1351,16 @@
4);%0A
-
packet =
@@ -1402,26 +1402,24 @@
n + 4);%0A
-
-
console.log(
@@ -1459,22 +1459,18 @@
%7D));%0A
-
-
%7D%0A
-
var db
@@ -1494,18 +1494,16 @@
tter();%0A
-
var st
@@ -1535,26 +1535,24 @@
(packet);%0A
-
-
dbus.on('mes
@@ -1570,34 +1570,32 @@
tion(msg) %7B%0A
-
console.log(msg)
@@ -1592,26 +1592,24 @@
e.log(msg);%0A
-
console.
@@ -1619,18 +1619,16 @@
(%0A
-
'=======
@@ -1650,18 +1650,16 @@
,%0A
-
data.len
@@ -1663,18 +1663,16 @@
length,%0A
-
of
@@ -1683,18 +1683,16 @@
,%0A
-
4 + pack
@@ -1705,27 +1705,23 @@
gth%0A
-
);%0A
-
-
readPack
@@ -1758,26 +1758,22 @@
data);%0A
-
%7D);%0A
-
dbus.o
@@ -1796,34 +1796,32 @@
tion(msg) %7B%0A
-
-
console.log('hea
@@ -1834,18 +1834,16 @@
, msg);%0A
-
if (
@@ -1874,26 +1874,20 @@
) %7B%0A
-
%7D%0A
-
%7D);%0A
-
me
@@ -1921,15 +1921,11 @@
s);%0A
-
%7D%0A%0A
-
read
@@ -1958,14 +1958,12 @@
, packets);%0A
-%7D%0A
|
fc0bcc9db1e93a520706d21e8766ad38ac1fe00f
|
Add front end ajax call
|
public/src/bacon-0.0.1.js
|
public/src/bacon-0.0.1.js
|
(function() {
var metaKeyword = '';
var src = window.location.href;
var metas = document.getElementsByTagName('meta');
for (i in metas) {
console.log(metas[i]);
if (metas[i].name && metas[i].name.indexOf('keyword') > -1) {
metaKeyword += metas[i].content;
}
}
console.log(metaKeyword, src);
})();
|
JavaScript
| 0.000001 |
@@ -32,16 +32,59 @@
d = '';%0A
+ var baconServerUrl = %22http://127.0.0.1%22;%0A
var sr
@@ -109,16 +109,16 @@
n.href;%0A
-
var me
@@ -187,35 +187,8 @@
) %7B%0A
- console.log(metas%5Bi%5D);%0A
@@ -307,38 +307,901 @@
%0A
-console.log(metaKeyword, src);
+var divs = document.getElementsByClassName('baconLink');%0A %0A var defaultUrlArgs = %22?metaKeyword=%22 + encodeURIComponent(metaKeyword);%0A defaultUrlArgs += %22&src=%22 + encodeURIComponent(src);%0A %0A for (i in divs) %7B%0A var div = divs%5Bi%5D;%0A var args = defaultUrlArgs;%0A var width = div.getAttribute('width');%0A if (width) %7B%0A args += %22&width=%22 + width;%0A %7D%0A var height = div.getAttribute('width');%0A if (height) %7B%0A args += %22&height=%22 + height;%0A %7D%0A var keywords = div.getAttribute('keywords');%0A if (keywords) %7B%0A args += %22&keywords=%22 + encodeURIComponent(keywords);%0A %7D%0A %0A var xmlhttp = new XMLHttpRequest();%0A xmlhttp.open(%22GET%22, baconServerUrl + %22/getDonationLink%22 + args, true);%0A xmlhttp.onreadystatechange = function() %7B%0A if (xmlhttp.readyState == 4 && xmlhttp.status == 200) %7B%0A div.innerHTML = xmlhttp.responseText;%0A %7D%0A %7D%0A %7D
%0A%7D)(
|
b9cbc5b12cd9cadce17bf5c9d9b0300707c28d6f
|
add total_events or total_repos
|
archives/index.js
|
archives/index.js
|
'use strict';
var moment = require('moment-timezone');
var request = require('request');
var clc = require('cli-color');
module.exports = {
'init': function(config) {
function getBranchName() {
if (process.env.NODE_ENV === 'production') {
return 'master'
} else {
return 'staging'
}
}
function getFilename(type) {
var prefix = '';
if (type === 'events') {
prefix = 'events';
} else {
prefix = 'repos';
}
return prefix + '_archive_' + moment().format('YYYY_MM_DD_HHmmss') + '.json';
}
function getCommitMessage(type) {
return 'data: ' + type + ' archive on ' + moment().format('DD MMM YYYY h:mm a');
}
// NOTE: not required when the api provides /events/today and /repos/yesterday
function getCurrentDayData(response, type) {
var data = JSON.parse(response);
var today = moment(data.meta.generated_at);
var compare = type === 'events' ? 0 : 1;
var compareTime = type === 'events' ? 'start_time' : 'pushed_at';
var answer = {};
answer.meta = data.meta;
answer[ type ] = [];
data[ type ].forEach(function(element) {
if (today.diff(moment(element[ compareTime ]), 'days') === compare) {
answer[ type ].push(element);
}
})
return JSON.stringify(answer);
}
function storeToArchives(type, callback) {
var url = config.apiUrl + type;
request(url, function(err, msg, response) {
if (err) {
console.error(clc.red('Error: Reading We Build API '));
console.log(err);
console.log(msg);
callback(err);
}
var filename = getFilename(type);
var uri = 'https://api.github.com/repos/' + config.archives.githubRepoFolder + 'contents/' + type + '/v1/' + filename;
var token = new Buffer(process.env.BOT_TOKEN.toString()).toString('base64');
var content = new Buffer(getCurrentDayData(response, type)).toString('base64');
var body = {
'message': getCommitMessage(type),
'committer': {
'name': config.archives.committer.name,
'email': config.archives.committer.email
},
'content': content,
'branch': getBranchName(type)
};
request({
method: 'PUT',
uri: uri,
headers: {
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json',
'User-Agent': 'We Build ' + config.symbol + ' Archives',
'Authorization': 'Basic ' + token
},
body: JSON.stringify(body)
}, function(error, response) {
if (error) {
callback(error, null);
} else if (response.statusCode !== 201 && response.statusCode !== 200) {
callback(new Error(), JSON.parse(response.body).message);
} else {
var reply = 'Uploaded ' + filename + ' to Github ' + config.archives.githubRepoFolder + 'contents/' + type + ' in branch ' + getBranchName(type);
callback(null, reply);
}
})
});
}
function update() {
function createCallbackHandler(type) {
return function(error, reply) {
if (error) {
console.error(clc.red('Error: Cannot push to We Build Archives for ' + type + ': ' + error + '. Reply: ' + reply));
} else {
console.log(reply);
}
}
}
storeToArchives('repos', createCallbackHandler('repos'));
setTimeout(function() {
storeToArchives('events', createCallbackHandler('events'))
}, 5000)
}
return {
'getBranchName': getBranchName,
'getFilename': getFilename,
'getCommitMessage': getCommitMessage,
'getCurrentDayData': getCurrentDayData,
'storeToArchives': storeToArchives,
'update': update
}
}
}
|
JavaScript
| 0.000005 |
@@ -1320,16 +1320,76 @@
%7D)%0A%0A
+ answer.meta%5B'total_' + type%5D = answer%5B type %5D.length;%0A
re
|
d963188553258eec34ac5b634945e3ed522293f7
|
Update ripple.js
|
ripple.js
|
ripple.js
|
/***********************************************************************
* Ripple Directive
* Author: Brenton Klik
*
* Prerequisites:
* - AngularJS
* - $styleSheet (https://github.com/bklik/styleSheetFactory)
*
* Description:
* Creates the expanding/fading material design circle effect, that
* radiates from a click/touch's origin. Any element where this
* directive is used, should have the following CSS properties:
* - position: relative;
* - overflow: hidden; (recommended)
/**********************************************************************/
angular.module('rippleDirective', [])
.directive('ripple', ['$timeout', '$styleSheet', function($timeout, $styleSheet) {
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
// Tracks when a touch event fires before a mouse event.
var isTouch = false;
// The amount of time (in miliseconds) you want the animation to last.
var animationLength = 600;
// The document's stylesheet.
var styleSheet = $styleSheet.getStyleSheet();
// The prefix used by the browser for non-standard properties.
var prefix = $styleSheet.getPrefix();
// Sets the default color for the ripple.
var rippleColor = $attrs.ripplecolor || '#ccc';
// Add this directive's styles to the document's stylesheet.
$styleSheet.addCSSRule(styleSheet, '.ripple-effect',
'border-radius: 50%;' +
'position: absolute;'
, 1);
// Add the animation used to the directove to the document's stylesheet.
$styleSheet.addCSSKeyframes(styleSheet, 'ripple-effect',
'0% {' +
'opacity: .75;' +
'-'+prefix+'-transform: scale(0);' +
'transform: scale(0);' +
'}' +
'100% {' +
'opacity: 0;' +
'-'+prefix+'-transform: scale(1);' +
'transform: scale(1);' +
'}'
, 1);
// Add the element that will be animated to the element using this directive.
$element.append(angular.element('<div class="ripple-effect"></div>'));
// A method for removing the directive's style and animation.
var removeStyle = function() {
$element[0].querySelector('.ripple-effect').setAttribute('style', '');
};
// Causes the ripple effect to happen from the event's point of origin.
var makeRipple = function(event, isTouch) {
var root = $element[0];
var effect = root.querySelector('.ripple-effect');
var rootRect = root.getBoundingClientRect();
var size = (rootRect.width > rootRect.height) ? rootRect.width : rootRect.height;
var animation = 'ripple-effect ease-out ' + animationLength + 'ms forwards;';
var eventX = 0;
var eventY = 0;
if(isTouch) {
eventX = event.touches[0].clientX;
eventY = event.touches[0].clientY;
} else {
eventX = event.clientX;
eventY = event.clientY;
}
effect.setAttribute('style',
'background-color:' + rippleColor + ';' +
'width: ' + size + 'px;' +
'height: ' + size + 'px;' +
'top:' + ((eventY - rootRect.top) - (size / 2)) + 'px;' +
'left:' + ((eventX - rootRect.left) - (size / 2)) + 'px;' +
'-'+prefix+'-animation: ' + animation +
'animation: ' + animation
);
$timeout.cancel(removeStyle);
$timeout(removeStyle, animationLength);
};
// Creates a touchstart event handler which triggers a ripple.
$element.bind('touchstart', function(event) {
isTouch = true;
makeRipple(event, true);
});
// Creates a mousedown event handler, which triggers a ripple if
// the element wasn't 'touched' first.
$element.bind('mousedown', function(event) {
if(!isTouch) {
makeRipple(event, false);
}
isTouch = false;
});
}
}
}])
|
JavaScript
| 0 |
@@ -599,19 +599,38 @@
tive', %5B
+'styleSheetFactory'
%5D)%0A
-
%0A.direct
@@ -1016,17 +1016,94 @@
h = 600;
-
+%0A%0A // Fuse for removeing the style.%0A var removeTime = 0;
%0A%0A
@@ -1612,24 +1612,66 @@
us: 50%25;' +%0A
+ 'pointer-events: none;' +%0A
@@ -2786,32 +2786,379 @@
ent, isTouch) %7B%0A
+ // If the fuse is lit, reset the length of the fuse, otherwise, light the fuse%0A if(removeTime %3C= 0) %7B%0A removeTime = animationLength;%0A delayRemove();%0A %7D else %7B%0A removeTime = animationLength;%0A removeStyle();%0A %7D%0A%0A
@@ -4356,42 +4356,187 @@
- $timeout.cancel(removeStyle);%0A
+%7D;%0A%0A // Fuse function to remove the animation%0A var delayRemove = function() %7B%0A if(removeTime %3E 0) %7B%0A removeTime -= 100;%0A
@@ -4547,16 +4547,17 @@
+
$timeout
@@ -4561,38 +4561,104 @@
out(
-removeStyle, animationLength);
+delayRemove, 100);%0A %7D else %7B%0A removeStyle();%0A %7D
%0A
@@ -5242,8 +5242,9 @@
%7D%0A
-
%7D%5D)
+;
%0A
|
41d0af924843ae8d884df5dbe4dae32c393b27f6
|
Add open devtools option in main menu
|
dawn/main.js
|
dawn/main.js
|
// Electron entrypoint
'use strict';
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const Menu = electron.Menu;
let template = [
{
label: 'Dawn',
submenu: [
{
label: 'Quit',
accelerator: 'CommandOrControl+Q',
click: function() { app.quit(); }
}
]
},
{
label: 'Edit',
submenu: [
{
label: 'Cut',
accelerator: 'CommandOrControl+X',
role: 'cut'
},
{
label: 'Copy',
accelerator: 'CommandOrControl+C',
role: 'copy'
},
{
label: 'Paste',
accelerator: 'CommandOrControl+V',
role: 'paste'
}
]
}
];
let mainWindow;
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
app.on('ready', function() {
mainWindow = new BrowserWindow();
mainWindow.maximize();
mainWindow.loadURL('file://' + __dirname + '/static/index.html');
if (process.env.NODE_ENV === 'development') {
mainWindow.webContents.openDevTools(); // Open dev tools
}
mainWindow.on('closed', function() {
mainWindow = null;
});
let menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
});
|
JavaScript
| 0.000001 |
@@ -1046,24 +1046,77 @@
lopment') %7B%0A
+ // Open dev tools on startup in dev environment.%0A
mainWind
@@ -1145,34 +1145,16 @@
Tools();
- // Open dev tools
%0A %7D%0A m
@@ -1219,16 +1219,202 @@
%0A %7D);%0A%0A
+ // Add open devtools option to main menu.%0A template%5B0%5D.submenu.unshift(%7B%0A label: 'Open DevTools',%0A click: function() %7B%0A mainWindow.webContents.openDevTools();%0A %7D%0A %7D);%0A%0A
let me
|
bd42878d39a42486565548f0c4cc69fcf4e7ce69
|
Move function creation out of loop
|
test/web-platform.js
|
test/web-platform.js
|
"use strict";
/*global describe */
/*global it */
const assert = require("assert");
const fs = require("fs");
const URL = require("../lib/url").URL;
const uRLTestParser = require("./web-platform-tests/urltestparser");
const testCases = fs.readFileSync(__dirname + "/web-platform-tests/urltestdata.txt", { encoding: "utf-8" });
const urlTests = uRLTestParser(testCases);
describe("Web Platform Tests", function () {
const l = urlTests.length;
for (let i = 0; i < l; i++) {
const expected = urlTests[i];
it("Parsing: <" + expected.input + "> against <" + expected.base + ">", function () {
let url;
try {
url = new URL(expected.input, expected.base);
} catch (e) {
if (e instanceof TypeError && expected.protocol === ":") {
return;
}
throw e;
}
if (expected.protocol === ":" && url.protocol !== ":") {
assert.fail(null, null, "Expected URL to fail parsing");
}
assert.equal(url.href, expected.href, "href");
});
}
});
|
JavaScript
| 0 |
@@ -370,224 +370,45 @@
);%0A%0A
-describe(%22Web Platform Tests%22, function () %7B%0A const l = urlTests.length;%0A for (let i = 0; i %3C l; i++) %7B%0A const expected = urlTests%5Bi%5D;%0A%0A it(%22Parsing: %3C%22 + expected.input + %22%3E against %3C%22 + expected.base + %22%3E%22,
+function testURL(expected) %7B%0A return
fun
@@ -422,18 +422,16 @@
) %7B%0A
-
-
let url;
@@ -439,18 +439,14 @@
-
try %7B%0A
-
@@ -497,18 +497,16 @@
e);%0A
-
-
%7D catch
@@ -507,26 +507,24 @@
catch (e) %7B%0A
-
if (e
@@ -584,18 +584,16 @@
-
return;%0A
@@ -602,14 +602,10 @@
-
-
%7D%0A
-
@@ -615,31 +615,27 @@
hrow e;%0A
-
%7D%0A%0A
-
if (expe
@@ -685,26 +685,24 @@
:%22) %7B%0A
-
assert.fail(
@@ -705,18 +705,20 @@
ail(
-null, null
+url.href, %22%22
, %22E
@@ -748,79 +748,663 @@
sing
-%22);%0A %7D%0A%0A assert.equal(url.href, expected.href, %22href%22);%0A %7D
+, got %22 + url.href);%0A %7D%0A%0A /*assert.equal(url.protocol, expected.protocol, %22scheme%22);%0A assert.equal(url.hostname, expected.host, %22host%22);%0A assert.equal(url.port, expected.port, %22port%22);%0A assert.equal(url.pathname, expected.path, %22path%22);%0A assert.equal(url.search, expected.search, %22search%22);%0A assert.equal(url.hash, expected.hash, %22hash%22);*/%0A assert.equal(url.href, expected.href, %22href%22);%0A %7D;%0A%7D%0A%0Adescribe(%22Web Platform Tests%22, function () %7B%0A const l = urlTests.length;%0A for (let i = 0; i %3C l; i++) %7B%0A const expected = urlTests%5Bi%5D;%0A%0A it(%22Parsing: %3C%22 + expected.input + %22%3E against %3C%22 + expected.base + %22%3E%22, testURL(expected)
);%0A
|
9bf683703552d67eadaf3c08fb031e893613a561
|
Update extensions.js
|
extensions.js
|
extensions.js
|
!function() {
var DATE_EXT = {},
ARR_EXT = {},
OBJ_EXT = {};
var extendMe;
DATE_EXT.getLabel = (function() {
return function() {
if( isNaN( this.getTime() ) ) return NaN;
return (this.getMonth() + 1) + '/' + this.getDate() + '/' + this.getFullYear().toString().substr(2,2);
};
})();
DATE_EXT.isDate = (function() {
return function() {
return !isNaN( this.getTime() );
};
})();
DATE_EXT.getDelta = (function() {
return function(deltaDate) {
if( typeof deltaDate == "string" ) deltaDate = new Date(deltaDate);
if( !this.isDate() || !deltaDate.isDate() ) return false;
// Get # of milliseconds between dates
var delta = this.getTime() > deltaDate.getTime() ?
this.getTime() - deltaDate.getTime() :
deltaDate.getTime() - this.getTime();
// Set up some helper methods
var toSecond = function(d) { return Math.floor( d / 1000 ); }
, secondToMilli = function(d) { return d * 1000; }
, toMinute = function(d) { return Math.floor( d / 1000 / 60 ); }
, minuteToMilli = function(d) { return d * 1000 * 60; }
, toHour = function(d) { return Math.floor( d / 1000 / 60 / 60 ); }
, hourToMilli = function(d) { return d * 1000 * 60 * 60; }
, toDay = function(d) { return Math.floor( d / 1000 / 60 / 60 / 24 ); }
, dayToMilli = function(d) { return d * 1000 * 60 * 60 * 24; };
// Calculate Days and remove from total delta
var dayDelta = toDay( delta );
delta -= dayToMilli( dayDelta );
// Calculate hours, remove from total again
var hourDelta = toHour( delta );
delta -= hourToMilli( hourDelta );
// Calculate minutes
var minuteDelta = toMinute( delta );
delta -= minuteToMilli( minuteDelta );
// And seconds
var secondDelta = toSecond( delta );
delta -= secondToMilli( secondDelta );
// Leftover delta === millisecond time delta
// Return that shit!
return {
"days" : dayDelta,
"hours" : hourDelta,
"minutes" : minuteDelta,
"seconds" : secondDelta,
"milliseconds" : delta
};
};
})();
ARR_EXT.merge = (function() {
return function(arr) {
Array.prototype.push.apply(this, arr);
return this;
};
})();
OBJ_EXT.get = (function() {
var _get = function(obj, path) {
var key = path.shift(),
lb, rb, idx, val;
lb = key.lastIndexOf('[');
rb = key.slice(lb).indexOf(']');
if( lb !== -1 && rb !== -1 ) {
rb += lb;
var _idx = key.substring( lb + 1, rb );
idx = parseInt(_idx, 10) || _idx;
key = key.substring(0, lb);
if(!key) {
key = idx;
idx = false;
}
}
if (idx && obj[key]) {
val = obj[key][idx];
} else {
val = obj[key];
}
if(!!val && path.length > 0) return _get(val, path);
return val;
};
return function(loc) {
var locArr = loc.split('.');
var searchArr = [];
for ( var i = 0, l = locArr.length; i < l; i++ ) {
var piece = locArr[i].replace(/\[([a-z]+)\]/ig, '.$1');
if ( i === 0 && piece[i] === '.') piece = piece.slice(1);
searchArr.push.apply( searchArr, piece.split('.') );
}
return _get(this, searchArr);
};
})();
String.prototype.formatPhone = function() {
var numStr = this.replace(/[^0-9]/g, '');
var result = '';
while (numStr.length < 10) {
numStr += '_';
}
result += '(' + numStr.substring(0, 3) + ') ';
result += numStr.substring(3, 6) + '-';
result += numStr.substring(6, 10);
if (numStr.length > 10) {
result += ' x' + numStr.substring(11);
}
return result;
};
String.prototype.trim = function(str) {
var string = str || this,
changed = false;
if (string.substr(0, 1) == ' ') {
string = string.substring(1);
changed = true;
}
if (string.substr((string.length -1), 1) == ' ') {
string = string.substr(0, (string.length - 1));
changed = true;
}
return (changed ? this.trim(string) : string);
};
if (Object.defineProperty) {
extendMe = function(nativeObj, extensions) {
for (var extension in extensions) {
Object.defineProperty( nativeObj.prototype, extension, {
configurable : true,
writable : true,
enumerable : false,
value : extensions[extension]
});
}
};
} else {
extendMe = function(nativeObj, extensions) {
for (var extension in extensions) {
obj.prototype[extension] = extensions[extension];
}
};
}
extendMe(Date, DATE_EXT);
extendMe(Array, ARR_EXT);
extendMe(Object, OBJ_EXT);
}();
|
JavaScript
| 0.000002 |
@@ -4716,17 +4716,23 @@
-o
+nativeO
bj.proto
|
d5ee8380e285e906bfccc1a6654799d4a0cca0e3
|
Fix reading html entities
|
frontend/src/components/individual-recipe/CookRecipe.js
|
frontend/src/components/individual-recipe/CookRecipe.js
|
// Copyright 2020 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.
import Button from "react-bootstrap/Button";
import React, { Component } from "react";
import Tab from "react-bootstrap/Tab";
import Tabs from "react-bootstrap/Tabs";
import "./CookRecipe.css";
import navigatePrevious from "../../icons/navigate_previous.svg";
import Tutorial from "./Tutorial";
class CookRecipe extends Component {
constructor(properties) {
super(properties);
this.state = {
recipe: localStorage.getItem("recipe")
? JSON.parse(localStorage.getItem("recipe"))
: this.props.location.state.recipe,
};
}
render() {
const recipe = this.state.recipe;
return (
<div>
<Button variant="" className="back-btn" onClick={this.goBack}>
<img src={navigatePrevious} alt="go back to recommendations" />
Back
</Button>
<h1>{recipe.name}</h1>
<Tabs defaultActiveKey="tutorial">
<Tab eventKey="ingredients" title="Ingredients">
<div className="tab-content">
<ul>
{recipe.ingredients.map((item, i) => (
<li key={i}>{item}</li>
))}
</ul>
</div>
</Tab>
<Tab eventKey="full-recipe" title="Full recipe">
<div className="tab-content">
<ol>
{recipe.instructions.map((step, i) => (
<li key={i}>{step}</li>
))}
</ol>
</div>
</Tab>
<Tab eventKey="tutorial" title="Tutorial">
<div className="tab-content">
<Tutorial recipe={this.state.recipe} />
</div>
</Tab>
</Tabs>
</div>
);
}
goBack() {
window.history.back();
}
}
export default CookRecipe;
|
JavaScript
| 0.000047 |
@@ -1184,16 +1184,131 @@
recipe;%0A
+ const renderHTML = (rawHTML) =%3E React.createElement(%22div%22, %7B dangerouslySetInnerHTML: %7B __html: rawHTML %7D %7D);%0A%0A
retu
@@ -1782,20 +1782,32 @@
ey=%7Bi%7D%3E%7B
+renderHTML(
item
+)
%7D%3C/li%3E%0A
|
8782e83ece9e06c666370141ca1ad75e5ddb0346
|
set slide timing
|
assets/js/main.js
|
assets/js/main.js
|
$(document).ready(function() {
$('#email_signup_form').ajaxForm({
dataType: 'json',
success: processJson
});
function processJson(data){
if(data.status == true) { //form submission was successful
//alert(data.message + '/n' + data.status);
$('#signerupper').load('signups/messages.html #successkid').hide().fadeIn('slow');
}
else { //form submission was NIT successful
//alert(data.message + '/n' + data.status);
$('<span></span').insertAfter('.cta').load('signups/messages.html #msg-bubble', function() {
$('.msg').empty().append(data.message);
}).hide().fadeIn('slow');
$('#id_email_signup').keyup(function() {
$('.msg-bubble').fadeOut('fast');
});
}
}
$(function(){
$('#maximage').maximage({
cycleOptions: {
fx: 'fade',
speed: 1000, // Has to match the speed for CSS transitions in jQuery.maximage.css (lines 30 - 33)
timeout: 0, // 0 for stop 6000 live
prev: '#arrow_left',
next: '#arrow_right',
pause: 1,
before: function(last,current){
if(!$.browser.msie){
// Start HTML5 video when you arrive
if($(current).find('video').length > 0) $(current).find('video')[0].play();
}
},
after: function(last,current){
if(!$.browser.msie){
// Pauses HTML5 video when you leave it
if($(last).find('video').length > 0) $(last).find('video')[0].pause();
}
//var elementht = $('#bigslide').height();
//var pageht = $('.page-wrap').height();
//alert('element :' + elementht + '\n page:'+ pageht);
}
},
onFirstImageLoaded: function(){
jQuery('#cycle-loader').hide();
jQuery('#maximage').fadeIn('fast');
jQuery('#aheadlist').cycle({
fx: 'fade',
speed: 300,
timeout: 300,
});
}
});
// Helper function to Fill and Center the HTML5 Video
jQuery('video,object').maximage('maxcover');
// To show it is dynamic html text
jQuery('.in-slide-content').delay(1200).fadeIn();
});
$(function(){
$('input:text').each(function(){
var txtval = $(this).val();
$(this).focus(function(){
$(this).val('').css('color', 'black')
});
$(this).blur(function(){
if($(this).val() == ""){
$(this).val(txtval).css('color', '#bab9b9');
}
});
});
});
});
|
JavaScript
| 0.000001 |
@@ -1177,16 +1177,19 @@
imeout:
+600
0, // 0
|
1a3d0116d64172faf741eb1fd4844cc9690e7ed7
|
Fix test on node v8
|
spec/unit/xlsx/xform/test-xform-helper.js
|
spec/unit/xlsx/xform/test-xform-helper.js
|
const {Readable} = require('stream');
const {cloneDeep, each} = require('../../../utils/under-dash');
const CompyXform = require('./compy-xform');
const parseSax = verquire('utils/parse-sax');
const XmlStream = verquire('utils/xml-stream');
const BooleanXform = verquire('xlsx/xform/simple/boolean-xform');
function getExpectation(expectation, name) {
if (!expectation.hasOwnProperty(name)) {
throw new Error(`Expectation missing required field: ${name}`);
}
return cloneDeep(expectation[name]);
}
// ===============================================================================================================
// provides boilerplate examples for the four transform steps: prepare, render, parse and reconcile
// prepare: model => preparedModel
// render: preparedModel => xml
// parse: xml => parsedModel
// reconcile: parsedModel => reconciledModel
const its = {
prepare(expectation) {
it('Prepare Model', () =>
new Promise(resolve => {
const model = getExpectation(expectation, 'initialModel');
const result = getExpectation(expectation, 'preparedModel');
const xform = expectation.create();
xform.prepare(model, expectation.options);
expect(cloneDeep(model, false)).to.deep.equal(result);
resolve();
}));
},
render(expectation) {
it('Render to XML', () =>
new Promise(resolve => {
const model = getExpectation(expectation, 'preparedModel');
const result = getExpectation(expectation, 'xml');
const xform = expectation.create();
const xmlStream = new XmlStream();
xform.render(xmlStream, model, 0);
// console.log(xmlStream.xml);
// console.log(result);
expect(xmlStream.xml).xml.to.equal(result);
resolve();
}));
},
'prepare-render': function(expectation) {
// when implementation details get in the way of testing the prepared result
it('Prepare and Render to XML', () =>
new Promise(resolve => {
const model = getExpectation(expectation, 'initialModel');
const result = getExpectation(expectation, 'xml');
const xform = expectation.create();
const xmlStream = new XmlStream();
xform.prepare(model, expectation.options);
xform.render(xmlStream, model);
expect(xmlStream.xml).xml.to.equal(result);
resolve();
}));
},
renderIn(expectation) {
it('Render in Composite to XML ', () =>
new Promise(resolve => {
const model = {
pre: true,
child: getExpectation(expectation, 'preparedModel'),
post: true,
};
const result = `<compy><pre/>${getExpectation(
expectation,
'xml'
)}<post/></compy>`;
const xform = new CompyXform({
tag: 'compy',
children: [
{
name: 'pre',
xform: new BooleanXform({tag: 'pre', attr: 'val'}),
},
{name: 'child', xform: expectation.create()},
{
name: 'post',
xform: new BooleanXform({tag: 'post', attr: 'val'}),
},
],
});
const xmlStream = new XmlStream();
xform.render(xmlStream, model);
// console.log(xmlStream.xml);
expect(xmlStream.xml).xml.to.equal(result);
resolve();
}));
},
parseIn(expectation) {
it('Parse within composite', () =>
new Promise((resolve, reject) => {
const xml = `<compy><pre/>${getExpectation(
expectation,
'xml'
)}<post/></compy>`;
const childXform = expectation.create();
const result = {pre: true};
result[childXform.tag] = getExpectation(expectation, 'parsedModel');
result.post = true;
const xform = new CompyXform({
tag: 'compy',
children: [
{
name: 'pre',
xform: new BooleanXform({tag: 'pre', attr: 'val'}),
},
{name: childXform.tag, xform: childXform},
{
name: 'post',
xform: new BooleanXform({tag: 'post', attr: 'val'}),
},
],
});
xform
.parse(parseSax(Readable.from(xml)))
.then(model => {
// console.log('parsed Model', JSON.stringify(model));
// console.log('expected Model', JSON.stringify(result));
// eliminate the undefined
const clone = cloneDeep(model, false);
// console.log('result', JSON.stringify(clone));
// console.log('expect', JSON.stringify(result));
expect(clone).to.deep.equal(result);
resolve();
})
.catch(reject);
}));
},
parse(expectation) {
it('Parse to Model', () =>
new Promise((resolve, reject) => {
const xml = getExpectation(expectation, 'xml');
const result = getExpectation(expectation, 'parsedModel');
const xform = expectation.create();
xform
.parse(parseSax(Readable.from(xml)))
.then(model => {
// eliminate the undefined
const clone = cloneDeep(model, false);
// console.log('result', JSON.stringify(clone));
// console.log('expect', JSON.stringify(result));
expect(clone).to.deep.equal(result);
resolve();
})
.catch(reject);
}));
},
reconcile(expectation) {
it('Reconcile Model', () =>
new Promise(resolve => {
const model = getExpectation(expectation, 'parsedModel');
const result = getExpectation(expectation, 'reconciledModel');
const xform = expectation.create();
xform.reconcile(model, expectation.options);
// eliminate the undefined
const clone = cloneDeep(model, false);
expect(clone).to.deep.equal(result);
resolve();
}));
},
};
function testXform(expectations) {
each(expectations, expectation => {
const tests = getExpectation(expectation, 'tests');
describe(expectation.title, () => {
each(tests, test => {
its[test](expectation);
});
});
});
}
module.exports = testXform;
|
JavaScript
| 0.000002 |
@@ -21,16 +21,25 @@
equire('
+readable-
stream')
|
96610753cfe0b9dd850d7863205f2bfc67ce2686
|
change test setup
|
Gruntfile.js
|
Gruntfile.js
|
module.exports = function (grunt) {
var browsers = [
// chrome
{
browserName: "chrome",
platform: "Windows XP",
version: "26.0"
}, {
browserName: "chrome",
platform: "OS X 10.9",
version: "38.0"
}, {
browserName: "chrome",
platform: "Windows 8.1",
version: "40.0"
}, {
browserName: "chrome",
platform: "Linux",
version: "30.0"
},
// firefox
{
browserName: "firefox",
platform: "Windows XP",
version: "10.0"
}, {
browserName: "firefox",
platform: "Windows 7",
version: "17.0"
}, {
browserName: "firefox",
platform: "Linux",
version: "35.0"
},
// internet explorer
{
browserName: "internet explorer",
platform: "Windows XP",
version: "8.0"
}, {
browserName: "internet explorer",
platform: "Windows 7",
version: "9.0"
}, {
browserName: "internet explorer",
platform: "Windows 8",
version: "10.0"
}, {
browserName: "internet explorer",
platform: "Windows 8.1",
version: "11.0"
},
// opera
{
browserName: "opera",
platform: "Windows 7",
version: "11"
}, {
browserName: "opera",
platform: "Linux",
version: "12"
// safari
}, {
browserName: "safari",
platform: "Windows 7",
version: "5.1"
}, {
browserName: "safari",
platform: "OS X 10.8",
version: "6.0"
},
// apple
{
browserName: "iphone",
platform: "OS X 10.10",
deviceName: "iPhone Simulator",
"device-orientation": "portrait",
version: "6.1"
}, {
browserName: "iphone",
platform: "OS X 10.10",
deviceName: "iPad Simulator",
"device-orientation": "portrait",
version: "6.0"
}, {
browserName: "iphone",
platform: "OS X 10.10",
deviceName: "iPhone Simulator",
"device-orientation": "portrait",
version: "7.1"
}, {
browserName: "iphone",
platform: "OS X 10.10",
deviceName: "iPad Simulator",
"device-orientation": "portrait",
version: "8.1"
},
// android
{
browserName: "android",
platform: "Linux",
deviceName: "Samsung Galaxy S2 Emulator",
version: "4.2"
}, {
browserName: "android",
platform: "Linux",
deviceName: "Motorola Droid Razr Emulator",
version: "4.0"
}, {
browserName: "android",
platform: "Linux",
deviceName: "Samsung Galaxy S3 Emulator",
version: "4.1"
}];
grunt.initConfig({
jshint: {
files: [
"Gruntfile.js",
"src/**/*.js",
"spec/**/*.js"
]
},
jasmine: {
src: "src/**/*.js",
options: {
vendor: [
"jasmine-standalone/lib/jasmine-jquery-2.0.7/jquery.js",
"jasmine-standalone/lib/jasmine-jquery-2.0.7/jasmine-jquery.js",
"jasmine-standalone/phantomjs-config.js"
],
specs: "spec/**/*.js"
}
},
connect: {
server: {
options: {
base: "",
port: 9999
}
}
},
"saucelabs-jasmine": {
all: {
options: {
urls: ["http://127.0.0.1:9999/jasmine-standalone/SpecRunner.html"],
build: process.env.TRAVIS_JOB_ID,
browsers: browsers,
testname: "lazymaltbeer.js tests",
"max-duration": 60,
tags: ["master"]
}
}
},
watch: {}
});
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-contrib-jasmine");
grunt.loadNpmTasks("grunt-saucelabs");
grunt.loadNpmTasks("grunt-contrib-connect");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.registerTask("server", ["connect", "watch"]);
grunt.registerTask("test-jshint", ["jshint"]);
grunt.registerTask("test-jasmine", ["jasmine"]);
grunt.registerTask("test-browsers", ["connect", "saucelabs-jasmine"]);
grunt.registerTask("test-all", ["jshint", "jasmine", "connect", "saucelabs-jasmine"]);
grunt.registerTask("travis-ci", ["test-all"]);
grunt.registerTask("default", ["test-jshint", "test-jasmine"]);
};
|
JavaScript
| 0.000001 |
@@ -2599,34 +2599,36 @@
deviceName: %22iP
-ad
+hone
Simulator%22,%0A
|
898b320d2fac46aaadac9eb9df5b1bd79a426102
|
correct grunt test target
|
Gruntfile.js
|
Gruntfile.js
|
'use strict';
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
// project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
config: {
sources: 'lib',
tests: 'test',
dist: 'dist'
},
eslint: {
check: {
src: [
'{lib,test}/**/*.js'
]
},
fix: {
src: [
'{lib,test}/**/*.js'
],
options: {
fix: true
}
}
},
mochaTest: {
test: {
options: {
reporter: 'spec',
require: [
'./test/expect.js'
]
},
src: ['test/**/*.js']
},
watch: {
options: {
noFail: true,
reporter: 'spec',
require: [
'./test/expect.js'
]
},
src: [ 'test/**/*.js' ]
}
},
release: {
options: {
tagName: 'v<%= version %>',
commitMessage: 'chore(project): release v<%= version %>',
tagMessage: 'chore(project): tag v<%= version %>'
}
},
watch: {
test: {
files: [
'<%= config.sources %>/**/*.js',
'<%= config.tests %>/spec/**/*.js'
],
tasks: [ 'mochaTest:watch' ]
}
}
});
// tasks
grunt.registerTask('test', [ 'mochaTest' ]);
grunt.registerTask('auto-test', [ 'mochaTest:watch', 'watch:test' ]);
grunt.registerTask('default', [ 'eslint:check', 'test' ]);
};
|
JavaScript
| 0.000005 |
@@ -504,36 +504,38 @@
haTest: %7B%0A
-test
+single
: %7B%0A opti
@@ -1354,16 +1354,23 @@
ochaTest
+:single
' %5D);%0A%0A
|
1113b8a14181db4703c8bb0ce98f891ba770f3bc
|
Make Grunt tasks alphabetical
|
Gruntfile.js
|
Gruntfile.js
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
bump: {
options: {
files: ['package.json'],
updateConfigs: ['pkg'],
commit: true,
commitMessage: 'Release v%VERSION%',
createTag: true,
tagName: 'v%VERSION%',
tagMessage: 'Version %VERSION%',
push: true,
pushTo: 'origin',
gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d'
}
},
jshint: {
options: {
esversion: 6,
reporter: require('jshint-stylish')
},
build: ['*.js', 'features/**/*.js', 'public/**/*.js', '!public/lib/**/*.js']
},
cucumberjs: {
options: {
format: 'html',
output: 'reports/my_report.html',
theme: 'bootstrap'
},
features: ['features/**/*.feature']
}
});
// LOAD GRUNT PACKAGES
grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-cucumberjs');
};
|
JavaScript
| 0.998556 |
@@ -598,22 +598,26 @@
-jshint
+cucumberjs
: %7B%0A
@@ -655,20 +655,22 @@
-esversion: 6
+format: 'html'
,%0A
@@ -687,43 +687,76 @@
-reporter: require('jshint-stylish')
+output: 'reports/my_report.html',%0A theme: 'bootstrap'
%0A
@@ -759,33 +759,32 @@
%0A %7D,%0A
-%0A
buil
@@ -783,82 +783,41 @@
-build: %5B'*.js', 'features/**/*.js', 'public/**/*.js', '!public/lib/**/*.js
+features: %5B'features/**/*.feature
'%5D%0A
@@ -831,34 +831,30 @@
%7D,%0A%0A
-cucumberjs
+jshint
: %7B%0A
@@ -880,38 +880,36 @@
-format: 'html'
+esversion: 6
,%0A
@@ -918,76 +918,43 @@
-output: 'reports/my_report.html',%0A theme: 'bootstrap'
+reporter: require('jshint-stylish')
%0A
@@ -957,32 +957,33 @@
%0A %7D,%0A
+%0A
feat
@@ -982,41 +982,82 @@
-features: %5B'features/**/*.feature
+build: %5B'*.js', 'features/**/*.js', 'public/**/*.js', '!public/lib/**/*.js
'%5D%0A
|
21ebc728da11477599b8cda7ce9002ffec3cf950
|
change sub-task name in "grunt less" task in Gruntfile.js
|
Gruntfile.js
|
Gruntfile.js
|
module.exports = function(grunt) {
// Project config
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// start "bowercopy" task
bowercopy: {
// don't send messages to saying that Bower components aren't
// configured...ignore them instead. Also, don't run any bower
// tasks when grunt runs this task.
options: {
ignore: ['gulp', 'jquery'],
runBower: false
},
// Copy Bootstrap CCS over
bs: {
// copy to the "css-build" directory
options: {
destPrefix: 'css-build/'
},
files: {
'bootstrap.css': 'bootstrap/dist/css/bootstrap.css'
}
}, // end "bowercopy:bs" task
// Copy scrollNav over
scrollnav: {
// copy to the "css-build" directory
options: {
destPrefix: 'build/js/libs/'
},
files: {
'jquery.scrollNav.min.js': 'scrollNav/dist/jquery.scrollNav.min.js'
}
}, // end "bowercopy:scrollnav" task
// Copy jQuery over
jq: {
// copy to the "css-build" directory
options: {
destPrefix: 'build/js/libs/'
},
files: {
'jquery.min.js': 'jquery/dist/jquery.min.js'
}
} // end "bowercopy:jq" task
}, // end "bowercopy" task
less: {
development: {
files: {
"build/css/styles.css": ["css-build/styles.less"]
}
}
},
coffee: {
compile: {
options: {
bare: true
},
files: {
'build/js/main.js': 'coffee/*.coffee' // compile and concat into single file
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-bowercopy');
};
|
JavaScript
| 0.000007 |
@@ -1349,19 +1349,18 @@
-development
+core_build
: %7B%0A
@@ -1410,17 +1410,16 @@
s.css%22:
-%5B
%22css-bui
@@ -1433,17 +1433,16 @@
es.less%22
-%5D
%0A
|
4488b54bdfacd3b61bb48bc67037bb5e2882bd36
|
Add karma:debug task to Gruntfile
|
Gruntfile.js
|
Gruntfile.js
|
/*
* @copyright 2015 CoNWeT Lab., Universidad Politécnica de Madrid
* @license Apache v2 (http://www.apache.org/licenses/)
*/
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
isDev: grunt.option('target') === 'release' ? '' : '-dev',
banner: ' * @version <%= pkg.version %>\n' +
' * \n' +
' * @copyright 2014 <%= pkg.author %>\n' +
' * @license <%= pkg.license.type %> (<%= pkg.license.url %>)\n' +
' */',
compress: {
widget: {
options: {
archive: 'build/<%= pkg.vendor %>_<%= pkg.name %>_<%= pkg.version %><%= isDev %>.wgt',
mode: 'zip',
level: 9,
pretty: true
},
files: [
{expand: true, src: ['**/*'], cwd: 'build/wgt'}
]
}
},
concat: {
dist: {
src: grunt.file.readJSON("src/test/fixtures/json/wirecloudStyleDependencies.json"),
dest: "build/helpers/StyledElements.js"
}
},
copy: {
main: {
files: [
{expand: true, src: ['**/*', '!test/**'], dest: 'build/wgt', cwd: 'src'},
{expand: true, src: ['jquery.min.map', 'jquery.min.js'], dest: 'build/wgt/lib/js', cwd: 'node_modules/jquery/dist'},
{expand: true, src: ['jquery.min.map', 'jquery.min.js'], dest: 'build/wgt/lib/js', cwd: 'node_modules/jquery/dist'},
{expand: true, src: ['js/bootstrap.min.js', 'css/bootstrap.min.css', 'fonts/*'], dest: 'build/wgt/lib', cwd: 'node_modules/bootstrap/dist'},
{expand: true, src: ['css/font-awesome.min.css', 'fonts/*'], dest: 'build/wgt/lib', cwd: 'node_modules/font-awesome'}
]
}
},
karma: {
headless: {
configFile: 'karma.conf.js',
options: {
browsers: ['PhantomJS']
}
},
all: {
configFile: 'karma.conf.js',
}
},
replace: {
version: {
src: ['src/config.xml'],
overwrite: true,
replacements: [{
from: /version="[0-9]+\.[0-9]+\.[0-9]+(-dev)?"/g,
to: 'version="<%= pkg.version %>"'
}]
},
},
clean: ['build'],
jshint: {
options: {
jshintrc: true
},
all: {
files: {
src: ['src/js/**/*.js']
}
},
grunt: {
options: {
jshintrc: '.jshintrc-node'
},
files: {
src: ['Gruntfile.js']
}
},
test: {
options: {
jshintrc: '.jshintrc-jasmine'
},
files: {
src: ['src/test/**/*.js', '!src/test/fixtures/', '!src/test/StyledElements/*']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-compress');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-gitinfo');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('manifest', 'Creates a manifest.json file', function() {
this.requiresConfig('gitinfo');
var current = grunt.config(['gitinfo', 'local', 'branch', 'current']);
var content = JSON.stringify({
'Branch': current.name,
'SHA': current.SHA,
'User': current.currentUser,
'Build-Timestamp': grunt.template.today('UTC:yyyy-mm-dd HH:MM:ss Z'),
'Build-By' : 'Grunt ' + grunt.version
}, null, '\t');
grunt.file.write('build/wgt/manifest.json', content);
});
grunt.registerTask('package', ['gitinfo', 'manifest', 'copy', 'compress:widget']);
grunt.registerTask('test', ['concat', 'karma:headless']);
grunt.registerTask('default',
['jshint',
'test',
'replace:version',
'package'
]);
};
|
JavaScript
| 0.000037 |
@@ -1921,24 +1921,171 @@
a.conf.js',%0A
+ %7D,%0A%0A debug: %7B%0A configFile: 'karma.conf.js',%0A options: %7B%0A preprocessors: %5B%5D,%0A singleRun: false%0A %7D%0A
%7D%0A
|
6b98e70b9833dc5ea94199cf235d88bded97d8fd
|
Fix a typo. 'user strict'; => 'use strict';
|
Gruntfile.js
|
Gruntfile.js
|
/*
* Copyright (c) 2012-2015 S-Core Co., 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.
*/
'user strict';
module.exports = function (grunt) {
grunt.initConfig({
// for jshint check based on .jshintrc
// package.json doesn't have jshint-stylish and grunt-contrib-jshint plugins.
// Therefore, users of jshint must install these plugins by using npm install ...
jshint : {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
files: {
expand: true,
cwd: './',
src: ['apps/dashboard/**/*.js', // dashboard
'apps/deploy/**/*.js', //deploy
'apps/desktop/**/*.js', // desktop
'apps/ide/**/*.js', // ide
'apps/site/**/*.js', //site
'common/**/*.js', // common
'!**/lib/**', '!**/custom-lib/**', '!**/Gruntfile.js', // ignore lib and Gruntfile
'!**/*.min.js', '!**/*.back.js', // ignore min/back.js files
'!**/ProjectWizard-templates/**',
'!apps/ide/obsolete-src/**',
'!apps/ide/r.js']
}
},
bower: {
install: {
// just run grunt bower install
},
options: {
copy: false
}
},
copy: {
all: {
files: [
{
expand: true,
cwd: './',
src: ['**'],
dest: 'deploy/'
}
]
},
uncompressed: {
files: [
{
expand: true,
cwd: './',
src: ['**/*.js', '**/lib/**', '!node_modules/**', '!deploy/**'],
dest: 'deploy/',
rename: function (dest, src) {
return dest + src.substring(0, src.lastIndexOf('.js')) + '.uncompressed.js';
}
}
]
}
},
uglify: {
debug: {
options: {
mangle: true,
compress: true,
preserveComments: false,
sourceMap: function(path) {
return path + '.map';
},
sourceMappingURL: function(path) {
return path.substring(path.lastIndexOf('/') + 1) + '.map';
}
},
files: [
{
expand: true,
cwd: 'deploy/',
src: ['**/*.js', '!node_modules/*.js', '!node_modules/**/*.js', '!**/lib/**/*.js', '!&&/lib/*.js', '!*.uncompressed.js', '!**/*.uncompressed.js'],
dest: 'deploy/'
}
]
},
release: {
options: {
mangle: true,
compress: true,
preserveCommnets: false
},
files: [
{
expand: true,
cwd: 'deploy/',
src: ['**/*.js', '!node_modules/**/*.js', '!node_modules/*.js', '!**/lib/**/*.js', '!**/lib/*.js'],
dest: 'deploy/'
}
]
}
},
clean: {
all: ['deploy'],
unnecessary: ['deploy/Gruntfile.js', 'deploy/node_modules']
},
fix_source_maps: {
files: {
expand: true,
cwd: 'deploy/',
src: ['*.map', '**/*.map'],
dest: 'deploy'
}
}
});
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-bower-task');
grunt.registerMultiTask('fix_source_maps', 'Fixes uglified source maps', function() {
this.files.forEach(function(f) {
var json, src;
src = f.src.filter(function(filepath) {
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
});
json = grunt.file.readJSON(src);
var length = json.sources.length;
for(var i = 0; i < length; i++) {
json.sources[i] = json.sources[i].substring(json.sources[i].lastIndexOf('/') + 1);
json.sources[i] = json.sources[i].substring(0, json.sources[i].lastIndexOf('.js')) + '.uncompressed.js';
}
json.file= json.file.substring(json.file.lastIndexOf('/') + 1);
grunt.file.write(f.dest, JSON.stringify(json));
grunt.log.writeln('Source map in ' + src + ' fixed');
});
});
grunt.registerTask('default', ['clean:all', 'bower', 'copy:all'/*, 'copy:uncompressed', 'clean:unnecessary', 'uglify:debug', 'fix_source_maps'*/]);
grunt.registerTask('release', ['clean:all', 'bower', 'copy:all', 'clean:unnecessary', 'uglify:release']);
grunt.registerTask('convention', ['jshint']);
};
|
JavaScript
| 0.999999 |
@@ -607,17 +607,16 @@
*/%0A%0A'use
-r
strict'
|
a254f196a6136b14b0ad1b9d4c1619389e0cfb40
|
Add new resize
|
Gruntfile.js
|
Gruntfile.js
|
module.exports = function (grunt) {
function getImgRespSizes (sprite) {
var monitors = [
1024,
1152,
1280,
1366, // 487
1400,
1440,
1536,
1600,
1680,
1980
],
proportion = sprite ? 0.361 : 0.6639526276831976,
result = [];
if (!sprite) {
monitors.push(2000);
}
for (var i = monitors.length; i--;) {
result.push({
width: Math.round((monitors[i] - 15) * proportion),
name: monitors[i]
})
}
return result;
}
// Configure grunt
grunt.initConfig({
sprite:{
all: {
src: 'client/img/sprites/*',
destImg: 'client/img/2000/sprites.png',
destCSS: 'client/scss/base/_sprites.scss',
padding: 4
// , algorithm: 'binary-tree'
}
},
responsive_images: {
sprite: {
options: {
// Task-specific options go here.
engine: 'im',
newFilesOnly: false,
sizes: getImgRespSizes(true)
},
files: [{
expand: true,
src: ['sprites.png'],
cwd: 'client/img/2000',
custom_dest: 'client/img/{%= name %}/'
}]
},
letters: {
options: {
// Task-specific options go here.
engine: 'im',
newFilesOnly: false,
sizes: getImgRespSizes()
},
files: [{
expand: true,
src: ['*'],
cwd: 'client/img/letters',
custom_dest: 'client/img/{%= name %}/'
}]
}
}
});
// Load in `grunt-spritesmith`
grunt.loadNpmTasks('grunt-spritesmith');
grunt.loadNpmTasks('grunt-responsive-images');
};
|
JavaScript
| 0.000001 |
@@ -60,22 +60,39 @@
pSizes (
-sprite
+exclude2000, proportion
) %7B%0A
@@ -321,77 +321,74 @@
-proportion = sprite ? 0.361 : 0.6639526276831976,%0A result = %5B%5D
+result = %5B%5D;%0A proportion = proportion %7C%7C 0.6639526276831976
;%0A%0A
@@ -399,22 +399,27 @@
if (!
-sprite
+exclude2000
) %7B%0A
@@ -1283,16 +1283,23 @@
zes(true
+, 0.361
)%0A
@@ -2002,32 +2002,532 @@
%7D%5D%0A
+ %7D,%0A productsBg: %7B%0A options: %7B%0A // Task-specific options go here.%0A engine: 'im',%0A newFilesOnly: false,%0A sizes: getImgRespSizes(true, 0.4265)%0A %7D,%0A files: %5B%7B%0A expand: true,%0A src: %5B'productsBg.png'%5D,%0A cwd: 'client/img/2000',%0A custom_dest: 'client/img/%7B%25= name %25%7D/'%0A %7D%5D%0A
%7D%0A
|
0f4b7e7bfbae559bf672820972e4f6ff79dcca72
|
Fix #462: Prevent user from double-submitting "create variant set from file".
|
genome_designer/main/static/js/variant_set_list_view.js
|
genome_designer/main/static/js/variant_set_list_view.js
|
/**
* @fileoverview List of variant sets.
*/
gd.VariantSetListView = Backbone.View.extend({
el: '#gd-page-container',
initialize: function() {
this.render();
},
render: function() {
$('#gd-sidenav-link-variant-sets').addClass('active');
this.datatableComponent = new gd.DataTableComponent({
el: $('#gd-variant_set_list_view-datatable-hook'),
serverTarget: '/_/sets',
controlsTemplate: '/_/templates/variant_set_list_controls',
requestData: {projectUid: this.model.get('uid')}
});
this.listenTo(this.datatableComponent, 'DONE_CONTROLS_REDRAW',
_.bind(this.listenToControls, this));
},
listenToControls: function() {
$('#gd-variant-set-form-from-file-submit').click(
_.bind(this.handleFormSubmitFromFile, this));
$('#gd-variant-set-form-empty-submit').click(
_.bind(this.handleFormSubmitEmpty, this));
},
/**
* Handles submitting the request to create a new VariantSet from a file
* containing a list of Variants.
*/
handleFormSubmitFromFile: function() {
// We validate by parsing the input elements, but then use the HTML5
// FormData API to actually send the data to the server. FormData
// makes the file upload "just work".
var formDataForValidation = this.prepareRequestData(
'gd-variant-set-create-form-from-file');
if (!this.validateCreateFromFileRequestData(formDataForValidation)) {
return;
}
var onSuccess = function(responseData) {
if ('error' in responseData && responseData.error.length) {
alert('Error creating variant set: ' + responseData.error);
return;
}
// Success, reload the page.
window.location.reload();
}
var formData = new FormData($('#gd-variant-set-create-form-from-file')[0]);
$.ajax({
url: '/_/sets/create',
type: 'POST',
data: formData,
success: onSuccess,
// The following 3 param settings are necessary for properly passing
// formData. See: http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery
cache: false,
contentType: false,
processData: false
});
},
/** Handles creating a new empty Variant set. */
handleFormSubmitEmpty: function() {
// Parse the inputs.
var requestData = this.prepareRequestData('gd-variant-set-form-empty');
// Validate the request client-side.
if (!this.validateCreateEmptyRequestData(requestData)) {
return;
}
// Make the request.
$.post('/_/sets/create', requestData, function(responseData) {
// Check for error and show in ui. Don't reload the page.
if (responseData.error.length) {
alert('Error creating variant set: ' + responseData.error);
return;
}
// Success, reload the page.
window.location.reload();
});
},
/** Parses the form files and prepares the data. */
prepareRequestData: function(formId) {
var requestData = {}
var formInputs = $('#' + formId + ' :input');
_.each(formInputs, function(inputObj) {
requestData[inputObj.name] = inputObj.value;
});
return requestData;
},
/** Validates the request to be sent to the server. */
validateCreateEmptyRequestData: function(requestData) {
if (!this.validateCommon(requestData)) {
return false;
}
return true;
},
/** Validates the request to be sent to the server. */
validateCreateFromFileRequestData: function(requestData) {
if (!this.validateCommon(requestData)) {
return false;
}
if (!requestData['vcfFile'].length) {
alert('Please select a vcf file to upload.');
return false;
}
return true;
},
/** Validation common to both forms. */
validateCommon: function(requestData) {
if (!requestData['refGenomeUid'].length) {
alert('Please select a reference genome.');
return false;
}
if (!requestData['variantSetName'].length) {
alert('Please enter a variant set name.');
return false;
}
return true;
}
});
|
JavaScript
| 0 |
@@ -1064,24 +1064,94 @@
unction() %7B%0A
+ $('#gd-variant-set-form-from-file-submit').addClass('disabled');%0A%0A
// We va
|
cd4e8c23567518623e6c99f6e464ac30e6fc26c0
|
add bump-commit to release
|
Gruntfile.js
|
Gruntfile.js
|
module.exports = function(grunt) {
'use strict';
var app = {},
config = {},
tasks = [
'grunt-contrib-jshint',
'grunt-contrib-concat',
'grunt-contrib-jasmine',
'grunt-contrib-watch',
'grunt-contrib-uglify',
'grunt-coveralls',
'grunt-bump',
'grunt-umd'
];
// get patch if it's release
app.patch = grunt.option('patch');
// config pack
app.pack = grunt.config('pkg', grunt.file.readJSON('package.json'));
// really?? I mean, really????
function updateBanner() {
app.banner = '/** ' +
'\n* ' + app.pack.name + ' -v' + grunt.file.readJSON('package.json').version +
'\n* Copyright (c) '+ grunt.template.today('yyyy') + ' ' + app.pack.author +
'\n* Licensed ' + app.pack.license + '\n*/\n\n';
config.concat.options.banner = app.banner;
config.uglify.all.options.banner = app.banner;
};
// =============================================
// bump
config.bump = {};
config.bump.options = {
files: ['package.json'],
updateConfigs: [],
commit: true,
commitMessage: 'Release v%VERSION%',
commitFiles: [
'package.json',
'dist'
],
createTag: true,
tagName: 'v%VERSION%',
tagMessage: 'Version %VERSION%',
push: true,
pushTo: 'origin',
gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d'
};
// =============================================
// jshint
config.jshint = {};
config.jshint.options = {
debug: true,
sub: true
};
config.jshint.all = ['dist/core.js'];
// =============================================
// concat
config.concat = {
options: {
banner: app.banner
},
dist: {
src: [
'src/core/core.js',
'src/helpers/*.js',
'src/core/**/*.js',
'src/sandbox/sandbox.js'
],
dest: 'dist/core.js'
}
};
// =============================================
// watch
config.watch = {};
config.watch.scripts = {
files: ['src/**/*.js'],
tasks: ['concat', 'umd','jshint'],
options: {
spawn: false,
}
}
// =============================================
// uglify
config.uglify = {};
config.uglify.all = {
files: {
'dist/core.min.js': [ 'dist/core.js' ]
},
options: {
preserveComments: false,
sourceMap: 'dist/core.min.map',
sourceMappingURL: 'core.min.map',
report: 'min',
beautify: {
ascii_only: true
},
banner: app.banner,
compress: {
hoist_funs: false,
loops: false,
unused: false
}
}
}
// =============================================
// jasmine
config.jasmine = {};
config.jasmine.coverage = {
src: [
'dist/core.js'
],
options: {
specs: 'tests/**/*Spec.js',
template: require('grunt-template-jasmine-istanbul'),
templateOptions: {
coverage: 'bin/coverage/coverage.json',
report: {
type: 'lcov',
options: {
dir: 'bin/coverage'
}
},
thresholds: {
lines: 75,
statements: 75,
branches: 75,
functions: 90
}
}
}
}
// =============================================
// umd
config.umd = {};
config.umd = {
all: {
options: {
src: 'dist/core.js',
objectToExport: 'Core'
}
}
};
// =============================================
// coveralls
config.coveralls = {
src: 'bin/coverage/lcov.info'
};
updateBanner();
// Load all tasks
tasks.forEach(grunt.loadNpmTasks);
// config
grunt.initConfig(config);
grunt.registerTask('dist', ['jshint', 'concat', 'umd', 'jasmine', 'uglify']);
grunt.registerTask('ci', ['jshint', 'jasmine', 'coveralls']);
grunt.registerTask('release', function () {
grunt.task.run('bump-only%patch%'.replace('%patch%', app.patch ? ':' + app.patch : ''));
setTimeout(function() {
updateBanner();
grunt.task.run('dist');
}, 0);
// grunt.task.run('dist');
});
};
|
JavaScript
| 0 |
@@ -4052,16 +4052,53 @@
dist');%0A
+ grunt.task.run('bump-commit');%0A
%7D, 0
@@ -4100,16 +4100,17 @@
%7D, 0);%0A
+%0A
// g
|
a980fca4ac601d865249a044e96ad4d0a1d4c617
|
Comment out console.log
|
src/LambdaFunctionPool.js
|
src/LambdaFunctionPool.js
|
'use strict'
const LambdaFunction = require('./LambdaFunction.js')
module.exports = class LambdaFunctionPool {
constructor() {
// key (functionName), value: Set of instances
this._lambdaFunctionPool = new Map()
// start cleaner
this._startCleanTimer()
}
_startCleanTimer() {
// NOTE: don't use setInterval, as it would schedule always a new run,
// regardless of function processing time and e.g. user action (debugging)
this._timerRef = setTimeout(() => {
// console.log('run cleanup')
this._lambdaFunctionPool.forEach((lambdaFunctions) => {
lambdaFunctions.forEach((lambdaFunction) => {
const { idleTimeInMinutes, status } = lambdaFunction
console.log(idleTimeInMinutes, status)
// 45 // TODO config, or maybe option?
if (status === 'IDLE' && idleTimeInMinutes >= 1) {
console.log(`removed Lambda Function ${lambdaFunction.name}`)
lambdaFunctions.delete(lambdaFunction)
}
})
})
// schedule new timer
this._startCleanTimer()
}, 10000) // TODO: config, or maybe option?
}
_cleanupPool() {
const wait = []
this._lambdaFunctionPool.forEach((lambdaFunctions) => {
lambdaFunctions.forEach((lambdaFunction) => {
// collect promises
wait.push(lambdaFunction.cleanup())
lambdaFunctions.delete(lambdaFunction)
})
})
return Promise.all(wait)
}
// TODO make sure to call this
async cleanup() {
clearTimeout(this._timerRef)
return this._cleanupPool()
}
get(functionName, functionObj, provider, config, options) {
const lambdaFunctions = this._lambdaFunctionPool.get(functionName)
// we don't have any instances
if (lambdaFunctions == null) {
const lambdaFunction = new LambdaFunction(
functionName,
functionObj,
provider,
config,
options,
)
this._lambdaFunctionPool.set(functionName, new Set([lambdaFunction]))
return lambdaFunction
}
console.log(`${lambdaFunctions.size} lambdaFunctions`)
// find any IDLE ones
const lambdaFunction = Array.from(lambdaFunctions).find(
({ status }) => status === 'IDLE',
)
// we don't have any IDLE instances
if (lambdaFunction == null) {
const lambdaFunction = new LambdaFunction(
functionName,
functionObj,
provider,
config,
options,
)
lambdaFunctions.add(lambdaFunction)
console.log(`${lambdaFunctions.size} lambdaFunctions`)
return lambdaFunction
}
return lambdaFunction
}
}
|
JavaScript
| 0.000001 |
@@ -704,32 +704,35 @@
nction%0A
+ //
console.log(idl
@@ -873,24 +873,27 @@
%0A
+ //
console.log
@@ -2049,24 +2049,27 @@
n%0A %7D%0A%0A
+ //
console.log
@@ -2517,24 +2517,27 @@
tion)%0A%0A
+ //
console.log
|
96ebb82bcb2b869a3dcb76a448bf9bf792e1903e
|
Delete useless empty line
|
SPAWithAngularJS/module2/providerService/js/app.shoppingListController.js
|
SPAWithAngularJS/module2/providerService/js/app.shoppingListController.js
|
// app.shoppingListController.js
(function() {
"use strict";
angular.module("MyApp")
.controller("ShoppingListController", ShoppingListController);
ShoppingListController.$inject = ["ShoppingListService"];
function ShoppingListController(ShoppingListService) {
let list = this;
list.items = ShoppingListService.getItems();
list.addItem = addItem;
list.removeItem = removeItem;
function addItem() {
try {
ShoppingListService.addItem(list.itemName, list.itemQuantity);
list.itemName = "";
list.itemQuantity = "";
} catch (error) {
list.errorMessage = error;
}
}
function removeItem(index) {
if (index < ShoppingListService.getMaxItems()) {
list.errorMessage = "";
}
ShoppingListService.removeItem(index);
}
}
})();
|
JavaScript
| 0.998532 |
@@ -342,17 +342,16 @@
ems();%0A%0A
-%0A
list
|
6eff5cb24110730e4c7814cc93d41fc7db0d3a2e
|
call method from hedgehog object
|
src/client/app/blockly/lib/generators/python/hedgehog.js
|
src/client/app/blockly/lib/generators/python/hedgehog.js
|
'use strict';
goog.provide('Blockly.Python.hedgehog');
goog.require('Blockly.Python');
Blockly.Python['hedgehog_scope'] = function(block) {
var statements = Blockly.Python.statementToCode(block, 'IN');
Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';
var code = 'with connect(emergency=15) as hedgehog:\n' + statements;
return code;
};
Blockly.Python['hedgehog_turn'] = function(block) {
var number_motor1 = block.getFieldValue('MOTOR1');
var number_motor2 = block.getFieldValue('MOTOR2');
var dropdown_dir = block.getFieldValue('DIR');
var value_num = Blockly.Python.valueToCode(block, 'NUM', Blockly.Python.ORDER_ATOMIC);
var dropdown_unit = block.getFieldValue('UNIT');
// imports
Blockly.Python.definitions_['import_sleep'] = 'from time import sleep';
Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';
// TODO: Assemble Python into code variable.
var code = 'blub\n';
return code;
};
Blockly.Python['hedgehog_move'] = function(block) {
var port = block.getFieldValue('PORT');
var speed = Blockly.Python.valueToCode(block, 'SPEED', Blockly.Python.ORDER_ATOMIC);
var time = Blockly.Python.valueToCode(block, 'TIME', Blockly.Python.ORDER_ATOMIC);
// imports
Blockly.Python.definitions_['import_sleep'] = 'from time import sleep';
Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';
var code = 'hedgehog.move(' + port + ', ' + speed + ')' + '; sleep(' + time + ')\n';
// return [code, Blockly.Python.ORDER_FUNCTION];
return code;
};
Blockly.Python['hedgehog_speed'] = function(block) {
var speed = block.getFieldValue('SPEED');
return [speed, Blockly.Python.ORDER_NONE];
};
Blockly.Python['hedgehog_read_analog'] = function(block) {
var port = block.getFieldValue('PORT');
var code = 'get_analog(' + port + ')';
return [code, Blockly.Python.ORDER_NONE];
};
Blockly.Python['hedgehog_read_digital'] = function(block) {
var port = block.getFieldValue('PORT');
var code = 'get_digital(' + port + ')';
return [code, Blockly.Python.ORDER_NONE];
};
|
JavaScript
| 0.000003 |
@@ -1912,24 +1912,33 @@
var code = '
+hedgehog.
get_analog('
@@ -2123,16 +2123,24 @@
code = '
+hedgeho.
get_digi
|
a8f8f08b03f7fc2b8aa7fc0f9ddda246a2cecef5
|
Remove HMR router hack
|
src/RootWithIntl.js
|
src/RootWithIntl.js
|
import React from 'react';
import PropTypes from 'prop-types';
import Router from 'react-router-dom/Router';
import Switch from 'react-router-dom/Switch';
import { Provider } from 'react-redux';
import { CookiesProvider } from 'react-cookie';
import { HotKeys } from '@folio/stripes-components/lib/HotKeys';
import { connectFor } from '@folio/stripes-connect';
import { intlShape } from 'react-intl';
import MainContainer from './components/MainContainer';
import MainNav from './components/MainNav';
import ModuleContainer from './components/ModuleContainer';
import ModuleTranslator from './components/ModuleTranslator';
import TitledRoute from './components/TitledRoute';
import Front from './components/Front';
import SSOLanding from './components/SSOLanding';
import SSORedirect from './components/SSORedirect';
import Settings from './components/Settings/Settings';
import HandlerManager from './components/HandlerManager';
import TitleManager from './components/TitleManager';
import LoginCtrl from './components/Login';
import OverlayContainer from './components/OverlayContainer';
import getModuleRoutes from './moduleRoutes';
import { stripesShape } from './Stripes';
import { StripesContext } from './StripesContext';
import events from './events';
class RootWithIntl extends React.Component {
static propTypes = {
stripes: stripesShape.isRequired,
token: PropTypes.string,
disableAuth: PropTypes.bool.isRequired,
history: PropTypes.shape({}),
};
static contextTypes = {
intl: intlShape.isRequired,
};
render() {
const intl = this.context.intl;
const connect = connectFor('@folio/core', this.props.stripes.epics, this.props.stripes.logger);
const stripes = this.props.stripes.clone({ intl, connect });
const { token, disableAuth, history } = this.props;
return (
<StripesContext.Provider value={stripes}>
<ModuleTranslator>
<TitleManager>
<HotKeys keyMap={stripes.bindings} noWrapper>
<Provider store={stripes.store}>
<Router history={history} key={Math.random()}>
{ token || disableAuth ?
<MainContainer>
<OverlayContainer />
<MainNav stripes={stripes} />
<HandlerManager event={events.LOGIN} stripes={stripes} />
{ (stripes.okapi !== 'object' || stripes.discovery.isFinished) && (
<ModuleContainer id="content">
<Switch>
<TitledRoute name="home" path="/" key="root" exact component={<Front stripes={stripes} />} />
<TitledRoute name="ssoRedirect" path="/sso-landing" key="sso-landing" component={<SSORedirect stripes={stripes} />} />
<TitledRoute name="settings" path="/settings" component={<Settings stripes={stripes} />} />
{getModuleRoutes(stripes)}
<TitledRoute
name="notFound"
component={(
<div>
<h2>Uh-oh!</h2>
<p>This route does not exist.</p>
</div>
)}
/>
</Switch>
</ModuleContainer>
)}
</MainContainer> :
<Switch>
<TitledRoute name="ssoLanding" exact path="/sso-landing" component={<CookiesProvider><SSOLanding stripes={stripes} /></CookiesProvider>} key="sso-landing" />
<TitledRoute name="login" component={<LoginCtrl autoLogin={stripes.config.autoLogin} stripes={stripes} />} />
</Switch>
}
</Router>
</Provider>
</HotKeys>
</TitleManager>
</ModuleTranslator>
</StripesContext.Provider>
);
}
}
export default RootWithIntl;
|
JavaScript
| 0 |
@@ -2072,28 +2072,8 @@
ory%7D
- key=%7BMath.random()%7D
%3E%0A
|
b3c3a328b0e254656e3461f81862f3b67e56335c
|
Allow embedders to include their own stylesheet.
|
censusreporter/apps/census/static/js/embed.chart.frame.js
|
censusreporter/apps/census/static/js/embed.chart.frame.js
|
function makeEmbedFrame() {
var embedFrame = {
params: {},
data: {},
elements: {}
};
embedFrame.chartSetup = function() {
var match,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query)) {
embedFrame.params[decode(match[1])] = decode(match[2]);
}
embedFrame.trackEvent('Embedded Charts', 'GeoID', embedFrame.params.geoID);
embedFrame.trackEvent('Embedded Charts', 'DataID', embedFrame.params.chartDataID);
embedFrame.trackEvent('Embedded Charts', 'Parent URL', document.referrer);
embedFrame.parentContainerID = 'cr-embed-'+embedFrame.params.geoID+'-'+embedFrame.params.chartDataID;
embedFrame.params.chartDataID = embedFrame.params.chartDataID.split('-');
embedFrame.dataSource = 'http://embed.wazimap.co.za/embed_data/profiles/'+embedFrame.params.geoID+'.json';
// avoid css media-query caching issues with multiple embeds on same page
$('#chart-styles').attr('href','css/charts.css?'+embedFrame.parentContainerID)
embedFrame.makeChartFooter();
}
embedFrame.getChartData = function() {
$.getJSON(embedFrame.dataSource)
.done(function(results) {
// allow arbitrary nesting in API data structure
var data = results[embedFrame.params.chartDataID[0]],
drilldown = embedFrame.params.chartDataID.length - 1;
if (drilldown >= 1) {
for (var i = 1; i <= drilldown; i++) {
data = data[embedFrame.params.chartDataID[i]];
}
}
embedFrame.data.chartData = data;
embedFrame.data.geographyData = results.geography;
embedFrame.makeChart();
embedFrame.makeChartAbout();
});
}
embedFrame.makeChart = function() {
embedFrame.resetContainer();
embedFrame.makeChartPlace();
embedFrame.elements.chart = Chart({
chartContainer: 'census-chart',
chartType: embedFrame.gracefulType(embedFrame.params.chartType),
chartData: embedFrame.data.chartData,
chartHeight: embedFrame.params.chartHeight,
chartQualifier: embedFrame.params.chartQualifier,
chartChartTitle: embedFrame.params.chartTitle,
chartInitialSort: embedFrame.params.chartInitialSort,
chartStatType: embedFrame.params.statType,
geographyData: embedFrame.data.geographyData
});
if (!!embedFrame.parentOrigin) {
embedFrame.sendDataToParent({
containerID: embedFrame.parentContainerID,
chartHeight: embedFrame.elements.chart.settings.height
});
}
}
embedFrame.makeChartPlace = function() {
d3.select('#census-chart').append('h3')
.classed('chart-header', true)
.text(embedFrame.data.geographyData['this'].full_name);
}
embedFrame.makeChartAbout = function() {
var aboutData = embedFrame.data.chartData.metadata;
console.log(embedFrame)
embedFrame.elements.chartAbout = [
'<h3 class="chart-header">' + embedFrame.data.geographyData['this'].full_name + '</h3>',
'<h3 class="chart-title">' + embedFrame.params.chartTitle + '</h3>',
'<ul>',
'<li>This chart was generated by <a href="http://wazimap.co.za/" target="_blank">Wazimap</a>, using data from either <a href="http://www.statssa.gov.za/" target="_blank">Stats SA</a> or <a href="http://www.elections.org.za/" target="_blank"> the IEC</a>.</li>',
'<li><a href="http://wazimap.co.za/" target="_blank">Wazimap</a> is a project to make South African census & elections data easier to use and understand.</li>',
'<li><a href="http://wazimap.co.za/profiles/' + embedFrame.params.geoID + '/" target="_blank">See more data from ' + embedFrame.data.geographyData['this'].full_name + '</a>',
'</ul>'
].join('');
}
embedFrame.makeChartFooter = function() {
embedFrame.elements.footer = d3.select('.census-chart-embed').append('div')
.classed('embed-footer', true);
embedFrame.elements.footer.append('ul')
.append('li')
.html('<a href="#" id="about-trigger">About this chart</a>');
embedFrame.elements.footer.append('a')
.classed('title', true)
.attr('href', 'http://wazimap.co.za/profiles/' + embedFrame.params.geoID + '/')
.attr('target', '_blank')
.html('<img src="http://embed.wazimap.co.za/static/img/wazi-logo.png"> Wazi');
}
embedFrame.addChartListeners = function() {
// allow for older IE
var eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent',
eventListener = window[eventMethod],
messageEvent = (eventMethod == 'attachEvent') ? 'onmessage' : 'message';
eventListener(messageEvent, embedFrame.handleMessage, false);
var flip = flippant.flip,
back;
embedFrame.flipped = false,
$('.embed-footer').on('click', '#about-trigger', function(e) {
e.preventDefault();
if (!embedFrame.flipped) {
back = flip(embedFrame.elements.container, embedFrame.elements.chartAbout)
embedFrame.flipped = true;
} else {
back.close();
embedFrame.flipped = false;
}
var flipText = (embedFrame.flipped) ? 'Back to chart' : 'About this chart';
$(this).text(flipText);
embedFrame.trackEvent('Embedded Charts', 'About pane open', embedFrame.flipped.toString());
});
}
embedFrame.resetContainer = function() {
window.browserWidth = document.documentElement.clientWidth;
embedFrame.elements.container = document.getElementById('census-chart');
embedFrame.elements.container.innerHTML = "";
}
embedFrame.gracefulType = function(chartType) {
// convert certain chart types to more readable versions at narrow widths
if (window.browserWidth <= 480) {
if (chartType == 'column' || chartType == 'histogram') {
return 'bar'
} else if (chartType == 'grouped_column') {
return 'grouped_bar'
}
}
return chartType
}
embedFrame.handleMessage = function(event) {
var messageData = JSON.parse(event.data);
embedFrame.parentOrigin = event.origin;
if (messageData.resize && embedFrame.data.chartData) {
embedFrame.makeChart();
}
}
embedFrame.sendDataToParent = function(data) {
// IE9 can only send strings via postmessage
parent.postMessage(JSON.stringify(data), embedFrame.parentOrigin);
}
embedFrame.trackEvent = function(category, action, label) {
// make sure we have Google Analytics function available
if (typeof(ga) == 'function') {
ga('send', 'event', category, action, label);
}
}
embedFrame.chartSetup();
embedFrame.getChartData();
embedFrame.addChartListeners();
}
makeEmbedFrame();
|
JavaScript
| 0 |
@@ -1228,16 +1228,238 @@
inerID)%0A
+%0A // allow embedders to inject their own stylesheet%0A if (embedFrame.params%5B'stylesheet'%5D) %7B%0A $('%3Clink rel=%22stylesheet%22%3E').attr('href', embedFrame.params.stylesheet).appendTo($('head'));%0A %7D%0A%0A
|
b30c8d9a983ce5b9462e90c57ea9dd46d27b17b7
|
Send jsQuery ready error message on GET /infowindow errors
|
lib/cartodb/cartodb_windshaft.js
|
lib/cartodb/cartodb_windshaft.js
|
var _ = require('underscore')
, Step = require('step')
, Windshaft = require('windshaft')
, Cache = require('./cache_validator');
var CartodbWindshaft = function(serverOptions) {
// set the cache chanel info to invalidate the cache on the frontend server
serverOptions.afterTileRender = function(req, res, tile, headers, callback) {
Cache.generateCacheChannel(req, function(channel){
res.header('X-Cache-Channel', channel);
res.header('Last-Modified', new Date().toUTCString());
res.header('Cache-Control', 'no-cache,max-age=86400,must-revalidate, public');
callback(null, tile, headers);
});
};
if(serverOptions.cache_enabled) {
console.log("cache invalidation enabled, varnish on ", serverOptions.varnish_host, ' ', serverOptions.varnish_port);
Cache.init(serverOptions.varnish_host, serverOptions.varnish_port);
serverOptions.afterStateChange = function(req, data, callback) {
Cache.invalidate_db(req.params.dbname, req.params.table);
callback(null, data);
}
}
serverOptions.beforeStateChange = function(req, callback) {
var err = null;
if ( ! req.params.hasOwnProperty('dbuser') ) {
err = new Error("map state cannot be changed by unauthenticated request!");
}
callback(err, req);
}
serverOptions.afterStyleChange = function(req, data, callback) {
if ( req.params.hasOwnProperty('dbuser') ) {
// also change the style of the anonim. request
var params = _.extend(req.params); // make a copy here
delete params.dbuser;
var style = req.body.style;
var that = this;
this.setStyle(params, style, function(err, data) {
if ( err ) callback(err, null);
else that.afterStateChange(req, data, callback);
});
} else {
callback(new Error("map style cannot be changed by unauthenticated request!"));
}
}
serverOptions.afterStyleDelete = function(req, data, callback) {
if ( req.params.hasOwnProperty('dbuser') ) {
// also change the style of the anonim. request
var params = _.extend(req.params); // make a copy here
delete params.dbuser;
var that = this;
this.delStyle(params, function(err, data) {
if ( err ) callback(err, null);
else that.afterStateChange(req, data, callback);
});
} else {
callback(new Error("map style cannot be deleted by unauthenticated request!"));
}
}
// boot
var ws = new Windshaft.Server(serverOptions);
/**
* Helper to allow access to the layer to be used in the maps infowindow popup.
*/
ws.get(serverOptions.base_url + '/infowindow', function(req, res){
ws.doCORS(res);
Step(
function(){
serverOptions.getInfowindow(req, this);
},
function(err, data){
if (err){
res.send(err.message, 500);
} else {
res.send({infowindow: data}, 200);
}
}
);
});
/**
* Helper to allow access to metadata to be used in embedded maps.
*/
ws.get(serverOptions.base_url + '/map_metadata', function(req, res){
ws.doCORS(res);
Step(
function(){
serverOptions.getMapMetadata(req, this);
},
function(err, data){
if (err){
res.send(err.message, 500);
} else {
res.send({map_metadata: data}, 200);
}
}
);
});
/**
* Helper API to allow per table tile cache (and sql cache) to be invalidated remotely.
* TODO: Move?
*/
ws.del(serverOptions.base_url + '/flush_cache', function(req, res){
ws.doCORS(res);
Step(
function(){
serverOptions.flushCache(req, Cache, this);
},
function(err, data){
if (err){
res.send(500);
} else {
res.send({status: 'ok'}, 200);
}
}
);
});
return ws;
}
module.exports = CartodbWindshaft;
|
JavaScript
| 0 |
@@ -3090,32 +3090,40 @@
res.send(
+%7Berror:
err.message, 500
@@ -3109,32 +3109,33 @@
ror: err.message
+%7D
, 500);%0A
|
c606a7d8c4bd008098e6bda631b13cefe96cc82f
|
Add new fields and add method to set notification as read
|
lib/collections/notifications.js
|
lib/collections/notifications.js
|
Notifications = new Mongo.Collection('notifications');
// TODO add allow/deny rules
// user is owner of project - deny
// user is not logged in - deny
createRequestNotification = function(request) {
check(request, {
user: Object,
project: Object,
createdAt: Date,
status: String
});
Notifications.insert({
userId: request.project.ownerId,
requestingUserId: Meteor.userId(),
text: Meteor.user().username + ' has requested to join ' + request.project.name,
createdAt: new Date(),
read: false,
type: 'interactive',
extraFields: {
projectId: request.project.projectId
}
});
};
|
JavaScript
| 0 |
@@ -284,16 +284,33 @@
status:
+ String,%0A _id:
String%0A
@@ -636,20 +636,293 @@
ctId
-%0A %7D%0A %7D);%0A%7D
+,%0A requestId: request._id%0A %7D%0A %7D);%0A%7D;%0A%0AMeteor.methods(%7B%0A setNotificationAsRead: function(notification) %7B%0A check(notification, String);%0A console.log(notification);%0A Notifications.update(%7B _id: notification._id %7D, %7B%0A $set: %7B%0A read: true%0A %7D%0A %7D);%0A %7D%0A%7D)
;%0A
|
ed664e1a69e241766848cd628d56f820064c6c19
|
remove options from promise launcher
|
lib/commando/launcher/promise.js
|
lib/commando/launcher/promise.js
|
export default PromiseLauncher;
// Create a command launcher with `options`.
function PromiseLauncher(options) {
this.options = options;
}
PromiseLauncher.prototype = {
// Launch the execution of `Command` function. It create the command and wraps it in a Promise.
execute: function(Command, args, options) {
var resolver,
_this = this;
// create the resolver responsible for the creation and the execution
// of the `Command`.
// The command created must conform to the API `Command(resolve, reject)`.
resolver = function(resolve, reject) {
var command;
command = new Command(resolve, reject);
return command.execute.apply(command, args);
};
// return the created promise
return this.promise(resolver).catch(options.error);
},
// This function is the one responsible for creating the promise around the `resolver` provided .
// The purpose of this function is to permit overriding of the promise definition based on any logic or context.
promise: function (resolver) {
// create the promise based on the promise function given
// as an option
return new this.options.promise(resolver);
}
};
|
JavaScript
| 0.000013 |
@@ -301,17 +301,8 @@
args
-, options
) %7B%0A
@@ -755,29 +755,8 @@
ver)
-.catch(options.error)
;%0A
|
18a6d79171270f5c38d093a0be9b3dccbd05535f
|
Fix jshint error
|
lib/commands/csm/group/group._js
|
lib/commands/csm/group/group._js
|
/**
* Copyright (c) Microsoft. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var util = require('util');
var profile = require('../../../util/profile');
var utils = require('../../../util/utils');
var groupUtils = require('./groupUtils');
var $ = utils.getLocaleString;
exports.init = function (cli) {
var log = cli.output;
var group = cli.category('group')
.description($('Commands to manage your resource groups'));
group.command('create [name] [location]')
.description($('Create a new resource group'))
.option('-n --name <name>', $('The resource group name'))
.option('-l --location <location>', $('Location to create group in'))
.option('-d --deployment-name <deployment-name>', $('the name of the deployment it\'s going to create. Only valid when a template is used.'))
.option('-y --gallery-template <gallery-template>', $('the name of the template in the gallery'))
.option('-f --file-template <file-template>', $('the path to the template file, local or remote'))
//TODO: comment out till CSM supports contentHash
// .option('--template-hash <template-hash>', $('the content hash of the template'))
// .option('--template-hash-algorithm <template-hash-algorithm>', $('the algorithm used to hash the template content'))
.option('--template-version <template-version>', $('the content version of the template'))
.option('-s --storage-account <storage-account>', $('the storage account where to upload the template file to'))
.option('-m --mode <mode>', $('the mode of the template deployment. Valid values are Replace, New and Incremental'))
.option('-p --parameters <parameters>', $('the string in JSON format which represents the parameters'))
.option('-e --parameters-file <parametersFile>', $('the file with parameters'))
//TODO: comment out till CSM supports contentHash
// .option('--parameters-hash <parameters-hash>', $('the content hash of the parameters'))
// .option('--parameters-hash-algorithm <parameters-hash-algorithm>', $('the algorithm used to hash the parameters content'))
.option('--parameters-version <parameters-version>', $('the content version of the parameters'))
.option('--subscription <subscription>', $('the subscription identifier'))
.option('--env [env]', $('Azure environment to run against'))
.execute(function (name, location, options, _) {
location = groupUtils.validateLocation(location, log, cli.interaction, _);
var subscription = profile.current.getSubscription(options.subscription);
var client = subscription.createResourceClient('createResourceManagementClient');
cli.interaction.withProgress(util.format($('Creating resource group %s'), name),
function (log, _) {
if (groupUtils.groupExists(client, name, _)) {
log.error(util.format($('The resource group %s already exists'), name));
} else {
client.resourceGroups.createOrUpdate(name, { location: location}, _);
log.info(util.format($('Created resource group %s'), name));
}
}, _);
if (options.galleryTemplate || options.fileTemplate || options.deploymentName) {
groupUtils.createDeployment(cli, name, options.deploymentName, name, options, _);
}
});
group.command('delete [name]')
.description($('Delete a resource group'))
.option('-n --name <name>', $('The resource group name'))
.option('-q, --quiet', $('quiet mode, do not ask for delete confirmation'))
.option('--subscription <subscription>', $('the subscription identifier'))
.execute(function (name, options, _) {
if (!options.quiet && !cli.interaction.confirm(util.format($('Delete resource group %s? [y/n] '), name), _)) {
return;
}
var subscription = profile.current.getSubscription(options.subscription);
var client = subscription.createResourceClient('createResourceManagementClient');
var progress = cli.interaction.progress(util.format($('Deleting resource group %s'), name));
try {
client.resourceGroups.delete(name, _);
} finally {
progress.end();
}
});
group.command('list')
.description($('List the resource groups for your subscription'))
.option('-d, --details', $('show additional resource group details'))
.option('--subscription <subscription>', $('the subscription identifier'))
.execute(function (options, _) {
var subscription = profile.current.getSubscription(options.subscription);
var client = subscription.createResourceClient('createResourceManagementClient');
var progress = cli.interaction.progress($('Listing resource groups'));
var result;
try {
result = client.resourceGroups.list({}, _);
} finally {
progress.end();
}
if (options.details) {
progress = cli.interaction.progress($('Listing resources for the groups'));
try {
for (var i in result.resourceGroups) {
var resourceGroup = result.resourceGroups[i];
resourceGroup.resources = client.resources.list({ resourceGroupName: resourceGroup.name }, _).resources;
}
} finally {
progress.end();
}
}
cli.interaction.formatOutput(result.resourceGroups, function (data) {
if (data.length === 0) {
log.info($('No resource groups defined'));
} else {
if (options.details) {
for (var i in data) {
showDetailedResourceGroup(data[i]);
log.data($(''));
}
} else {
log.table(data, function (row, group) {
row.cell($('Name'), group.name);
row.cell($('Location'), group.location);
});
}
}
});
});
group.command('show [name]')
.description($('Shows a resource groups for your subscription'))
.option('-n --name <name>', $('The resource group name'))
.option('--subscription <subscription>', $('the subscription identifier'))
.execute(function (name, options, _) {
var subscription = profile.current.getSubscription(options.subscription);
var client = subscription.createResourceClient('createResourceManagementClient');
var progress = cli.interaction.progress($('Listing resource groups'));
var resourceGroup;
try {
resourceGroup = client.resourceGroups.get(name, _).resourceGroup;
} finally {
progress.end();
}
// Get resources for the resource group
progress = cli.interaction.progress($('Listing resources for the group'));
try {
resourceGroup.resources = client.resources.list({ resourceGroupName: name }, _).resources;
} finally {
progress.end();
}
cli.interaction.formatOutput(resourceGroup, function (outputData) {
showDetailedResourceGroup(outputData);
});
});
function showDetailedResourceGroup(resourceGroup) {
log.data($('Name: '), resourceGroup.name);
if (resourceGroup.resources && resourceGroup.resources.length > 0) {
log.data($('Resources:'));
log.data($(''));
log.table(resourceGroup.resources, function (row, item) {
row.cell($('Name'), item.name);
row.cell($('Type'), item.type);
row.cell($('Location'), item.location);
});
} else {
log.data($('Resources: []'));
log.data($(''));
}
}
};
|
JavaScript
| 0.000006 |
@@ -7508,16 +7508,17 @@
rceGroup
+
(resourc
|
46e3b6cdb638afc99472f7ad772085397a7dcce7
|
Fix baseline contrast
|
lib/components/chart/defaults.js
|
lib/components/chart/defaults.js
|
const { format } = require('../utils')
module.exports = {
chart: {
backgroundColor: 'transparent',
spacing: [ 0, 12, 0, 12 ],
style: {
fontFamily: 'inherit',
fontSize: '14px'
}
},
loading: {
labelStyle: {
position: 'absolute',
top: '50%',
left: '50%'
},
style: {
backgroundColor: 'transparent',
opacity: 1
}
},
noData: {
useHTML: true,
style: {
fontSize: '14px',
color: '#222'
}
},
responsive: {
rules: [{
chartOptions: {
yAxis: {
maxPadding: 0.2,
minPadding: 0.3
}
},
condition: {
minWidth: 400
}
}, {
chartOptions: {
chart: {
height: '40%',
spacing: [ 0, 24, 0, 24 ]
},
yAxis: {
maxPadding: 0.2
},
legend: {
layout: 'horizontal'
}
},
condition: {
minWidth: 800
}
}, {
chartOptions: {
chart: {
height: '35%'
}
},
condition: {
minWidth: 1000
}
}]
},
credits: {
enabled: false
},
title: { text: null },
legend: {
title: {
text: null
},
useHTML: true,
floating: true,
align: 'left',
verticalAlign: 'top',
layout: 'vertical',
margin: 0,
padding: 0,
itemStyle: {
color: 'currentColor',
textDecoration: 'none',
fontStyle: 'italic'
},
itemHiddenStyle: {
color: '#C5CCD3',
textDecoration: 'none'
},
itemHoverStyle: {
color: 'currentColor',
textDecoration: 'underline'
}
},
tooltip: {
padding: 0,
borderWidth: 0,
borderRadius: 3,
backgroundColor: 'transparent',
useHTML: true,
shadow: false,
shared: false,
style: {
fontSize: 'inherit',
color: 'inherit',
lineHeight: '21px'
}
},
xAxis: {
type: 'datetime',
lineWidth: 0,
tickWidth: 0,
offset: 25,
crosshair: {
width: 1,
color: 'rgba(255, 255, 255, 0.26)'
},
labels: {
style: {
color: 'currentColor'
}
}
},
yAxis: {
min: 0,
title: { text: null },
labels: { enabled: false },
gridLineWidth: 0,
maxPadding: 0.4,
softMin: 0,
plotLines: [{
color: 'rgba(255, 255, 255, 0.25)',
width: 1,
value: 0,
label: {
align: 'left',
text: '0 kWh',
style: {
fontSize: 11,
color: 'rgba(255, 255, 255, 0.25)'
},
x: 0,
y: 15
}
}]
},
plotOptions: {
spline: {
dataLabels: {
enabled: true,
formatter () {
return format(this.y)
},
y: -8,
verticalAlign: 'bottom',
style: {
color: 'currentColor',
textOutline: 'none',
fontWeight: 'bold'
}
},
lineWidth: 2,
states: {
hover: {
lineWidth: 2
}
},
events: {
mouseOver () {
this.chart.series.slice(0, 2).forEach(serie => {
serie.dataLabelsGroup.hide()
})
},
mouseOut () {
setTimeout(() => {
this.chart.series.slice(0, 2).forEach(serie => {
if (serie.visible) {
serie.dataLabelsGroup.show()
}
})
}, 500)
}
}
}
},
series: [
/**
* Primary data serie
*/
{
type: 'spline',
color: 'currentColor',
zIndex: 1,
marker: {
fillColor: '#388EE8',
lineWidth: 2,
states: {
hover: {
enabled: false
}
}
},
data: []
},
/**
* Comparative data serie
*/
{
type: 'spline',
color: '#19DDC0',
dataLabels: {
style: {
color: '#19DDC0'
}
},
tooltip: {
enabled: false
},
enableMouseTracking: false,
marker: {
fillColor: '#19DDC0',
lineColor: '#19DDC0',
symbol: 'circle',
states: {
hover: {
enabled: false
}
}
},
data: []
},
/**
* Actions
*/
{
type: 'scatter',
showInLegend: false,
tooltip: {
enabled: false
},
marker: {
enabled: false
},
dataLabels: {
enabled: true,
align: 'right',
color: 'currentColor',
useHTML: true,
zIndex: 0,
formatter () {
return `
<span class="Chart-action">
${this.point.name}
</span>
`
},
y: 0,
x: 3
},
enableMouseTracking: false,
data: []
}
]
}
|
JavaScript
| 0.000008 |
@@ -2360,18 +2360,17 @@
255, 0.
-25
+3
)',%0A
@@ -2539,18 +2539,17 @@
255, 0.
-25
+3
)'%0A
|
d9b6d84086f721fd6eed3019bdecd3bc26a909d4
|
add all HTTP methods supported by node to the router:
|
lib/connect/middleware/router.js
|
lib/connect/middleware/router.js
|
/*!
* Ext JS Connect
* Copyright(c) 2010 Sencha Inc.
* MIT Licensed
*/
/**
* Module dependencies.
*/
var parse = require('url').parse,
querystring = require('querystring');
/**
* Provides Sinatra and Express like routing capabilities.
*
* Examples:
*
* connect.router(function(app){
* app.get('/user/:id', function(req, res, next){
* // populates req.params.id
* });
* })
*
* @param {Function} fn
* @return {Function}
* @api public
*/
module.exports = function router(fn){
var routes
, self = this;
if (fn) {
routes = {};
var methods = {
post: method.call(this, 'post'),
get: method.call(this, 'get'),
put: method.call(this, 'put'),
delete: method.call(this, 'delete'),
};
methods.del = methods.delete;
methods.all = function(path, fn){
methods.get(path, fn);
methods.post(path, fn);
methods.put(path, fn);
methods.del(path, fn);
return self;
};
fn.call(this, methods);
} else {
throw new Error('router provider requires a callback function');
}
function method(name) {
var self = this,
localRoutes = routes[name] = routes[name] || [];
return function(path, fn){
var keys = [];
path = path instanceof RegExp
? path
: normalizePath(path, keys);
localRoutes.push({
fn: fn,
path: path,
keys: keys
});
return self;
};
}
return function router(req, res, next){
var route,
self = this;
(function pass(i){
if (route = match(req, routes, i)) {
req.params = route._params;
try {
route.call(self, req, res, function(err){
if (err === true) {
next();
} else if (err) {
next(err);
} else {
pass(route._index+1);
}
});
} catch (err) {
next(err);
}
} else {
next();
}
})();
};
}
/**
* Normalize the given path string,
* returning a regular expression.
*
* An empty array should be passed,
* which will contain the placeholder
* key names. For example "/user/:id" will
* then contain ["id"].
*
* @param {String} path
* @param {Array} keys
* @return {RegExp}
* @api private
*/
function normalizePath(path, keys) {
path = path
.concat('/?')
.replace(/\/\(/g, '(?:/')
.replace(/(\/)?(\.)?:(\w+)(\?)?/g, function(_, slash, format, key, optional){
keys.push(key);
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (format || '') + '([^/.]+))'
+ (optional || '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/\*/g, '(.+)');
return new RegExp('^' + path + '$', 'i');
}
/**
* Attempt to match the given request to
* one of the routes. When successful
* a route function is returned.
*
* @param {ServerRequest} req
* @param {Object} routes
* @return {Function}
* @api private
*/
function match(req, routes, i) {
var captures,
method = req.method.toLowerCase(),
i = i || 0;
if ('head' == method) method = 'get';
if (routes = routes[method]) {
var url = parse(req.url),
pathname = url.pathname;
for (var len = routes.length; i < len; ++i) {
var route = routes[i],
fn = route.fn,
path = route.path,
keys = route.keys;
if (captures = path.exec(pathname)) {
fn._params = [];
for (var j = 1, len = captures.length; j < len; ++j) {
var key = keys[j-1],
val = typeof captures[j] === 'string'
? querystring.unescape(captures[j])
: captures[j];
if (key) {
fn._params[key] = val;
} else {
fn._params.push(val);
}
}
fn._index = i;
return fn;
}
}
}
}
|
JavaScript
| 0.000023 |
@@ -639,20 +639,66 @@
-post
+%22del%22: method.call(this, 'del'),%0A %22get%22
: method
@@ -710,19 +710,18 @@
(this, '
-pos
+ge
t'),%0A
@@ -729,19 +729,22 @@
-get
+%22head%22
: method
@@ -748,34 +748,82 @@
hod.call(this, '
-ge
+head'),%0A %22post%22: method.call(this, 'pos
t'),%0A
@@ -823,19 +823,21 @@
+%22
put
+%22
: method
@@ -868,22 +868,24 @@
+%22
delete
+%22
: method
@@ -919,256 +919,771 @@
-%7D;%0A methods.del = methods.delete;%0A
+ %22connect%22: method.call(this, 'connect'),%0A %22options%22: method.call(this, 'options'),%0A %22trace%22: method.call(this, 'trace'),%0A %22copy%22:
method
-s
.
+c
all
- = function(path, fn)%7B%0A methods.get(path, fn);%0A methods.post(path, fn);%0A methods.put(path, fn);%0A methods.del(path, fn);%0A return self;%0A %7D
+(this, 'copy'),%0A %22lock%22: method.call(this, 'lock'),%0A %22mkcol%22: method.call(this, 'mkcol'),%0A %22move%22: method.call(this, 'move'),%0A %22propfind%22: method.call(this, 'propfind'),%0A %22proppatch%22: method.call(this, 'proppatch'),%0A %22unlock%22: method.call(this, 'unlock'),%0A %22report%22: method.call(this, 'report'),%0A %22mkactivity%22: method.call(this, 'mkactivity'),%0A %22checkout%22: method.call(this, 'checkout'),%0A %22merge%22: method.call(this, 'merge')%0A %7D;%0A methods.del = methods%5B%22delete%22%5D
;%0A
@@ -1711,17 +1711,16 @@
ethods);
-%0A
%7D el
|
af72784593016264a89cf55b1656907eb2ecf73a
|
Add Location to TBC
|
src/database/DataTypes/TemperatureBreachConfiguration.js
|
src/database/DataTypes/TemperatureBreachConfiguration.js
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
import Realm from 'realm';
import moment from 'moment';
import { createRecord } from '../utilities';
export class TemperatureBreachConfiguration extends Realm.Object {
/**
* With the provided temperatureLog, determines if the passed location
* was in a breach at the time of the temperature log and if so, will
* create a temperature breach record. Also adds to each of the temperature
* logs which are currently part of that breach, the related breach
* record.
*
* A breach has a duration and minimum and maximum temperatures defined by this
* configuration - for example above 8 degrees for 2 hours. To determine if a
* location has currently been breached, look back from the temperature logs
* timestamp the duration of this configuration and determine if every temperature
* log since that time has been outside of the threshold.
*
* @param {Realm} database App-wide database interface
* @param {Location} location A Location record to create a breach for.
* @param {TemperatureLog} temperatureLog A potential log which may create a breach.
*/
createBreach(database, location, temperatureLog) {
const { timestamp } = temperatureLog;
const { temperatureLogs } = location;
// The potential start time of the breach - looking back from the passed
// temperature log to the pre-configured minimum duration of a breach.
const startTime = moment(timestamp).subtract(this.duration, 'ms').toDate();
// Find all of the temperature logs since the possible start time of the
// breach.
const proximalLogs = temperatureLogs.filtered(
'timestamp >= $0 && timestamp <= $1',
startTime,
timestamp
);
// Ensure the duration of the temporally proximal temperature logs is
// greater than the duration required for a breach.
const mostRecentTimestamp = moment(proximalLogs.max('timestamp'));
const leastRecentTimestamp = moment(proximalLogs.min('timestamp'));
const isDurationLongEnough =
mostRecentTimestamp.diff(leastRecentTimestamp, 'ms') >= this.duration;
// If the duration of logs is sufficiently long enough, also ensure each temperature
// log exceeds the threshold required for a breach
const logInBreachRange = ({ temperature: logTemperature }) =>
logTemperature >= this.minimumTemperature && logTemperature <= this.maximumTemperature;
const willCreateBreach = isDurationLongEnough && proximalLogs.every(logInBreachRange);
// Create a breach if the duration of logs and temperatures define a breach and set
// each temperature log as part of the breach.
if (willCreateBreach) {
const breach = createRecord(database, 'TemperatureBreach', startTime, location, this);
proximalLogs.forEach(log => database.update('TemperatureLog', { ...log, breach }));
}
return willCreateBreach;
}
}
TemperatureBreachConfiguration.schema = {
name: 'TemperatureBreachConfiguration',
primaryKey: 'id',
properties: {
id: 'string',
minimumTemperature: { type: 'double', optional: true },
maximumTemperature: { type: 'double', optional: true },
duration: { type: 'double', optional: true },
description: { type: 'string', optional: true },
colour: { type: 'string', optional: true },
type: 'string',
},
};
export default TemperatureBreachConfiguration;
|
JavaScript
| 0 |
@@ -3354,24 +3354,76 @@
al: true %7D,%0A
+ location: %7B type: 'Location', optional: true %7D,%0A
type: 's
|
d2bfa4fc9abb6b47cd5c2c64652d315e9a0d1699
|
Allow setting hide text related css classes on wrapper
|
app/assets/javascripts/pageflow/slideshow/hidden_text_indicator_widget.js
|
app/assets/javascripts/pageflow/slideshow/hidden_text_indicator_widget.js
|
(function($) {
$.widget('pageflow.hiddenTextIndicator', {
_create: function() {
var parent = this.options.parent,
that = this;
parent.on('pageactivate', function(event) {
that.element.toggleClass('invert', $(event.target).hasClass('invert'));
that.element.toggleClass('hidden',
$(event.target).hasClass('hide_content_with_text') ||
$(event.target).hasClass('no_hidden_text_indicator'));
});
parent.on('hidetextactivate', function() {
that.element.addClass('visible');
});
parent.on('hidetextdeactivate', function() {
that.element.removeClass('visible');
});
}
});
}(jQuery));
|
JavaScript
| 0 |
@@ -189,24 +189,119 @@
on(event) %7B%0A
+ var pageOrPageWrapper = $(event.target).add('.content_and_background', event.target);%0A%0A
that
@@ -440,39 +440,41 @@
-$(event.target)
+pageOrPageWrapper
.hasClass('h
@@ -533,31 +533,33 @@
-$(event.target)
+pageOrPageWrapper
.hasClas
|
493ace65fe293d1ec1f276afaad3ceab5b3cc81e
|
improved checking if given image is a canvas
|
JsBarcode.js
|
JsBarcode.js
|
(function($){
JsBarcode = function(image, content, options) {
var merge = function(m1, m2) {
var newMerge = {};
for (var k in m1) {
newMerge[k] = m1[k];
}
for (var k in m2) {
newMerge[k] = m2[k];
}
return newMerge;
};
//Merge the user options with the default
options = merge(JsBarcode.defaults, options);
//Create the canvas where the barcode will be drawn on
// Check if the given image is already a canvas
var canvas = image;
// check if it is a jQuery selection
if (image instanceof jQuery) {
// get the DOM element of the selection
canvas = image.get(0);
// check if DOM element is a canvas, otherwise it will be probably an image so create a canvas
if (!(canvas instanceof HTMLCanvasElement)) {
canvas = document.createElement('canvas');
}
} else if (!(image instanceof HTMLCanvasElement)) {
// there is no jQuery selection so just check if DOM element is a canvas, otherwise it will be probably
// an image so create a canvas
canvas = document.createElement('canvas');
}
//Abort if the browser does not support HTML5canvas
if (!canvas.getContext) {
return image;
}
var encoder = new window[options.format](content);
//Abort if the barcode format does not support the content
if(!encoder.valid()){
return this;
}
//Encode the content
var binary = encoder.encoded();
var _drawBarcodeText = function (text) {
var x, y;
y = options.height;
ctx.font = options.fontSize + "px "+options.font;
ctx.textBaseline = "bottom";
ctx.textBaseline = 'top';
if(options.textAlign == "left"){
x = options.quite;
ctx.textAlign = 'left';
}
else if(options.textAlign == "right"){
x = canvas.width - options.quite;
ctx.textAlign = 'right';
}
else{ //All other center
x = canvas.width / 2;
ctx.textAlign = 'center';
}
ctx.fillText(text, x, y);
}
//Get the canvas context
var ctx = canvas.getContext("2d");
//Set the width and height of the barcode
canvas.width = binary.length*options.width+2*options.quite;
canvas.height = options.height + (options.displayValue ? options.fontSize : 0);
//Paint the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
if(options.backgroundColor){
ctx.fillStyle = options.backgroundColor;
ctx.fillRect(0,0,canvas.width,canvas.height);
}
//Creates the barcode out of the encoded binary
ctx.fillStyle = options.lineColor;
for(var i=0;i<binary.length;i++){
var x = i*options.width+options.quite;
if(binary[i] == "1"){
ctx.fillRect(x,0,options.width,options.height);
}
}
if(options.displayValue){
_drawBarcodeText(content);
}
//Grab the dataUri from the canvas
uri = canvas.toDataURL('image/png');
// check if given image is a jQuery selection
if (image instanceof jQuery) {
// check if the given image was a canvas, if not set the source attribute of the image
if (!(image.get(0) instanceof HTMLCanvasElement)) {
//Put the data uri into the image
return image.attr("src", uri);
}
} else if (!(image instanceof HTMLCanvasElement)) {
// There is no jQuery selection so just check if the given image was a canvas, if not set the source attr
image.setAttribute("src", uri);
}
};
JsBarcode.defaults = {
width: 2,
height: 100,
quite: 10,
format: "CODE128",
displayValue: false,
font:"Monospaced",
textAlign:"center",
fontSize: 12,
backgroundColor:"",
lineColor:"#000"
};
$.fn.JsBarcode = function(content, options){
JsBarcode(this, content, options);
return this;
};
})(jQuery);
|
JavaScript
| 0.999763 |
@@ -523,33 +523,30 @@
jQuery
-selection
+object
%0D%0A%09%09if (
image in
@@ -529,37 +529,38 @@
y object%0D%0A%09%09if (
-image
+canvas
instanceof jQue
@@ -599,25 +599,22 @@
of the
-selection
+object
%0D%0A%09%09%09can
@@ -635,16 +635,22 @@
t(0);%0D%0A%09
+%09%7D%0D%0A%0D%0A
%09%09// che
@@ -737,25 +737,24 @@
a canvas%0D%0A%09%09
-%09
if (!(canvas
@@ -792,260 +792,8 @@
%7B%0D%0A
-%09%09%09%09canvas = document.createElement('canvas');%0D%0A%09%09%09%7D%0D%0A%09%09%7D else if (!(image instanceof HTMLCanvasElement)) %7B%0D%0A%09%09%09// there is no jQuery selection so just check if DOM element is a canvas, otherwise it will be probably%0D%0A%09%09%09// an image so create a canvas%0D%0A
%09%09%09c
@@ -2704,25 +2704,22 @@
jQuery
-selection
+object
%0D%0A%09%09if (
@@ -2765,76 +2765,80 @@
if
-the given image was a canvas, if not set the source attribute of the
+DOM element of jQuery selection is not a canvas, so assume that it is an
ima
@@ -2901,16 +2901,17 @@
%7B%0D%0A%09%09%09%09
+
//Put th
@@ -2940,16 +2940,17 @@
age%0D%0A%09%09%09
+
%09return
@@ -3060,25 +3060,22 @@
jQuery
-selection
+object
so just
|
ea24bbecd53b5d7d415d06714cf318871824235c
|
Correct copy/paste fail
|
lib/items/commit-preview-item.js
|
lib/items/commit-preview-item.js
|
import React from 'react';
import PropTypes from 'prop-types';
import {Emitter} from 'event-kit';
import {WorkdirContextPoolPropType} from '../prop-types';
import CommitPreviewContainer from '../containers/commit-preview-container';
export default class CommitPreviewItem extends React.Component {
static propTypes = {
workdirContextPool: WorkdirContextPoolPropType.isRequired,
workingDirectory: PropTypes.string.isRequired,
}
static uriPattern = 'atom-github://commit-preview?workdir={workingDirectory}'
static buildURI(relPath, workingDirectory) {
return `atom-github://commit-preview?workdir=${encodeURIComponent(workingDirectory)}`;
}
constructor(props) {
super(props);
this.emitter = new Emitter();
this.isDestroyed = false;
this.hasTerminatedPendingState = false;
}
terminatePendingState() {
if (!this.hasTerminatedPendingState) {
this.emitter.emit('did-terminate-pending-state');
this.hasTerminatedPendingState = true;
}
}
onDidTerminatePendingState(callback) {
return this.emitter.on('did-terminate-pending-state', callback);
}
destroy() {
/* istanbul ignore else */
if (!this.isDestroyed) {
this.emitter.emit('did-destroy');
this.isDestroyed = true;
}
}
onDidDestroy(callback) {
return this.emitter.on('did-destroy', callback);
}
render() {
const repository = this.props.workdirContextPool.getContext(this.props.workingDirectory).getRepository();
return (
<CommitPreviewContainer
repository={repository}
{...this.props}
/>
);
}
getTitle() {
return 'Commit preview';
}
getIconName() {
return 'git-commit';
}
}
|
JavaScript
| 0.000001 |
@@ -538,17 +538,8 @@
URI(
-relPath,
work
|
5e7c9cc137aaf8ba821a09b70452261d30043c78
|
fix reducer for selected node after delete
|
src/reducers/pipelineUIReducer.js
|
src/reducers/pipelineUIReducer.js
|
import {
UNSELECT_NODE
} from '../actions';
import {
DELETE_NODE,
INSPECT_NODE,
NODE_CHANGED
} from '../larissa/redux/actions';
const defaultState = {
selectedNode: {
node: {}
},
};
export default function (state = defaultState, action) {
switch (action.type) {
case INSPECT_NODE:
return {...state, selectedNode: action.payload};
case NODE_CHANGED:
if (state.selectedNode.node.id === action.payload.node.id) {
return {...state, selectedNode: action.payload};
}
return state;
case UNSELECT_NODE:
return {...state, selectedNode: {node: {}}};
case DELETE_NODE: {
if (state.selectedNode.id === action.payload) {
return {...state, selectedNode: {node: {}}};
} else {
return state;
}
}
default:
return state;
}
}
|
JavaScript
| 0 |
@@ -730,24 +730,29 @@
electedNode.
+node.
id === actio
|
5c105d7023debcf2c745836dd0c2ae0f6bc12fe0
|
fix for missing airport panel
|
app/protected/modules/gamification/views/assets/gamification-dashboard.js
|
app/protected/modules/gamification/views/assets/gamification-dashboard.js
|
var highestZIndex,
leftAnimation,
animationTime,
easingType,
carouselWidth,
viewfinderWidth,
maxLeft,
maxRight,
myLeft,
fixedStep,
firstVisible,
numPanels,
numToScroll;
function getCurrentVisibleCollections(direction){
if( firstVisible >= 1 && firstVisible <= (numPanels + 1) - numToScroll ){
$('.gd-collection-panel').removeClass('visible-panel');
$('.gd-collection-panel').removeClass('visible-panel-last');
var step = fixedStep;
myLeft = parseInt($('#gd-carousel').css('margin-left'));
if(direction === 'forward'){
if((myLeft - step) <= maxLeft){
step = maxLeft;
currentLeftMargin = maxLeft;
} else {
step = '-=' + fixedStep.toString();
}
firstVisible++;
}
if(direction === 'back'){
if( (myLeft + step) > maxRight){
step = 0;
currentLeftMargin = 0;
} else {
step = '+=' + fixedStep.toString();
}
firstVisible--;
}
if(firstVisible === 0){
firstVisible = 1;
}
if(firstVisible > (numPanels + 1) - numToScroll){
firstVisible = (numPanels + 1) - 4;
}
$('#gd-carousel').stop( true, true ).animate({ marginLeft : step.toString() }, animationTime, easingType);
var i;
for (i = firstVisible; i < firstVisible + numToScroll; i++){
$( '.gd-collection-panel:nth-child(' + i + ')').addClass('visible-panel');
}
$( '.gd-collection-panel:nth-child(' + (i-1) + ')').addClass('visible-panel-last');
}
}
$(window).ready(function(){
highestZIndex = 100;
leftAnimation = 0;
animationTime = 425;
easingType = 'easeOutQuint';
carouselWidth = $('#gd-carousel').outerWidth();
viewfinderWidth = 1140;
maxLeft = viewfinderWidth - carouselWidth;
maxRight = 0;
myLeft;
fixedStep = 285;
firstVisible = 1;
numPanels = $('.gd-collection-panel').length;
numToScroll = 4;
$('#gd-carousel').on('mouseenter', '.gd-collection-panel', function() {
if ($(this).hasClass('visible-panel-last') === true){
leftAnimation = -285;
} else {
leftAnimation = 0;
}
$('> div', this).css('z-index', highestZIndex++).stop( true, true ).animate({
width:'570px', top:'-95px', left: leftAnimation
}, animationTime, easingType);
});
$('#gd-carousel').on('mouseleave', '.gd-collection-panel', function() {
$('> div', this).stop( true, true ).animate({width:'100%', top:0, left: 0}, animationTime, easingType,
function(){
$(this).css('z-index', 0);
});
}
);
$('#nav-right').click(function(){
getCurrentVisibleCollections('forward');
return false;
});
$('#nav-left').click(function(){
getCurrentVisibleCollections('back');
return false;
});
$(document).on('mouseover', '.gd-collection-item img', function(event) {
$(this).qtip({
overwrite: false,
content: {'attr':'data-tooltip'},
position: {my: 'bottom center', at: 'top center'},
show: {
event: event.type,
ready: true
}
}, event);
})
getCurrentVisibleCollections('forward');
});
|
JavaScript
| 0 |
@@ -258,16 +258,26 @@
irection
+, firstRun
)%7B%0A i
@@ -346,16 +346,37 @@
oScroll
+%7C%7C firstRun === true
)%7B%0A
@@ -1330,32 +1330,67 @@
- 4;%0A %7D%0A
+ if(firstRun !== true)%7B%0A
$('#gd-c
@@ -1484,24 +1484,34 @@
asingType);%0A
+ %7D%0A
var
@@ -2108,24 +2108,25 @@
stVisible =
+-
1;%0A numPa
@@ -2692,28 +2692,24 @@
) %7B%0A
-
$('%3E div', t
@@ -2811,20 +2811,16 @@
-
function
@@ -2819,28 +2819,24 @@
function()%7B%0A
-
@@ -2866,20 +2866,16 @@
x', 0);%0A
-
@@ -3495,16 +3495,16 @@
%7D)%0A%0A
-
getC
@@ -3537,14 +3537,20 @@
forward'
+, true
);%0A%7D);
|
7683ea1bb58a61fc8f64b824b6e9d3b941fd785c
|
add reset check state after answer
|
app/scripts/category/alphabet/origin/practice/originpractice.component.js
|
app/scripts/category/alphabet/origin/practice/originpractice.component.js
|
'use strict';
(function () {
// Define the `header` module
var app = angular.module('app.category');
// Register `headerList` component, along with its associated controller and template
app.component('originPractice', {
template: '<div ng-include="$ctrl.templateUrl"></div>',
bindings: {
jsonData: '<',
subData: '<'
},
controller: [
'$scope',
'$state',
'$element',
'$location',
'$interval',
'Config',
'Util',
'Json',
controller]
});
function controller($scope, $state, $element, $location, $interval, config, util, json) {
var self = this;
//define self variables
self.templateUrl = config.templateUrl.originpractice;
self.langs = {};
self.audio = {};
self.answerAlphas = [];
self.correct = false;
self.error = false;
self.$onInit = function () {
self.langs.name = self.jsonData[0].name + config.alphaLangs.practice;
self.langs.selectAlpha = config.alphaLangs.selectAlpha;
self.langs.checkAnswer = config.alphaLangs.checkAnswer;
self.langs.exit = config.alphaLangs.exit;
self.langs.notSupportHtml5Audio = config.alphaLangs.notSupportHtml5Audio;
self.langs.nextTest = config.alphaLangs.nextTest;
setFourAlphas();
};
self.$postLink = function () {
var stop = $interval(function () {
if (!audioElem) {
audioElem = $element.find('audio')[0];
} else {
$interval.cancel(stop);
audioElem.onended = self.playAudios;
}
}, 10);
};
self.exitPractice = function () {
$location.path("/" + config.app.url + "/" + config.pagesUrl.alphaOrigin);
};
self.getAlphaClass = function (alpha) {
var name = config.alphaCss.practiceEmpty;
if(answered) {
name = 'origin-' + alpha.fileName;
}
return name;
};
self.playAudios = function () {
if (playedAudioId == testAlphas.length) {
playedAudioId = 0;
return;
}
var name = testAlphas[playedAudioId].fileName;
var gender = util.getRandomGender();
self.audio = {
mpeg: url + config.data.audios + '/' + name + '/' + name + gender + config.dataTypes.audios[1],
ogg: url + config.data.audios + '/' + name + '/' + name + gender + config.dataTypes.audios[0]
};
if (playedAudioId != 0) {
$scope.$digest();
}
audioElem.load();
audioElem.play();
playedAudioId++;
};
self.selectAlphaClick = function() {
$scope.$broadcast(config.events.displayOriginRandom);
};
self.checkAnswerClick = function() {
self.correct = false;
self.error = false;
if(!answered) {
return;
}
if(answerCorrect()) {
self.correct = true;
} else {
self.error = true;
}
};
self.nextTestClick = function() {
$state.reload();
};
var testAlphas = [];
var audioElem = null;
var playedAudioId = 0;
var url = config.mediaUrl.alphaOrigin;
var answered = false;
var setFourAlphas = function () {
var position = Math.floor(Math.random() * (self.subData.length - 3));
testAlphas = self.subData.slice(position, position + 4);
self.answerAlphas = angular.copy(testAlphas);
};
var autoPlayAudio = function () {
self.playAudios();
};
var selectRandomAlphas = function(event, alphas) {
if((answered == true) && (alphas.length == 0)) {
self.answerAlphas = angular.copy(testAlphas);
answered = false;
return;
}
if(alphas.length != 4) {
return;
}
self.answerAlphas = angular.copy(alphas);
answered = true;
};
var answerCorrect = function() {
var correct = true;
$.each(testAlphas, function(i, v){
if(v.id != self.answerAlphas[i].id) {
correct = false;
}
});
return correct;
};
// add listener and hold on to deregister function
var deregister = [];
deregister.push($scope.$on(config.events.selectRandomAlphas, selectRandomAlphas));
//deregister.push(videoElem.on('ended', videoEnded));
// clean up listener when directive's scope is destroyed
$.each(deregister, function (i, val) {
$scope.$on('$destroy', val);
});
};
})();
|
JavaScript
| 0 |
@@ -2665,54 +2665,14 @@
-self.correct = false;%0A self.error = false
+init()
;%0A
@@ -3048,16 +3048,106 @@
false;%0A%0A
+ var init = function() %7B%0A self.correct = false;%0A self.error = false;%0A %7D;%0A%0A
var
@@ -3711,24 +3711,38 @@
rn;%0A %7D%0A
+ init();%0A
self.a
|
c1bc0c32fa688c64754fc590aa12c645785c6d69
|
Improve our externs for async.
|
externs/async.js
|
externs/async.js
|
// The subset of the Async API that we use.
var async = {
each: function() {},
every: function() {},
map: function() {},
parallel: function() {},
series: function () {},
waterfall: function () {}
}
|
JavaScript
| 0 |
@@ -1,10 +1,28 @@
/
-/
+**%0A * @fileoverview
The sub
@@ -32,17 +32,17 @@
of the
-A
+a
sync API
@@ -59,29 +59,179 @@
se.%0A
-var async = %7B%0A
+ */%0A%0A/** @type %7BObject%7D */%0Avar async = %7B%7D%0A%0A/**%0A * @param %7BArray%7D arr%0A * @param %7Bfunction(*,function(Error))%7D iterator%0A * @param %7Bfunction(Error)%7D callback%0A */%0Aasync.
each
-:
+ =
fun
@@ -239,45 +239,176 @@
tion
-() %7B%7D,%0A every: function() %7B%7D,%0A map:
+ (arr, iterator, callback) %7B%7D%0A%0A/**%0A * @param %7BArray%7D arr%0A * @param %7Bfunction(*,function(Error, *))%7D iterator%0A * @param %7Bfunction(Error, Array)%7D callback%0A */%0Aasync.map =
fun
@@ -416,70 +416,692 @@
tion
-() %7B%7D,%0A parallel: function() %7B%7D,%0A series: function () %7B%7D,%0A
+ (arr, iterator, callback) %7B%7D%0A%0A/**%0A * @param %7BArray%7D arr%0A * @param %7Bfunction(*,function(boolean))%7D iterator%0A * @param %7Bfunction(boolean)%7D callback%0A */%0Aasync.every = function (arr, iterator, callback) %7B%7D%0A%0A/**%0A * @param %7BArray.%3Cfunction(Error,*)%3E%7CObject.%3Cfunction(Error,*)%3E%7D tasks%0A * @param %7Bfunction(Error,Array)=%7D callback%0A */%0Aasync.series = function (tasks, callback) %7B%7D%0A%0A/**%0A * @param %7BArray.%3Cfunction(Error,*)%3E%7CObject.%3Cfunction(Error,*)%3E%7D tasks%0A * @param %7Bfunction(Error,Array)=%7D callback%0A */%0Aasync.parallel = function (tasks, callback) %7B%7D%0A%0A/**%0A * @param %7BArray.%3Cfunction(Error,...%5B?%5D)%3E%7CObject.%3Cfunction(Error,...%5B?%5D)%3E%7D tasks%0A * @param %7Bfunction(Error,Array=)=%7D callback%0A */%0Aasync.
wate
@@ -1109,9 +1109,10 @@
fall
-:
+ =
fun
@@ -1122,11 +1122,48 @@
on (
-) %7B%7D%0A%7D
+tasks, callback) %7B%7D%0A%0Amodule.exports = async
%0A
|
f1205d44b572d8a9e6044976b13f317076d07004
|
create #search function in searchcomponentCtrl
|
client/app/search/components/searchComponentController.js
|
client/app/search/components/searchComponentController.js
|
(function(){
'use strict';
angular.module('topFive.search')
.controller('searchComponentController', searchComponentCtrl);
searchComponentCtrl.$inject = ['searchFactory'];
function searchComponentCtrl(searchFactory){
var vm = this;
vm.options = {
type:'',
query:'',
limit:20
};
vm.getResults = getResults;
function getResults(resultsArr){
// should capture results array and set it to "results"
// object in home ctrl
vm.onSearch(resultsArr);
}
// create search function that calls search factory
// grabs results and calls vm.getResults to calls onSearch
// REFACTOR: get rid of #getResults and call vm.onSearch directly
}
})();
|
JavaScript
| 0.000001 |
@@ -348,16 +348,223 @@
esults;%0A
+ vm.search = search;%0A%0A function search(options)%7B%0A searchFactory.search(vm.options).then(function(data)%7B%0A console.log('search results', data);%0A // vm.onSearch(data);%0A %7D);%0A %7D%0A%0A
%0A fun
|
4ab11c13ee5f65b13779834280c12594bd56fdc3
|
version JS changes in webpack
|
pkg/interface/config/webpack.prod.js
|
pkg/interface/config/webpack.prod.js
|
const path = require('path');
// const HtmlWebpackPlugin = require('html-webpack-plugin');
// const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'production',
entry: {
app: './src/index.js'
},
module: {
rules: [
{
test: /\.(j|t)sx?$/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/typescript', '@babel/preset-react'],
plugins: [
'@babel/transform-runtime',
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-proposal-class-properties'
]
}
},
exclude: /node_modules/
},
{
test: /\.css$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader'
]
}
]
},
resolve: {
extensions: ['.js', '.ts', '.tsx']
},
devtool: 'inline-source-map',
// devServer: {
// contentBase: path.join(__dirname, './'),
// hot: true,
// port: 9000,
// historyApiFallback: true
// },
plugins: [
// new CleanWebpackPlugin(),
// new HtmlWebpackPlugin({
// title: 'Hot Module Replacement',
// template: './public/index.html',
// }),
],
output: {
filename: 'index.js',
chunkFilename: 'index.js',
path: path.resolve(__dirname, '../../arvo/app/landscape/js'),
publicPath: '/'
},
optimization: {
minimize: true,
usedExports: true
}
};
|
JavaScript
| 0 |
@@ -1497,38 +1497,21 @@
dex.
-js',%0A chunkFilename: 'index
+%5Bcontenthash%5D
.js'
|
922888db6e3fc5debe3dc4a823ad64da61f69056
|
put extra resource to terminal if possible
|
src/action/store.js
|
src/action/store.js
|
let mod = new ActionObj('Store');
module.exports = mod;
const targetInitFunc = function(creep) {
const storage = Game.rooms[creep.memory.homeRoom].storage;
if(storage) {
return storage;
} else {
const keepers = _.filter(creep.room.cachedFind(FIND_MY_CREEPS), c => c.memory.role === C.KEEPER);
if(keepers.length>0) {
return keepers[0];
} else {
return false;
}
}
};
mod.nextTarget = function() {
return Util.Mark.handleMark(this.creep, targetInitFunc, this.actionName);
};
mod.word = '➡︎ store';
mod.loop = function(creep) {
return this.loop0(creep, (creep, target) => {
// store all resources
let result;
for(const resourceType in creep.carry) {
result = creep.transfer(target, resourceType);
}
if(result == ERR_NOT_IN_RANGE) {
creep.moveTo(target, {visualizePathStyle: {stroke: '#ffaa00'}});
} else if(result == OK) {
if(_.sum(creep.carry) > 0) {
//So there may be resource remain
} else {
Util.Mark.unmarkTarget(creep, this.actionName);
}
} else if(result == ERR_FULL) {
Util.Mark.unmarkTarget(creep, this.actionName);
}
});
};
|
JavaScript
| 0.000001 |
@@ -162,44 +162,254 @@
-if(storage) %7B%0A return storage
+const terminal = Game.rooms%5Bcreep.memory.homeRoom%5D.terminal;%0A if(storage && _.sum(storage.store)%3Cstorage.storeCapacity) %7B%0A return storage;%0A %7D else if(terminal && _.sum(terminal.store)%3Cterminal.storeCapacity) %7B%0A return terminal
;%0A
@@ -755,18 +755,442 @@
tionName
-);
+, validateFunc);%0A%7D;%0A%0Aconst validateFunc = function(creep, target) %7B%0A if(!target.room %7C%7C target.room.name!==creep.room.name) return false;%0A const carryRemain = _.sum(creep.carry);%0A if(target.store) %7B%0A return (target.storeCapacity-_.sum(target.store)) %3E= carryRemain;%0A %7D else if(target.carry) %7B%0A return (target.carryCapacity-_.sum(target.carry)) %3E= carryRemain;%0A %7D else %7B%0A return false;%0A %7D
%0A%7D;%0A%0Amod
|
6961e6e10eb4190a715bc9dfc05065d2f2ceeeeb
|
remove comments
|
modules/client/app/tasks/tasks.controller.js
|
modules/client/app/tasks/tasks.controller.js
|
'use strict';
import angular from 'angular';
import $ from 'jquery';
let ipc = require('ipc');
const index = {
'folderList': '.row > .col-md-6:first-child > ul',
'taskList': '.row > .col-md-6:nth-child(2) > ul',
'editTaskBody': '#editTaskModal > .modal-dialog > .modal-content > .container-fluid > .row > .modal-body'
}
const TaskCtrl = ($scope) => {
setTimeout(() => {
console.log(getActiveFolder());
ipc.send('tasks', {query: 'get', where: {'name': getActiveFolder().name, 'path': getActiveFolder().path}});
}, 0);
ipc.on('tasks/get', (res) => {
if(res.status === 200) {
console.log('Got the tasks!');
console.log(res);
$scope.tasks = res.data;
$scope.safeApply();
console.log($scope.tasks);
} else if(res.status === 404) {
console.log('No tasks found because: "%s"', res.error);
console.log(res);
}
});
$scope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if(phase === '$apply' || phase === '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
}
module.exports = TaskCtrl;
function getActiveFolder() {
console.log($(index.folderList).children().find('.activeFolder'));
let folderName = $('.activeFolder').find('h3').html();
let folderPath = $('.activeFolder').find('p').find('i').html();
setTimeout(() => {console.log($('.activeFolder'))}, 0);
return {
'name': folderName,
'path': folderPath
}
}
|
JavaScript
| 0 |
@@ -598,69 +598,8 @@
) %7B%0A
- console.log('Got the tasks!');%0A console.log(res);%0A
@@ -655,41 +655,8 @@
();%0A
- console.log($scope.tasks);%0A
|
4dd6869c15e872103f7e2cc9f82fb88dae68c474
|
fix exception in mobile safari's private browsing mode
|
src/adapters/dom.js
|
src/adapters/dom.js
|
/**
* dom storage adapter
* ===
* - originally authored by Joseph Pecoraro
*
*/
//
// TODO does it make sense to be chainable all over the place?
// chainable: nuke, remove, all, get, save, all
// not chainable: valid, keys
//
Lawnchair.adapter('dom', (function() {
var storage = window.localStorage
// the indexer is an encapsulation of the helpers needed to keep an ordered index of the keys
var indexer = function(name) {
return {
// the key
key: name + '._index_',
// returns the index
all: function() {
var a = storage.getItem(this.key)
if (a) {
a = JSON.parse(a)
}
if (a === null) storage.setItem(this.key, JSON.stringify([])) // lazy init
return JSON.parse(storage.getItem(this.key))
},
// adds a key to the index
add: function (key) {
var a = this.all()
a.push(key)
storage.setItem(this.key, JSON.stringify(a))
},
// deletes a key from the index
del: function (key) {
var a = this.all(), r = []
// FIXME this is crazy inefficient but I'm in a strata meeting and half concentrating
for (var i = 0, l = a.length; i < l; i++) {
if (a[i] != key) r.push(a[i])
}
storage.setItem(this.key, JSON.stringify(r))
},
// returns index for a key
find: function (key) {
var a = this.all()
for (var i = 0, l = a.length; i < l; i++) {
if (key === a[i]) return i
}
return false
}
}
}
// adapter api
return {
// ensure we are in an env with localStorage
valid: function () {
return !!storage
},
init: function (options, callback) {
this.indexer = indexer(this.name)
if (callback) this.fn(this.name, callback).call(this, this)
},
save: function (obj, callback) {
var key = obj.key ? this.name + '.' + obj.key : this.name + '.' + this.uuid()
// if the key is not in the index push it on
if (this.indexer.find(key) === false) this.indexer.add(key)
// now we kil the key and use it in the store colleciton
delete obj.key;
storage.setItem(key, JSON.stringify(obj))
obj.key = key.slice(this.name.length + 1)
if (callback) {
this.lambda(callback).call(this, obj)
}
return this
},
batch: function (ary, callback) {
var saved = []
// not particularily efficient but this is more for sqlite situations
for (var i = 0, l = ary.length; i < l; i++) {
this.save(ary[i], function(r){
saved.push(r)
})
}
if (callback) this.lambda(callback).call(this, saved)
return this
},
// accepts [options], callback
keys: function(callback) {
if (callback) {
var name = this.name
, keys = this.indexer.all().map(function(r){ return r.replace(name + '.', '') })
this.fn('keys', callback).call(this, keys)
}
return this // TODO options for limit/offset, return promise
},
get: function (key, callback) {
if (this.isArray(key)) {
var r = []
for (var i = 0, l = key.length; i < l; i++) {
var k = this.name + '.' + key[i]
var obj = storage.getItem(k)
if (obj) {
obj = JSON.parse(obj)
obj.key = key[i]
r.push(obj)
}
}
if (callback) this.lambda(callback).call(this, r)
} else {
var k = this.name + '.' + key
var obj = storage.getItem(k)
if (obj) {
obj = JSON.parse(obj)
obj.key = key
}
if (callback) this.lambda(callback).call(this, obj)
}
return this
},
exists: function (key, cb) {
var exists = this.indexer.find(this.name+'.'+key) === false ? false : true ;
this.lambda(cb).call(this, exists);
return this;
},
// NOTE adapters cannot set this.__results but plugins do
// this probably should be reviewed
all: function (callback) {
var idx = this.indexer.all()
, r = []
, o
, k
for (var i = 0, l = idx.length; i < l; i++) {
k = idx[i] //v
o = JSON.parse(storage.getItem(k))
o.key = k.replace(this.name + '.', '')
r.push(o)
}
if (callback) this.fn(this.name, callback).call(this, r)
return this
},
remove: function (keyOrObj, callback) {
var key = this.name + '.' + ((keyOrObj.key) ? keyOrObj.key : keyOrObj)
this.indexer.del(key)
storage.removeItem(key)
if (callback) this.lambda(callback).call(this)
return this
},
nuke: function (callback) {
this.all(function(r) {
for (var i = 0, l = r.length; i < l; i++) {
this.remove(r[i]);
}
if (callback) this.lambda(callback).call(this)
})
return this
}
}})());
|
JavaScript
| 0.000005 |
@@ -1913,24 +1913,481 @@
n !!storage
+&& function() %7B%0A // in mobile safari if safe browsing is enabled, window.storage%0A // is defined but setItem calls throw exceptions.%0A var success = true%0A var value = Math.random()%0A try %7B%0A storage.setItem(value, value)%0A %7D catch (e) %7B%0A success = false%0A %7D%0A storage.removeItem(value)%0A return success%0A %7D()
%0A %7D,%0A
|
1733bac3bbf6612dc9697ac028676b04d05b51a4
|
move chokidar to top
|
bin/6to5/dir.js
|
bin/6to5/dir.js
|
var chokidar = require("chokidar");
var outputFileSync = require("output-file-sync");
var path = require("path");
var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
module.exports = function (commander, filenames, opts) {
if (commander.sourceMapsInline) {
opts.sourceMap = "inline";
}
var write = function (src, relative) {
var dest = path.join(commander.outDir, relative);
var data = util.compile(src, { sourceMapName: dest });
if (commander.sourceMaps) {
var mapLoc = dest + ".map";
data.code = util.addSourceMappingUrl(data.code, mapLoc);
outputFileSync(mapLoc, JSON.stringify(data.map));
}
outputFileSync(dest, data.code);
console.log(src + " -> " + dest);
};
var handle = function (filename) {
if (!fs.existsSync(filename)) return;
var stat = fs.statSync(filename);
if (stat.isDirectory(filename)) {
var dirname = filename;
_.each(util.readdirFilter(dirname), function (filename) {
write(path.join(dirname, filename), filename);
});
} else {
write(filename, filename);
}
};
_.each(filenames, handle);
if (commander.watch) {
_.each(filenames, function (dirname) {
var watcher = chokidar.watch(dirname, {
persistent: true,
ignoreInitial: true
});
_.each(["add", "change", "unlink"], function (type) {
watcher.on(type, function (filename) {
// chop off the dirname plus the path separator
var relative = filename.slice(dirname.length + 1);
console.log(type, filename);
write(filename, relative);
});
});
});
}
};
|
JavaScript
| 0 |
@@ -1,46 +1,4 @@
-var chokidar = require(%22chokidar%22);%0A
var
@@ -39,24 +39,66 @@
ile-sync%22);%0A
+var chokidar = require(%22chokidar%22);%0A
var path
|
a64db43bc862401070e52953226644a307cf6670
|
switch to a new Transitland Google Analytics id
|
config/environment.js
|
config/environment.js
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'mobility-playground',
environment: environment,
baseURL: '/',
location: '#',
transitlandDatastoreHost: 'https://transit.land',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
mapMatching: true
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
// ENV.transitlandDatastoreHost = 'https://transit.land';
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.googleAnalytics = {
webPropertyId: 'UA-47035811-1'
};
ENV.baseURL = '/';
ENV.mapMatching = true;
}
return ENV;
};
|
JavaScript
| 0 |
@@ -1219,18 +1219,19 @@
'UA-
-47035811-1
+113349190-2
'%0A
|
c0fd909ac0a8de44c28b8bfa7eab920284243555
|
Change number of default letter Resolves: ADWD-1990
|
config/environment.js
|
config/environment.js
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'leibniz-frontend',
environment: environment,
baseURL: '/',
contentSecurityPolicy: {
'default-src': "'none'",
'script-src': "*",
'font-src': "'self'",
'connect-src': "*",
'img-src': "'self' data:",
'style-src': "'self' 'unsafe-inline'",
'media-src': "'self'"
},
intl: {
defaultLocale: 'de-de'
},
firstLetterID: 'l3717', // TODO: Get first letter ID from Solr
solrURL: 'http://adw-dev.tc.sub.uni-goettingen.de/solr/leibniz/select',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
JavaScript
| 0.000024 |
@@ -483,17 +483,17 @@
D: 'l371
-7
+4
', // TO
|
59af6cbb4e9f782eccd1e0389cfe66021022d987
|
Remove redundant definitions.
|
src/api/property.js
|
src/api/property.js
|
import dashCase from '../util/dash-case';
import data from '../util/data';
import emit from '../api/emit';
// TODO Decouple boolean attributes from the Boolean function.
// TODO Split apart createNativePropertyDefinition function.
function getLinkedAttribute (name, attr) {
return attr === true ? dashCase(name) : attr;
}
function createNativePropertyDefinition (name, opts) {
let prop = {};
prop.created = function (elem, initialValue) {
let info = data(elem, `api/property/${name}`);
info.internalValue = initialValue;
info.isBoolean = opts.type === Boolean;
info.linkedAttribute = getLinkedAttribute(name, opts.attr);
info.removeAttribute = elem.removeAttribute;
info.setAttribute = elem.setAttribute;
info.updatingProperty = false;
// TODO Refactor
if (info.linkedAttribute) {
if (!info.attributeMap) {
info.attributeMap = {};
info.removeAttribute = elem.removeAttribute;
info.setAttribute = elem.setAttribute;
elem.removeAttribute = function (attrName) {
info.removeAttribute.call(this, attrName);
if (attrName in info.attributeMap) {
elem[info.attributeMap[attrName]] = undefined;
}
};
elem.setAttribute = function (attrName, attrValue) {
info.setAttribute.call(this, attrName, attrValue);
if (attrName in info.attributeMap) {
elem[info.attributeMap[attrName]] = attrValue;
}
};
}
info.attributeMap[info.linkedAttribute] = name;
}
if (info.linkedAttribute && elem.hasAttribute(info.linkedAttribute)) {
info.internalValue = info.isBoolean ? elem.hasAttribute(info.linkedAttribute) : elem.getAttribute(info.linkedAttribute);
} else if (typeof opts.init === 'function') {
info.internalValue = opts.init();
} else if (typeof opts.init !== 'undefined') {
info.internalValue = opts.init;
}
if (opts.type) {
info.internalValue = opts.type(info.internalValue);
}
};
prop.get = function () {
let info = data(this, `api/property/${name}`);
return info.internalValue;
};
prop.ready = function (value) {
if (opts.update) {
opts.update.call(this, value);
}
};
prop.set = function (value) {
let info = data(this, `api/property/${name}`);
if (info.updatingProperty) {
return;
}
info.updatingProperty = true;
let newValue = opts.type ? opts.type(value) : value;
let oldValue = info.internalValue;
info.internalValue = newValue;
if (newValue === oldValue) {
info.updatingProperty = false;
return;
}
if (info.linkedAttribute) {
if (info.isBoolean && newValue) {
info.setAttribute.call(this, info.linkedAttribute, '');
} else if (value === undefined || info.isBoolean && !newValue) {
info.removeAttribute.call(this, info.linkedAttribute, '');
} else {
info.setAttribute.call(this, info.linkedAttribute, newValue);
}
}
if (opts.update) {
opts.update.call(this, newValue, oldValue);
}
if (opts.emit) {
emit(this, opts.emit, {
bubbles: false,
cancelable: false,
detail: {
name: name,
newValue: newValue,
oldValue: oldValue
}
});
}
info.updatingProperty = false;
};
return prop;
}
export default function (opts) {
opts = opts || {};
if (typeof opts === 'function') {
opts = { type: opts };
}
return function (name) {
return createNativePropertyDefinition(name, opts);
};
}
|
JavaScript
| 0.000509 |
@@ -888,108 +888,8 @@
%7B%7D;
-%0A info.removeAttribute = elem.removeAttribute;%0A info.setAttribute = elem.setAttribute;
%0A%0A
|
995d6378f32587ae8e36d5a119a176a9480e77fa
|
create `ENV` with mirage enabled
|
config/environment.js
|
config/environment.js
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
rootURL: '/',
locationType: 'auto',
modulePrefix: 'irene',
environment: environment,
pusherKey: "216d53b13aaa5c6fc2cf",
deviceFarmSsl: false,
deviceFarmHost: "devicefarm.appknox.com",
deviceFarmPor: "8080",
stripe: {
publishableKey: "pk_test_UOgd8ILsBsx7R5uUPttDJNgk"
},
i18n: {
defaultLocale: 'en',
},
emblemOptions: {
blueprints: false
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
'ember-simple-auth': {
loginEndPoint: '/login',
checkEndPoint: '/check',
logoutEndPoint: '/logout',
routeAfterAuthentication: 'authenticated.index',
routeIfAlreadyAuthenticated: 'authenticated.index',
},
endpoints: {
token: 'token',
tokenNew: 'token/new.json',
signedUrl: 'signed_url',
uploadedFile: 'uploaded_file',
invoice: 'invoice',
logout: 'logout',
dynamic: 'dynamic',
dynamicShutdown: 'dynamic_shutdown',
signedPdfUrl: 'signed_pdf_url',
storeUrl: 'store_url',
deleteProject: 'projects/delete',
recover: 'recover',
reset: 'reset',
init: 'init',
manual: 'manual',
githubRepos: 'github_repos',
jiraProjects: 'jira_projects',
setGithub: 'set_github',
setJira: 'set_jira',
feedback: 'feedback',
revokeGitHub: 'unauthorize_github',
revokeJira: 'unauthorize_jira',
integrateJira: 'integrate_jira',
changePassword: 'change_password',
namespaceAdd: 'namespace_add',
stripePayment: 'stripe_payment',
applyCoupon: 'apply_coupon',
saveCredentials: 'projects/save_credentials',
collaboration: 'collaboration',
deleteCollaboration: 'collaboration/delete',
invitation: 'invitation',
signup: 'signup'
},
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
ENV['ember-cli-mirage'] = {
enabled: false
};
ENV['namespace'] = "api-v2";
ENV['host'] = "http://0.0.0.0:8000";
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.stripe = {
publishableKey: "pk_live_9G633HADop7N2NLdi6g2BHHA"
};
}
return ENV;
};
|
JavaScript
| 0 |
@@ -2890,16 +2890,189 @@
%7D;%0A %7D
+%0A%0A if (environment === 'yashwin') %7B%0A ENV%5B'ember-cli-mirage'%5D = %7B%0A enabled: true%0A %7D;%0A ENV%5B'namespace'%5D = %22api-v2%22;%0A ENV%5B'host'%5D = %22http://0.0.0.0:8000%22;%0A %7D
%0A retur
|
34eb1f59e76d5da7dab68cc7cca504e5b953e208
|
Add unit test for refill bucket
|
test/limiter.js
|
test/limiter.js
|
var expect = require('chai').expect,
epsilonDelta = require('../lib/limiter');
describe('limiter', function () {
describe('rate', function () {
it('should correctly rate limit a user', function (done) {
var limiter = epsilonDelta({
capacity: 10, // 100 requests
});
var username = 'someone';
for (var a = 0; a < 10; a++) {
limiter.rate(username);
}
limiter.rate(username, function (err, limitReached) {
expect(limitReached).to.be.true;
done();
});
});
it('should correctly let non limit reached user through', function (done) {
var limiter = epsilonDelta({
capacity: 10, // 100 requests
});
var username = 'someone';
for (var a = 0; a < 5; a++) {
limiter.rate(username);
}
limiter.rate(username, function (err, limitReached) {
expect(limitReached).to.be.false;
done();
});
});
});
describe('manualSet', function () {
it('should correctly set user rate limit data when capacity is object', function (done) {
var limiter = epsilonDelta({
capacity: 10, // 100 requests
});
var username = 'someone';
for (var a = 0; a < 10; a++) {
limiter.rate(username);
}
limiter.manualSet(username, {
capacity: 100
});
limiter.updateUser(username, function (err, data) {
expect(data.capacity).to.equal(99);
done();
});
});
it('should correctly set user rate limit data when capacity is number', function (done) {
var limiter = epsilonDelta({
capacity: 10, // 100 requests
});
var username = 'someone';
for (var a = 0; a < 10; a++) {
limiter.rate(username);
}
limiter.manualSet(username, 100);
limiter.updateUser(username, function (err, data) {
expect(data.capacity).to.equal(99);
done();
});
});
it('should correctly set user rate limit data back to defaults if no args given', function (done) {
var limiter = epsilonDelta({
capacity: 10, // 100 requests
});
var username = 'someone';
for (var a = 0; a < 5; a++) {
limiter.rate(username);
}
limiter.manualSet(username);
limiter.updateUser(username, function (err, data) {
expect(data.capacity).to.equal(9);
done();
});
});
});
});
|
JavaScript
| 0 |
@@ -72,16 +72,51 @@
imiter')
+,%0A MockDate = require('mockdate');
;%0A%0Adescr
@@ -974,24 +974,623 @@
%7D);%0A %7D);
+%0A%0A it('should correctly refill bucket', function (done) %7B%0A MockDate.set(10000);%0A var limiter = epsilonDelta(%7B%0A capacity: 10, // 100 requests,%0A expire: 10000 // 10 seconds%0A %7D);%0A var username = 'someone';%0A%0A for (var a = 0; a %3C 10; a++) %7B%0A limiter.rate(username);%0A %7D%0A %0A limiter.rate(username, function (err, limitReached) %7B%0A expect(limitReached).to.be.true;%0A %7D);%0A%0A MockDate.set(20001);%0A limiter.rate(username, function (err, limitReached) %7B%0A expect(limitReached).to.be.false;%0A done();%0A %7D);%0A %7D);
%0A %7D);%0A%0A de
|
74465a557f683bcd1d0a7e747ba0329dc9d4bf3e
|
use https;
|
config/environment.js
|
config/environment.js
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'wordset',
environment: environment,
baseURL: '/',
locationType: 'auto',
apiPrefix: 'api/v1',
posList: ["adv", "adj", "verb", "noun", "conj", "pronoun", "prep"],
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
},
contentSecurityPolicy: {
'default-src': "'none'",
'script-src': "'self' 'unsafe-inline' https://www.google-analytics.com https://cdn.mxpnl.com https://stats.pusher.com",
'font-src': "'self'",
'connect-src': "'self' https://api.wordset.org https://api.mixpanel.com wss://ws.pusherapp.com",
'img-src': "'self' https://www.google-analytics.com https://secure.gravatar.com",
'style-src': "'self' 'unsafe-inline'",
'media-src': "'self'"
},
"simple-auth": {
store: 'simple-auth-session-store:local-storage',
authorizer: 'authorizer:api',
crossOriginWhitelist: ['http://api.wordset.org', 'http://localhost:3000'],
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
ENV.apiHost = 'http://localhost:3000';
ENV.APP.PUSHER_OPTS = {
key: 'e8039c23fe140e473468',
};
ENV.contentSecurityPolicy['connect-src'] += " http://localhost:3000 http://api.mixpanel.com ws://ws.pusherapp.com";
ENV.contentSecurityPolicy['script-src'] += " http://stats.pusher.com";
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.apiHost = 'http://api.wordset.org';
ENV.APP.PUSHER_OPTS = {
key: '48d537b460788bef06f4',
};
}
ENV.api = ENV.apiHost + "/" + ENV.apiPrefix;
return ENV;
};
|
JavaScript
| 0 |
@@ -2060,24 +2060,25 @@
Host = 'http
+s
://api.words
|
0282e3950d000aef035de85a1a7211554f81d207
|
Fix date range filter
|
src/assetFilters.js
|
src/assetFilters.js
|
import distance from "@turf/distance";
import booleanPointInPolygon from "@turf/boolean-point-in-polygon";
import { isEmpty } from "./utils";
import { GeoListenMode } from "./mixer";
export const ASSET_PRIORITIES = Object.freeze({
DISCARD: false,
NEUTRAL: 0,
LOWEST: 1,
NORMAL: 100,
HIGHEST: 999,
});
const alwaysLowest = () => ASSET_PRIORITIES.LOWEST;
const alwaysNeutral = () => ASSET_PRIORITIES.NEUTRAL; // eslint-disable-line no-unused-vars
// Accept an asset if any one of the provided filters passes, returns the first
// non-discarded and non-neutral rank
function anyAssetFilter(filters = [], { ...mixParams }) {
if (isEmpty(filters)) return alwaysLowest;
return (asset, { ...stateParams }) => {
for (const filter of filters) {
let rank = filter(asset, { ...mixParams, ...stateParams });
if (
rank !== ASSET_PRIORITIES.DISCARD &&
rank !== ASSET_PRIORITIES.NEUTRAL
) {
return rank;
}
}
return ASSET_PRIORITIES.DISCARD;
};
}
/** Filter composed of multiple inner filters that accepts assets which pass every inner filter. */
export function allAssetFilter(filters = [], { ...mixParams }) {
if (isEmpty(filters)) return alwaysLowest;
return (asset, { ...stateParams }) => {
const ranks = [];
for (let filter of filters) {
//console.info("CONSOLEDEBUG",filter);
let rank = filter(asset, { ...mixParams, ...stateParams });
if (rank === ASSET_PRIORITIES.DISCARD) return rank; // can skip remaining filters
ranks.push(rank);
}
const finalRank =
ranks.find((r) => r !== ASSET_PRIORITIES.NEUTRAL) || ranks[0];
return finalRank;
};
}
// a "pre-filter" used by geo-enabled filters to make sure if we are missing data, or geoListenMode is DISABLED,
// we always return a neutral ranking
function rankForGeofilteringEligibility(
asset,
{ listenerPoint, geoListenMode }
) {
return geoListenMode !== GeoListenMode.DISABLED && listenerPoint && asset;
}
const calculateDistanceInMeters = (loc1, loc2) =>
distance(loc1, loc2, { units: "meters" });
/** Only accepts an asset if the user is within the project-configured recording radius */
export const distanceFixedFilter = () => (asset, options = {}) => {
if (options.geoListenMode === GeoListenMode.DISABLED) {
return ASSET_PRIORITIES.LOWEST;
}
if (!rankForGeofilteringEligibility(asset, options))
return ASSET_PRIORITIES.NEUTRAL;
const { locationPoint: assetLocationPoint } = asset;
const { listenerPoint, recordingRadius } = options;
const distance = calculateDistanceInMeters(listenerPoint, assetLocationPoint);
if (distance < recordingRadius) {
return ASSET_PRIORITIES.NORMAL;
} else {
return ASSET_PRIORITIES.DISCARD;
}
};
/**
Accepts an asset if the user is within range of it based on the current dynamic distance range.
*/
export const distanceRangesFilter = () => (asset, options = {}) => {
if (options.geoListenMode === GeoListenMode.DISABLED) {
return ASSET_PRIORITIES.LOWEST;
}
if (!rankForGeofilteringEligibility(asset, options)) {
return ASSET_PRIORITIES.NEUTRAL;
}
const { listenerPoint, minDist, maxDist } = options;
if (minDist === undefined || maxDist === undefined) {
return ASSET_PRIORITIES.NEUTRAL;
}
const { locationPoint } = asset;
const distance = calculateDistanceInMeters(listenerPoint, locationPoint);
if (distance >= minDist && distance <= maxDist) {
return ASSET_PRIORITIES.NORMAL;
} else {
return ASSET_PRIORITIES.DISCARD;
}
};
// Rank the asset if it is tagged with one of the currently-enabled tag IDs
export function anyTagsFilter() {
return (asset, { listenTagIds }) => {
if (isEmpty(listenTagIds)) return ASSET_PRIORITIES.LOWEST;
const { id: assetId, tag_ids: assetTagIds = [] } = asset;
for (const tagId of assetTagIds) {
if (listenTagIds.includes(tagId)) return ASSET_PRIORITIES.LOWEST; // matching only by tag should be the least-important filter
}
console.log(`anyTagsFilter discard asset #${assetId}`, assetTagIds);
return ASSET_PRIORITIES.DISCARD;
};
}
// keep assets that are slated to start now or in the past few minutes AND haven't been played before
export function timedAssetFilter() {
return (asset, { elapsedSeconds = 0, timedAssetPriority = "normal" }) => {
const { timedAssetStart, timedAssetEnd, playCount } = asset;
if (!timedAssetStart || !timedAssetEnd) return ASSET_PRIORITIES.DISCARD;
if (
timedAssetStart >= elapsedSeconds ||
timedAssetEnd <= elapsedSeconds ||
playCount > 0
)
return ASSET_PRIORITIES.DISCARD;
const priorityEnumStr = timedAssetPriority.toUpperCase(); // "highest", "lowest", "normal", etc.
return ASSET_PRIORITIES[priorityEnumStr] || ASSET_PRIORITIES.NEUTRAL;
};
}
// Accept an asset if the user is currently within its defined shape
export function assetShapeFilter() {
return (asset, options = {}) => {
const { shape } = asset;
if (!(shape && rankForGeofilteringEligibility(asset, options)))
return ASSET_PRIORITIES.NEUTRAL;
const { listenerPoint } = options;
if (booleanPointInPolygon(listenerPoint, shape)) {
return ASSET_PRIORITIES.NORMAL;
} else {
return ASSET_PRIORITIES.DISCARD;
}
};
}
// Prevents assets from repeating until a certain time threshold has passed
export const timedRepeatFilter = () => (asset, { bannedDuration = 600 }) => {
const { lastListenTime } = asset;
if (!lastListenTime) return ASSET_PRIORITIES.NORMAL; // e.g. asset has never been heard before
const durationSinceLastListen = (new Date() - lastListenTime) / 1000;
if (durationSinceLastListen <= bannedDuration) {
return ASSET_PRIORITIES.DISCARD;
} else {
return ASSET_PRIORITIES.LOWEST;
}
};
export const dateRangeFilter = () => (asset, { startDate, endDate }) => {
if (startDate || endDate) {
return (!startDate || asset.created >= startDate) &&
(!endDate || asset.created <= endDate)
? ASSET_PRIORITIES.NORMAL
: ASSET_PRIORITIES.DISCARD;
} else {
return ASSET_PRIORITIES.NEUTRAL;
}
};
export const roundwareDefaultFilterChain = allAssetFilter([
anyAssetFilter([
timedAssetFilter(), // if an asset is scheduled to play right now, or
assetShapeFilter(), // if an asset has a shape and we AREN'T in it, reject entirely, or
allAssetFilter([
distanceFixedFilter(), // if it has no shape, consider a fixed distance from it, or
distanceRangesFilter(),
//angleFilter() // if the listener is within a user-configured distance or angle range
]),
]),
timedRepeatFilter(), // only repeat assets if there's no other choice
//blockedAssetsFilter(), // skip blocked assets and users
anyTagsFilter(), // all the tags on an asset must be in our list of tags to listen for
dateRangeFilter(),
//trackTagsFilter(), // if any track-level tag filters exist, apply them
//dynamicTagFilter("_ten_most_recent_days",mostRecentFilter({ days: 10 })) // Only pass assets created within the most recent 10 days
]);
|
JavaScript
| 0.000002 |
@@ -6104,31 +6104,30 @@
_PRIORITIES.
-NEUTRAL
+LOWEST
;%0A %7D%0A%7D;%0A%0Aex
|
322f73fcacc29a6063d2f8e0c0dba7be017221c5
|
Use triple equals
|
scripts/pi-hole/js/db_lists.js
|
scripts/pi-hole/js/db_lists.js
|
/* Pi-hole: A black hole for Internet advertisements
* (c) 2017 Pi-hole, LLC (https://pi-hole.net)
* Network-wide ad blocking via your own hardware.
*
* This file is copyright under the latest version of the EUPL.
* Please see LICENSE file for your rights under this license. */
/*global
moment
*/
var start__ = moment().subtract(6, "days");
var from = moment(start__).utc().valueOf()/1000;
var end__ = moment();
var until = moment(end__).utc().valueOf()/1000;
var timeoutWarning = $("#timeoutWarning");
var listsStillLoading = 0;
$(function () {
$("#querytime").daterangepicker(
{
timePicker: true, timePickerIncrement: 15,
locale: { format: "MMMM Do YYYY, HH:mm" },
ranges: {
"Today": [moment().startOf("day"), moment()],
"Yesterday": [moment().subtract(1, "days").startOf("day"), moment().subtract(1, "days").endOf("day")],
"Last 7 Days": [moment().subtract(6, "days"), moment()],
"Last 30 Days": [moment().subtract(29, "days"), moment()],
"This Month": [moment().startOf("month"), moment()],
"Last Month": [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")],
"This Year": [moment().startOf("year"), moment()],
"All Time": [moment(0), moment()]
},
"opens": "center", "showDropdowns": true
},
function (startt, endt) {
from = moment(startt).utc().valueOf()/1000;
until = moment(endt).utc().valueOf()/1000;
});
});
// Credit: http://stackoverflow.com/questions/1787322/htmlspecialchars-equivalent-in-javascript/4835406#4835406
function escapeHtml(text) {
var map = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"\'": "'"
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
function updateTopClientsChart() {
$("#client-frequency .overlay").show();
$.getJSON("api_db.php?topClients&from="+from+"&until="+until, function(data) {
// Clear tables before filling them with data
$("#client-frequency td").parent().remove();
var clienttable = $("#client-frequency").find("tbody:last");
var client, percentage, clientname, clientip;
var sum = 0;
for (client in data.top_sources) {
if ({}.hasOwnProperty.call(data.top_sources, client)){
sum += data.top_sources[client];
}
}
for (client in data.top_sources) {
if ({}.hasOwnProperty.call(data.top_sources, client)){
// Sanitize client
client = escapeHtml(client);
if(escapeHtml(client) !== client)
{
// Make a copy with the escaped index if necessary
data.top_sources[escapeHtml(client)] = data.top_sources[client];
}
if(client.indexOf("|") > -1)
{
var idx = client.indexOf("|");
clientname = client.substr(0, idx);
clientip = client.substr(idx+1, client.length-idx);
}
else
{
clientname = client;
clientip = client;
}
var url = clientname;
percentage = data.top_sources[client] / sum * 100.0;
clienttable.append("<tr> <td>" + url +
"</td> <td>" + data.top_sources[client] + "</td> <td> <div class=\"progress progress-sm\" title=\""+percentage.toFixed(1)+"% of " + sum + "\"> <div class=\"progress-bar progress-bar-blue\" style=\"width: " +
percentage + "%\"></div> </div> </td> </tr> ");
}
}
$("#client-frequency .overlay").hide();
listsStillLoading--;
if(listsStillLoading == 0)
timeoutWarning.hide();
});
}
function updateTopDomainsChart() {
$("#domain-frequency .overlay").show();
$.getJSON("api_db.php?topDomains&from="+from+"&until="+until, function(data) {
// Clear tables before filling them with data
$("#domain-frequency td").parent().remove();
var domaintable = $("#domain-frequency").find("tbody:last");
var domain, percentage;
var sum = 0;
for (domain in data.top_domains) {
if ({}.hasOwnProperty.call(data.top_domains, domain)){
sum += data.top_domains[domain];
}
}
for (domain in data.top_domains) {
if ({}.hasOwnProperty.call(data.top_domains, domain)){
// Sanitize domain
domain = escapeHtml(domain);
if(escapeHtml(domain) !== domain)
{
// Make a copy with the escaped index if necessary
data.top_domains[escapeHtml(domain)] = data.top_domains[domain];
}
percentage = data.top_domains[domain] / sum * 100.0;
domaintable.append("<tr> <td>" + domain +
"</td> <td>" + data.top_domains[domain] + "</td> <td> <div class=\"progress progress-sm\" title=\""+percentage.toFixed(1)+"% of " + sum + "\"> <div class=\"progress-bar progress-bar-blue\" style=\"width: " +
percentage + "%\"></div> </div> </td> </tr> ");
}
}
$("#domain-frequency .overlay").hide();
listsStillLoading--;
if(listsStillLoading == 0)
timeoutWarning.hide();
});
}
function updateTopAdsChart() {
$("#ad-frequency .overlay").show();
$.getJSON("api_db.php?topAds&from="+from+"&until="+until, function(data) {
// Clear tables before filling them with data
$("#ad-frequency td").parent().remove();
var adtable = $("#ad-frequency").find("tbody:last");
var ad, percentage;
var sum = 0;
for (ad in data.top_ads) {
if ({}.hasOwnProperty.call(data.top_ads, ad)){
sum += data.top_ads[ad];
}
}
for (ad in data.top_ads) {
if ({}.hasOwnProperty.call(data.top_ads, ad)){
// Sanitize ad
ad = escapeHtml(ad);
if(escapeHtml(ad) !== ad)
{
// Make a copy with the escaped index if necessary
data.top_ads[escapeHtml(ad)] = data.top_ads[ad];
}
percentage = data.top_ads[ad] / sum * 100.0;
adtable.append("<tr> <td>" + ad + "</td> <td>" + data.top_ads[ad] + "</td> <td> <div class=\"progress progress-sm\" title=\""+percentage.toFixed(1)+"% of " + sum + "\"> <div class=\"progress-bar progress-bar-blue\" style=\"width: " + percentage + "%\"></div> </div> </td> </tr> ");
}
}
$("#ad-frequency .overlay").hide();
listsStillLoading--;
if(listsStillLoading == 0)
timeoutWarning.hide();
});
}
$("#querytime").on("apply.daterangepicker", function(ev, picker) {
timeoutWarning.show();
listsStillLoading = 3;
updateTopClientsChart();
updateTopDomainsChart();
updateTopAdsChart();
});
|
JavaScript
| 0.000003 |
@@ -3827,32 +3827,33 @@
sStillLoading ==
+=
0)%0A
|
5bbdc1e2a83673fcfad239e7683da9298da39a65
|
fix demo
|
demo/main.js
|
demo/main.js
|
;(function() {
'use strict';
var schemaUrlForm = document.getElementById('schema-url-form');
var schemaUrlInput;
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
url = window.__REDOC_DEV__ ? url : '\\\\cors.apis.guru/' + url;
document.getElementsByTagName('redoc')[0].setAttribute('spec-url', url);
}
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)", "i");
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
var hash = '';
if( uri.indexOf('#') !== -1 ){
hash = uri.replace(/.*#/, '#');
uri = uri.replace(/#.*/, '');
}
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
return uri + separator + key + "=" + value + hash;
}
}
var specs = document.querySelector('#specs');
specs.addEventListener('dom-change', function() {
schemaUrlForm = document.getElementById('schema-url-form');
schemaUrlInput = document.getElementById('schema-url-input');
schemaUrlForm.addEventListener('submit', function(event) {
event.preventDefault();
event.stopPropagation();
location.search = updateQueryStringParameter(location.search, 'url', schemaUrlInput.value)
return false;
})
schemaUrlInput.addEventListener('mousedown', function(e) {
e.stopPropagation();
});
schemaUrlInput.value = url;
specs.specs = [
'https://api.apis.guru/v2/specs/instagram.com/1.0.0/swagger.yaml',
'https://api.apis.guru/v2/specs/googleapis.com/calendar/v3/swagger.yaml',
'https://api.apis.guru/v2/specs/data2crm.com/1/swagger.yaml',
'https://api.apis.guru/v2/specs/graphhopper.com/1.0/swagger.yaml'
];
var $specInput = document.getElementById('spec-input');
// $specInput.addEventListener('value-changed', function(e) {
// schemaUrlInput.value = e.detail.value;
// location.search = updateQueryStringParameter(location.search, 'url', schemaUrlInput.value);
// });
function selectItem() {
let value = this.innerText.trim();
schemaUrlInput.value = value;
location.search = updateQueryStringParameter(location.search, 'url', schemaUrlInput.value);
}
// for some reason events are not triggered so have to dirty fix this
$specInput.addEventListener('click', function(event) {
let $elems = document.querySelectorAll('.item.vaadin-combo-box-overlay');
$elems.forEach(function($el) {
$el.addEventListener('mousedown', selectItem);
$el.addEventListener('mousedown', selectItem);
});
});
});
})();
|
JavaScript
| 0.000001 |
@@ -1883,19 +1883,16 @@
');%0A%0A
- //
$specIn
@@ -1946,19 +1946,16 @@
e) %7B%0A
- //
schem
@@ -1991,19 +1991,16 @@
lue;%0A
- //
locat
@@ -2089,19 +2089,16 @@
ue);%0A
- //
%7D);%0A%0A
|
89a2f72bf0ee4a4c68e7cc16319a177a4ef03ae1
|
fix on demo js
|
demo/myjs.js
|
demo/myjs.js
|
(function ($, window, document, undefined) {
'use strict';
$('#cont1').ScrollSubMenu();
$('#cont2').ScrollSubMenu({
animEnterFn: function(){
this.menu.wrapper.css({display:'block'}).find('li').each(function(i){
var el = $(this).css({marginLeft:'-100%', opacity:0});
setTimeout(function() {
el.animate({
marginLeft: '0',
opacity:1
}, 100);
}, i * 100);
});
},
animExitFn: function(){
this.menu.wrapper.find('li').each(function(i){
var el = $(this);
setTimeout(function() {
el.animate({
marginLeft: '-100%',
opacity:0
}, 100);
}, i * 100);
});
}
});
$('#cont3').ScrollSubMenu({animWhileClass:''});
})($, this, this.document);
|
JavaScript
| 0 |
@@ -478,37 +478,90 @@
Fn: function()%7B%0A
+%0A
+ var $wrapper = this.menu.wrapper;%0A var $list =
this.menu.wrapp
@@ -565,32 +565,48 @@
apper.find('li')
+;%0A%0A $list
.each(function(i
@@ -748,16 +748,16 @@
acity:0%0A
-
@@ -759,32 +759,134 @@
%7D, 100);%0A
+%0A if ( i === $list.length - 1 ) %7B%0A $wrapper.css(%7Bdisplay:'none'%7D);%0A %7D%0A%0A
%7D, i * 1
|
89d81fd8029a622fd00a7064526984c02b29eee0
|
Use .info and fix bug with db queries
|
CachedOpenWeatherAPI.js
|
CachedOpenWeatherAPI.js
|
var weather = require('openweathermap')
var db = null;
var city_id = 0;
// http://api.openweathermap.org/data/2.5/forecast?id=2643123&mode=json&appid=
// f3794e46bd7505e6a7746cb0379550ed
// http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
exports.config = function(weather_config, city, database) {
weather.defaults(weather_config);
db = database;
city_id = city;
// Ensure the database is ready for use
db.serialize(function() {
db.run("CREATE TABLE IF NOT EXISTS daily_weather (timestamp INTEGER PRIMARY KEY, main TEXT, description TEXT, mapping TEXT, temp_min INTEGER, temp_max INTEGER, temp INTEGER)");
db.run("CREATE TABLE IF NOT EXISTS hourly_weather (timestamp INTEGER PRIMARY KEY, main TEXT, description TEXT, mapping TEXT, temp_min INTEGER, temp_max INTEGER, temp INTEGER)");
db.run("CREATE TABLE IF NOT EXISTS update_times (timestamp INTEGER)");
});
}
exports.start = function(update_minutes) {
if(!db) {
console.error("No database has been defined, use config() first!");
return;
}
db.get("SELECT * FROM update_times ORDER BY timestamp DESC LIMIT 1", function(err, res) {
if(res && (getTimestamp() - res.timestamp < (update_minutes * 60 * 1000 * 0.5)))
console.log("Not updating as we have updated in the last "+update_minutes*0.5+" minutes.");
else
updateWeatherCache();
});
setInterval(updateWeatherCache, update_minutes * 60 * 1000);
}
exports.getWeatherAt = function(timestamp, callback) {
db.get("SELECT * FROM hourly_weather ORDER BY timestamp DESC LIMIT 1", function(err, res) {
// We need to check daily if hourly is too old
var oldestHourly = getTimestamp();
if(res && res.timestamp)
oldestHourly = res.timestamp;
if(oldestHourly < timestamp)
getHourlyWeather(timestamp, callback);
else
getDailyWeather(timestamp, callback);
});
}
exports.getDayWeatherAt = function(timestamp, callback) {
getDailyWeather(timestamp, callback);
}
function getHourlyWeather(timestamp, callback) {
var hourly = db.prepare("SELECT * FROM hourly_weather WHERE timestamp <= $timestamp ORDER BY timestamp DESC LIMIT 1");
hourly.get({$timestamp: timestamp}, function(err, res) {
callback(res);
});
}
function getDailyWeather(timestamp, callback) {
var daily = db.prepare("SELECT * FROM daily_weather WHERE timestamp <= $timestamp ORDER BY timestamp DESC LIMIT 1");
daily.get({$timestamp: timestamp}, function(err, res) {
callback(res);
});
}
function getTimestamp() {
return Math.round(new Date().getTime()/1000);
}
function updateWeatherCache() {
var insert = db.prepare("INSERT INTO update_times VALUES ($timestamp)");
console.log("Updating the stored weather information");
// The 3 hours forecast is available for 5 days. Daily forecast is available for 14 days
/*weather.now({id: MANCHESTER_CITY_ID}, function(data) {
weatherCache.now = weatherDataToWeatherObject(data);
});*/
var insertHourly = db.prepare("INSERT OR IGNORE INTO hourly_weather (timestamp, main, description, mapping, temp_min, temp_max, temp)"
+ "VALUES ($timestamp, $main, $description, $mapping, $temp_min, $temp_max, $temp)");
weather.forecast({id: city_id, cnt: 5}, function(reply) {
reply.list.forEach(function(data) {
insertHourly.run(weatherDataToWeatherObject(data));
})
insert.run({$timestamp: getTimestamp()});
console.log("Update of hourly weather complete");
});
var insertDaily = db.prepare("INSERT OR IGNORE INTO daily_weather (timestamp, main, description, mapping, temp_min, temp_max, temp)"
+ "VALUES ($timestamp, $main, $description, $mapping, $temp_min, $temp_max, $temp)");
weather.daily({id: city_id, cnt: 14}, function(reply) {
reply.list.forEach(function(data) {
insertDaily.run(weatherDataToWeatherObject(data));
})
insert.run({$timestamp: getTimestamp()});
console.log("Update of daily weather complete");
});
}
function weatherDataToWeatherObject(data) {
// weather_type: snow, rain, hail, thunder, sunny, cloudy
var weathermapping = {
'01': 'clear',
'02': 'few clouds',
'03': 'scattered clouds',
'04': 'broken clouds',
'09': 'drizzle',
'10': 'rain',
'11': 'thunder',
'13': 'snow',
'50': 'mist'
}
var weather = {};
if(data.dt)
weather.$timestamp = data.dt;
if(data.weather && data.weather[0]) {
weather.$main = data.weather[0].main;
weather.$description = data.weather[0].description;
var iconID = data.weather[0].icon.substring(0,2);
weather.$mapping = weathermapping[iconID];
}
if(data.temp) {
weather.$temp = data.temp.day;
weather.$temp_min = data.temp.min;
weather.$temp_max = data.temp.max;
} else if(data.main) {
weather.$temp = data.main.temp;
weather.$temp_min = data.main.temp_min;
weather.$temp_max = data.main.temp_max;
};
return weather;
}
|
JavaScript
| 0 |
@@ -1294,19 +1294,20 @@
console.
-log
+info
(%22Not up
@@ -1313,16 +1313,24 @@
pdating
+weather
as we ha
@@ -1870,17 +1870,18 @@
tHourly
-%3C
+%3E=
timesta
@@ -2340,32 +2340,115 @@
ion(err, res) %7B%0A
+ if(err) %0A console.warn(%22While searching hourly weather: %22, err)%0A
callback
@@ -2443,32 +2443,43 @@
callback(res
+, timestamp
);%0A %7D);%0A%7D%0A%0Afu
@@ -2697,32 +2697,114 @@
ion(err, res) %7B%0A
+ if(err) %0A console.warn(%22While searching daily weather: %22, err)%0A
callback
@@ -2807,16 +2807,27 @@
back(res
+, timestamp
);%0A %7D
@@ -3028,27 +3028,28 @@
console.
-log
+info
(%22Updating t
@@ -3837,35 +3837,36 @@
console.
-log
+info
(%22Update of hour
@@ -4399,11 +4399,12 @@
ole.
-log
+info
(%22Up
|
60c5a8561081cbca9fec481593f2641576967695
|
Fix condition
|
src/RedaxtorCodemirror.js
|
src/RedaxtorCodemirror.js
|
import React, {Component} from "react"
import Codemirror from 'react-codemirror'
import {html as html_beautify} from 'js-beautify'
import Modal from 'react-modal'
require('codemirror/mode/htmlmixed/htmlmixed');
export default class CodeMirror extends Component {
constructor(props) {
super(props);
this.onClickBound = this.onClick.bind(this);
this.beautifyOptions = {
"wrap_line_length": 140
};
if (this.props.node) {
this.state = {
sourceEditorActive: false
};
} else {
this.state = {}
}
this.code = this.props.data && this.props.data.html || this.props.html;
}
componentWillUnmount(){
console.log(`Code mirror ${this.props.id} unmounted`);
}
updateCode(newCode) {
this.code = newCode
}
onSave() {
this.props.updatePiece && this.props.updatePiece(this.props.id, {data: {html: this.code}});
this.props.savePiece && this.props.savePiece(this.props.id);
this.setState({sourceEditorActive: false})
}
onClose() {
this.props.node ? this.setState({sourceEditorActive: false}) : (this.props.onClose && this.props.onClose())
}
createEditor(){
// this.props.node
if(this.props.node) {
this.props.node.addEventListener('click', this.onClickBound);
}
}
destroyEditor(){
if(this.props.node) {
this.props.node.removeEventListener('click', this.onClickBound);
}
}
renderNonReactAttributes(){
if (this.props.editorActive && !this.state.sourceEditorActive) {
this.createEditor();
if(this.props.node) {
this.props.node.classList.add(...this.props.className.split(' '));
}
}
else {
this.destroyEditor();
if(this.props.node) {
this.props.node.classList.remove(...this.props.className.split(' '));
}
}
//render new data
if(this.props.node) {
let content = this.props.node.innerHTML;
let data = this.props.data;
if (content != data.html) {
this.props.node.innerHTML = data.html;
}
}
}
onClick(e){
e.preventDefault();
this.setState({sourceEditorActive: true});
}
render() {
let codemirror = React.createElement(this.props.wrapper, {});
if(this.state.sourceEditorActive){
let options = {
lineNumbers: true,
mode: 'htmlmixed'
};
codemirror = <Modal contentLabel="Edit source" isOpen={true} overlayClassName="r_modal-overlay r_visible"
className="r_modal-content"
onRequestClose={this.onClose.bind(this)}>
<Codemirror
value={html_beautify(this.props.node ? this.props.data.html : this.props.html, this.beautifyOptions)}
onChange={this.updateCode.bind(this)} options={options}/>
<div className="actions-bar">
<div className="button button-cancel" onClick={this.onClose.bind(this)}>Cancel</div>
<div className="button button-save"
onClick={()=>this.props.node ? this.onSave() : (this.props.onSave && this.props.onSave(this.code))}>
Save
</div>
</div>
</Modal>;
}
this.renderNonReactAttributes();
return codemirror;
}
}
/**
* Specify component should be rendered inside target node and capture all inside html
* @type {string}
*/
CodeMirror.__renderType = "BEFORE";
CodeMirror.__name = "Source";
|
JavaScript
| 0.000001 |
@@ -2445,61 +2445,242 @@
r =
-React.createElement(this.props.wrapper, %7B%7D);%0A
+null;%0A%0A if(this.state.sourceEditorActive %7C%7C !this.props.node)%7B%0A //if there is no this.props.node, it means this component is invoked manually with custom html directly in props and should be just rendered%0A
if(t
@@ -2667,35 +2667,38 @@
ered%0A
+ //
if
-(
+
this.state.sourc
@@ -2710,18 +2710,145 @@
orActive
-)%7B
+ and this.props.node presents, it means that is a regular piece with control over node and sourceEditorActive means modal is open
%0A
@@ -2944,32 +2944,115 @@
%0A %7D;%0A
+ const html = this.props.node ? this.props.data.html : this.props.html;%0A
code
@@ -3363,86 +3363,12 @@
ify(
-this.props.node ? this.props.data.html : this.props.html, this.beautifyOptions
+html
)%7D%0A
@@ -3848,32 +3848,32 @@
%3C/div%3E%0A
-
%3C/Mo
@@ -3879,32 +3879,119 @@
odal%3E;%0A %7D
+ else %7B%0A codemirror = React.createElement(this.props.wrapper, %7B%7D);%0A %7D
%0A%0A this.r
|
bf2c1b5f09c348f172846087db10344f53bd3c44
|
Read note on and control change events from MIDI input
|
js/MidiInput.js
|
js/MidiInput.js
|
var MidiInput = function() {
this.init = function(visualizer) {
this.visualizer = visualizer;
if (navigator.requestMIDIAccess) {
navigator.requestMIDIAccess().then(onMidiSuccess, onMidiReject);
} else {
console.log('No MIDI support: navigator.requestMIDIAccess is not defined');
}
};
function onMidiReject(err) {
console.log('MIDI init error: ' + err);
}
function onMidiSuccess(midi) {
console.log('MIDI init ok!');
}
};
|
JavaScript
| 0 |
@@ -189,16 +189,27 @@
iSuccess
+.bind(this)
, onMidi
@@ -217,16 +217,16 @@
eject);%0A
-
%7D el
@@ -445,37 +445,938 @@
-console.log('MIDI init ok!');
+if (midi.inputs.size %3E 0) %7B%0A // Get first MIDI device%0A var input = midi.inputs.values().next().value;%0A console.log('MIDI device found: ' + input.name);%0A%0A // Set MIDI message handler%0A input.onmidimessage = messageHandler.bind(this);%0A %7D else %7B%0A console.log('No MIDI input devices available');%0A %7D%0A %7D%0A%0A function messageHandler(event) %7B%0A var data = %7B%0A status: event.data%5B0%5D & 0xf0,%0A data: %5B%0A event.data%5B1%5D,%0A event.data%5B2%5D%0A %5D%0A %7D;%0A%0A handleInput(data);%0A %7D%0A%0A function handleInput(data) %7B%0A // Note on event%0A if (data.status === 144) %7B%0A var note = data.data%5B0%5D;%0A var velocity = data.data%5B1%5D;%0A console.log('Note on: ' + note + ', ' + velocity);%0A%0A // Control change event%0A %7D else if (data.status === 176) %7B%0A var index = data.data%5B0%5D;%0A var value = data.data%5B1%5D;%0A console.log('Control change: ' + index + ', ' + value);%0A %7D
%0A %7D
|
e28ce79a95ce5983a97d5bc24dd5600e9d1d1c1e
|
make createTickMarkNode private
|
js/RulerNode.js
|
js/RulerNode.js
|
// Copyright 2002-2013, University of Colorado Boulder
/**
* Visual representation of a ruler.
* Lots of options, see default options in constructor.
*
* @author Chris Malley (PixelZoom, Inc.)
*/
define( function( require ) {
'use strict';
// imports
var assert = require( 'ASSERT/assert' )( 'scenery-phet' );
var inherit = require( "PHET_CORE/inherit" );
var Node = require( "SCENERY/nodes/Node" );
var Path = require( "SCENERY/nodes/Path" );
var Rectangle = require( "SCENERY/nodes/Rectangle" );
var Shape = require( "KITE/Shape" );
var Text = require( "SCENERY/nodes/Text" );
/**
* @param {number} width distance between left-most and right-most tick, insets will be added to this
* @param {number} height
* @param {Array<String>} majorTickLabels
* @param {String} units
* @param {object} options
* @constructor
*/
function RulerNode( width, height, majorTickLabels, units, options ) {
// default options
options = _.extend(
{
// body of the ruler
backgroundFill: "rgb(236, 225, 113)",
backgroundStroke: "black",
backgroundLineWidth: 1,
insetsWidth: 14, // space between the ends of the ruler and the first and last tick marks
// major tick options
majorTickFont: "18px Arial",
majorTickHeight: ( 0.4 * height ) / 2,
majorTickStroke: "black",
majorTickLineWidth: 1,
// minor tick options
minorTickFont: "18px Arial",
minorTickHeight: ( 0.2 * height ) / 2,
minorTickStroke: "black",
minorTickLineWidth: 1,
minorTicksPerMajorTick: 0,
// units options
unitsFont: "18px Arial",
unitsMajorTickIndex: 0, // units will be place to the right of this major tick
unitsSpacing: 3 // horizontal space between the tick label and the units
}, options );
// things you're likely to mess up, add more as needed
assert && assert( options.unitsMajorTickIndex < majorTickLabels.length );
assert && assert( options.majorTickHeight < height / 2 );
assert && assert( options.minorTickHeight < height / 2 );
var thisNode = this;
Node.call( thisNode, options );
// background
var backgroundNode = new Rectangle( 0, 0, width + ( 2 * options.insetsWidth ), height,
{ fill: options.backgroundFill,
stroke: options.backgroundStroke,
lineWidth: options.backgroundLineWidth } );
thisNode.addChild( backgroundNode );
var distBetweenMajorReadings = width / ( majorTickLabels.length - 1 );
var distBetweenMinor = distBetweenMajorReadings / ( options.minorTicksPerMajorTick + 1 );
// Lay out tick marks from left to right
for ( var i = 0; i < majorTickLabels.length; i++ ) {
// Major tick label
var majorTickLabel = majorTickLabels[i];
var majorTickLabelNode = new Text( majorTickLabel, { font: options.majorTickFont } );
var xVal = ( distBetweenMajorReadings * i ) + options.insetsWidth;
var yVal = ( height / 2 ) - ( majorTickLabelNode.height / 2 );
//Clamp and make sure the labels stay within the ruler, especially if the insetsWidth has been set low (or to zero)
majorTickLabelNode.x = xVal - ( majorTickLabelNode.width / 2 );
majorTickLabelNode.centerY = backgroundNode.centerY;
// Only add the major tick label if the insetsWidth is nonzero, or if it is not an end label
if ( options.insetsWidth !== 0 || ( i !== 0 && i !== majorTickLabels.length - 1 ) ) {
thisNode.addChild( majorTickLabelNode );
}
// Major tick mark
var majorTickNode = thisNode.createTickMarkNode( xVal, height, options.majorTickHeight, options.majorTickStroke, options.majorTickLineWidth );
thisNode.addChild( majorTickNode );
// Minor tick marks
if ( i < majorTickLabels.length - 1 ) {
for ( var k = 1; k <= options.minorTicksPerMajorTick; k++ ) {
var minorTickNode = thisNode.createTickMarkNode( xVal + k * distBetweenMinor, height, options.minorTickHeight, options.minorTickStroke, options.minorTickLineWidth );
thisNode.addChild( minorTickNode );
}
}
// units label
if ( i === options.unitsMajorTickIndex ) {
var unitsNode = new Text( units, { font: options.unitsFont } );
thisNode.addChild( unitsNode );
unitsNode.x = majorTickLabelNode.x + majorTickLabelNode.width + options.unitsSpacing;
unitsNode.y = majorTickLabelNode.y + majorTickLabelNode.height - unitsNode.height;
}
}
}
inherit( Node, RulerNode );
/**
* Creates a tick mark at a specific x location.
* Each tick is marked at the top and bottom of the ruler.
* If you desire a different style of tick mark, override this method.
*
* @param {number} x
* @param {number} rulerHeight
* @param {number} tickHeight
* @param {String} stroke stroke color as a CSS string
* @param {number} lineWidth
* @return {Node}
*/
RulerNode.prototype.createTickMarkNode = function( x, rulerHeight, tickHeight, stroke, lineWidth ) {
var shape = new Shape().moveTo( x, 0 ).lineTo( x, tickHeight ).moveTo( x, rulerHeight - tickHeight ).lineTo( x, rulerHeight );
return new Path( { stroke: stroke, lineWidth: lineWidth, shape: shape } );
};
return RulerNode;
} );
|
JavaScript
| 0.000001 |
@@ -3751,33 +3751,24 @@
rTickNode =
-thisNode.
createTickMa
@@ -4084,25 +4084,16 @@
kNode =
-thisNode.
createTi
@@ -5107,28 +5107,12 @@
/%0A
-RulerNode.prototype.
+var
crea
|
bd656afc105ea02a5a424011d3cd3b7458f4d38a
|
convert _.extend to PHET_CORE/merge, https://github.com/phetsims/phet-core/issues/71
|
js/StatusBar.js
|
js/StatusBar.js
|
// Copyright 2018-2019, University of Colorado Boulder
/**
* Base type for the status bar that appears at the top of games.
* The base type is primarily responsible for resizing and 'floating' the bar.
*
* @author Chris Malley (PixelZoom, Inc.)
*/
define( require => {
'use strict';
// modules
const inherit = require( 'PHET_CORE/inherit' );
const Node = require( 'SCENERY/nodes/Node' );
const PhetFont = require( 'SCENERY_PHET/PhetFont' );
const Rectangle = require( 'SCENERY/nodes/Rectangle' );
const vegas = require( 'VEGAS/vegas' );
// constants
const DEFAULT_FONT = new PhetFont( 20 );
/**
* @param {Bounds2} layoutBounds
* @param {Property.<Bounds2>} visibleBoundsProperty - visible bounds of the parent ScreenView
* @param {Object} [options]
* @constructor
*/
function StatusBar( layoutBounds, visibleBoundsProperty, options ) {
const self = this;
options = _.extend( {
barHeight: 50,
xMargin: 10,
yMargin: 8,
barFill: 'lightGray',
barStroke: null,
// true: float bar to top of visible bounds; false: bar at top of layoutBounds
floatToTop: false,
// true: keeps things on the status bar aligned with left and right edges of window bounds
// false: align things on status bar with left and right edges of static layoutBounds
dynamicAlignment: true
}, options );
// @private
this.layoutBounds = layoutBounds;
this.xMargin = options.xMargin;
this.yMargin = options.yMargin;
this.dynamicAlignment = options.dynamicAlignment;
// @private size will be set by visibleBoundsListener
this.barNode = new Rectangle( {
fill: options.barFill,
stroke: options.barStroke
} );
// Support decoration, with the bar behind everything else
options.children = [ this.barNode ].concat( options.children || [] );
Node.call( this, options );
const visibleBoundsListener = function( visibleBounds ) {
// resize the bar
const y = ( options.floatToTop ) ? visibleBounds.top : layoutBounds.top;
self.barNode.setRect( visibleBounds.minX, y, visibleBounds.width, options.barHeight );
// update layout of things on the bar
self.updateLayout();
};
visibleBoundsProperty.link( visibleBoundsListener );
// @private
this.disposeStatusBar = function() {
if ( visibleBoundsProperty.hasListener( visibleBoundsListener ) ) {
visibleBoundsProperty.unlink( visibleBoundsListener );
}
};
}
vegas.register( 'StatusBar', StatusBar );
return inherit( Node, StatusBar, {
/**
* @public
* @override
*/
dispose: function() {
this.disposeStatusBar();
Node.prototype.dispose.call( this );
},
/**
* Updates the layout of things on the bar.
* @protected
*/
updateLayout: function() {
const leftEdge = ( ( this.dynamicAlignment ) ? this.barNode.left : this.layoutBounds.minX ) + this.xMargin;
const rightEdge = ( ( this.dynamicAlignment ) ? this.barNode.right : this.layoutBounds.maxX ) - this.xMargin;
this.updateLayoutProtected( leftEdge, rightEdge, this.barNode.centerY );
},
/**
* Layout that is specific to subtypes.
* @param {number} leftEdge - the bar's left edge, compensated for xMargin
* @param {number} rightEdge - the bar's right edge, compensated for xMargin
* @param {number} centerY - the bar's vertical center
* @protected
* @abstract
*/
updateLayoutProtected: function( leftEdge, rightEdge, centerY ) {
throw new Error( 'updateLayout must be implemented by subtypes' );
}
}, {
// Default font for things text that appears in the status bar subtypes
DEFAULT_FONT: DEFAULT_FONT
} );
} );
|
JavaScript
| 0.004581 |
@@ -344,24 +344,70 @@
inherit' );%0A
+ const merge = require( 'PHET_CORE/merge' );%0A
const Node
@@ -964,16 +964,13 @@
s =
-_.extend
+merge
( %7B%0A
|
59d4d3ab0a4ecd4de8a5b25d5ee4c648643ad254
|
Update urlparam-proc.js
|
inc/urlparam-proc.js
|
inc/urlparam-proc.js
|
//Processamento de parâmentros via URL
//Se foi solicitado marcador no mapa
if (mrgMarkerLatLonByURL !=null){
if (!mrgMapOnClickAddLock){
mrgMapOnClickAddLock = true;
mrgUserTempMarker.setLatLng(mrgMarkerLatLonByURL);
map.setView(mrgMarkerLatLonByURL, 18);
var Msg = TempMarkerMsg(mrgMarkerLatLonByURL[0],mrgMarkerLatLonByURL[1]);
mrgUserTempMarker.bindPopup(Msg).addTo(map);
mrgUserTempMarker.openPopup();
}else{
mrgMapOnClickAddLock = false;
map.removeLayer(mrgUserTempMarker);
}
}
if (mrgCamadaDeDados !=null){
var OK = true;
switch( mrgCamadaDeDados ) {
case 'paroquiabomjesus' : mrgAddDataOverlay('paroquiabomjesus','Paróquia Bom Jesus',null,'church',true); break;
case 'turismo' :
mrgAddDataOverlay('turismo','aeb','A & B',null,'utensils',false);
mrgAddDataOverlay('turismo','eventos','Eventos',null,'calendar-alt',false);
mrgAddDataOverlay('turismo','atrativos','Atrativos',null,'map-marked-alt',false);
mrgAddDataOverlay('turismo','hospedagem','Hospedagem',null,'bed',true)
break;
default : OK = false;
}
}
|
JavaScript
| 0.000001 |
@@ -664,16 +664,27 @@
jesus','
+paroquia','
Par%C3%B3quia
|
c36adec51c8a603dbd37166e6e1ff6536f62bf80
|
add logging to npm start
|
dev/start.js
|
dev/start.js
|
'use strict';
const WebpackDevServer = require('webpack-dev-server');
const webpack = require('webpack');
const metalsmith = require('./metalsmith');
const Logger = require('./logger');
const watch = require('./watch');
const webpackConfig = require('../webpack.config');
function serv() {
return new Promise(resolve => {
const compiler = webpack(webpackConfig);
const server = new WebpackDevServer(compiler, {
contentBase: './build',
noInfo: false, // display no info to console (only warnings and errors)
quiet: false, // display nothing to the console
colors: true,
stats: { colors: true },
watchOptions: {
aggregateTimeout: 1200,
poll: 1000
}
});
server.listen(3000, () => {
Logger.ok('webpack server');
resolve();
});
});
}
function start() {
return metalsmith()
.then(serv)
.then(watch)
.catch( (err) => {
Logger.error(err);
});
}
module.exports = start;
|
JavaScript
| 0.000001 |
@@ -283,24 +283,79 @@
n serv() %7B%0A%0A
+ Logger.info('Starting webpack development server');%0A%0A
return new
@@ -826,23 +826,44 @@
ger.ok('
-webpack
+Finished webpack development
server'
|
b7ee56e260830c5e8c2edc45e4b5f5552b0e298c
|
fix interceptor to account for NULL messages
|
irods-cloud-frontend/app/components/httpInterceptors.js
|
irods-cloud-frontend/app/components/httpInterceptors.js
|
/**
*
* Defines interceptors for auth and error handling with the REST back end
* Created by mikeconway on 3/7/14.
*
*
*/
angular.module('httpInterceptorModule', []).factory('myHttpResponseInterceptor', ['$q', '$location', '$log', 'MessageService', 'globals', function ($q, $location, $log, MessageService, globals) {
return {
// On request success
request: function (config) {
// console.log(config); // Contains the data about the request before it is sent.
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
// On request failure
requestError: function (rejection) {
// console.log(rejection); // Contains the data about the error on the request.
// Return the promise rejection.
return $q.reject(rejection);
},
// On response success
response: function (response) {
// console.log(response); // Contains the data from the response.
$log.info(response);
/* if (response.config.method.toUpperCase() != 'GET') {
messageCenterService.add('success', 'Success');
}*/
// Return the response or promise.
return response || $q.when(response);
},
// On response failture
responseError: function (rejection) {
// console.log(rejection); // Contains the data about the error.
$log.error(rejection);
var status = rejection.status;
if (status == 401) { // unauthorized - redirect to login again
//save last path for subsequent re-login
if ($location.path() != "/login") {
$log.info("intercepted unauthorized, save the last path");
globals.setLastPath($location.path());
$log.info("saved last path:" + $location.path());
}
$location.path("/login");
} else if (status == 400) { // validation error display errors
//alert(JSON.stringify(rejection.data.error.message)); // here really we need to format this but just showing as alert.
var len = rejection.data.errors.errors.length;
if (len > 0) {
for (var i = 0; i < len; i++) {
MessageService.warn(rejection.data.errors.errors[i].message);
}
}
return $q.reject(rejection);
} else {
// otherwise reject other status codes
var msg = rejection.data.error;
if (!msg) {
msg = "unknown exception occurred"; //FIXME: i18n
}
MessageService.error(msg.message);
return $q.reject(rejection);
}
// Return the promise rejection.
//return $q.reject(rejection);
}
};
}])//Http Intercpetor to check auth failures for xhr requests
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('myHttpResponseInterceptor');
/* configure xsrf token
see: http://stackoverflow.com/questions/14734243/rails-csrf-protection-angular-js-protect-from-forgery-makes-me-to-log-out-on
*/
}]);
|
JavaScript
| 0 |
@@ -2884,16 +2884,31 @@
if (!msg
+ %7C%7C msg == null
) %7B%0A
|
e8de9c7916e121cad3a0bbb11ad3c3dcc57291b7
|
Move Blur handling into InitScripts.js
|
DistFiles/factoryCollections/InitScripts.js
|
DistFiles/factoryCollections/InitScripts.js
|
//Run any needed functions here:
jQuery(document).ready(function () {
//Apply overflow handling to all textareas
jQuery("textarea").each(function(){ jQuery(this).SignalOverflow() } );
//Other needed functions:
//...
//...
});
|
JavaScript
| 0.000001 |
@@ -63,16 +63,20 @@
on () %7B%0A
+%0A%0A
//Appl
@@ -112,16 +112,18 @@
xtareas%0A
+
jQuery
@@ -148,18 +148,20 @@
function
+
()
+
%7B jQuery
@@ -189,13 +189,181 @@
() %7D
-
);%0A%0A
+ //make textarea edits go back into the dom (they were designed to be POST'ed via forms)%0A jQuery(%22textarea%22).blur(function () %7B this.innerHTML = this.value; %7D);%0A
//
@@ -386,24 +386,26 @@
ctions:%0A
+
//...%0A
//...%0A
@@ -396,16 +396,18 @@
//...%0A
+
//...%0A
|
e44eb0b078fe7d0610c00a5c63b165f2ed31039f
|
Update component ErrorList
|
src/common/components/utils/ErrorList.js
|
src/common/components/utils/ErrorList.js
|
import React from 'react';
import { connect } from 'react-redux';
import Grid from 'react-bootstrap/lib/Grid';
import Errors from '../../constants/Errors';
import { removeError } from '../../actions/errorActions';
let ErrorList = ({ errors, dispatch }) => (
<Grid>
{errors.map((error) => (
<div
key={error.id}
className="alert alert-danger alert-dismissible"
role="alert"
>
<button
type="button"
className="close"
data-dismiss="alert"
aria-label="Close"
onClick={() => dispatch(removeError(error.id))}
>
<span aria-hidden="true">×</span>
</button>
<strong>{error.title}</strong>
{' ' + error.detail}
{error.meta && [(
<p key="0">
{error.code === Errors.STATE_PRE_FETCHING_FAIL.code && (
<span>{error.meta.detail}</span>
)}
</p>
), (
<p key="1">
{error.meta.path && `(at path '${error.meta.path}')`}
</p>
), (
<p key="2">
{error.code === Errors.UNKNOWN_EXCEPTION.code && (
<span>{error.meta.toString()}</span>
)}
</p>
)]}
</div>
))}
</Grid>
);
export default connect(state => ({
errors: state.errors,
}))(ErrorList);
|
JavaScript
| 0 |
@@ -104,16 +104,63 @@
/Grid';%0A
+import Alert from 'react-bootstrap/lib/Alert';%0A
import E
@@ -255,16 +255,443 @@
ions';%0A%0A
+function renderMeta(error) %7B%0A let messages = %5B%5D;%0A if (error.code === Errors.STATE_PRE_FETCHING_FAIL.code) %7B%0A messages.push(error.meta.detail);%0A %7D%0A if (error.meta.path) %7B%0A messages.push(%60(at path '$%7Berror.meta.path%7D')%60);%0A %7D%0A if (error.code === Errors.UNKNOWN_EXCEPTION.code) %7B%0A messages.push(error.meta.toString());%0A %7D%0A return messages.map((message) =%3E (%0A %3Cp key=%7Bmessage%7D%3E%0A %7Bmessage%7D%0A %3C/p%3E%0A ));%0A%7D%0A%0A
let Erro
@@ -771,19 +771,21 @@
%0A %3C
-div
+Alert
%0A
@@ -812,231 +812,42 @@
-className=%22alert alert-danger alert-dismissible%22%0A role=%22alert%22%0A %3E%0A %3Cbutton%0A type=%22button%22%0A className=%22close%22%0A data-dismiss=%22alert%22%0A aria-label=%22Close%22%0A onClick
+bsStyle=%22danger%22%0A onDismiss
=%7B()
@@ -889,18 +889,16 @@
%7D%0A
-
%3E%0A
@@ -903,83 +903,11 @@
- %3Cspan aria-hidden=%22true%22%3E×%3C/span%3E%0A %3C/button%3E%0A %3Cstrong
+%3Ch4
%3E%7Ber
@@ -922,14 +922,10 @@
e%7D%3C/
-strong
+h4
%3E%0A
@@ -978,497 +978,40 @@
&&
-%5B(%0A %3Cp key=%220%22%3E%0A %7Berror.code === Errors.STATE_PRE_FETCHING_FAIL.code && (%0A %3Cspan%3E%7Berror.meta.detail%7D%3C/span%3E%0A )%7D%0A %3C/p%3E%0A ), (%0A %3Cp key=%221%22%3E%0A %7Berror.meta.path && %60(at path '$%7Berror.meta.path%7D')%60%7D%0A %3C/p%3E%0A ), (%0A %3Cp key=%222%22%3E%0A %7Berror.code === Errors.UNKNOWN_EXCEPTION.code && (%0A %3Cspan%3E%7Berror.meta.toString()%7D%3C/span%3E%0A )%7D%0A %3C/p%3E%0A )%5D%7D%0A %3C/div
+renderMeta(error)%7D%0A %3C/Alert
%3E%0A
|
6c16eaffd7f32254708f4848669e411ba71f0024
|
Remove console log
|
src/legacy/js/functions/_externalLinkAccordionSection.js
|
src/legacy/js/functions/_externalLinkAccordionSection.js
|
/**
* Manages links
* @param collectionId
* @param data
* @param field - JSON data key
* @param idField - HTML id for the template
*/
function renderExternalLinkAccordionSection(collectionId, data, field, idField) {
console.log(collectionId, data, field, idField);
var list = data[field];
var dataTemplate = {list: list, idField: idField};
var html = templates.editorLinks(dataTemplate);
$('#' + idField).replaceWith(html);
// Load
$(data[field]).each(function (index) {
$('#' + idField + '-edit_' + index).click(function () {
var uri = data[field][index].uri;
var title = data[field][index].title;
if (idField === "filterable-dataset") {
addFilteredDatasetLink('edit', uri, index);
return;
}
addEditLinksModal('edit', uri, title, index);
});
// Delete
$('#' + idField + '-delete_' + index).click(function () {
swal({
title: "Warning",
text: "Are you sure you want to delete?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Delete",
cancelButtonText: "Cancel",
closeOnConfirm: false
}, function (result) {
if (result === true) {
var position = $(".workspace-edit").scrollTop();
Florence.globalVars.pagePos = position + 300;
$(this).parent().remove();
data[field].splice(index, 1);
saveLink(collectionId, data.uri, data, field, idField);
refreshPreview(data.uri);
swal({
title: "Deleted",
text: "This link has been deleted",
type: "success",
timer: 2000
});
}
});
});
});
//Add
$('#add-' + idField).click(function () {
var position = $(".workspace-edit").scrollTop();
Florence.globalVars.pagePos = position + 300;
if (idField === "filterable-dataset") {
addFilteredDatasetLink();
return;
}
addEditLinksModal();
});
function sortable() {
$('#sortable-' + idField).sortable({
stop: function () {
$('#' + idField + ' .edit-section__sortable-item--counter').each(function (index) {
$(this).empty().append(index + 1);
});
}
});
}
sortable();
function saveLink(collectionId, path, data, field, idField) {
putContent(collectionId, path, JSON.stringify(data),
success = function () {
Florence.Editor.isDirty = false;
renderExternalLinkAccordionSection(collectionId, data, field, idField);
refreshPreview(data.uri);
},
error = function (response) {
if (response.status === 400) {
sweetAlert("Cannot edit this page", "It is already part of another collection.");
}
else {
handleApiError(response);
}
}
);
}
function addEditLinksModal(mode, uri, title, index) {
var uri = uri;
var title = title;
if (!data[field]) {
data[field] = [];
}
var linkData = {title: title, uri: uri, showTitleField: true};
var modal = templates.linkExternalModal(linkData);
$('.workspace-menu').append(modal);
$('#uri-input').change(function () {
uri = $('#uri-input').val();
});
$('#uri-title').change(function () {
title = $('#uri-title').val();
});
$('.btn-uri-get').off().click(function () {
if (!title) {
sweetAlert('You need to enter a title to continue');
} else if (uri.match(/\s/g)) {
sweetAlert('Your link cannot contain spaces');
} else {
if (mode == 'edit') {
data[field][index].uri = uri;
data[field][index].title = title;
} else {
data[field].push({uri: uri, title: title});
}
saveLink(collectionId, data.uri, data, field, idField);
$('.modal').remove();
}
});
$('.btn-uri-cancel').off().click(function () {
$('.modal').remove();
});
}
function addFilteredDatasetLink(mode, uri, index) {
var uri = uri;
if (!data[field]) {
data[field] = [];
}
var linkData = {uri: uri, showTitleField: false};
var modal = templates.linkExternalModal(linkData);
$('.workspace-menu').append(modal);
$('#uri-input').change(function () {
uri = $('#uri-input').val();
});
$('.btn-uri-get').off().click(function () {
try {
var parsedURL = new URL(uri)
}
catch(error) {
sweetAlert("That doesn't look like a valid URL. Plese include all parts of the URL e.g. 'http://', 'www', etc.");
console.error("Error parsing URL \n", error)
return;
}
if (mode == 'edit') {
data[field][index].uri = parsedURL.pathname;
} else {
data[field].push({uri: parsedURL.pathname});
}
saveLink(collectionId, data.uri, data, field, idField);
$('.modal').remove();
});
$('.btn-uri-cancel').off().click(function () {
$('.modal').remove();
});
}
}
|
JavaScript
| 0.000002 |
@@ -220,61 +220,8 @@
) %7B%0A
- console.log(collectionId, data, field, idField);%0A
|
d91e43a273e0ff0ed0080edf89ae32cc9b67d476
|
Fix Facebook mobile social login and comment React Native recommended usage
|
src/common/lib/redux-firebase/actions.js
|
src/common/lib/redux-firebase/actions.js
|
import mapAuthToUser from './mapAuthToUser';
export const REDUX_FIREBASE_LOGIN_ERROR = 'REDUX_FIREBASE_LOGIN_ERROR';
export const REDUX_FIREBASE_LOGIN_START = 'REDUX_FIREBASE_LOGIN_START';
export const REDUX_FIREBASE_LOGIN_SUCCESS = 'REDUX_FIREBASE_LOGIN_SUCCESS';
export const REDUX_FIREBASE_OFF_QUERY = 'REDUX_FIREBASE_OFF_QUERY';
export const REDUX_FIREBASE_ON_AUTH = 'REDUX_FIREBASE_ON_AUTH';
export const REDUX_FIREBASE_ON_QUERY = 'REDUX_FIREBASE_ON_QUERY';
export const REDUX_FIREBASE_RESET_PASSWORD_ERROR = 'REDUX_FIREBASE_RESET_PASSWORD_ERROR';
export const REDUX_FIREBASE_RESET_PASSWORD_START = 'REDUX_FIREBASE_RESET_PASSWORD_START';
export const REDUX_FIREBASE_RESET_PASSWORD_SUCCESS = 'REDUX_FIREBASE_RESET_PASSWORD_SUCCESS';
export const REDUX_FIREBASE_SAVE_USER_ON_AUTH_ERROR = 'REDUX_FIREBASE_SAVE_USER_ON_AUTH_ERROR';
export const REDUX_FIREBASE_SAVE_USER_ON_AUTH_START = 'REDUX_FIREBASE_SAVE_USER_ON_AUTH_START';
export const REDUX_FIREBASE_SAVE_USER_ON_AUTH_SUCCESS = 'REDUX_FIREBASE_SAVE_USER_ON_AUTH_SUCCESS';
export const REDUX_FIREBASE_SIGN_UP_ERROR = 'REDUX_FIREBASE_SIGN_UP_ERROR';
export const REDUX_FIREBASE_SIGN_UP_START = 'REDUX_FIREBASE_SIGN_UP_START';
export const REDUX_FIREBASE_SIGN_UP_SUCCESS = 'REDUX_FIREBASE_SIGN_UP_SUCCESS';
export const REDUX_FIREBASE_WATCH_AUTH = 'REDUX_FIREBASE_WATCH_AUTH';
async function socialLogin(firebase, provider) {
const settings = { scope: 'email, user_friends' };
// https://www.firebase.com/docs/web/guide/user-auth.html#section-popups
try {
await firebase.authWithOAuthPopup(provider, settings);
} catch (error) {
if (error.code === 'TRANSPORT_UNAVAILABLE') {
await firebase.authWithOAuthRedirect(provider, settings);
}
throw error;
}
}
function saveUserOnAuth(authData) {
return ({ firebase }) => {
const user = mapAuthToUser(authData);
user.authenticatedAt = firebase.constructor.ServerValue.TIMESTAMP;
const { email } = user;
delete user.email;
// With Firebase multi-path updates, we can update values at multiple
// locations at the same time. Powerful feature for data denormalization.
const promise = firebase.update({
[`users/${user.id}`]: user,
[`users-emails/${user.id}`]: { email }
});
return {
type: 'REDUX_FIREBASE_SAVE_USER_ON_AUTH',
payload: { promise }
};
};
}
export function login(provider, fields) {
return ({ firebase }) => {
const promise = provider === 'password'
? firebase.authWithPassword(fields)
: socialLogin(firebase, provider);
return {
type: 'REDUX_FIREBASE_LOGIN',
payload: { promise }
};
};
}
export function onAuth(authData) {
return {
type: REDUX_FIREBASE_ON_AUTH,
payload: { authData }
};
}
export function resetPassword(email) {
return ({ firebase }) => {
const promise = firebase.resetPassword({ email });
return {
type: 'REDUX_FIREBASE_RESET_PASSWORD',
payload: { promise }
};
};
}
export function signUp(fields) {
return ({ firebase }) => {
// This is a beautiful example of async / await over plain promises.
// Note async function handles errors automatically.
async function getPromise() {
await firebase.createUser(fields);
await firebase.authWithPassword(fields);
}
return {
type: 'REDUX_FIREBASE_SIGN_UP',
payload: {
promise: getPromise()
}
};
};
}
export function watchAuth(logout) {
return ({ dispatch, firebase }) => {
// Use sync getAuth to set app state immediately.
dispatch(onAuth(firebase.getAuth()));
// Watch auth.
firebase.onAuth(authData => {
dispatch(onAuth(authData));
if (authData) {
dispatch(saveUserOnAuth(authData));
} else {
dispatch(logout());
}
});
return {
type: REDUX_FIREBASE_WATCH_AUTH
};
};
}
|
JavaScript
| 0 |
@@ -1326,16 +1326,168 @@
AUTH';%0A%0A
+// Doesn't work on React Native, because there is no window nor redirect.%0A// Use React Native Facebook login component with authWithOAuthToken instead.%0A
async fu
@@ -1562,17 +1562,16 @@
'email,
-
user_fri
@@ -1787,24 +1787,80 @@
AILABLE') %7B%0A
+ // Pass an empty function until Firebase fix bug.%0A
await
@@ -1891,32 +1891,42 @@
direct(provider,
+ () =%3E %7B%7D,
settings);%0A
|
f5c6b7e79d4806685e8d10a9b7a85a0b6601a137
|
add support for 'xml' conform type
|
test/sources.js
|
test/sources.js
|
var test = require('tape').test,
glob = require('glob'),
fs = require('fs');
var manifest = glob.sync('sources/*.json');
var index = 0;
checkSource(index);
function validateJSON(body) {
try {
var data = JSON.parse(body);
return data;
} catch(e) {
return null;
}
}
function checkSource(i){
var source = manifest[i];
if (i == manifest.lenght-1 || !source) process.exit(0);
test(source, function(t) {
var raw = fs.readFileSync(source, 'utf8');
var data = validateJSON(raw);
t.ok(data, "Data is valid JSON");
if (data) {
if (data.skip) t.pass("WARN - Skip Flag Detected");
//Ensure people don't make up values
generalOptions = ['email', 'attribution', 'year', 'skip', 'conform', 'coverage', 'data', 'compression', 'type', 'coverage', 'website', 'license', 'note'];
Object.keys(data).forEach(function (generalKey) {
t.ok(generalOptions.indexOf(generalKey) !== -1, generalKey + " is supported");
});
//Mandatory Fields & Coverage
t.ok(data.data, "Checking for data");
t.ok(data.type, "Checking for type");
if (data.compression && ['zip'].indexOf(data.compression) === -1) t.fail("Compression type not supported");
t.ok(typeof data.coverage === 'object', "Coverage Object Exists");
t.ok(typeof data.coverage.country === 'string', "coverage - Country must be a string");
t.ok(data.coverage.province ? typeof data.coverage.country === 'string' : true, "coverage - Province must be a string");
t.ok(data.coverage.county ? typeof data.coverage.county === 'string' : true, "coverage - County must be a string");
t.ok(data.coverage.city ? typeof data.coverage.city === 'string' : true, "coverage - City must be a string");
t.ok(['http', 'ftp', 'ESRI'].indexOf(data.type) !== -1, "Type valid");
if (data.conform) {
//Ensure people don't make up new values
var conformOptions = ['type', 'csvsplit', 'merge', 'advanced_merge', 'split', 'srs', 'file', 'encoding', 'headers', 'skiplines', 'lon', 'lat', 'number', 'street', 'city', 'postcode', 'district', 'region', 'addrtype', 'notes'];
Object.keys(data.conform).forEach(function (conformKey) {
t.ok(conformOptions.indexOf(conformKey) !== -1, "conform - " + conformKey + " is supported");
});
//Mandator Conform Fields
t.ok(data.conform.lon && typeof data.conform.lon === 'string', "conform - lon attribute required");
t.ok(data.conform.lat && typeof data.conform.lat === 'string', "conform - lat attribute required");
t.ok(data.conform.number && typeof data.conform.number === 'string', "conform - number attribute required");
t.ok(data.conform.street && typeof data.conform.street === 'string', "conform - street attribute required");
t.ok(data.conform.type && typeof data.conform.type === 'string', "conform - type attribute required");
t.ok(['shapefile', 'shapefile-polygon', 'csv', 'geojson'].indexOf(data.conform.type) !== -1, "conform - type is supported");
//Optional Conform Fields
t.ok(data.conform.merge ? Array.isArray(data.conform.merge) : true, "conform - Merge is an array");
t.ok(data.conform.addrtype ? typeof data.conform.addrtype === 'string' : true, "conform - addrtype is a string");
t.ok(data.conform.accuracy ? typeof data.conform.accuracy === 'number' : true, "conform - accuracy is a number");
t.ok(data.conform.accuracy ? data.conform.accuracy !== 0 : true, "conform - accuracy is not 0");
t.ok(data.conform.csvsplit ? typeof data.conform.csvsplit === 'string' : true, "conform - csvsplit is a string");
t.ok(data.conform.split ? typeof data.conform.split === 'string' : true, "conform - split is a string");
t.ok(data.conform.srs ? typeof data.conform.srs === 'string' : true, "conform - srs is a string");
t.ok(data.conform.file ? typeof data.conform.file === 'string' : true, "conform - file is a string");
t.ok(data.conform.encoding ? typeof data.conform.encoding === 'string' : true, "conform - encoding is a string");
t.ok(data.conform.city ? typeof data.conform.city === 'string' : true, "conform - city is a string");
t.ok(data.conform.postcode ? typeof data.conform.postcode === 'string' : true, "conform - postcode is a string");
t.ok(data.conform.district ? typeof data.conform.district === 'string' : true, "conform - district is a string");
t.ok(data.conform.region ? typeof data.conform.region === 'string' : true, "conform - region is a string");
t.ok(data.conform.addrtype ? typeof data.conform.addrtype === 'string' : true, "conform - addrtype is a string");
t.ok(data.conform.notes ? typeof data.conform.notes === 'string' : true, "conform - notes is a string");
}
//Optional General Fields
t.ok(data.coverage.email ? typeof data.coverage.email === 'string' : true, "email must be a string");
t.ok(data.coverage.website ? typeof data.coverage.website === 'string' : true, "website must be a string");
t.ok(data.coverage.license ? typeof data.coverage.license === 'string' : true, "license must be a string");
}
t.end();
checkSource(++index);
});
}
|
JavaScript
| 0.000001 |
@@ -3226,16 +3226,23 @@
geojson'
+, 'xml'
%5D.indexO
|
6216220c933e54df96a2e5bed7e320d93c195522
|
add docstring to classify method
|
jssnips/math_numbers/perfect-numbers/perfect-numbers.js
|
jssnips/math_numbers/perfect-numbers/perfect-numbers.js
|
class PerfectNumbers{
/**
* Classifies numbers to either perfect, abundant or deficient base on their
aliquot sum
@param {Number} number to classify
@returns {String} whether the number is perfect, abundant or deficient
*/
classify(number){
if(number <= 0){
return "Classification is only possible for natural numbers."
}
// classify deficient numbers
if(this.getAliquotSum(number) < number || number === 1){
return "deficient";
}
// classify perfect numbers
if(this.getAliquotSum(number) == number){
return "perfect";
}
//classify abundant numbers
if(this.getAliquotSum(number) > number){
return "abundant";
}
}
/**
Gets the aliquot sum
@param {Number} num the number to derive the aliquot sum
@returns {Number} the sum of the factors of the provided number
*/
getAliquotSum(num){
// ensures a whole number, total = 1, 1 will be part of the solution
var half = Math.floor(num / 2), total = 1, i, j;
// determine the increment value for the loop and starting point
num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);
for(i; i <= half;i += j){
num % i === 0 ? total += i: false;
}
return total;
}
}
module.exports = PerfectNumbers;
|
JavaScript
| 0.000015 |
@@ -722,16 +722,346 @@
uot sum%0A
+ This speeds up the process by checking if the number is odd/even%0A Odd numbers don't need to be checked against each number like evens do. Odd numbers can be checked%0A against every other number.%0A There is not need to check beyond half the given number as nothing beyond half the number will work%0A Excludes 0 and starts from 1
%0A @para
|
d6e44c75ac3c2de2a74d5ddd64caae9054694cdb
|
Add function to switch html.color-- class based on header-archive hovers
|
assets/js/main.js
|
assets/js/main.js
|
/**
* main.js
*
* Author: Marian Friedmann
*
*/
/**
* Disqus function makes it possible to work with the
* disqus comment count.
*
*/
var Disqus = function() {
var data = true,
_self = this;
this.options = {};
this.options.cache = 120 * 1000;
};
/**
* Set data
*
* @param {object} data disqus data returned by retrieveData function
*/
Disqus.prototype.setCache = function (data) {
var date = Date.now();
data.timestamp = date;
localStorage.setItem('data', JSON.stringify(this.processData(data)));
return this;
};
/**
* Get cached data
*
* @return {data|boolean} cached data object or false if cache time is expired
*/
Disqus.prototype.getCache = function () {
var data = JSON.parse(localStorage.getItem('data'));
if (data && data.timestamp >= Date.now() - this.options.cache) {
return data;
} else {
return false;
}
};
/**
* Return comment count for given identifier. Should
* be called inside ready function to make sure
* current data is available.
*
* @param {string} identifier disqus identifier
* @return {number} comment count for identifier
*/
Disqus.prototype.getComments = function(identifier) {
return this.getCache()[identifier].posts;
};
/**
* Ready function to make sure current data is available.
*
* @param {Function} callback function that is called when
* current data is available
*/
Disqus.prototype.ready = function(callback) {
var _self = this;
if (!_self.getCache()) {
_self.retrieveData(function(data) {
_self.setCache(data);
callback();
});
} else {
callback();
}
};
/**
* Retrieve data from disqus api
*
* @return {Function} callback containing retrieved data
*/
Disqus.prototype.retrieveData = function (callback) {
var apiKey = '',
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var json = JSON.parse(xhr.responseText);
callback(json);
}
};
xhr.open('GET', 'https://disqus.com/api/3.0/forums/listThreads.json?forum=frdmn&limit=100&include=open&api_key='+apiKey, true);
xhr.send(null);
};
/**
* Process disqus data object, remove items lacking identifiers
*
* @param {object} data disqus data returned by retrieveData function
* @return {object} processed data
*/
Disqus.prototype.processData = function (data) {
var output = {};
output.timestamp = data.timestamp;
data.response.forEach(function(v,k) {
var id = v.identifiers[0];
if (id) {
output[id] = v;
}
});
return output;
};
$.fn.removeClassPrefix = function(prefix) {
this.each(function(i, el) {
var classes = el.className.split(" ").filter(function(c) {
return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = $.trim(classes.join(" "));
});
return this;
};
$(function() {
var $headerNav = $('.header-archive'),
$archiveToggle = $('.archive-toggle'),
$titleBar = $('#static-title-bar'),
$body = $('body');
$headerNav.headroom({
offset: 180,
tolerance: 5,
classes : {
pinned : 'header-archive--visible',
},
onPin : function() {
if(!$headerNav.hasClass('header-archive')) $headerNav.addClass('header-archive');
if(this.lastKnownScrollY < 200) $headerNav.removeClass('header-archive--visible');
},
onUnpin : function() {
if(!$headerNav.hasClass('header-archive')) $headerNav.addClass('header-archive');
},
onTop : function() {
if(!$headerNav.hasClass('header-archive')) $headerNav.addClass('header-archive');
$headerNav.removeClass('header-archive--visible');
},
onNotTop : function() {
if(!$headerNav.hasClass('header-archive')) $headerNav.addClass('header-archive');
}
});
$archiveToggle.click(function() {
$archiveToggle.toggleClass('archive-toggle--active');
$headerNav.toggleClass('header-archive--active');
$body.toggleClass('no-scroll');
$titleBar.toggleClass('title-bar--hidden');
});
$('.post-content pre code').each(function() {
$(this).parent().wrap('<div class="code-block"></div>');
hljs.initHighlighting();
});
$('.post-content p img').each(function() {
$(this).parent().wrap('<div class="img-block"></div>');
});
var test = new Disqus();
test.ready(function(e) {
$('.comment-single').each(function() {
var $c = $(this),
id = $c.attr('data-disqus-identifier');
$c.text(test.getComments(id));
});
$('.comment').each(function() {
var $c = $(this),
id = $c.attr('data-disqus-identifier'),
comments = test.getComments(id),
buzz = false;
[15,30,100].forEach(function(v,k) {
if (v <= comments) {
buzz = Array(k + 2).join('🔥');
}
});
if (buzz) {
$c.html('<span class="tooltip">' + buzz + '<span class="tooltip__content">Hot Topic!<br><i class="tooltip__highlight">' + comments + '</i> comments <br>waiting inside!</span></span>');
setTimeout(function() {
$c.parent().addClass('comment-wrap--active');
},50);
}
});
});
});
|
JavaScript
| 0.000001 |
@@ -4331,16 +4331,204 @@
qus();%0A%0A
+ $('a%5Bdata-page-color%5D').hover(function() %7B%0A var color = $(this).attr('data-page-color');%0A $('html').removeClassPrefix('color--');%0A $('html').addClass('color--' + color);%0A %7D);%0A%0A
test.r
|
c78bbbe75e3824477fb89eff57152e21eaaa80cd
|
Fix failing creation of a booking
|
indico/modules/rb_new/client/js/containers/BookRoomModal.js
|
indico/modules/rb_new/client/js/containers/BookRoomModal.js
|
/* This file is part of Indico.
* Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
*
* Indico is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Indico is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Indico; if not, see <http://www.gnu.org/licenses/>.
*/
import {connect} from 'react-redux';
import BookRoomModal from '../components/modals/BookRoomModal';
import {createBooking, fetchBookingAvailability} from '../actions';
import {selectors as roomsSelectors} from '../common/rooms';
const mapStateToProps = (state, {roomId}) => {
const {
bookRoom: {filters: {recurrence, dates, timeSlot}},
bookRoomForm: {timeline},
user,
} = state;
const room = roomsSelectors.getRoom(state, {roomId});
return {
bookingData: {recurrence, dates, timeSlot},
availability: timeline && timeline.availability,
dateRange: timeline && timeline.dateRange,
user,
room,
};
};
const mapDispatchToProps = (dispatch) => ({
onSubmit: (
{reason, usage, user, isPrebooking},
{bookingData: {recurrence, dates, timeSlot, room: roomData}}) => {
return dispatch(createBooking({
reason,
usage,
user,
recurrence,
dates,
timeSlot,
room: roomData,
isPrebooking
}));
},
dispatch
});
const mergeProps = (stateProps, dispatchProps, ownProps) => {
const {bookingData: filters, room} = stateProps;
const {dispatch} = dispatchProps;
return {
...stateProps,
...dispatchProps,
...ownProps,
fetchAvailability() {
dispatch(fetchBookingAvailability(room, filters));
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps,
mergeProps,
)(BookRoomModal);
|
JavaScript
| 0.000002 |
@@ -1579,16 +1579,17 @@
timeSlot
+%7D
, room:
@@ -1597,17 +1597,16 @@
oomData%7D
-%7D
) =%3E %7B%0A
|
fcb68da317bc75ac282203d62fd128008df7cb45
|
fix popup position
|
assets/js/main.js
|
assets/js/main.js
|
$(document).ready(function() {
// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {
37: 1,
38: 1,
39: 1,
40: 1
};
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
}
function preventDefaultForScrollKeys(e) {
if (keys[e.keyCode]) {
preventDefault(e);
return false;
}
}
function disableScroll() {
if (window.addEventListener) { // older FF
window.addEventListener('DOMMouseScroll', preventDefault, false);
}
window.onwheel = preventDefault; // modern standard
window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
window.ontouchmove = preventDefault; // mobile
document.onkeydown = preventDefaultForScrollKeys;
}
function enableScroll() {
if (window.removeEventListener) {
window.removeEventListener('DOMMouseScroll', preventDefault, false);
}
window.onmousewheel = document.onmousewheel = null;
window.onwheel = null;
window.ontouchmove = null;
document.onkeydown = null;
}
$('#order').on('click', function() {
$('#order_popup').show();
$('#order_popup').css({
'position': 'absolute',
'top': 0,
'right': 0,
'bottom': 0,
'left': 0,
'background': 'rgba(0, 0, 0, 0.5)'
}).find('.b-order').css({
'position': 'relative',
'top': '50%',
'margin-top': '-100px'
});
disableScroll();
});
$('#order_popup').on('click', function(e) {
if (e.target != this) {
return;
}
$('#order_popup').hide();
enableScroll();
});
});
|
JavaScript
| 0.000002 |
@@ -1297,16 +1297,13 @@
': '
-absolute
+fixed
',%0A
|
116ac14f2c9166e2c1c8020c99dbd1ea900e7fd7
|
add our url-root to hivemind
|
dev/js/hivemind.js
|
dev/js/hivemind.js
|
/*global module */
'use strict';
module.exports = (function() {
var Backbone = require('backbone');
var $ = Backbone.$ = require('jquery-browserify');
var Dust = require('../../build/js/dust_templates.js')();
var Env_config = require('./config');
var Model = new Backbone.Model.extend({
});
var Collection = new Backbone.Model.extend({
});
var View = Backbone.View.extend({
model_type: Model,
self: this,
before_render: function(){},
after_render: function(){},
attach: function(selector) {
this.$el = $(selector);
this.render();
},
initialize: function() {
this.listenTo(this.model.id, 'change', function() {
this.loaded = null;
this.load();
});
this.listenTo(this.model, 'change', this.render);
},
when: function(promises) {
return $.when.apply(null, promises);
},
dustbase: Dust.makeBase({
media_base : Env_config.MEDIA_STORE,
load_asset: function(chunk, context, bodies, params) {
var asset = context.stack.head;
var asset_model = new Model(asset);
var asset_view = new View(asset_model);
if (params && params.template) {
asset_view.model.set('template', params.template);
}
return chunk.map(function(chunk) {
chunk.end('<div id="asset_' + asset.slug + '"></div>');
asset_view.attach('#asset_' + asset.slug);
});
},
}),
$el: $('<div></div>'),
render: function() {
this.before_render();
var promise = $.Deferred();
var context = this.dustbase().push(context);
var self = this;
self.$el.hide();
Dust.render( this.model.template, this.model.attributes,
function(err, out) { //callback
if (err) {
Env_config.ERROR_HANDLER(err, self);
} else {
self.el = out;
}
self.$el.html(self.el).show();
self.after_render();
}
);
return promise;
},
load: function() {
if (this.loaded && this.loaded.state()) { //already has a promise, is being loaded
return this.loaded;
}
if (false) { //FIXME test if local storage of this exists
//fill model from local storage
return this.loaded;
}
var self = this;
this.loaded = new $.Deferred();
this.model.fetch({
success : function() {
//FIXME ask real nice if we cna not have resource uri on here
self.model.set(
'resource_uri',
Env_config.DATA_STORE +
self.model.get('resource_uri')
);
self.loaded.resolve();
},
error : function(err) {
Env_config.ERROR_HANDLER(err);
self.loaded.resolve();
},
});
return this.loaded;
},
});
return {
View: View,
Model: Model,
Collection: Collection,
};
})();
|
JavaScript
| 0 |
@@ -295,32 +295,83 @@
.Model.extend(%7B%0A
+ urlRoot: EnvConfig.DATA_STORE + 'content',%0A
%7D);%0A%0A var
|
3c26119632381f8f8c79be0a9f75dcd46d0f0ef4
|
Fix bug student model
|
src/server/models/lophoc-model.js
|
src/server/models/lophoc-model.js
|
import { sequelize, Sequelize } from './index';
import Khoi from './khoi-model';
import NamHoc from './namhoc-model';
const LopHoc = sequelize.define('M_LOP_HOC', {
maLop_pkey: {
type: Sequelize.INTEGER,
primaryKey: true,
notNull: true,
autoIncrement: true,
field: 'MA_LOP_PKEY'
},
maLopHoc: {
type: Sequelize.STRING,
notNull: true,
unique: true,
field: 'MA_LOP_HOC'
},
tenLop: {
type: Sequelize.STRING,
notNull: true,
field: 'TEN_LOP'
},
siSo: {
type: Sequelize.INTEGER,
defaultValue: 0,
field: 'SISO'
},
siSoMax: {
type: Sequelize.INTEGER,
defaultValue: 0,
field: 'SISO_MAX'
},
maKhoi: {
type: Sequelize.INTEGER,
field: 'MA_KHOI'
},
maNamHoc: {
type: Sequelize.INTEGER,
field: 'MA_NAM_HOC'
}
});
Khoi.hasMany(LopHoc, { foreignKey: 'maKhoi', sourceKey: 'maKhoi_pkey' });
LopHoc.belongsTo(Khoi, { foreignKey: 'maKhoi', targetKey: 'maKhoi_pkey' });
NamHoc.hasMany(LopHoc, { foreignKey: 'maNamHoc', sourceKey: 'namHoc_pkey' });
LopHoc.belongsTo(Khoi, { foreignKey: 'maNamHoc', sourceKey: 'namHoc_pkey' });
export default LopHoc;
|
JavaScript
| 0.000001 |
@@ -1164,36 +1164,38 @@
opHoc.belongsTo(
-Khoi
+NamHoc
, %7B foreignKey:
@@ -1198,38 +1198,38 @@
ey: 'maNamHoc',
-source
+target
Key: 'namHoc_pke
|
102e8120046d6a39aa0db05961288fec320eb3f3
|
Add tests for upload-validation-active helper.
|
tests/unit/helpers/upload-validation-active-test.js
|
tests/unit/helpers/upload-validation-active-test.js
|
import { uploadValidationActive } from 'preprint-service/helpers/upload-validation-active';
import { module, test } from 'qunit';
module('Unit | Helper | upload validation active');
// Replace this with your real tests.
test('it works', function(assert) {
var editMode = true;
var nodeLocked = true;
var hasOpened = true;
let result = uploadValidationActive([editMode, nodeLocked, hasOpened]);
assert.ok(result);
});
|
JavaScript
| 0 |
@@ -182,60 +182,48 @@
);%0A%0A
-// Replace this with your real tests.%0Atest('it works
+test('edit mode upload validation active
', f
@@ -409,17 +409,798 @@
ert.
-ok(result
+equal(result, true);%0A%7D);%0A%0Atest('edit mode upload validation not active', function(assert) %7B%0A var editMode = true;%0A var nodeLocked = false;%0A var hasOpened = true;%0A let result = uploadValidationActive(%5BeditMode, nodeLocked, hasOpened%5D);%0A assert.equal(result, false);%0A%7D);%0A%0Atest('add mode upload validation active', function(assert) %7B%0A var editMode = false;%0A var nodeLocked = true;%0A var hasOpened = true;%0A let result = uploadValidationActive(%5BeditMode, nodeLocked, hasOpened%5D);%0A assert.equal(result, true);%0A%7D);%0A%0A%0Atest('add mode upload validation not active', function(assert) %7B%0A var editMode = false;%0A var nodeLocked = false;%0A var hasOpened = true;%0A let result = uploadValidationActive(%5BeditMode, nodeLocked, hasOpened%5D);%0A assert.equal(result, false
);%0A%7D
|
46bbb266b572b37023c0cea5daa6581672b5ef7f
|
Update fileManager.js
|
lib/FileManager/fileManager.js
|
lib/FileManager/fileManager.js
|
/**
* fileManager.js
* Andrea Tino - 2015
*/
/**
* Handles files.
* We create a shadow file in order to store escaped source Javascript
* so that we can call the parser on that file.
*/
module.exports = function(fpath) {
var fs = require('fs');
var path = require('path');
var text = require('../text.js');
// Module construction
var validatePath = function(p) {
if (!p) {
throw 'Error: Path cannot be null or undefined!';
}
return p;
};
var processPath = function(p) {
return path.resolve('/', p); // Returns a normalized path
};
// Private variables
var EXT = '.3kaku';
var filepath = processPath(validatePath(fpath));
var fileContent = null;
// Private functions
var escapeContent = function(str) {
return text().jsEscape(str);
};
var fetchFileContent = function() {
try {
fileContent = fs.readFileSync(filepath, {encoding: 'utf8'});
} catch(e) {
throw 'Error loading file content from ' + filepath + '!';
}
};
var getShadowFileName = function() {
return filepath + EXT;
};
// Constructor
{
fetchFileContent();
};
return {
/**
* Gets the name of the shadow file.
*/
shadowFileName: function() {
return getShadowFileName();
},
/**
* Gets the original Javascript source.
*/
source: function() {
return fileContent;
},
/**
* Creates the shadow file and initializes its content basing
* on the original file.
*/
createShadowFile: function() {
if (!fileContent) {
throw 'Error: File content not available to create shadow file!';
}
var dir = path.dirname(filepath);
var shadowFilePath = path.join(dir, getShadowFileName());
// If file exists, overwrite it, if it does not exists, create it
var fd = fs.openSync(shadowFilePath, 'w');
var shadowContent = escapeContent(fileContent); // fileContent available from cton time
shadowContent = 'print(Reflect.parse(\"' + shadowContent + '\"));';
var bytes = fs.writeSync(fd, shadowContent, 0, {encoding: 'utf8'});
fs.closeSync(fd);
if (bytes <= 0) {
throw 'Error: Error while writing shadow file!';
}
},
/**
* Removes the shadow file.
*/
removeShadowFile: function(errorIfDoesNotExists) {
errorIfDoesNotExists = (typeof errorIfDoesNotExists === 'undefined') ?
false : errorIfDoesNotExists;
var dir = path.dirname(filepath);
var shadowFilePath = path.join(dir, shadowFileName());
// If the file does not exist, do nothing or throw
if (!fs.existsSync(shadowFilePath) && errorIfDoesNotExists) {
throw 'Error: Cannot find shadow file to remove!';
} else {
return;
}
// The shadow file exists: we need to remove it
fs.unlinkSync(shadowFilePath);
}
};
};
|
JavaScript
| 0.000001 |
@@ -540,13 +540,8 @@
lve(
-'/',
p);
@@ -564,16 +564,25 @@
malized
+absolute
path%0A %7D
|
6e628a6fd337700f4219469e3ec16f360dd08745
|
Add ALT eraser
|
censored.js
|
censored.js
|
;(function(global) {
'use strict';
function Censored(el) {
var md = false;
var er = false;
var img = document.getElementById(el);
img.onload = function() {
var wrapper = document.createElement('div');
wrapper.style.position = 'relative'
var parent = img.parentNode;
parent.insertBefore(wrapper, img);
var canvas1 = document.createElement('canvas');
canvas1.height = img.height;
canvas1.width = img.width;
canvas1.style.position = 'absolute';
var ctx1 = canvas1.getContext('2d');
ctx1.mozImageSmoothingEnabled = false;
ctx1.webkitImageSmoothingEnabled = false;
ctx1.imageSmoothingEnabled = false;
var w = img.width * 0.1;
var h = img.height * 0.1;
ctx1.drawImage(img, 0, 0, w, h);
ctx1.drawImage(canvas1, 0, 0, w, h, 0, 0, canvas1.width, canvas1.height);
var canvas2 = document.createElement('canvas');
canvas2.height = img.height;
canvas2.width = img.width;
canvas2.style.position = 'absolute';
var ctx2 = canvas2.getContext('2d');
ctx2.drawImage(img, 0, 0);
var canvas3 = document.createElement('canvas');
canvas3.height = img.height;
canvas3.width = img.width;
canvas3.style.position = 'absolute';
var ctx3 = canvas3.getContext('2d');
wrapper.appendChild(canvas1);
wrapper.appendChild(canvas2);
wrapper.appendChild(canvas3);
parent.removeChild(img);
canvas3.addEventListener('mousedown', function() {
md = true;
});
canvas3.addEventListener('mouseup', function() {
md = false;
});
canvas3.addEventListener('mousemove', function(e) {
if (md) {
if (er) {
ctx3.clearRect(e.pageX - 20, e.pageY - 20, 40, 40);
} else {
ctx3.putImageData(ctx1.getImageData(e.pageX - 20, e.pageY - 20, 40, 40), e.pageX - 20, e.pageY - 20);
}
}
});
};
}
global.Censored = Censored;
})(window);
|
JavaScript
| 0.000001 |
@@ -1951,24 +1951,233 @@
%0A %7D);%0A%0A
+ document.addEventListener('keydown', function(e) %7B%0A if (e.altKey) %7B%0A er = true;%0A %7D%0A %7D);%0A%0A document.addEventListener('keyup', function(e) %7B%0A er = false;%0A %7D);%0A%0A
%7D;%0A%0A %7D%0A
|
ba26d751b7467eda5e630f659f4836a4c2441023
|
improve stream preload state
|
src/components/VideoPlayer/MP4/Stream.js
|
src/components/VideoPlayer/MP4/Stream.js
|
import React from 'react';
import PropTypes from 'prop-types';
import DropdownPanel from '../../utils/DropdownPanel.js'
export default class PlayerStream extends React.Component {
render() {
const { player, loadedmetadata } = this.props
if (loadedmetadata) {
return (
<DropdownPanel title={"Stream"} data={{
src: player.currentSource().src,
duration: player.duration(),
type: player.currentSource().type,
isAudio: player.isAudio(),
videoWidth: player.videoWidth(),
videoHeight: player.videoHeight(),
poster: player.poster()
}
} />
)
}
return (
<div>
"Loading..."
</div>
)
}
}
PlayerStream.propTypes = {
player: PropTypes.object,
loadedmetadata: PropTypes.bool
};
PlayerStream.defaultProps = {
player: null,
loadedmetadata: false
}
|
JavaScript
| 0.000001 |
@@ -179,16 +179,129 @@
%7B%0A%0A
+shouldComponentUpdate(newProps,newState) %7B%0A return (newProps.loadedmetadata && newProps.player)%0A %7D%0A
render()
@@ -329,24 +329,8 @@
ayer
-, loadedmetadata
%7D =
@@ -353,30 +353,22 @@
if (
-loadedmetadata
+player
) %7B%0A
@@ -863,32 +863,30 @@
%7D%0A
-return (
+else %7B
%0A
@@ -890,61 +890,28 @@
-%3Cdiv%3E%0A %22Loading...%22%0A
+return (%3Cdiv%3E
%3C/div%3E
+)
%0A
@@ -911,25 +911,25 @@
v%3E)%0A
-)
+%7D
%0A %7D%0A%7D%0A%0APl
|
4abe722d783edd627a8c237811d6be3bdaf06488
|
add real description
|
gatsby-config.js
|
gatsby-config.js
|
module.exports = {
siteMetadata: {
title: 'Thibault Friedrich',
description: 'PROJECT_DESCRIPTION.',
author: 'Thibault Friedrich <[email protected]>',
},
plugins: [
'gatsby-plugin-react-helmet',
{
resolve: 'gatsby-source-filesystem',
options: {
name: 'images',
path: `${__dirname}/src/assets`,
},
},
'gatsby-transformer-sharp',
'gatsby-plugin-sharp',
{
resolve: 'gatsby-plugin-manifest',
options: {
name: 'gatsby-starter-default',
short_name: 'starter',
start_url: '/',
background_color: '#663399',
theme_color: '#663399',
display: 'minimal-ui',
icon: 'src/assets/gatsby-icon.png', // This path is relative to the root of the site.
},
},
{
resolve: `gatsby-plugin-sass`,
options: {
// Override the file regex for SASS
sassRuleTest: /\.style.global\.s(a|c)ss$/,
// Override the file regex for CSS modules
sassRuleModulesTest: /\.style\.s(a|c)ss$/,
},
},
'gatsby-plugin-resolve-src',
'gatsby-plugin-react-svg',
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
{
resolve: `gatsby-plugin-google-analytics`,
options: {
// The property ID; the tracking code won't be generated without it
trackingId: 'UA-105183271-1',
// Defines where to place the tracking script - `true` in the head and `false` in the body
head: false,
// Setting this parameter is optional
anonymize: true,
// Setting this parameter is also optional
respectDNT: true,
// Avoids sending pageview hits from custom paths
exclude: ['/preview/**', '/do-not-track/me/too/'],
// Delays sending pageview hits on route update (in milliseconds)
pageTransitionDelay: 0,
// Enables Google Optimize using your container Id
// optimizeId: 'YOUR_GOOGLE_OPTIMIZE_TRACKING_ID',
// // Enables Google Optimize Experiment ID
// experimentId: 'YOUR_GOOGLE_EXPERIMENT_ID',
// // Set Variation ID. 0 for original 1,2,3....
// variationId: 'YOUR_GOOGLE_OPTIMIZE_VARIATION_ID',
// Any additional optional fields
sampleRate: 5,
siteSpeedSampleRate: 10,
cookieDomain: 'thibaultfriedrich.io',
},
},
],
}
|
JavaScript
| 0.000508 |
@@ -85,27 +85,57 @@
n: '
-PROJECT_DESCRIPTION
+My portfolio to show you my projects, my missions
.',%0A
|
2647c886bbff161544e8a825d828e94a865ff5cd
|
Remove st-required class from quote block citations
|
src/blocks/quote.js
|
src/blocks/quote.js
|
"use strict";
/*
Block Quote
*/
var _ = require('../lodash');
var Block = require('../block');
var stToHTML = require('../to-html');
var ScribeHeadingPlugin = require('./scribe-plugins/scribe-heading-plugin');
var ScribeQuotePlugin = require('./scribe-plugins/scribe-quote-plugin');
var template = _.template([
'<blockquote class="st-required st-text-block st-text-block--quote" contenteditable="true"></blockquote>',
'<label class="st-input-label"> <%= i18n.t("blocks:quote:credit_field") %></label>',
'<input maxlength="140" name="cite" placeholder="<%= i18n.t("blocks:quote:credit_field") %>"',
' class="st-input-string st-required js-cite-input" type="text" />'
].join("\n"));
module.exports = Block.extend({
type: "quote",
title: function() { return i18n.t('blocks:quote:title'); },
icon_name: 'quote',
textable: true,
toolbarEnabled: false,
editorHTML: function() {
return template(this);
},
configureScribe: function(scribe) {
scribe.use(new ScribeHeadingPlugin(this));
scribe.use(new ScribeQuotePlugin(this));
},
loadData: function(data){
if (this.options.convertFromMarkdown && data.format !== "html") {
this.setTextBlockHTML(stToHTML(data.text, this.type));
} else {
this.setTextBlockHTML(data.text);
}
if (data.cite) {
this.$('.js-cite-input')[0].value = data.cite;
}
}
});
|
JavaScript
| 0 |
@@ -630,28 +630,16 @@
-string
-st-required
js-cite-
|
0ec8469c017bbaa51f03fba7a3053a1dc17d1b2c
|
Simplify color method to arrow function
|
kitsune/kpi/static/kpi/js/components/Chart.es6.js
|
kitsune/kpi/static/kpi/js/components/Chart.es6.js
|
/* globals d3:false, $:false, _:false */
/* jshint esnext: true */
export default class Chart {
constructor($container, options) {
let defaults = {
chartColors: ['#EE2820', '#F25743', '#F58667', '#F9B58B', '#FDE4AF', '#E3F1B6', '#AADA9F', '#72C489', '#39AD72', '#00975C'],
axes: {
xAxis: {
labels: [],
labelOffsets: { x: 15, y: 23 }
},
yAxis: {
labels: [],
labelOffsets: { x: 5, y: 23 }
},
getPosition: (position, axis, index) => {
let gridSize = (position === 'y') ? this.gridSize/2 : this.gridSize;
if (position === axis[0]) {
return index * gridSize;
} else {
return -gridSize;
}
}
},
margin: { top: 40, right: 0, bottom: 20, left: 75 },
width: 860,
height: 430,
grid: { rows: 12, columns: 12 },
gridSize: 71,
buckets: 10,
legendElementWidth: 95,
data: [],
dom: {
graphContainer: $container.find('.graph').get()[0]
}
};
$.extend(true, this, defaults, options);
this.init();
}
// Render whatever pieces of the chart we can while waiting for data
preRender() {
// draw the container svg for the chart
this.dom.svg = d3.select(this.dom.graphContainer).append('svg')
.attr('width', this.width + this.margin.left + this.margin.right)
.attr('height', this.height + this.margin.top + this.margin.bottom)
.append('g')
.attr('transform', `translate(${this.margin.left}, ${this.margin.top})`);
this.dom.svg.append('g')
.attr('class', 'data');
this.setupAxis('xAxis');
this.setupLegend();
}
setupAxis(axis) {
let axisGroup = this.dom.svg.append('g')
.attr('class', axis);
axisGroup.selectAll()
.data(this.axes[axis].labels)
.enter().append('text')
.text((d,i) => d)
.attr('x', (d, i) => {
return this.axes.getPosition('x', axis, i) + this.axes[axis].labelOffsets.x;
})
.attr('y', (d, i) => {
return this.axes.getPosition('y', axis, i) + this.axes[axis].labelOffsets.y;
})
}
setupLegend() {
let legendData = this.chartColors;
let legendYPosition = (this.grid.rows * this.gridSize/2);
let legendXPositions = i => (this.legendElementWidth * i) - this.gridSize;
let legend = this.dom.svg.append('g')
.attr('class', 'legend');
legend.selectAll('rect')
.data(legendData, function(d) { return d; })
.enter().append('rect')
.attr('x', (d, i) => legendXPositions(i))
.attr('y', legendYPosition)
.attr('width', this.legendElementWidth)
.attr('height', this.gridSize / 3.6)
.style('fill', (d, i) => this.chartColors[i]);
legend.selectAll('text')
.data(legendData, function(d) { return d; })
.enter().append('text')
.text((d, i) => `≥${Math.round(i / this.buckets * 100)}%`)
.attr('x', (d, i) => legendXPositions(i) + 7)
.attr('y', legendYPosition + 14);
}
init() {
this.preRender();
}
setupGrid(filteredData, filter) {
let kindFilter = filter;
this.dom.cohorts = this.dom.svg.select('.data').selectAll('g')
.data(filteredData);
this.dom.cohorts.enter().append('g');
this.dom.cohorts
.attr('width', this.width)
.attr('height', this.gridSize/2)
.attr('x', 0)
.attr('y', (d, i) => i * this.gridSize / 2)
.attr('class', `cohort-group ${kindFilter}`);
this.dom.cohorts.exit().remove();
}
populateData(filter) {
let self = this;
let kindFilter = filter;
let filteredData = _.filter(self.data, function(datum, index) {
return datum.kind === kindFilter;
});
self.setupGrid(filteredData, kindFilter);
self.dom.cohorts.each(function(cohort, i) {
let cohortGroupNumber = i;
let cohortOriginalSize = cohort.size;
let coloredBoxes = d3.select(this).selectAll('rect')
.data(cohort.retention_metrics);
coloredBoxes.enter().append('rect');
coloredBoxes
.attr('class', 'retention-week')
.attr('height', self.gridSize/2)
.attr('width', self.gridSize)
.attr('x', (d, i) => i * self.gridSize)
.attr('y', (d, i) => cohortGroupNumber * self.gridSize/2)
.style('fill', function(d) {
return self.colorScale(Math.floor((d.size / cohortOriginalSize) * 100) || 0);
})
.style('stroke', '#000')
.style('stroke-opacity', 0.05)
.style('stroke-width', 1);
coloredBoxes.exit().remove();
let sizeText = d3.select(this).selectAll('text')
.data(cohort.retention_metrics)
sizeText.enter().append('text');
sizeText
.text(function(d, i) {
let percentage = Math.floor((d.size / cohortOriginalSize) * 100) || 0;
return `${d.size} (${percentage}%)`;
})
.attr('x', (d, i) => i * self.gridSize + 10)
.attr('y', (d, i) => (cohortGroupNumber * self.gridSize/2) + 23);
sizeText.exit().remove();
});
}
}
|
JavaScript
| 0.000113 |
@@ -4364,27 +4364,22 @@
'fill',
-function
(d)
+ =%3E
%7B%0A
|
1f4b2607cca815ffb72f3e6e37af06202c6facc2
|
Replace flatMap method with reduce and map
|
bin/test_api.js
|
bin/test_api.js
|
/**
* Copyright (c) 2019 The xterm.js authors. All rights reserved.
* @license MIT
*/
const cp = require('child_process');
const path = require('path');
// Add `out` to the NODE_PATH so absolute paths can be resolved.
const env = { ...process.env };
env.NODE_PATH = path.resolve(__dirname, '../out');
let testFiles = [
'./addons/**/out/*api.js',
'./out-test/**/*api.js',
];
let flagArgs = [];
if (process.argv.length > 2) {
const args = process.argv.slice(2);
flagArgs = args.filter(e => e.startsWith('--')).flatMap(arg => arg.split('='));
console.info(flagArgs);
// ability to inject particular test files via
// yarn test [testFileA testFileB ...]
files = args.filter(e => !e.startsWith('--'));
if (files.length) {
testFiles = files;
}
}
env.DEBUG = flagArgs.indexOf('--debug') >= 0 ? 'debug' : '';
const run = cp.spawnSync(
npmBinScript('mocha'),
[...testFiles, ...flagArgs],
{
cwd: path.resolve(__dirname, '..'),
env,
stdio: 'inherit'
}
);
function npmBinScript(script) {
return path.resolve(__dirname, `../node_modules/.bin/` + (process.platform === 'win32' ? `${script}.cmd` : script));
}
process.exit(run.status);
|
JavaScript
| 0.000001 |
@@ -523,13 +523,9 @@
')).
-flatM
+m
ap(a
@@ -545,16 +545,63 @@
it('='))
+.reduce((arr, val) =%3E arr.concat(%5B...val%5D, %5B%5D))
;%0A cons
|
1bbc1d44628b15771fbbd0627a8a9180e2394234
|
update schema
|
schema.js
|
schema.js
|
(function() {'use strict';})();
// model dependencies and connection instance
var Sequelize = require('sequelize'),
uri = "postgres://postgres:ALMIGHTY@localhost/ubuntu",
db = new Sequelize(uri);
// define the model for users
var User = db.define("User", {
firstName: {
type: Sequelize.STRING,
allowNull: false,
validate:{
isAlpha: true
}
},
lastName: {
type: Sequelize.STRING,
allowNull: false,
validate:{
isAlpha: true
}
},
role: {
type: Sequelize.STRING,
allowNull: false,
}
}),
// define the model for roles
Role = db.define("Role", {
title: {
type: Sequelize.STRING,
allowNull: false,
primaryKey : true,
unique: true
}
}),
// define the model for document
Document = db.define("Document", {
docTitle : {
type: Sequelize.TEXT,
allowNull : false
},
datePublished: {
type: Sequelize.STRING,
allowNull: false,
validate:{
isDate: true
}
},
AccessTo: {
type: Sequelize.STRING,
allowNull:false
}
});
// each user has a role with a foreignKey set as 'role'
User.belongsTo(Role, {
foreignKey: 'role',
targetKey: 'title'
});
// each document is accessible to a particular role
Document.belongsTo(Role, {
foreignKey: 'AccessTo',
targetKey: 'title'
});
// synchronize database with the model
db.sync().then();
/**
* [schema exports]
* @type {[type]}
*/
exports.User = User;
exports.Role = Role;
exports.Document = Document;
|
JavaScript
| 0.000001 |
@@ -257,20 +257,16 @@
ser%22, %7B%0A
-
%0A f
|
7fd30719a70ce123d3e1ef5e3db18b107ad79ee5
|
Add file API check
|
Kinect2Scratch.js
|
Kinect2Scratch.js
|
(function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
['r', '%m.k', 'k', 'heady']
],
menus: {
k: ['headx', 'heady']
}
};
ext.my_first_block = function() {
console.log("hello, world.");
};
ext.power = function(base, exponent) {
return Math.pow(base, exponent);
};
ext.k = function(m) {
switch(m){
case 'headx': return 1;
case 'heady': return 2;
}
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({});
|
JavaScript
| 0.000001 |
@@ -255,41 +255,304 @@
-return %7Bstatus: 2, msg: 'Ready'%7D;
+// Check for the various File API support.%0A if (window.File && window.FileReader && window.FileList && window.Blob) %7B%0A return %7Bstatus: 2, msg: 'Ready'%7D; %0A %7D else %7B%0A return %7Bstatus: 1, msg: 'The File APIs are not fully supported by your browser.'%7D;%0A %7D
%0A
|
5749e2e6620766929dd02fb79038ff1867e9b682
|
fix linter errors
|
src/components/dropdown/dropdown.spec.js
|
src/components/dropdown/dropdown.spec.js
|
import { loadFixture, testVM } from '../../../tests/utils'
describe('dropdown', async () => {
beforeEach(loadFixture(__dirname, 'dropdown'))
testVM()
it('should work', async () => {
const { app: { $refs } } = window
const dds = Object.keys($refs).map(ref => $refs[ref])
dds.forEach(dd => {
expect(dd._isVue).toBe(true)
expect(dd).toHaveClass('dropdown')
})
})
it('should work with shorthand component tag names', async () => {
const { app: { $refs } } = window
const { dd_5 } = $refs
expect(dd_5).toBeComponent('b-dd')
})
/*
// This test complains somewhat due to mising Range functions in JSDOM
// Commenting out for now
it("should open only one dropdown at a time", async () => {
const { app: { $refs } } = window;
const dds = Object.keys($refs).map(ref => $refs[ref]);
// Without async iterators, just use a for loop.
for (let i = 0; i < dds.length; i++) {
Array.from(dds[i].$el.children)
.find(node => node.tagName === "BUTTON" && node.id === `${dds[i].safeId('_BV_toggle_')}`)
.click();
// Await the next render after click triggers dropdown.
await nextTick();
const openDds = dds.filter(dd => dd.$el.classList.contains("show"));
expect(openDds.length).toBe(1);
}
});
*/
it('should not have a toggle caret when no-caret is true', async () => {
const { app: { $refs } } = window
const { dd_7 } = $refs
const toggle = Array.from(dd_7.$el.children)
.find(node => node.tagName === 'BUTTON' && node.id === `${dd_7.safeId('_BV_toggle_')}`)
expect(toggle).not.toHaveClass('dropdown-toggle')
})
it('should have a toggle caret when no-caret and split are true', async () => {
const { app: { $refs } } = window
const { dd_8 } = $refs
const toggle = Array.from(dd_8.$el.children)
.find(node => node.tagName === 'BUTTON' && node.id === `${dd_8.safeId('_BV_toggle_')}`)
expect(toggle).toHaveClass('dropdown-toggle')
})
/*
it('boundary set to viewport should have class position-static', async () => {
const {app: {$refs}} = window
const {dd_9} = $refs
expect(dd_9).toHaveClass('position-static')
})
it('boundary not set should not have class position-static', async () => {
const {app: {$refs}} = window
const {dd_1} = $refs
expect(dd_1).not.toHaveClass('position-static')
})
*/
it('dd-item should render as link by default', async () => {
const {app: {$refs}} = window
const {dd_6} = $refs
expect(Array.from(dd_6.$refs.menu.children).find(node => node.innerHTML === 'link')).toBeElement('a')
})
it('dd-item-button should render as button', async () => {
const {app: {$refs}} = window
const {dd_6} = $refs
expect(Array.from(dd_6.$refs.menu.children).find(node => node.innerHTML === 'button')).toBeElement('button')
})
it('dd-item-button should emit click event', async () => {
const {app: {$refs}} = window
const {dd_6} = $refs
const spy = jest.fn()
dd_6.$parent.$root.$on('clicked::link', spy)
const buttonItem = Array.from(dd_6.$refs.menu.children).find(node => node.innerHTML === 'button')
buttonItem.click()
expect(spy).toHaveBeenCalled()
})
it('dd-divider should render', async () => {
const {app: {$refs}} = window
const {dd_6} = $refs
expect(Array.from(dd_6.$refs.menu.children).filter(node => node.classList.contains('dropdown-divider')).length).toBe(1)
})
})
|
JavaScript
| 0.000011 |
@@ -518,33 +518,66 @@
%7B dd_5 %7D = $refs
+ // eslint-disable-line camelcase
%0A
-
%0A expect(dd_5
@@ -1543,32 +1543,65 @@
%7B dd_7 %7D = $refs
+ // eslint-disable-line camelcase
%0A%0A const togg
@@ -1927,32 +1927,65 @@
%7B dd_8 %7D = $refs
+ // eslint-disable-line camelcase
%0A%0A const togg
@@ -2680,32 +2680,65 @@
t %7Bdd_6%7D = $refs
+ // eslint-disable-line camelcase
%0A%0A expect(Arr
@@ -2946,32 +2946,65 @@
t %7Bdd_6%7D = $refs
+ // eslint-disable-line camelcase
%0A%0A expect(Arr
@@ -3223,24 +3223,57 @@
d_6%7D = $refs
+ // eslint-disable-line camelcase
%0A%0A const
@@ -3579,32 +3579,32 @@
refs%7D%7D = window%0A
-
const %7Bdd_6%7D
@@ -3603,32 +3603,65 @@
t %7Bdd_6%7D = $refs
+ // eslint-disable-line camelcase
%0A%0A expect(Arr
|
dfad7ad6785566bc9ceae50d706ef1f3108d5927
|
update booking order
|
src/garment-master-plan/booking-order-validator.js
|
src/garment-master-plan/booking-order-validator.js
|
require("should");
var validatorItems = require('./booking-order-item-validator');
module.exports = function (data) {
data.should.not.equal(null);
data.should.instanceOf(Object);
data.should.have.property('code');
data.code.should.be.String();
data.should.have.property('bookingDate');
data.bookingDate.should.instanceof(Date);
data.should.have.property('deliveryDate');
data.deliveryDate.should.instanceof(Date);
data.should.have.property('garmentBuyerId');
data.garmentBuyerId.should.instanceOf(Object);
data.should.have.property('garmentBuyerName');
data.garmentBuyerName.should.be.String();
data.should.have.property('garmentBuyerCode');
data.garmentBuyerCode.should.be.String();
data.should.have.property('remark');
data.remark.should.be.String();
data.should.have.property('isMasterPlan');
data.isMasterPlan.should.instanceOf(Boolean);
data.should.have.property('isCanceled');
data.isCanceled.should.instanceOf(Boolean);
data.should.have.property('items');
data.items.should.instanceOf(Array);
for (var item of data.items) {
validatorItems(item);
}
};
|
JavaScript
| 0 |
@@ -1027,32 +1027,34 @@
(Boolean);%0A%0A
+//
data.should.have
@@ -1069,24 +1069,48 @@
y('items');%0A
+ if(data.items)%7B%0A
data.ite
@@ -1138,20 +1138,25 @@
Array);%0A
+%0A
+
for (var
@@ -1186,16 +1186,20 @@
+
+
validato
@@ -1212,16 +1212,26 @@
(item);%0A
+ %7D%0A
%7D%0A%7D;
|
07aaf7df4bd3ce607dc5209dd888385f77b96b92
|
refactor app playbook command
|
scripts/setup-apps.js
|
scripts/setup-apps.js
|
var sarah_root = '/etc/SARAH/',
app_root = 'www/apps/',
// app_root_exist = ,
sh = require('execSync'), // executing system commands
clc = require('cli-color'), // colours in the console
fs = require('fs'), // for file streams
fs_filename = "registered.php",
DB_CONFIG = JSON.parse(fs.readFileSync(sarah_root + 'config.json', 'utf8'));
function compileSassFolder (folderPath) {
console.log (folderPath);
fs.readdir (folderPath, function (error, files) {
files.forEach (function (file) {
if (file.toLowerCase().indexOf(".scss") >= 0) {
console.log ("SASSing " + folderPath + file);
console.log (sh.exec ("cd " + folderPath + " && " + "sass " + file + " " + file.split('.scss')[0] + ".css").stdout);
}
});
});
}
console.log (clc.whiteBright.bgGreen("Updating root SARAH framework repo"));
console.log (sh.exec ("cd " + sarah_root + " && git pull").stdout);
// load inital sql
console.log (sh.exec ("mysql -u " + DB_CONFIG.DB_USER + " --password=" + DB_CONFIG.DB_PASS + " " + " < " + sarah_root + "/init.sql").stdout);
console.log ("Reading package.json");
var packagejson = require (sarah_root + 'package.json'),
numberOfApps = packagejson.apps.length;
var registeredPhpOutput = "<?php " +
"$registered_apps = array ();";
// create apps folder if needed
var result = sh.exec ("mkdir " + sarah_root + app_root);
console.log (result.stdout);
for (var i = 0; i <= numberOfApps - 1; i++) {
// load package name
console.log ();
console.log (clc.whiteBright.bgGreen(" Loading " + packagejson.apps[i].name + " "));
var appName = packagejson.apps[i].name,
gitPath = packagejson.apps[i].git,
appPath = packagejson.apps[i].path;
// if the responce back from git clone contains "already exists" try doing a git pull
var cmd = "cd " + sarah_root + app_root + " && " + "git clone " + gitPath;
console.log ("> " + cmd)
var clone = sh.exec (cmd).stdout
if (clone.indexOf ("already exists") >= 0) {
var cmd = "cd " + sarah_root + app_root + appPath + " && " + "git pull";
console.log ("> " + cmd);
console.log (sh.exec (cmd).stdout);
}
// compile SASS
compileSassFolder (sarah_root + app_root + appPath + "/css/");
// load inital sql
console.log (sh.exec ("mysql -u " + DB_CONFIG.DB_USER + " --password=" + DB_CONFIG.DB_PASS + " " + DB_CONFIG.DB_NAME + " < " + sarah_root + app_root + appPath + "/init.sql").stdout);
// compile updaters
console.log (sh.exec ("cd " + sarah_root + app_root + appPath + "/updater && bash compile.sh").stdout);
// configure system for app
console.log (sh.exec ("cd " + sarah_root + app_root + appPath + " && ansible-playbook -i \"localhost,\" playbook.yml").stdout);
// update buffered output of registered.php
registeredPhpOutput += "$registered_apps[] = '" + appPath + "';";
}
// write registered.php
fs.writeFile(sarah_root + app_root + fs_filename, registeredPhpOutput, function(err) {
if(err) {
console.log(err);
} else {
console.log(fs_filename + " updated");
}
});
// compile SASS
compileSassFolder (sarah_root + "www/css/");
|
JavaScript
| 0.000005 |
@@ -2592,34 +2592,66 @@
.log (sh.exec (%22
-cd
+ansible-playbook -i %5C%22localhost,%5C%22
%22 + sarah_root
@@ -2678,47 +2678,9 @@
+ %22
- && ansible-playbook -i %5C%22localhost,%5C%22
+/
play
|
7fb0032f9d92a91bf3bdccd334584ac50b275637
|
Set crossorigin on font preload
|
gatsby-config.js
|
gatsby-config.js
|
module.exports = {
siteMetadata: {
title: "Jesse B. Hannah",
},
plugins: [
"gatsby-plugin-emotion",
{
resolve: "gatsby-plugin-html-attributes",
options: {
lang: "en",
},
},
"gatsby-plugin-react-helmet",
{
resolve: "gatsby-plugin-typography",
options: {
pathToConfigModule: "src/utils/typography.js",
},
},
{
resolve: "gatsby-source-filesystem",
options: {
name: "pages",
path: `${__dirname}/src/pages`,
},
},
{
resolve: "gatsby-source-filesystem",
options: {
name: "articles",
path: `${__dirname}/src/articles`,
},
},
{
resolve: "gatsby-transformer-remark",
options: {
plugins: [
"gatsby-remark-numbered-footnotes",
{
resolve: "gatsby-remark-prismjs",
options: { inlineCodeMarker: "›" },
},
],
},
},
{
resolve: "gatsby-plugin-netlify",
options: {
allPageHeaders: [
"Link: </static/hack-regular-subset.woff>; rel=preload; as=font; type=font/woff",
"Link: </static/hack-regular-subset.woff2>; rel=preload; as=font; type=font/woff2",
"Link: </static/lora-latin-400.woff>; rel=preload; as=font; type=font/woff",
"Link: </static/lora-latin-400.woff2>; rel=preload; as=font; type=font/woff2",
"Link: </static/lora-latin-400italic.woff>; rel=preload; as=font; type=font/woff",
"Link: </static/lora-latin-400italic.woff2>; rel=preload; as=font; type=font/woff2",
"Link: </static/lora-latin-700.woff>; rel=preload; as=font; type=font/woff",
"Link: </static/lora-latin-700.woff2>; rel=preload; as=font; type=font/woff2",
"Link: </static/lora-latin-700italic.woff>; rel=preload; as=font; type=font/woff",
"Link: </static/lora-latin-700italic.woff2>; rel=preload; as=font; type=font/woff2",
"Link: </static/varela-round-latin-400.woff>; rel=preload; as=font; type=font/woff",
"Link: </static/varela-round-latin-400.woff2>; rel=preload; as=font; type=font/woff2",
],
},
},
],
}
|
JavaScript
| 0 |
@@ -1129,32 +1129,45 @@
; type=font/woff
+; crossorigin
%22,%0A %22Li
@@ -1236,32 +1236,45 @@
type=font/woff2
+; crossorigin
%22,%0A %22Li
@@ -1336,32 +1336,45 @@
; type=font/woff
+; crossorigin
%22,%0A %22Li
@@ -1438,32 +1438,45 @@
type=font/woff2
+; crossorigin
%22,%0A %22Li
@@ -1544,32 +1544,45 @@
; type=font/woff
+; crossorigin
%22,%0A %22Li
@@ -1652,32 +1652,45 @@
type=font/woff2
+; crossorigin
%22,%0A %22Li
@@ -1752,32 +1752,45 @@
; type=font/woff
+; crossorigin
%22,%0A %22Li
@@ -1854,32 +1854,45 @@
type=font/woff2
+; crossorigin
%22,%0A %22Li
@@ -1960,32 +1960,45 @@
; type=font/woff
+; crossorigin
%22,%0A %22Li
@@ -2068,32 +2068,45 @@
type=font/woff2
+; crossorigin
%22,%0A %22Li
@@ -2184,16 +2184,29 @@
ont/woff
+; crossorigin
%22,%0A
@@ -2294,16 +2294,29 @@
nt/woff2
+; crossorigin
%22,%0A
|
8988852eb8bbd57cc52aa40ec19f02c41fd11367
|
correct maths in updated portal weakness - oops
|
plugins/show-portal-weakness.user.js
|
plugins/show-portal-weakness.user.js
|
// ==UserScript==
// @id iitc-plugin-show-portal-weakness@vita10gy
// @name IITC plugin: show portal weakness
// @category Highlighter
// @version 0.7.2.@@DATETIMEVERSION@@
// @namespace https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL @@UPDATEURL@@
// @downloadURL @@DOWNLOADURL@@
// @description [@@BUILDNAME@@-@@BUILDDATE@@] Uses the fill color of the portals to denote if the portal is weak (Needs recharging, missing a resonator, needs mods) Red, needs energy and mods. Orange, only needs energy (either recharge or resonators). Yellow, only needs mods.
// @include https://www.ingress.com/intel*
// @include http://www.ingress.com/intel*
// @match https://www.ingress.com/intel*
// @match http://www.ingress.com/intel*
// @grant none
// ==/UserScript==
@@PLUGINSTART@@
// PLUGIN START ////////////////////////////////////////////////////////
// use own namespace for plugin
window.plugin.portalWeakness = function() {};
window.plugin.portalWeakness.highlightWeakness = function(data) {
if(data.portal.options.team != TEAM_NONE) {
var res_count = data.portal.options.data.resCount;
var portal_health = data.portal.options.data.health/100;
var weakness = (res_count/8) * (portal_health/100);
if(weakness < 1) {
var fill_opacity = weakness*.85 + .15;
var color = 'red';
fill_opacity = Math.round(fill_opacity*100)/100;
var params = {fillColor: color, fillOpacity: fill_opacity};
// Hole per missing resonator
if (res_count < 8) {
var dash = new Array((8 - res_count) + 1).join("1,4,") + "100,0"
params.dashArray = dash;
}
data.portal.setStyle(params);
}
}
}
var setup = function() {
window.addPortalHighlighter('Portal Weakness', window.plugin.portalWeakness.highlightWeakness);
}
// PLUGIN END //////////////////////////////////////////////////////////
@@PLUGINEND@@
|
JavaScript
| 0 |
@@ -1264,20 +1264,16 @@
a.health
-/100
;%0A%0A v
@@ -1275,24 +1275,24 @@
var
-weakness
+strength
= (res_
@@ -1334,24 +1334,24 @@
%0A if(
-weakness
+strength
%3C 1) %7B%0A
@@ -1375,24 +1375,28 @@
acity =
-weakness
+(1-strength)
*.85 + .
@@ -1428,63 +1428,8 @@
d';%0A
- fill_opacity = Math.round(fill_opacity*100)/100;%0A
|
d0f08c672d21e236e928bb9e5404046486102802
|
Remove comment
|
src/browser/user.js
|
src/browser/user.js
|
const Events = require('events');
// User won't notice lower intervals than these
const MAX_READ_INTERVAL = 250; // msecs
module.exports = () => {
const user = {events: new Events()};
const triggerReadIfNeeded = (() => {
let lastRead;
return () => {
const now = Date.now();
if (!lastRead || now > lastRead + MAX_READ_INTERVAL) {
user.events.emit('read');
lastRead = now;
}
};
})();
(function _userViewTimer() {
// requestAnimationFrame() consumes less CPU than d3.timer()
requestAnimationFrame(_userViewTimer);
user.events.emit('view');
triggerReadIfNeeded();
}());
// requestanimationframe() is not always triggered when the tab is not
// active. Here we ensure it is called often enough
setInterval(triggerReadIfNeeded, MAX_READ_INTERVAL);
setInterval(() => user.events.emit('hear'), 250);
return user;
};
|
JavaScript
| 0 |
@@ -466,73 +466,8 @@
) %7B%0A
- // requestAnimationFrame() consumes less CPU than d3.timer()%0A
|
57ea947e8570f008a31ea2d16d78f18942e3942d
|
Remove JSDoc comment
|
lib/node_modules/@stdlib/blas/base/daxpy/lib/browser.js
|
lib/node_modules/@stdlib/blas/base/daxpy/lib/browser.js
|
'use strict';
/**
* Blas level 1 routine to multiply `x` and a constant and add the result to `y`.
*
* @module @stdlib/blas/base/daxpy
*
* @example
* var daxpy = require( '@stdlib/blas/base/daxpy' );
*
* var x = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] );
* var y = new Float64Array( [ 1.0, 1.0, 1.0, 1.0, 1.0 ] );
* var alpha = 5.0;
*
* daxpy( x.length, alpha, x, 1, y, 1 );
* // y => <Float64Array>[ 6.0, 11.0, 16.0, 21.0, 26.0 ]
*
*
* @example
* var daxpy = require( '@stdlib/blas/base/daxpy' );
*
* var x = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] );
* var y = new Float64Array( [ 1.0, 1.0, 1.0, 1.0, 1.0 ] );
* var alpha = 5.0;
*
* daxpy.ndarray( x.length, alpha, x, 1, 0, y, 1, 0 );
* // y => <Float64Array>[ 6.0, 11.0, 16.0, 21.0, 26.0 ]
*
* @example
* // Use the `wasm` interface:
* var wasm = require( '@stdlib/blas/base/daxpy' ).wasm;
*
* // Number of data elements:
* var N = 5;
*
* // Allocate space on the heap:
* var xbytes = wasm.malloc( N * 8 ); // 8 bytes per double
* var ybytes = wasm.malloc( N * 8 );
*
* // Create Float64Array views:
* var x = new Float64Array( xbytes.buffer, xbytes.byteOffset, N );
* var y = new Float64Array( ybytes.buffer, ybytes.byteOffset, N );
*
* // Copy data to the heap:
* x.set( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] );
* y.set( [ 1.0, 1.0, 1.0, 1.0, 1.0 ] );
*
* // Multiply and add:
* wasm( N, 5.0, xbytes, 1, ybytes, 1 );
*
* // Extract the results from the heap:
* var z = new Float64Array( N );
* var i;
* for ( i = 0; i < N; i++ ) {
* z[ i ] = y[ i ];
* }
* // z => <Float64Array>[ 6.0, 11.0, 16.0, 21.0, 26.0 ]
*
* // Free the memory:
* wasm.free( xbytes );
* wasm.free( ybytes );
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var daxpy = require( './main.js' );
var wasm = require( './wasm.js' );
// MAIN //
setReadOnly( daxpy, 'wasm', wasm );
// EXPORTS //
module.exports = daxpy;
|
JavaScript
| 0 |
@@ -12,1639 +12,8 @@
';%0A%0A
-/**%0A* Blas level 1 routine to multiply %60x%60 and a constant and add the result to %60y%60.%0A*%0A* @module @stdlib/blas/base/daxpy%0A*%0A* @example%0A* var daxpy = require( '@stdlib/blas/base/daxpy' );%0A*%0A* var x = new Float64Array( %5B 1.0, 2.0, 3.0, 4.0, 5.0 %5D );%0A* var y = new Float64Array( %5B 1.0, 1.0, 1.0, 1.0, 1.0 %5D );%0A* var alpha = 5.0;%0A*%0A* daxpy( x.length, alpha, x, 1, y, 1 );%0A* // y =%3E %3CFloat64Array%3E%5B 6.0, 11.0, 16.0, 21.0, 26.0 %5D%0A*%0A*%0A* @example%0A* var daxpy = require( '@stdlib/blas/base/daxpy' );%0A*%0A* var x = new Float64Array( %5B 1.0, 2.0, 3.0, 4.0, 5.0 %5D );%0A* var y = new Float64Array( %5B 1.0, 1.0, 1.0, 1.0, 1.0 %5D );%0A* var alpha = 5.0;%0A*%0A* daxpy.ndarray( x.length, alpha, x, 1, 0, y, 1, 0 );%0A* // y =%3E %3CFloat64Array%3E%5B 6.0, 11.0, 16.0, 21.0, 26.0 %5D%0A*%0A* @example%0A* // Use the %60wasm%60 interface:%0A* var wasm = require( '@stdlib/blas/base/daxpy' ).wasm;%0A*%0A* // Number of data elements:%0A* var N = 5;%0A*%0A* // Allocate space on the heap:%0A* var xbytes = wasm.malloc( N * 8 ); // 8 bytes per double%0A* var ybytes = wasm.malloc( N * 8 );%0A*%0A* // Create Float64Array views:%0A* var x = new Float64Array( xbytes.buffer, xbytes.byteOffset, N );%0A* var y = new Float64Array( ybytes.buffer, ybytes.byteOffset, N );%0A*%0A* // Copy data to the heap:%0A* x.set( %5B 1.0, 2.0, 3.0, 4.0, 5.0 %5D );%0A* y.set( %5B 1.0, 1.0, 1.0, 1.0, 1.0 %5D );%0A*%0A* // Multiply and add:%0A* wasm( N, 5.0, xbytes, 1, ybytes, 1 );%0A*%0A* // Extract the results from the heap:%0A* var z = new Float64Array( N );%0A* var i;%0A* for ( i = 0; i %3C N; i++ ) %7B%0A* z%5B i %5D = y%5B i %5D;%0A* %7D%0A* // z =%3E %3CFloat64Array%3E%5B 6.0, 11.0, 16.0, 21.0, 26.0 %5D%0A*%0A* // Free the memory:%0A* wasm.free( xbytes );%0A* wasm.free( ybytes );%0A*/%0A%0A
// M
|
2b70731a5717ec4f46f537820e220bf3d3d52df0
|
Update input_mqtt.js
|
plugins/inputs/mqtt/input_mqtt.js
|
plugins/inputs/mqtt/input_mqtt.js
|
var base_input = require('@pastash/pastash').base_input,
util = require('util'),
mqtt = require('mqtt'),
logger = require('@pastash/pastash').logger;
function InputMQTT() {
base_input.BaseInput.call(this);
this.mergeConfig(this.unserializer_config());
this.mergeConfig({
name: 'MQTT',
host_field: 'address',
optional_params: ['topic'],
start_hook: this.start,
});
}
util.inherits(InputMQTT, base_input.BaseInput);
InputMQTT.prototype.start = function(callback) {
if(!this.topic||!this.address) return;
logger.info('Connecting to MQTT Server', this.address);
this.socket = mqtt.connect(this.address);
this.socket.on('connect', function() {
logger.info('Connected to MQTT Server', this.address);
this.socket.subscribe(this.topic);
callback();
}.bind(this));
this.socket.on('message', function(topic, data) {
try {
var obj = JSON.parse(data.toString());
obj.topic = topic;
this.emit('data', obj);
} catch(e) {
this.emit('data', data.toString());
}
}.bind(this));
};
InputMQTT.prototype.close = function(callback) {
logger.info('Closing input MQTT', this.address);
try { this.socket.end() } catch(e) {}
callback();
};
exports.create = function() {
return new InputMQTT();
};
|
JavaScript
| 0.000012 |
@@ -351,16 +351,24 @@
%5B'topic'
+, 'json'
%5D,%0A s
@@ -882,17 +882,16 @@
a) %7B%0A
-
try %7B%0A
@@ -908,19 +908,38 @@
j =
-JSON.parse(
+%7B message: this.json ? data :
data
@@ -953,35 +953,24 @@
ng()
-);%0A obj.
+,
topic
- =
+:
topic
-;
+ %7D
%0A
@@ -1037,31 +1037,33 @@
'data',
-data.toString()
+%7B message: data %7D
);%0A %7D
|
df8c0db3ad3725be2812d9583a88e5da0b9263ba
|
Test pageSize query parameter with a non-numeric value ending in a number
|
src/app/test/api/queryController.tests.js
|
src/app/test/api/queryController.tests.js
|
// test/queryController.tests.js
var chai = require('chai'),
should = chai.should(),
express = require('express'),
app = express(),
sinon = require('sinon'),
sinonChai = require('sinon-chai'),
_ = require('underscore'),
request = require('supertest'),
proxyquire = require('proxyquire').noPreserveCache();
/* We must provide some dummy values here for the module: */
config = require ('../../config');
config.eventStorePassword = '123';
config.eventStoreUser = 'admin';
config.eventStoreBaseUrl = 'http://nothing:7887';
chai.use(sinonChai);
chai.config.includeStack = true;
var eventStoreClient = {
streams: {
get: sinon.stub()
}
};
var controller = proxyquire('../../api/queryController', {
'./helpers/eventStoreClient': eventStoreClient
});
controller.init(app);
describe('queryController', function() {
var defaultPageSize = 5;
describe('when I issue a workitem query for an asset that has no associated commits', function() {
var mockData = {
body: '',
statusCode: '404'
};
beforeEach(function() {
eventStoreClient.streams.get = sinon.stub();
eventStoreClient.streams.get.callsArgWith(1, null, mockData);
});
it('returns a 200 OK response with an empty commits array', function(done) {
//exercise our api
request(app)
.get('/api/query?workitem=123&pageSize=5')
.end(function(err, res) {
should.not.exist(err);
res.statusCode.should.equal(200);
res.body.commits.should.deep.equal([]);
done();
});
});
});
describe('when I issue a query without a workitem as a parameter', function() {
it('returns a 400 Bad Request response with a error message', function(done) {
request(app)
.get('/api/query')
.end(function(err, res) {
should.not.exist(err);
res.statusCode.should.equal(400);
res.body.error.should.equal('Parameter workitem is required');
done();
});
});
});
describe('when I issue a query with a workitem=all as a parameter for default pageSize', function() {
var mockData = {
body: '{ "entries": [] }'
};
beforeEach(function() {
eventStoreClient.streams.get = sinon.stub();
eventStoreClient.streams.get.callsArgWith(1, null, mockData);
});
it('calls eventstore-client.streams.get asking for the github-events stream and pageSize of 5', function(done) {
request(app)
.get('/api/query?workitem=all')
.end(function(err, res) {
eventStoreClient.streams.get.should.have.been.calledWith({
name: 'github-events',
count: 5
}, sinon.match.any);
done();
});
});
});
describe('when I issue a query for an asset for default pageSize', function() {
var assetId = 'S-83940';
beforeEach(function() {
eventStoreClient.streams.get = sinon.stub();
eventStoreClient.streams.get.callsArgWith(1, null, {});
});
it('calls eventstore-client.streams.get asking for a asset-' + assetId + ' stream and pageSize of 5', function(done) {
request(app)
.get('/api/query?workitem=' + assetId)
.end(function(err, res) {
eventStoreClient.streams.get.should.have.been.calledWith({
name: 'asset-' + assetId,
count: 5
}, sinon.match.any);
done();
});
});
});
describe('when I issue a query for an asset for non-default pageSize', function() {
var assetId = 'S-83940';
beforeEach(function() {
eventStoreClient.streams.get = sinon.stub();
eventStoreClient.streams.get.callsArgWith(1, null, {});
});
it('of 10, it calls eventstore-client.streams.get asking for a asset-' + assetId + ' stream and pageSize of 10', function(done) {
var pageSize=10;
request(app)
.get('/api/query?workitem=' + assetId + '&pageSize=' + pageSize)
.end(function(err, res) {
eventStoreClient.streams.get.should.have.been.calledWith({
name: 'asset-' + assetId,
count: 10
}, sinon.match.any);
done();
});
});
describe('giving a non-numeric value', function() {
beforeEach(function() {
eventStoreClient.streams.get = sinon.stub();
eventStoreClient.streams.get.callsArgWith(1, null, {});
});
var nonNumericValue = '12ForYou';
it('it uses the default pageSize of ' + defaultPageSize + ' when passing the request to the event store client', function(done) {
request(app)
.get('/api/query?workitem=' + assetId + '&pageSize=' + nonNumericValue)
.end(function(err, res) {
eventStoreClient.streams.get.should.have.been.calledWith({
name: 'asset-' + assetId,
count: defaultPageSize
}, sinon.match.any);
done();
});
});
});
});
});
|
JavaScript
| 0.000006 |
@@ -4430,16 +4430,35 @@
ricValue
+StartingWithNumbers
= '12Fo
@@ -4474,16 +4474,61 @@
it(
+'of ' + nonNumericValueStartingWithNumbers +
'it uses
@@ -4747,16 +4747,655 @@
ricValue
+StartingWithNumbers)%0A .end(function(err, res) %7B%0A eventStoreClient.streams.get.should.have.been.calledWith(%7B%0A name: 'asset-' + assetId,%0A count: defaultPageSize%0A %7D, sinon.match.any);%0A%0A done();%0A %7D);%0A %7D);%0A%0A var nonNumericValueEndingWithNumbers = 'ForYou12';%0A%0A it('of ' + nonNumericValueEndingWithNumbers + 'it uses the default pageSize of ' + defaultPageSize + ' when passing the request to the event store client', function(done) %7B%0A request(app)%0A .get('/api/query?workitem=' + assetId + '&pageSize=' + nonNumericValueEndingWithNumbers
)%0A
|
c6c41a5d0354b41c7b8e23bdbf17fd8b14004b3b
|
Tidy up comments a bit.
|
jquery.example.js
|
jquery.example.js
|
/*
* jQuery Form Example Plugin 1.4.1
* Populate form inputs with example text that disappears on focus.
*
* e.g.
* $('input#name').example('Bob Smith');
* $('input[@title]').example(function() {
* return $(this).attr('title');
* });
* $('textarea#message').example('Type your message here', {
* className: 'example_text'
* });
*
* Copyright (c) Paul Mucur (http://mucur.name), 2007-2008.
* Dual-licensed under the BSD (BSD-LICENSE.txt) and GPL (GPL-LICENSE.txt)
* licenses.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
(function($) {
$.fn.example = function(text, args) {
/* Only calculate once whether a callback has been used. */
var isCallback = $.isFunction(text);
/* Merge the default options with the given arguments and the given
* text with the text option.
*/
var options = $.extend({}, args, {example: text});
return this.each(function() {
/* Reduce method calls by saving the current jQuery object. */
var $this = $(this);
if ($.metadata) {
/* If the Metadata plugin is being used merge in the options. */
var o = $.extend({}, $.fn.example.defaults, $this.metadata(), options);
} else {
var o = $.extend({}, $.fn.example.defaults, options);
}
/* The following event handlers only need to be bound once
* per class name. In order to do this, an array of used
* class names is stored and checked on each use of the plugin.
* If the class name is in the array then this whole section
* is skipped. If not, the events are bound and the class name
* added to the array.
*
* As of 1.3.2, the class names are stored as keys in the
* array, rather than as elements. This removes the need for
* $.inArray().
*/
if (!$.fn.example.boundClassNames[o.className]) {
/* Because Gecko-based browsers cache form values
* but ignore all other attributes such as class, all example
* values must be cleared on page unload to prevent them from
* being saved.
*/
$(window).unload(function() {
$('.' + o.className).val('');
});
/* Clear fields that are still examples before any form is submitted
* otherwise those examples will be sent along as well.
*
* Prior to 1.3, this would only be bound to forms that were
* parents of example fields but this meant that a page with
* multiple forms would not work correctly.
*/
$('form').submit(function() {
/* Clear only the fields inside this particular form. */
$(this).find('.' + o.className).val('');
});
/* Add the class name to the array. */
$.fn.example.boundClassNames[o.className] = true;
}
/* Internet Explorer will cache form values even if they are cleared
* on unload, so this will clear any value that matches the example
* text and hasn't been specified in the value attribute.
*
* If a callback is used, it is not possible or safe to predict
* what the example text is going to be so all non-default values
* are cleared. This means that caching is effectively disabled for
* that field.
*
* Many thanks to Klaus Hartl for helping resolve this issue.
*/
if ($.browser.msie && !$this.attr('defaultValue') && (isCallback || $this.val() == o.example))
$this.val('');
/* Initially place the example text in the field if it is empty
* and doesn't have focus yet.
*/
if ($this.val() == '' && this != document.activeElement) {
$this.addClass(o.className);
/* The text argument can now be a function; if this is the case,
* call it, passing the current element as `this`.
*/
$this.val(isCallback ? o.example.call(this) : o.example);
}
/* Make the example text disappear when someone focuses.
*
* To determine whether the value of the field is an example or not,
* check for the example class name only; comparing the actual value
* seems wasteful and can stop people from using example values as real
* input.
*/
$this.focus(function() {
/* jQuery 1.1 has no hasClass(), so is() must be used instead. */
if ($(this).is('.' + o.className)) {
$(this).val('');
$(this).removeClass(o.className);
}
});
/* Make the example text reappear if the input is blank on blurring. */
$this.blur(function() {
if ($(this).val() == '') {
$(this).addClass(o.className);
/* Re-evaluate the callback function every time the user
* blurs the field without entering anything. While this
* is not as efficient as caching the value, it allows for
* more dynamic applications of the plugin.
*/
$(this).val(isCallback ? o.example.call(this) : o.example);
}
});
});
};
/* Users can override the defaults for the plugin like so:
*
* $.fn.example.defaults.className = 'not_example';
*/
$.fn.example.defaults = {
className: 'example'
};
/* All the class names used are stored as keys in the following array. */
$.fn.example.boundClassNames = [];
})(jQuery);
|
JavaScript
| 0 |
@@ -1196,39 +1196,8 @@
the
-default options with the given
argu
@@ -1210,56 +1210,51 @@
and
-the
given
-%0A * text with the text option.%0A
+ example text into one options object.
*/%0A
@@ -1467,107 +1467,141 @@
-if ($.metadata) %7B%0A %0A /* If the Metadata plugin is being used merge in the options. */
+/* Merge the plugin defaults with the given options and, if present,%0A * any metadata.%0A */%0A if ($.metadata) %7B
%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.