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
|
---|---|---|---|---|---|---|---|
646532f753338a2b5f4f869b3453db5d520f5e76 | Add Remove All labels prompt | prompts/mainMenu.js | prompts/mainMenu.js | /**
* The "Initial"/"Main" prompts
*/
"use strict";
module.exports = [
{
type: "list",
name: "main",
message: "Welcome to git-labelmaker!\nWhat would you like to do?",
choices: [ "Add Custom Labels", "Add Labels From Package", "Remove Labels", "Reset Token" ]
}
];
| JavaScript | 0.000001 | @@ -269,16 +269,37 @@
Labels%22,
+ %22Remove All Labels%22,
%22Reset
|
3f3ad6a7eda8b2afad2a819b8ca6c35d1284d168 | FIX Javascript “Cannot read property 'length' of undefined” when checking a variable's length | www/public/adm/js/listener.js | www/public/adm/js/listener.js | $(function() {
var body = $('body');
/**
* Загрузка данных слушателя
*/
$('#listeners').on('click', 'input:checkbox', function() {
if ($(this).is(":checked")) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).prop("checked", false);
$(this).prop("checked", true);
} else {
$(this).prop("checked", true);
return;
}
$('#user_id').val($(this).val());
var f_statement = $('#statement'),
f_contract = $('#contract'),
listeners = $('#listeners'),
$this = $(this),
is_distrib = 0;
if ($('.distrib').length == 0)
is_distrib = 0;
else
is_distrib = 1;
$.ajax({
type : 'POST',
url : listeners.data('url'),
data : {
csrf : listeners.prev('input').val(),
user_id : $this.val(),
distrib : is_distrib
},
dataType : 'json',
beforeSend : function() {
listeners.find('.loader').remove();
$this.parent().append('<div class="loader"><i class="icon-refresh icon-spin icon-large"></i></div>');
f_statement.find('input,select').each(function() {
if ($(this).attr('type') != 'submit' && $(this).attr('type') != 'hidden')
if ($(this).attr('type') == 'checkbox')
$(this).prop("checked", false);
else
$(this).val('');
});
f_contract.find('input,select').each(function() {
if ($(this).attr('type') != 'submit' && $(this).attr('type') != 'hidden')
if ($(this).attr('type') == 'checkbox')
$(this).prop("checked", false);
else
$(this).val('');
});
},
success : function(response) {
fn_callback(response, $this, f_statement, f_contract, listeners);
},
error : function(request) {
if (request.status == '200') {
console.log('Исключение: ' + request.responseText);
} else {
console.log(request.status + ' ' + request.statusText);
}
}
});
});
if ($('#listeners').find('label').length == 0) {
$('#listeners').html('<div class="text-center">Слушателей нет</div>');
}
else
$('#listeners').find('input:checkbox').first().trigger('click');
$('#select2').on('change', function() {
var $this = $(this),
block = $('#listeners'),
f_statement = $('#statement'),
f_contract = $('#contract'),
active_checkbox = $('#listeners').find('input:checkbox:checked').val();
$.ajax({
type : 'POST',
url : $this.data('url'),
data : {
csrf : block.prev('input').val(),
group_id : $this.val()
},
dataType : 'json',
beforeSend : function() {
un_message();
block.html('<div class="loader"><i class="icon-refresh icon-spin icon-large"></i></div>');
f_statement.find('input,select').each(function() {
if ($(this).attr('type') != 'submit' && $(this).attr('type') != 'hidden')
$(this).val('');
});
f_contract.find('input,select').each(function() {
if ($(this).attr('type') != 'submit' && $(this).attr('type') != 'hidden')
$(this).val('');
});
},
success : function(response){
block.html('');
if (response.status == 'success')
{
if (response.data == '') {
block.html('<div class="text-center">Слушателей нет</div>');
} else {
block.html(response.data);
if (active_checkbox.length == 0)
$('#listeners').find('input:checkbox').first().trigger('click');
else
$('#listeners').find('input:checkbox[value="'+active_checkbox+'"]').trigger('click');
}
}
if (response.status == 'error')
{
message($('.container'), response.msg, response.status);
}
block.prev('input').val(response.csrf);
},
error : function(request) {
if (request.status == '200') {
console.log('Исключение: ' + request.responseText);
} else {
console.log(request.status + ' ' + request.statusText);
}
}
});
});
$('#statement, #contract').on('submit', function(e) {
e.preventDefault();
var $this = $(this),
btn = $this.find('#button');
$.ajax({
type : 'POST',
url : $this.attr('action'),
data : $this.serialize(),
dataType : 'json',
beforeSend : function() {
un_message();
wait(btn);
},
success : function(response) {
if (response.status == 'success' || response.status == 'error')
{
message($('.container'), response.msg, response.status);
}
if (response.status == 'success') {
if ($('.distrib').length == 0)
$('#select2').trigger('change');
else
$('#listeners').find('input:checkbox:checked').prop('checked', false).trigger('click');
}
after_wait(btn);
},
error : function(request) {
if (request.status == '200') {
console.log('Исключение: ' + request.responseText);
} else {
console.log(request.status + ' ' + request.statusText);
}
after_wait(btn);
}
});
});
});
| JavaScript | 0 | @@ -4251,24 +4251,144 @@
+//FIX Javascript %E2%80%9CCannot read property 'length' of undefined%E2%80%9D when checking a variable's length%0A
if (active_c
@@ -4394,28 +4394,16 @@
checkbox
-.length == 0
)%0A
|
fafe4280614d5b8eff2f28da9651f734b5d05229 | revert scanner | public/js/video.js | public/js/video.js | (function () {
var inputCanvas = document.createElement('canvas');
var inputContext = inputCanvas.getContext('2d');
var outputCanvas = document.getElementById('output');
var outputContext = outputCanvas.getContext('2d');
var video = document.getElementById('video');
var constraints = { video: true };
var width;
var height;
var outputImageData;
var pixelIndices = [];
ImageData.prototype.toInverted = function () {
var pixels = this.data;
for (var i=0; i<pixels.length / 4; i++) {
var p = i * 4;
pixels[p] = 255 - pixels[p];
pixels[p+1] = 255 - pixels[p+1];
pixels[p+2] = 255 - pixels[p+2];
}
};
ImageData.prototype.toBW = function () {
var pixels = this.data;
for (var i=0; i<pixels.length / 4; i++) {
var p = i * 4;
var intensity = Math.floor((pixels[p] + pixels[p+1] + pixels[p+2]) / 3);
pixels[p] = intensity;
pixels[p+1] = intensity;
pixels[p+2] = intensity;
}
};
ImageData.prototype.shiftChannels = function () {
var pixels = this.data;
for (var i=0; i<pixels.length / 4; i++) {
var p = i * 4;
pixels[p] = pixels[p+1];
pixels[p+1] = pixels[p+2];
pixels[p+2] = pixels[p];
}
}
ImageData.prototype.toChannelIntensity = function (channel) {
var pixels = this.data;
var ci = this.channelIndex[channel];
for (var i=0; i<pixels.length / 4; i++) {
var p = i * 4;
var cVal = pixels[p+ci];
pixels[p] = cVal;
pixels[p+1] = cVal;
pixels[p+2] = cVal;
}
};
ImageData.prototype.channelIndex = {
'r': 0,
'R': 0,
'red': 0,
'g': 1,
'G': 1,
'green': 1,
'b': 2,
'B': 2,
'blue': 2
};
function initializeCanvases () {
inputContext.drawImage(video, 0, 0);
outputImageData = inputContext.getImageData(0, 0, width, height);
var numPix = width * height;
var bufferLength = numPix / 4;
pixelIndices = [0, 1*bufferLength, 2*bufferLength, 3*bufferLength];
};
function draw () {
inputContext.drawImage(video, 0, 0);
drawScanner();
setTimeout(function () {
draw();
}, 1000/60);
};
function drawScanner () {
var inputPixels = inputContext.getImageData(0, 0, width, height).data;
var outputPixels = outputImageData.data;
for (var i=0; i<pixelIndices.length; i++) {
pi = pixelIndices[i];
for (var j=pi; j<pi+width; j++) {
var p = j * 4;
outputPixels[p] = inputPixels[p];
outputPixels[p+1] = inputPixels[p+1];
outputPixels[p+2] = inputPixels[p+2];
}
pixelIndices[i] = (pi + width < width * height) ? pi + width : 0;
}
outputContext.putImageData(outputImageData, 0, 0);
};
function errorCallback (e) {
console.log(e);
};
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia(constraints, function (stream) {
video.src = window.URL.createObjectURL(stream);
}, errorCallback);
}
video.addEventListener('canplay', function (e) {
width = video.videoWidth;
height = video.videoHeight;
inputCanvas.width = width;
outputCanvas.width = width;
inputCanvas.height = height;
outputCanvas.height = height;
initializeCanvases();
draw();
}, false);
})(); | JavaScript | 0 | @@ -376,17 +376,14 @@
lInd
-ices = %5B%5D
+ex = 0
;%0A%0A
@@ -1858,216 +1858,34 @@
t);%0A
-%0A var numPix = width * height;%0A var bufferLength = numPix / 4;%0A pixelIndices = %5B0, 1*bufferLength, 2*bufferLength, 3*bufferLength%5D;%0A %7D;%0A%0A function draw () %7B%0A inputContext.drawImage(video, 0, 0);
+ %7D;%0A%0A function draw () %7B
%0A
@@ -1900,17 +1900,16 @@
nner();%0A
-%0A
setT
@@ -1919,50 +1919,20 @@
out(
-function () %7B%0A draw(); %0A %7D
+draw
, 1000/
-6
+3
0);%0A
@@ -1961,24 +1961,65 @@
canner () %7B%0A
+ inputContext.drawImage(video, 0, 0);%0A
var inpu
@@ -2126,21 +2126,16 @@
a.data;%0A
- %0A
for
@@ -2145,21 +2145,16 @@
r i=
-0; i%3C
pixelInd
ices
@@ -2153,89 +2153,32 @@
lInd
-ices.length; i++) %7B%0A pi = pixelIndices%5Bi%5D;%0A for (var j=pi; j%3Cpi
+ex; i%3CpixelIndex
+width;
j++)
@@ -2177,17 +2177,15 @@
th;
-j
+i
++) %7B%0A
-
@@ -2198,18 +2198,15 @@
p =
-j
+i
* 4;%0A
-%0A
@@ -2239,34 +2239,32 @@
ixels%5Bp%5D;%0A
-
outputPixels%5Bp+1
@@ -2287,26 +2287,24 @@
p+1%5D;%0A
-
outputPixels
@@ -2333,22 +2333,18 @@
2%5D;%0A
- %7D%0A
+%7D%0A
pixe
@@ -2351,21 +2351,24 @@
lInd
-ices%5Bi%5D = (pi
+ex = (pixelIndex
+ w
@@ -2394,16 +2394,24 @@
ht) ? pi
+xelIndex
+ width
@@ -2416,22 +2416,16 @@
th : 0;%0A
- %7D%0A
outp
|
e70f999ff7ea98504c67404af22f9647226c9041 | refactor flowlet output code addressing comments | cdap-ui/app/features/flows/controllers/tabs/runs/flowlets/output-ctrl.js | cdap-ui/app/features/flows/controllers/tabs/runs/flowlets/output-ctrl.js | angular.module(PKG.name + '.feature.flows')
.controller('FlowletDetailOutputController', function($state, $scope, MyDataSource, MyMetricsQueryHelper, myFlowsApi) {
var dataSrc = new MyDataSource($scope);
var flowletid = $scope.$parent.activeFlowlet.name;
var runid = $scope.runs.selected.runid;
$scope.outputs = [];
var params = {
namespace: $state.params.namespace,
appId: $state.params.appId,
flowId: $state.params.programId,
scope: $scope
};
var flowletTags = {
namespace: $state.params.namespace,
app: $state.params.appId,
flow: $state.params.programId,
run: runid,
flowlet: flowletid
};
myFlowsApi.get(params)
.$promise
.then(function (res) {
// OUTPUTS
angular.forEach(res.connections, function(v) {
if (v.sourceName === flowletid) {
$scope.outputs.push(v.targetName);
}
});
if ($scope.outputs.length > 0) {
// OUTPUT METRICS
dataSrc
.poll({
_cdapPath: '/metrics/query?' + MyMetricsQueryHelper.tagsToParams(flowletTags)
+ '&metric=system.process.events.out&start=now-60s&count=60',
method: 'POST'
}, function(res) {
if (res.series[0]) {
updateOutput(res.series[0].data);
} else {
var val = [];
for (var i = 60; i > 0; i--) {
val.push({
time: Math.floor((new Date()).getTime()/1000 - (i)),
y: 0
});
}
if ($scope.outputHistory) {
$scope.outputStream = val.slice(-1);
}
$scope.outputHistory = [{
label: 'output',
values: val
}];
}
});
// Total
dataSrc
.poll({
_cdapPath: '/metrics/query?' + MyMetricsQueryHelper.tagsToParams(flowletTags)
+ '&metric=system.process.events.out',
method: 'POST'
}, function(res) {
if (res.series[0]) {
$scope.total = res.series[0].data[0].value;
}
});
}
});
function updateOutput(newVal) {
if(angular.isObject(newVal)) {
var v = [];
angular.forEach(newVal, function(val) {
v.push({
time: val.time,
y: val.value
});
});
if ($scope.outputHistory) {
$scope.outputStream = v.slice(-1);
}
$scope.outputHistory = [
{
label: 'output',
values: v
}
];
}
}
});
| JavaScript | 0.000001 | @@ -1307,609 +1307,26 @@
-if (res.series%5B0%5D) %7B%0A updateOutput(res.series%5B0%5D.data);%0A %7D else %7B%0A var val = %5B%5D;%0A%0A for (var i = 60; i %3E 0; i--) %7B%0A val.push(%7B%0A time: Math.floor((new Date()).getTime()/1000 - (i)),%0A y: 0%0A %7D);%0A %7D%0A%0A if ($scope.outputHistory) %7B%0A $scope.outputStream = val.slice(-1);%0A %7D%0A%0A $scope.outputHistory = %5B%7B%0A label: 'output',%0A values: val%0A %7D%5D;%0A%0A %7D
+updateOutput(res);
%0A
@@ -1791,22 +1791,19 @@
eOutput(
-newVal
+res
) %7B%0A
@@ -1808,59 +1808,47 @@
-if(angular.isObject(newVal)) %7B%0A var v = %5B%5D;%0A
+var v = %5B%5D;%0A%0A if (res.series%5B0%5D) %7B
%0A
@@ -1872,14 +1872,26 @@
ach(
-newVal
+res.series%5B0%5D.data
, fu
@@ -1994,35 +1994,220 @@
%7D);%0A %7D);%0A
-%0A
+ %7D else %7B%0A for (var i = 60; i %3E 0; i--) %7B%0A v.push(%7B%0A time: Math.floor((new Date()).getTime()/1000 - (i)),%0A y: 0%0A %7D);%0A %7D%0A %7D%0A%0A
if ($scope
@@ -2220,26 +2220,24 @@
tHistory) %7B%0A
-
$sco
@@ -2267,18 +2267,16 @@
ce(-1);%0A
-
%7D%0A
@@ -2278,26 +2278,24 @@
%7D%0A%0A
-
$scope.outpu
@@ -2306,27 +2306,16 @@
tory = %5B
-%0A
%7B%0A
@@ -2316,20 +2316,16 @@
-
-
label: '
@@ -2329,28 +2329,24 @@
: 'output',%0A
-
valu
@@ -2361,33 +2361,12 @@
- %7D%0A %5D;%0A%0A %7D
+%7D%5D;%0A
%0A
|
e0b1d23bf1911bc4134d6a4958b929780c74a661 | Remove trailing whitespace | scripts/create_pages.js | scripts/create_pages.js | #!/usr/bin/env node
var fs = require('fs'),
marked = require('marked');
process.chdir(__dirname);
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: false
});
var scripts = [
'session',
'utils',
'dom',
'hints',
'bookmarks',
'keys',
'clipboard',
'complete',
'mappings',
'find',
'cursor',
'status',
'hud',
'visual',
'command',
'scroll',
'search',
'frames',
'messenger',
];
var makeHTML = function(data) {
return '<!DOCTYPE html><html><head>' +
'<meta charset="utf-8">' +
'<link rel="stylesheet" href="./markdown.css">' +
'<link rel="stylesheet" href="../content_scripts/main.css">' +
scripts.map(function(e) { return '<script src="../content_scripts/' + e + '.js"></script>'; }).join('\n') +
'</head>' + marked(data) + '</html>';
};
(function() {
var fileMap = {
mappings: 'README.md',
changelog: 'CHANGELOG.md'
};
for (var key in fileMap) {
var data = fs.readFileSync('../' + fileMap[key], 'utf8');
fs.writeFileSync('../pages/' + key + '.html', makeHTML(data));
}
})();
| JavaScript | 0.999999 | @@ -645,17 +645,16 @@
f-8%22%3E' +
-
%0A
|
1163c7daefa9882a3989ef812d799e0caced24be | Update project1-chart1.js | project1/project1-chart1.js | project1/project1-chart1.js |
(function() {
var margin = { top: 30, left: 100, right: 30, bottom: 30},
height = 500 - margin.top - margin.bottom,
width = 780 - margin.left - margin.right;
console.log("Building chart 1");
// Create a time parser
var parse = d3.timeParse("%m/%d/%y")
// Create your scales, but ONLY give them a range
// (you'll set the domain once you read in your data)
var xPositionScale = d3.scaleLinear().range([0, width]);
var yPositionScale = d3.scaleLinear().range([height, 0])
var line = d3.line()
.x(function(d) {
return xPositionScale(d.datetime);
})
.y(function(d) {
return yPositionScale(d.Score);
})
.curve(d3.curveMonotoneX)
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
// .offset(function() {
// return [this.getBBox().height / 2, 0]
// })
.html(function(d) {
return "<span style='color:white; font-size: 10pt; font-family: sans-serif; align: center'>" + d.month + "<br>" + d.trump + "</span>"
})
var svg = d3.select("#project1-chart1")
.append("svg")
.attr("height", height + margin.top + margin.bottom)
.attr("width", width + margin.left + margin.right)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.call(tip);
console.log(tip)
d3.queue()
.defer(d3.csv, "project1_dataset.csv", function(d) {
// While we're reading the data in, parse each date
// into a datetime object so it isn't just a string
// save it as 'd.datetime'
// d.datetime is now your 'useful' date, you can ignore
// d.Date. Feel free to use console.log to check it out.
d.datetime = parse(d.Week);
console.log(d.datetime)
console.log(d.Week)
//console.log(d.datetime)
d.Score = +d.score;
console.log(d.Score)
//console.log(d.Close)
return d;
})
.await(ready);
function ready(error, datapoints) {
console.log(datapoints)
// Get the max and min of datetime and Close,
// then use that to set the domain of your scale
// NOTE:I've done it for the datetime, you do it for the close price
var minDatetime = d3.min(datapoints, function(d) { return d.datetime });
var maxDatetime = d3.max(datapoints, function(d) { return d.datetime });
xPositionScale.domain([minDatetime, maxDatetime])
var minClosetime = d3.min(datapoints, function(d) { return d.Score });
var maxClosetime = d3.max(datapoints, function(d) { return d.Score });
yPositionScale.domain([minClosetime, maxClosetime])
// Draw your dots
svg.selectAll(".trumpcircles")
.data(datapoints)
.enter().append("circle")
.attr("class", "trumpcircles")
.attr("r", function(d) {
if (d.trump != "") {return "6"}
else {return "none"}
})
.attr("stroke", function(d) {
if (d.Score > 1) {return "red"}
else {return "none"}
})
.attr("stroke-width", 2)
.attr("fill", "white")
.attr("cx", function(d) {
return xPositionScale(d.datetime)
})
.attr("cy", function(d) {
return yPositionScale(d.Score)
})
.on('mouseover', function(d,i) {
tip.show(d,i)
svg.selectAll(".trumpcircles")
.filter(function(e) {
return(e.datetime != d.datetime)
})
.transition()
.style("opacity", 0.2)
})
.on('mouseout', function(d,i) {
tip.hide(d,i)
svg.selectAll(".trumpcircles")
.filter(function(e) {
return(e.datetime != d.datetime)
})
.transition()
.style("opacity", 1)
})
// Draw your SINGLE line (but remember it isn't called a line)
svg.append("path")
.datum(datapoints)
.attr("d", line)
.attr("fill", "none")
.attr("stroke", "red")
.attr("stroke-width", 3)
// Add your axes - I've added the x axis for you
// Notice that xAxis gets a .tickFormat to format the dates!
// You won't use this again unless you're doing time again.
var xAxis = d3.axisBottom(xPositionScale).tickFormat(d3.timeFormat("%Y"));
svg.append("g")
.attr("class", "axis x-axis")
.attr("transform", "translate(0," + width + ")")
.call(xAxis);
var yAxis = d3.axisLeft(yPositionScale)
svg.append("g")
.attr("class", "axis y-axis")
.call(yAxis);
}
})();
| JavaScript | 0.000012 | @@ -4270,32 +4270,35 @@
%22axis x-axis%22)%0A
+//
.attr(%22t
|
f156c6450ac38c63e6df9f97dbd510a49f287ce3 | disable safari ios for indexedDB test. @rev tbliss@ @bug W-2747747@ | aura-components/src/test/components/auraStorageTest/noGetApplicationCache/noGetApplicationCacheTest.js | aura-components/src/test/components/auraStorageTest/noGetApplicationCache/noGetApplicationCacheTest.js | ({
tearDown: function() {
$A.storageService.getStorage('actions').remove('aura://ComponentController/ACTION$getApplication:{"name":"auraStorageTest:noGetApplicationCache"}');
},
testOfflineLaunch: {
// TODO(W-2701964): Flapping in autobuilds, needs to be revisited
labels: ["flapper"],
test: [
function loadIframe(cmp) {
cmp._frameLoaded = false;
var frame = document.createElement("iframe");
frame.src = "/auraStorageTest/noGetApplicationCache.app";
frame.scrolling = "auto";
frame.id = "myFrame";
$A.util.on(frame, "load", function () {
cmp._frameLoaded = true;
});
var content = cmp.find("iframeContainer");
$A.util.insertFirst(frame, content.getElement());
this.waitForIframeLoad(cmp);
},
function reloadIframeOffline(cmp) {
cmp._frameLoaded = false;
document.getElementById("myFrame").contentWindow.location.hash = "launchOffline";
document.getElementById("myFrame").contentWindow.location.reload();
this.waitForIframeLoad(cmp);
},
function verifyApplicationLoaded(cmp) {
var iframeCmp = document.getElementById("myFrame").contentWindow.$A.getRoot();
$A.test.addWaitFor("Loaded", function() {
return iframeCmp.get('v.status');
});
},
function verifyStorageGets(cmp) {
// First get is for GVP
var gets = document.getElementById("myFrame").contentWindow._storageGets;
$A.test.assertEquals(2, gets.length, "Expected two storage.get() on reload! " + JSON.stringify(gets));
}
]
},
testOnlineLaunch: {
test: [
function loadIframe(cmp) {
$A.test.setTestTimeout(100000);
cmp._frameLoaded = false;
var frame = document.createElement("iframe");
frame.src = "/auraStorageTest/noGetApplicationCache.app";
frame.scrolling = "auto";
frame.id = "myFrame";
$A.util.on(frame, "load", function () {
cmp._frameLoaded = true;
});
var content = cmp.find("iframeContainer");
$A.util.insertFirst(frame, content.getElement());
this.waitForIframeLoad(cmp);
},
function reloadIframeOffline(cmp) {
cmp._frameLoaded = false;
document.getElementById("myFrame").contentWindow.location.reload();
this.waitForIframeLoad(cmp);
},
function verifyApplicationLoaded(cmp) {
var iframeCmp = document.getElementById("myFrame").contentWindow.$A.getRoot();
$A.test.addWaitFor("Loaded", function() {
return iframeCmp.get('v.status');
});
},
function verifyStorageGets(cmp) {
// First get is for GVP
var gets = document.getElementById("myFrame").contentWindow._storageGets;
$A.test.assertEquals(1, gets.length, "More than one storage.get() on reload! " + JSON.stringify(gets));
}
]
},
waitForIframeLoad: function(cmp) {
var iframeWindow = document.getElementById("myFrame").contentWindow;
$A.test.addWaitFor(true, function() {
return cmp._frameLoaded
&& iframeWindow.$A
&& iframeWindow.$A.getRoot() !== undefined
&& !$A.test.isActionPending()
});
}
}) | JavaScript | 0 | @@ -1,11 +1,202 @@
(%7B%0A
+%09// IndexedDb not supported in IE %3C 10%0A // Disable IndexedDB for Safari because it doesn't work reliably in iframe.%0A browsers:%5B%22-IE7%22, %22-IE8%22, %22-IE9%22, %22-SAFARI%22, %22-IPAD%22, %22-IPHONE%22%5D,%0A%09%0A
tear
|
e1c59b8337344f158dd2348bea1991699ef86fcc | Add Page#getPrevious() and Page#getNext(). | lib/Page.js | lib/Page.js | var path = require('path'),
fs = require('fs'),
parsers = require('./parsers'),
woods = require('./woods'),
Site = require('./Site'),
Showdown = require('showdown'),
converter = new Showdown.converter(),
express = require('express');
var Page = function(site, parent, directory) {
var that = this;
this.site = site;
if (parent)
this.parent = parent;
this.directory = directory;
var uri = this.getUri(true);
// Only pages
// with a number prefixed to their directory name
// are marked as being visible.
this.visible = /^\/[0-9]/.test(uri);
// Remove numbers in path, since they are only used for order:
this.url = uri.replace(/\/[0-9]+-/g,'/')
.replace(/\s/g, '-');
site.pageByUrl[this.url] = this;
this.name = this.directory == ''
? 'home'
: path.basename(this.url).replace(/\/$/, '');
installRoute(this);
addChildren(this);
addResources(this);
parseContent(this);
};
Page.prototype.getTemplate = function(name) {
var type = this.data.type,
types = this.site.types;
return type && types[type][name]
? types[type][name]
: types['default'][name] || function(param) {
return 'Template not found: ' + name;
};
};
Page.prototype.getTemplateLocation = function(name) {
var templateLocations = this.site.templateLocations,
type = this.data.type;
return this.data.type && templateLocations[type][name]
? templateLocations[type][name]
: templateLocations['default'][name];
};
Page.prototype.renderTemplate = function(name) {
return this.getTemplate(name)({
page: this,
parse: function(content, param) {
return converter.makeHtml(content);
}
});
};
Page.prototype.getUri = function(url) {
var uri = this.directory,
parent = this.parent;
while (parent) {
uri = path.join(parent.directory, uri);
parent = parent.parent;
}
var site = url ? this.site.url : this.site.getUri('content');
var resolved = path.resolve(site, uri);
return resolved;
};
Page.prototype.hasChildren = function() {
return this.children.length > 0;
};
Page.prototype.getTitle = function() {
return this.data.title || this.name;
};
Page.prototype.isParent = function(page) {
return this.parent == page;
};
Page.prototype.isChild = function(page) {
return page && page.parent == this;
};
Page.prototype.isDescendant = function(page) {
var parent = this;
while (parent = parent.parent) {
if (parent == page)
return true;
}
return false;
};
Page.prototype.isAncestor = function(page) {
return page ? page.isDescendant(this) : false;
};
var reservedNames = {resources: true, error: true, home: true};
Page.nameIsReserved = function(name) {
return !!name && !!reservedNames[name];
};
var addResources = function(page) {
var routeUrl = path.join(page.url, 'resources'),
resourcesDir = path.join(page.getUri(), 'resources'),
images = page.images = [],
resources = page.resources = [];
woods.express.use(routeUrl, express.static(resourcesDir));
var addFile = function(file) {
if (/jpg|jpeg|png|gif/.test(file)) {
images.push(file);
} else {
resources.push(file);
}
};
var addFiles = function() {
fs.readdir(resourcesDir, function(err, files) {
files.forEach(addFile);
});
};
fs.exists(resourcesDir, function(err, exists) {
if (!exists) return;
addFiles();
});
};
var addChildren = function(page) {
// Read the directory and add child pagees (if any):
var children = page.children = [];
var uri = page.getUri();
var files = fs.readdirSync(uri);
var index = 0;
for (var i in files) {
var file = path.resolve(uri, files[i]);
var name = path.basename(file);
var isDirectory = fs.statSync(file).isDirectory();
if (isDirectory && !Page.nameIsReserved(name)) {
var isChild = /^[0-9]+\-/.test(name);
var child = new Page(page.site, page, path.relative(uri, file));
child.index = index++;
// Only add to children list if it is a child
// - i.e. its name starts in the style of: 01- or 02-
if (isChild)
children.push(child);
}
}
};
var parseContent = function(page) {
// Parse the content file and place values in page.data:
page.data = {};
var contentPath = path.join(page.getUri(), 'content.md');
parsers.parse(contentPath, page);
};
var installRoute = function(page) {
// Install the path in express:
woods.express.get(page.url, function(req, res) {
var template = page.getTemplateLocation('html');
res.render(template, {
site: page.site,
page: page,
parse: function(content, param) {
return converter.makeHtml(content);
}
});
});
};
module.exports = Page; | JavaScript | 0 | @@ -2491,24 +2491,458 @@
false;%0A%7D;%0A%0A
+Page.prototype.hasPrevious = function() %7B%0A%09return this.visible && this.index %3E 0;%0A%7D;%0A%0APage.prototype.hasNext = function() %7B%0A%09return this.visible && this.index + 1 %3C this.parent.children.length;%0A%7D;%0A%0APage.prototype.getPrevious = function() %7B%0A%09return this.hasPrevious() ? this.parent.children%5Bthis.index - 1%5D : null;%0A%7D;%0A%0APage.prototype.getNext = function(page) %7B%0A%09return this.hasNext() ? this.parent.children%5Bthis.index + 1%5D : null;%0A%7D;%0A%0A
var reserved
|
26e70b865e2f8a1d8a3916c72529d6fc96caa155 | fix wrong function method used to execute with context | web/static/js/modules/modalService.js | web/static/js/modules/modalService.js | /* global angular, console, $ */
/* jshint multistr: true */
(function() {
'use strict';
angular.module('modalService', []).
factory("$modalService", [
"$rootScope", "$templateCache", "$http", "$interpolate", "$compile", "$translate", "$notification",
function($rootScope, $templateCache, $http, $interpolate, $compile, $translate, $notification){
var defaultModalTemplate = '<div class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">\
<div class="modal-dialog {{bigModal}}">\
<div class="modal-content">\
<div class="modal-header">\
<button type="button" class="close glyphicon glyphicon-remove-circle" data-dismiss="modal" aria-hidden="true"></button>\
<span class="modal-title">{{title}}</span>\
</div>\
<div class="modal-notify"></div>\
<div class="modal-body">{{template}}</div>\
<div class="modal-footer"></div>\
</div>\
</div>\
</div>';
var actionButtonTemplate = '<button type="button" class="btn {{classes}}"><span ng-show="icon" class="glyphicon {{icon}}"></span> {{label}}</button>';
var defaultRoles = {
"cancel": {
label: "Cancel",
icon: "glyphicon-remove",
classes: "btn-link",
action: function(){
this.close();
}
},
"ok": {
label: "Ok",
icon: "glyphicon-ok",
classes: "btn-primary submit",
action: function(){
this.close();
}
}
};
/**
* Modal window
*/
function Modal(template, model, config){
var $modalFooter;
// inject user provided template into modal template
var modalTemplate = $interpolate(defaultModalTemplate)({
template: template,
title: $translate.instant(config.title),
bigModal: config.bigModal ? "big" : ""
});
// bind user provided model to final modal template
this.$el = $($compile(modalTemplate)(model)).modal();
$modalFooter = this.$el.find(".modal-footer");
// cache a reference to the notification holder
this.$notificationEl = this.$el.find(".modal-notify");
// create action buttons
config.actions.forEach(function(action){
// if this action has a role on it, merge role defaults
if(action.role && defaultRoles[action.role]){
for(var i in defaultRoles[action.role]){
action[i] = action[i] || defaultRoles[action.role][i];
}
}
// translate button label
action.label = $translate.instant(action.label);
var $button = $($interpolate(actionButtonTemplate)(action));
$button.on("click", action.action.bind(this));
$modalFooter.append($button);
}.bind(this));
// if no actions, remove footer
if(!config.actions.length){
$modalFooter.remove();
}
// setup/default validation function
this.validateFn = config.validate || function(){ return true; };
// listen for hide event and completely remove modal
// after it is hidden
this.$el.on("hidden.bs.modal", function(){
this.destroy();
}.bind(this));
}
Modal.prototype = {
constructor: Modal,
close: function(){
this.$el.modal("hide");
},
show: function(){
this.$el.modal("show");
},
validate: function(){
return this.validateFn();
},
destroy: function(){
this.$el.remove();
},
// convenience method for attaching notifications to the modal
createNotification: function(title, message){
return $notification.create(title, message, this.$notificationEl);
},
// convenience method to disable the default ok/submit button
disableSubmitButton: function(selector, disabledText){
selector = selector || ".submit";
disabledText = disabledText || "Submitting...";
var $button = this.$el.find(selector),
$buttonClone,
buttonContent, startWidth, endWidth;
// button wasnt found
if(!$button.length){
return;
}
// explicitly set width so it can be animated
startWidth = $button.width();
// clone the button and set the ending text so the
// explicit width can be calculated
$buttonClone = $button.clone().width("auto").text(disabledText).appendTo("body");
endWidth = $buttonClone.width();
$buttonClone.remove();
$button.width(startWidth);
buttonContent = $button.html();
$button.prop("disabled", true)
.addClass("disabled")
.text(disabledText)
.width(endWidth);
// return a function used to reenable the button
return function(){
$button.prop("disabled", false)
.removeClass("disabled")
.html(buttonContent)
.width(startWidth);
};
}
};
var modalsPath = "/static/partials/",
// keep track of existing modals so that they can be
// close/destroyed when a new one is created
// TODO - remove modals from this list when they are hidden
modals = [];
/**
* Fetches modal template and caches it in $templateCache.
* returns a promise for the http request
*/
function fetchModalTemplate(name){
var url = modalsPath + name;
return $http.get(url, {cache: $templateCache});
}
/**
* fetches modal template and passes it along to be attached
* to the DOM
*/
function create(config){
config = config || {};
// TODO - default config object
config.actions = config.actions || [];
config.onShow = config.onShow || function(){};
config.onHide = config.onHide || function(){};
var model = config.model || {};
// if the template was provided, use that
if(config.template){
_create(config.template, model, config);
// otherwise, request the template
// TODO - pop a modal with load spinner?
} else {
fetchModalTemplate(config.templateUrl).then(function(res){
_create(res.data, model, config);
});
}
}
function _create(template, model, config){
var modal = new Modal(template, model, config);
modal.show();
// immediately destroy any existing modals
modals.forEach(function(momo){
momo.destroy();
});
modals = [modal];
// perform onShow function after modal is visible
modal.$el.one("shown.bs.modal.", function(){
// search for and autofocus the focusme element
modal.$el.find("[focusme]").first().focus();
// call user provided onShow function
config.onShow.bind(modal);
});
modal.$el.one("hidden.bs.modal.", config.onHide.bind(modal));
}
return {
create: create
};
}
]);
})();
| JavaScript | 0.000006 | @@ -8732,20 +8732,20 @@
.onShow.
-bind
+call
(modal);
|
48b597b80b5a5bde9b4693c7991039b7e740b480 | Update jsPerf_Operation.js | CNN/jsPerf/jsPerf_Operation.js | CNN/jsPerf/jsPerf_Operation.js | export { testCorrectness };
//import * as RandTools from "../util/RandTools.js";
import * as TensorPlaceholder from "../Conv/TensorPlaceholder.js";
import * as Operation from "../Conv/Operation.js";
/**
* For testing Operation.Base.
*
*/
class Case {
/**
* @param {number} caseId The id of this test case.
*/
constructor( caseId, bInput0, bInput1, outputTensorCount, bKeepInputTensor0, bKeepInputTensor1 ) {
this.caseId = caseId;
this.assertPrefix = `jsPerf_Operation.Case( this.caseId == ${this.caseId} )`;
let input0;
if ( bInput0 )
input0 = new TensorPlaceholder.Base();
let input1;
if ( bInput1 )
input1 = new TensorPlaceholder.Base();
this.operation = new Operation.Base( input0, input1, outputTensorCount );
this.operation.setKeepInputTensor( bKeepInputTensor0, bKeepInputTensor1 );
tf.tidy( () => {
let memoryInfo_apply_before = tf.memory(); // Test memory leakage of .apply.
let numTensors_delta = 0;
if ( input0 ) {
input0.realTensor = tf.randomNormal( Case.testTensorShape );
++numTensors_delta;
if ( bKeepInputTensor0 )
++numTensors_delta;
}
if ( input1 ) {
input1.realTensor = tf.randomNormal( Case.testTensorShape );
++numTensors_delta;
if ( bKeepInputTensor1 )
++numTensors_delta;
}
this.operation.apply();
if ( !bInput0 && !bInput1 ) { // If no inputs, outputs should always be null.
if ( this.operation.output0 )
this.assert_property_equal( "operation", "output0", "realTensor", null );
if ( this.operation.output1 )
this.assert_property_equal( "operation", "output1", "realTensor", null );
} else {
numTensors_delta += outputTensorCount;
}
let memoryInfo_apply_after = tf.memory();
let numTensors_predicted = ( memoryInfo_apply_before.numTensors + numTensors_delta );
tf.util.assert( ( memoryInfo_apply_after.numTensors == ( memoryInfo_apply_before.numTensors + numTensors_delta ) ),
`${this.assertPrefix}: memory leak. `
+ `result tensor count (${memoryInfo_apply_after.numTensors}) `
+ `should be ( ${numTensors_predicted} ) = ( ${memoryInfo_apply_before.numTensors} + ${numTensors_delta} ).`
);
});
}
assert_property_equal( strPropertyName0, strPropertyName1, strPropertyName2, rhsValue ) {
let strWholeName = `Case( caseId = ${this.caseId} ).${strPropertyName0}`;
let thisValue = this[ strPropertyName0 ];
if ( strPropertyName1 != undefined ) {
thisValue = thisValue[ strPropertyName1 ];
strWholeName += strPropertyName1;
}
if ( strPropertyName2 != undefined ) {
thisValue = thisValue[ strPropertyName2 ];
strWholeName += strPropertyName2;
}
tf.util.assert( thisValue == rhsValue, `jsPerf_Operation.`
+ `${strWholeName} ( ${thisValue} ) should be ( ${rhsValue} ).` );
}
}
Case.testTensorShape = [ 1 ];
function testCorrectness() {
let caseId = -1;
let bInput0, bInput1, outputTensorCount, bKeepInputTensor0, bKeepInputTensor1;
for ( let nInput0 = 0; nInput0 <= 1; ++nInput0 ) {
for ( let nInput1 = 0; nInput1 <= 1; ++nInput1 ) {
for ( let outputTensorCount = 0; outputTensorCount <= 2; ++outputTensorCount ) {
for ( let nKeepInputTensor0 = 0; nKeepInputTensor0 <= 1; ++nKeepInputTensor0 ) {
for ( let nKeepInputTensor1 = 0; nKeepInputTensor1 <= 1; ++nKeepInputTensor1 ) {
++caseId;
bInput0 = ( nInput0 != 0 );
bInput1 = ( nInput1 != 0 );
//!!! (2022/06/02 Remarked) It could be supported. Just get null as result.
//if ( !bInput0 && !bInput1 )
// continue; // Operation should have at least one input.
bKeepInputTensor0 = ( nKeepInputTensor0 != 0 );
bKeepInputTensor1 = ( nKeepInputTensor1 != 0 );
let testCase = new Case( caseId, bInput0, bInput1, outputTensorCount, bKeepInputTensor0, bKeepInputTensor1 );
}
}
}
}
}
}
| JavaScript | 0.000001 | @@ -2313,24 +2313,296 @@
.%60%0A );%0A
+%0A//!!! ...unfinished... (2022/06/04)%0A// aTensorPlaceholder.height, aTensorPlaceholder.width,%0A// aTensorPlaceholder.channelCount, aTensorPlaceholder.channelCount_lowerHalf, aTensorPlaceholder.channelCount_higherHalf,%0A// aTensorPlaceholder.scaleBoundsArray%0A%0A
%7D);%0A%0A %7D
|
2be799f6cdc2c9812ace9a48e67e33139d2eba49 | Refactor users_by_id | web/static/js/reducers/users_by_id.js | web/static/js/reducers/users_by_id.js | import keyBy from "lodash/keyBy"
export default (state = {}, action) => {
switch (action.type) {
case "SET_INITIAL_STATE":
return keyBy(action.initialState.users, "id")
case "SET_USERS":
return Object.assign(state, keyBy(action.users, "id"))
case "SYNC_PRESENCE_DIFF": {
const presencesRepresentingJoins = Object.values(action.presenceDiff.joins)
const users = presencesRepresentingJoins.map(join => join.user)
return Object.assign(state, keyBy(users, "id"))
}
default:
return state
}
}
| JavaScript | 0.000001 | @@ -25,16 +25,82 @@
h/keyBy%22
+%0Aimport values from %22lodash/values%22%0A%0Aconst USER_PRIMARY_KEY = %22id%22
%0A%0Aexport
@@ -235,20 +235,32 @@
.users,
-%22id%22
+USER_PRIMARY_KEY
)%0A ca
@@ -288,37 +288,31 @@
return
-Object.assign(
+%7B ...
state,
+...
keyBy(ac
@@ -319,30 +319,43 @@
tion.users,
-%22id%22))
+USER_PRIMARY_KEY) %7D
%0A case %22S
@@ -417,23 +417,16 @@
Joins =
-Object.
values(a
@@ -538,29 +538,23 @@
urn
-Object.assign(
+%7B ...
state,
+...
keyB
@@ -566,14 +566,27 @@
rs,
-%22id%22))
+USER_PRIMARY_KEY) %7D
%0A
|
789a18e3f251bee5f1fad3b72f96a6a866ab40db | resolve conflict to make it build | web_app/vis_comm/routes/cis_karate.js | web_app/vis_comm/routes/cis_karate.js | var express = require('express');
var router = express.Router();
// change `/cis_karate` into `/`, here root directory is `/cis_karate`
router.get('/', function (req, res, next) {
res.render('cis_karate', {title: 'Express'});
});
// change `/comm_result/cis1` into `/comm_result` to make it more readable
router.get('/comm_result', function (req, res, next) {
const exec = require('child_process').execSync;
<<<<<<< HEAD
exec('cd ../../community_detection_algos; python exec_docker.py demo_cis karate_edges_input.csv; echo done > done', function (error, stdout, stderr) {
=======
exec('cd ../../community_detection_algos; python exec_docker.py demo_cis karate_edges_input.csv', function (error, stdout, stderr) {
>>>>>>> 5f3baead56f4eff08e76509d462fe3464c701d69
if (error) {
console.error(error.toString());
return;
}
console.log(stdout.toString());
console.log(stderr.toString());
});
var fs = require('fs');
var toy_graph_json = JSON.parse(fs.readFileSync('../../community_detection_algos/json_files/karate_cis.json', 'utf8'));
console.log(JSON.stringify(toy_graph_json));
res.json(toy_graph_json);
});
module.exports = router;
| JavaScript | 0.000001 | @@ -419,186 +419,8 @@
nc;%0A
-%3C%3C%3C%3C%3C%3C%3C HEAD%0A%0A exec('cd ../../community_detection_algos; python exec_docker.py demo_cis karate_edges_input.csv; echo done %3E done', function (error, stdout, stderr) %7B%0A%0A=======%0A
@@ -556,57 +556,8 @@
) %7B%0A
-%3E%3E%3E%3E%3E%3E%3E 5f3baead56f4eff08e76509d462fe3464c701d69%0A
|
ac6dca421aca4c6ab649b3decb73ba0eee278775 | support --foo bar parameters in CLI | lib/args.js | lib/args.js | /**
* Simple phantom.args parser
*/
exports.parse = function(args) {
var res = {};
args = args || [];
args.forEach(function(item) {
var idx = item.indexOf('='),
key, val;
// --foo
if (idx < 0) {
key = item.substring(2);
val = true;
}
// --foo=bar
else {
key = item.substring(2, idx);
val = item.substring(idx+1);
}
res[key] = val;
});
return res;
};
| JavaScript | 0.000001 | @@ -77,17 +77,37 @@
res = %7B%7D
-;
+,%0A%09%09lastKey = false;%0A
%0A%09args =
@@ -126,16 +126,25 @@
%0A%0A%09args.
+slice(1).
forEach(
@@ -166,17 +166,61 @@
%7B%0A%09%09var
-i
+hasDash = item.indexOf('--') === 0,%0A%09%09%09equalI
dx = ite
@@ -258,21 +258,156 @@
%09//
--
-foo
-%0A%09%09if (i
+ test%0A%09%09// assign value to a proper key%0A%09%09if (!hasDash && lastKey !== false) %7B%0A%09%09%09key = lastKey;%0A%09%09%09val = item;%0A%09%09%7D%0A%09%09// --foo%0A%09%09else if (equalI
dx %3C
@@ -510,17 +510,22 @@
ring(2,
-i
+equalI
dx);%0A%09%09%09
@@ -545,17 +545,22 @@
bstring(
-i
+equalI
dx+1);%0A%09
@@ -563,16 +563,34 @@
);%0A%09%09%7D%0A%0A
+%09%09lastKey = key;%0A%0A
%09%09res%5Bke
|
a05d00143c97bfddd1f3f0101986d0d543741e01 | update file /lib/auth.js | lib/auth.js | lib/auth.js | 'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var queryString = require('querystring');
function auth() {
var router = express.Router();
router.all('/init', function(req, res) {
var params = req.body; // params.userId params.password
if (params && params.idToken) {
console.log('Checking credentials for user ' + params.idToken);
initSession(idToken, function(err, result){
if (err) {
console.log('Invalid credentials for user ' + params.idToken);
res.status(400);
res.json({message: 'Invalid credentials'});
return;
} else {
res.json({
status: 'ok',
userId: params.idToken,
sessionToken: params.idToken + '_sessiontoken',
authResponse: result
});
});
// .then(function(profileData) {
// console.log('Valid credentials for user ' + params.userId);
// res.json({
// status: 'ok',
// userId: params.userId,
// sessionToken: params.userId + '_sessiontoken',
// authResponse: profileData
// });
// }, function(err) {
// console.log('Invalid credentials for user ' + params.userId);
// res.status(400);
// res.json({message: 'Invalid credentials'});
// });
// } else {
// console.log('No username provided');
// res.status(400);
// res.json({message: 'Invalid credentials'});
}
return router;
});
}
/**
* Validate the user's session info with Google, and create a session object.
* This will also create a account object if necessary.
*
* @param {String} idToken an idToken provided by an Android Client (see : https://developers.google.com/identity/sign-in/android/backend-auth)
* @param {Callback} nodeCallback a node callback
*/
function initSession(idToken, nodeCallback) {
//validate with google
var options = {
url: 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' + querystring.escape(idToken),
method: 'GET'
};
request(options, handleGoogleResponse(sessionToken, authResponse, nodeCallback)).end();
}
module.exports = auth;
| JavaScript | 0.000002 | @@ -919,32 +919,46 @@
%7D);%0A
+ %7D%0A
%7D);%0A
|
285cb8b8b52b09c55372c4f1fc3275d9bb2b8951 | Add docu for Auth | lib/auth.js | lib/auth.js | var _ = require('underscore');
var Promise = require('bluebird');
function Auth() {
this._validConnections = [];
}
/**
* @param {BrowserConnection} connection
*/
Auth.prototype.isValidConnection = function(connection) {
return _.some(this._validConnections, connection);
};
/**
* @param {BrowserConnection} connection
* @param {String} sessionId
*/
Auth.prototype.authorizeConnection = function(connection, sessionId) {
if (this.isValidConnection(connection)) {
return Promise.resolve();
}
var self = this;
return this._authenticate(sessionId).then(function() {
self._validConnections.push(connection);
})
};
/**
* @param {String} sessionId
* @returns {Promise}
*/
Auth.prototype._authenticate = function(sessionId) {
// do rpc call to CM app and return boolean depending if user exists
return Promise.resolve();
};
Auth.prototype.canPublish = function(sessionId, streamChannelName) {
return Promise.resolve();
};
Auth.prototype.canSubscribe = function(sessionId, streamChannelName) {
return Promise.resolve();
};
module.exports = new Auth();
| JavaScript | 0 | @@ -751,108 +751,133 @@
%7B%0A
-// do rpc call to CM app and return boolean depending if user exists%0A
+return Promise.resolve();%0A%7D;%0A%0A/**%0A * @param %7BString%7D sessionId%0A * @param %7BString%7D streamChannelName%0A * @
return
-
+s %7B
Promise
-.resolve();%0A%7D;%0A
+%7D%0A */
%0AAut
@@ -974,16 +974,112 @@
();%0A%7D;%0A%0A
+/**%0A * @param %7BString%7D sessionId%0A * @param %7BString%7D streamChannelName%0A * @returns %7BPromise%7D%0A */%0A
Auth.pro
|
987b3116e99cff342466eff60147138c6e6400e8 | Add better error reporting for child process | bin/cli.js | bin/cli.js | #!/usr/bin/env node
var program = require('commander')
, path = require('path')
, fs = require('fs')
, exec = require('child_process').exec
program.version(require('../package').version)
.usage('[options] <command> to run before reloading the browser')
.option('-d, --directory <path>', 'absolute or relative to the CWD', path.resolve)
.option('-x, --exclude <regexp>', 'a regexp to match against file paths', RegExp)
.option('-i, --include <regexp>', 'a regexp to match against file paths', RegExp)
.option('-v, --verbose', 'show whats going on')
program.on('--help', function () {
console.log(' Example: monitor the "src" sub-folder and run `make dist/file.js`:')
console.log('')
console.log(' $ bfresh -d src make dist/file.js')
console.log('')
})
program.parse(process.argv)
// the env has to be set before loading the submodules
// which use debug statements
if (program.verbose) process.env.DEBUG = '*'
var fsmonitor = require('fsmonitor')
, LiveReloadServer = require('livereload-server')
, debug = require('debug')('bfresh')
// default to CWD
if (!program.directory) program.directory = process.cwd()
// Join the leftover args since they make up the command
var command = program.args.join(' ')
// Create the filter functions if they are required
var filter
if (program.include || program.exclude) {
debug('Including files matching: %s', program.include || 'all')
debug('Excluding files matching: %s', program.exclude || 'null')
filter = {
matches: program.include
? function (path) {
return !!path.match(program.include)
}
: function () {return true},
excludes: program.exclude
? function (path) {
return !!path.match(program.exclude)
}
: function () {return false}
}
}
var server = new LiveReloadServer({
id: "component",
name: "development",
version: "1.0",
protocols: {
monitoring: 7,
saving: 1
}
});
server.on('connected', function(connection) {
debug("Client connected (%s)", connection.id)
});
server.on('disconnected', function(connection) {
debug("Client disconnected (%s)", connection.id)
})
server.on('command', function(connection, message) {
debug("Received command %s: %j", message.command, message)
})
server.on('error', function(err, connection) {
console.warn("Error (%s): %s", connection.id, err.message)
})
server.on('livereload.js', function(request, response) {
debug("Serving livereload.js.")
fs.readFile(require.resolve('../livereload'), 'utf8', function(err, data) {
if (err) throw err
response.writeHead(200, {'Content-Length': data.length, 'Content-Type': 'text/javascript'})
response.end(data)
})
})
server.on('httprequest', function(url, request, response) {
response.writeHead(404)
response.end()
})
server.listen(function(err) {
if (err) console.warn("Listening failed: %s", err.message)
else console.warn("Listening on port %d.", server.port)
})
console.warn('Watching directory: %s', program.directory)
/*!
* Watch for changes
*/
fsmonitor.watch(program.directory, filter, function(change) {
debug("Change detected:\n" + change)
var connections = Object.keys(server.connections).map(function (id) {
return server.connections[id]
})
debug('Running command: "%s"', command)
exec(command, {stdio: 'inherit', maxBuffer: 2000*1024}, function (err) {
if (err) throw err
var file = change.modifiedFiles[0] || ''
// Refresh the browser
connections.forEach(function (con) {
try {
con.send({
command:'reload',
path:file,
liveCSS:true
})
} catch (e) {
console.warn(e.message)
}
})
})
if (!connections.length) console.warn('No browsers connected')
})
| JavaScript | 0.000001 | @@ -3291,24 +3291,40 @@
unction (err
+, stdout, stderr
) %7B%0A%09%09if (er
@@ -3336,16 +3336,52 @@
row err%0A
+%09%09if (stderr) console.error(stderr)%0A
%09%09var fi
|
ab72eeb35a728172681079b16ea51b626942ed44 | comment out debug console.log line | bin/iob.js | bin/iob.js | #!/usr/bin/env node
function iobCalc(treatment, time) {
var dia = profile_data.dia;
var diaratio = dia / 3;
var peak = 75 * diaratio;
var sens = profile_data.sens;
if (typeof time === 'undefined') {
var time = new Date();
}
if (treatment.insulin) {
var bolusTime=new Date(treatment.date);
var minAgo=(time-bolusTime)/1000/60;
if (minAgo < 0) {
var iobContrib=0;
var activityContrib=0;
}
if (minAgo < peak) {
var x = (minAgo/5 + 1) / diaratio;
var iobContrib=treatment.insulin*(1-0.001852*x*x+0.001852*x);
var activityContrib=sens*treatment.insulin*(2/dia/60/peak)*minAgo;
}
else if (minAgo < 180) {
var x = (minAgo-peak)/5 / diaratio;
var iobContrib=treatment.insulin*(0.001323*x*x - .054233*x + .55556);
var activityContrib=sens*treatment.insulin*(2/dia/60-(minAgo-peak)*2/dia/60/(60*dia-peak));
}
else {
var iobContrib=0;
var activityContrib=0;
}
return {
iobContrib: iobContrib,
activityContrib: activityContrib
};
}
else {
return '';
}
}
function iobTotal(treatments, time) {
var iob= 0;
var activity = 0;
if (!treatments) return {};
//if (typeof time === 'undefined') {
//var time = new Date();
//}
treatments.forEach(function(treatment) {
if(treatment.date < time.getTime( )) {
var tIOB = iobCalc(treatment, time);
if (tIOB && tIOB.iobContrib) iob += tIOB.iobContrib;
if (tIOB && tIOB.activityContrib) activity += tIOB.activityContrib;
}
});
return {
iob: iob,
activity: activity
};
}
function calcTempTreatments() {
var tempHistory = [];
var tempBoluses = [];
var now = new Date();
var timeZone = now.toString().match(/([-\+][0-9]+)\s/)[1]
for (var i=0; i < pumpHistory.length; i++) {
var current = pumpHistory[i];
//if(pumpHistory[i].date < time) {
if (pumpHistory[i]._type == "Bolus") {
console.log(pumpHistory[i]);
var temp = {};
temp.timestamp = current.timestamp;
//temp.started_at = new Date(current.date);
temp.started_at = new Date(current.timestamp + timeZone);
//temp.date = current.date
temp.date = temp.started_at.getTime();
temp.insulin = current.amount
tempBoluses.push(temp);
} else if (pumpHistory[i]._type == "TempBasal") {
if (current.temp == 'percent') {
continue;
}
var rate = pumpHistory[i].rate;
var date = pumpHistory[i].date;
if (i>0 && pumpHistory[i-1].date == date && pumpHistory[i-1]._type == "TempBasalDuration") {
var duration = pumpHistory[i-1]['duration (min)'];
} else if (i+1<pumpHistory.length && pumpHistory[i+1].date == date && pumpHistory[i+1]._type == "TempBasalDuration") {
var duration = pumpHistory[i+1]['duration (min)'];
} else { console.log("No duration found for "+rate+" U/hr basal"+date); }
var temp = {};
temp.rate = rate;
//temp.date = date;
temp.timestamp = current.timestamp;
//temp.started_at = new Date(temp.date);
temp.started_at = new Date(temp.timestamp + timeZone);
temp.date = temp.started_at.getTime();
temp.duration = duration;
tempHistory.push(temp);
}
//}
};
for (var i=0; i+1 < tempHistory.length; i++) {
if (tempHistory[i].date + tempHistory[i].duration*60*1000 > tempHistory[i+1].date) {
tempHistory[i].duration = (tempHistory[i+1].date - tempHistory[i].date)/60/1000;
}
}
var tempBolusSize;
var now = new Date();
var timeZone = now.toString().match(/([-\+][0-9]+)\s/)[1]
for (var i=0; i < tempHistory.length; i++) {
if (tempHistory[i].duration > 0) {
var netBasalRate = tempHistory[i].rate-profile_data.current_basal;
if (netBasalRate < 0) { tempBolusSize = -0.05; }
else { tempBolusSize = 0.05; }
var netBasalAmount = Math.round(netBasalRate*tempHistory[i].duration*10/6)/100
var tempBolusCount = Math.round(netBasalAmount / tempBolusSize);
var tempBolusSpacing = tempHistory[i].duration / tempBolusCount;
for (var j=0; j < tempBolusCount; j++) {
var tempBolus = {};
tempBolus.insulin = tempBolusSize;
tempBolus.date = tempHistory[i].date + j * tempBolusSpacing*60*1000;
tempBolus.created_at = new Date(tempBolus.date);
tempBoluses.push(tempBolus);
}
}
}
return [ ].concat(tempBoluses).concat(tempHistory);
return {
tempBoluses: tempBoluses,
tempHistory: tempHistory
};
}
if (!module.parent) {
var iob_input = process.argv.slice(2, 3).pop()
var profile_input = process.argv.slice(3, 4).pop()
var clock_input = process.argv.slice(4, 5).pop()
if (!iob_input || !profile_input) {
console.log('usage: ', process.argv.slice(0, 2), '<pumphistory> <profile.json> <clock.json>');
process.exit(1);
}
var cwd = process.cwd()
var all_data = require(cwd + '/' + iob_input);
var profile_data = require(cwd + '/' + profile_input);
var clock_data = require(cwd + '/' + clock_input);
var pumpHistory = all_data;
pumpHistory.reverse( );
var all_treatments = calcTempTreatments( );
console.log(all_treatments);
var treatments = all_treatments; // .tempBoluses.concat(all_treatments.tempHistory);
treatments.sort(function (a, b) { return a.date > b.date });
//var lastTimestamp = new Date(treatments[treatments.length -1].date + 1000 * 60);
console.log(clock_data);
var now = new Date();
var timeZone = now.toString().match(/([-\+][0-9]+)\s/)[1]
var clock_iso = clock_data + timeZone;
var clock = new Date(clock_iso);
console.log(clock);
var iobs = iobTotal(treatments, clock);
//var iobs = iobTotal(treatments, lastTimestamp);
// console.log(iobs);
console.log(JSON.stringify(iobs));
}
| JavaScript | 0 | @@ -2430,24 +2430,26 @@
+//
console.log(
|
42d02d64ef550492cab6f46407791727949f0f34 | add png to mappable content types | lib/blob.js | lib/blob.js | var AuthRequest = require('./authRequest')
, fs = require('fs');
function Blob() {
this.id = null;
}
Blob.fromFile = function blobFromFile(path, callback) {
var suffix_mappings = [
{ suffix: 'jpg', content_type: "image/jpeg", message_type: "image" },
{ suffix: 'jpeg', content_type: "image/jpeg", message_type: "image" }
];
var blob = new Blob();
suffix_mappings.forEach(function(suffix_mapping) {
if (path.endsWith(suffix_mapping.suffix)) {
blob.content_type = suffix_mapping.content_type;
blob.message_type = suffix_mapping.message_type;
}
});
fs.stat(path, function(err, stats) {
if (err) return callback(err);
blob.timestamp = stats.mtime;
blob.content_length = stats.size;
return callback(null, blob);
});
};
Blob.prototype.save = function(session, stream, callback) {
if (!session.service.config.blobs_endpoint) return callback("blob endpoint not available on this service");
var self = this;
stream.pipe(
AuthRequest.post(session, { url: session.service.config.blobs_endpoint,
headers: { 'Content-Type': self.content_type,
'Content-Length': self.content_length } }, function (err, resp, body) {
if (err) return callback(err, null);
if (resp.statusCode != 200) return callback(resp.statusCode, null);
try {
var body_json = JSON.parse(body);
} catch (err) {
return callback(err, null);
}
self.url = session.service.config.blobs_endpoint + "/" + body_json.blob.id;
for (var prop in body_json.blob) {
self[prop] = body_json.blob[prop];
}
return callback(null, self);
})
);
};
module.exports = Blob;
| JavaScript | 0 | @@ -324,16 +324,93 @@
%22image%22
+ %7D,%0A %7B suffix: 'png', content_type: %22image/png%22, message_type: %22image%22
%7D%0A%09%5D;%0A%0A
@@ -646,16 +646,169 @@
%7D%0A%09%7D);%0A%0A
+ if (!blob.content_type %7C%7C !blob.message_type) %7B%0A console.log('WARNING: message_type not assigned in Blob.fromFile for path: ' + path);%0A %7D%0A%0A
%09fs.stat
|
69a277e147c113ff330539103c377254cbf8ccf2 | use data.url instead of localhost | gatsby-browser.js | gatsby-browser.js | import React from 'react';
import ReactGA from 'react-ga';
import { Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import createStore from './src/state/createStore';
const { ga_track_id } = require('./data/config');
const isLocalDevelopment = () =>
window && window.location.hostname.indexOf('localhost') !== -1;
if (isLocalDevelopment() === false) {
ReactGA.initialize(ga_track_id);
ReactGA.ga('require', 'GTM-WHP7SC5');
console.log('Welcome to online environment.');
}
// Inspired by APlayer
console.log(
`${'\n'} %c CALPA %c https://calpa.me ${'\n'}${'\n'}`,
'color: #6cf; background: #030307; padding:5px 0;',
'background: #6cf; padding:5px 0;',
);
exports.replaceRouterComponent = ({ history }) => {
const store = createStore();
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('./src/reducers', () => {
const nextRootReducer = require('./src/reducers/index');
store.replaceReducer(nextRootReducer);
});
}
const ConnectedRouterWrapper = ({ children }) => (
<Provider store={store}>
<Router history={history}>{children}</Router>
</Provider>
);
return ConnectedRouterWrapper;
};
if (isLocalDevelopment() !== true) {
exports.onRouteUpdate = (state) => {
ReactGA.pageview(state.location.pathname);
};
}
| JavaScript | 0.000004 | @@ -195,16 +195,21 @@
%0Aconst %7B
+ url,
ga_trac
@@ -308,45 +308,42 @@
tion
-.hostname.indexOf('localhost')
+ && window.location.origin
!==
--1
+url
;%0A%0Ai
|
467741cb179c7e80e13c9c126f4877cc2e45b74c | Trim the input to deal with accidental spaces | quiz.js | quiz.js | /**
* quiz.js - The quiz engine
*
* Author: Steve Kerrison <[email protected]>
* Copyright: Steve Kerrison 2015
* License: MIT, see bundled LICENSE file
*
**/
function NBQuiz() {
"use strict";
this.configs = {
'simple': {
'questions': 20,
'bases': [2, 10],
'pow': 4, // Unsigned: 0--2^(pow)-1, signed: -2^(pow-1) -- 2^(pow-1)-1
'signed': false
},
'medium': {
'questions': 20,
'bases': [2, 10, 16],
'pow': 4,
'signed': true
},
'hard': {
'questions': 30,
'bases': [2, 10, 16],
'pow': 6,
'signed': true
},
'infinite': {
'questions': 0,
'bases': [2, 8, 10, 16, 32, 36],
'pow': 12,
'signed': true
}
};
this.choose = function (a) {
return a[Math.floor(Math.random() * a.length)];
};
this.toBaseString = function (v, b) {
var s = '';
if (b !== 10) {
var ndigits = (Math.pow(2, this.config.pow) - 1).toString(b).length;
s = (v >>> 0).toString(b);
s = String("0".repeat(ndigits) + s).slice(-ndigits);
} else {
s = v.toString(10);
}
return s;
};
this.answer = function () {
$('#conversion').prop('disabled', true);
$('form#quiz').off('submit').submit($.proxy(this.nextq, this));
this.total += 1;
/* Ensure guess is formatted as requested */
var guess = $('#conversion').val();
var answer = this.toBaseString(this.value, this.to);
if (guess === answer) {
$('#anscorrect').show();
this.score += 1;
} else {
$('#ansincorrect').show().find('.answer span').text(answer);
}
$('#correct').text(this.score);
$('#total').text(this.total);
$('#progress').show();
/* Deal with quiz end or continuous quizzing */
if (this.total === this.config.questions || this.config.questions === 0) {
this.perct = (this.score / this.total * 100.0).toFixed(2);
$('#percentage span').text(this.perct);
$('#percentage').show();
}
if (this.total === this.config.questions) {
$('form#quiz input[type=submit]').val('Restart').focus();
$('form#quiz').off('submit').submit($.proxy(this.init, this));
$('#end').show();
} else {
$('form#quiz input[type=submit]').val('Continue').focus();
}
return false;
};
this.nextq = function () {
/* Calculate the value we want to use from the quiz mode */
this.base = this.choose(this.config.bases);
this.value = Math.floor(Math.random() * Math.pow(2, this.config.pow));
this.signed = false;
this.currq += 1;
if (this.config.signed === true && Math.random() > 0.5) {
this.signed = true;
this.value -= Math.pow(2, this.config.pow - 1);
}
this.to = this.base;
do {
this.to = this.choose( this.config.bases );
} while (this.to === this.base); //Ugh
if (this.to == 10) {
this.ndigits = this.toBaseString(this.value, this.to).length;
} else {
this.ndigits = (Math.pow(2, this.config.pow) - 1).toString(this.to).length;
}
/* Setup the content */
$('#orig').text(this.base);
$('#val').text(this.toBaseString(this.value, this.base));
$('#base').text(this.to);
$('#ndigit').text(this.ndigits);
$('#qno').text(this.currq);
$('#qof').text(this.config.questions > 0 ? ' of ' + this.config.questions : '');
if (this.to === 10) {
$('#sign').text( this.signed ? 'signed (negative symbol where needed)' : 'unsigned');
} else {
$('#sign').text( this.signed ? "2's complement signed" : 'unsigned');
}
/* Switch the submit handler */
$('form#quiz input[type=submit]').val('Check');
$('#conversion').prop('disabled', false).val('').focus();
$('#anscorrect, #ansincorrect').hide();
$('form#quiz').off('submit').submit($.proxy(this.answer, this));
return false;
};
this.init = function () {
$('#nojs').hide();
$('form#quiz').trigger('reset');
$('#start').show();
this.score = 0;
this.currq = 0;
this.total = 0;
this.perct = 0;
this.config = null;
$('#anscorrect, #ansincorrect, #end, #percentage, #progress, #question').hide();
return false;
};
this.start = function (difficulty) {
this.config = this.configs[difficulty];
$('#start').hide();
$('#question').show();
this.score = 0;
this.currq = 0;
this.total = 0;
this.perct = 0;
this.nextq();
};
$('form#quiz input[name=difficulty]').change( $.proxy(function () {
this.start($('form#quiz input[name=difficulty]:checked').val());
return false;
}, this));
}
$(function(){
"use strict";
var Q = new NBQuiz();
Q.init();
});
| JavaScript | 0.0003 | @@ -1753,16 +1753,23 @@
').val()
+.trim()
;%0A
|
d69924d5125bd92547ee801a85402e33131308da | Support using lusca.csrf() without a body | lib/csrf.js | lib/csrf.js | 'use strict';
var token = require('./token');
/**
* CSRF
* https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
* @param {Object} options
* key {String} The name of the CSRF token in the model. Default "_csrf".
* impl {Object} An object with create/validate methods for custom tokens. Optional.
* header {String} The name of the response header containing the CSRF token. Default "x-csrf-token".
*/
module.exports = function (options) {
var impl, key, header, secret;
options = options || {};
key = options.key || '_csrf';
impl = options.impl || token;
header = options.header || 'x-csrf-token';
secret = options.secret || '_csrfSecret';
return function csrf(req, res, next) {
var method, validate, _impl, _token;
//call impl
_impl = impl.create(req, secret);
validate = impl.validate || _impl.validate;
_token = _impl.token || _impl;
// Set the token
res.locals[key] = _token;
// Move along for safe verbs
method = req.method;
if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') {
return next();
}
// Validate token
_token = req.body[key] || req.headers[header];
if (validate(req, _token)) {
next();
} else {
res.statusCode = 403;
next(new Error('CSRF token mismatch'));
}
};
}; | JavaScript | 0 | @@ -1220,24 +1220,37 @@
_token =
+ (req.body &&
req.body%5Bke
@@ -1251,16 +1251,17 @@
ody%5Bkey%5D
+)
%7C%7C req.
@@ -1457,8 +1457,9 @@
%7D;%0A%7D;
+%0A
|
887d430a49a130fe849a0952ffa519028af06c96 | Handle 'wrong credentials' case | bin/sub.js | bin/sub.js | #!/usr/bin/env node
var mqtt = require('../')
, path = require('path')
, fs = require('fs')
, concat = require('concat-stream')
, helpMe = require('help-me')({
dir: path.join(__dirname, '..', 'doc')
})
, minimist = require('minimist');
function start(args) {
args = minimist(args, {
string: ['hostname', 'username', 'password', 'key', 'cert', 'ca'],
integer: ['port', 'qos', 'keepAlive'],
boolean: ['stdin', 'help', 'clean', 'insecure'],
alias: {
port: 'p',
hostname: ['h', 'host'],
topic: 't',
qos: 'q',
clean: 'c',
keepalive: 'k',
clientId: ['i', 'id'],
username: 'u',
password: 'P',
protocol: ['C', 'l'],
verbose: 'v',
help: '-H',
ca: 'cafile'
},
default: {
host: 'localhost',
qos: 0,
retain: false,
clean: true,
keepAlive: 30 // 30 sec
}
})
if (args.help) {
return helpMe.toStdout('subscribe');
}
args.topic = args.topic || args._.shift();
if (!args.topic) {
console.error('missing topic\n')
return helpMe.toStdout('subscribe');
}
if (args.key) {
args.key = fs.readFileSync(args.key);
}
if (args.cert) {
args.cert = fs.readFileSync(args.cert);
}
if (args.ca) {
args.ca = fs.readFileSync(args.ca);
}
if (args.key && args.cert && !args.protocol) {
args.protocol = 'mqtts';
}
if (args.insecure) {
args.rejectUnauthorized = false;
}
if (args.port){
if (typeof args.port !== 'number') {
console.warn('# Port: number expected, \'%s\' was given.', typeof args.port);
return;
}
}
if (args['will-topic']) {
args.will = {};
args.will.topic = args['will-topic'];
args.will.payload = args['will-message'];
args.will.qos = args['will-qos'];
args.will.retain = args['will-retain'];
}
args.keepAlive = args['keep-alive'];
var client = mqtt.connect(args);
client.on('connect', function() {
client.subscribe(args.topic, { qos: args.qos });
});
client.on('message', function(topic, payload) {
if (args.verbose) {
console.log(topic, payload.toString())
} else {
console.log(payload.toString())
}
});
}
module.exports = start;
if (require.main === module) {
start(process.argv.slice(2))
}
| JavaScript | 0 | @@ -2228,16 +2228,215 @@
%7D%0A %7D);%0A
+ %0A client.on('error', function(err)%7B%0A // Handle 'No Authentication'%0A console.warn(err);%0A client.end();%0A %7D);%0A // TODO: alert impossibility to subscribe to a topic, 'No authorization'.%0A %0A
%7D%0A%0Amodul
|
c466b2c7156da88d948ffb68b043dc38d972d072 | Send body with 204 for /update | bin/web.js | bin/web.js | var _ = require('lodash');
var Q = require('q');
var url = require('url');
var express = require('express');
var useragent = require('express-useragent');
var basicAuth = require('basic-auth');
var config = require('../lib/config');
var versions = require('../lib/versions');
var platforms = require('../lib/platforms');
var download = require('../lib/download');
var app = express();
var startTime = Date.now();
app.use(useragent.express());
app.get('/', function (req, res) {
res.redirect('/download/version/latest');
});
// Download links
app.get('/download/version/:tag/:platform?', function (req, res, next) {
var platform = req.params.platform;
// Detect platform from useragent
if (!platform) {
if (req.useragent.isMac) platform = platforms.OSX;
if (req.useragent.isWindows) platform = platforms.WINDOWS;
if (req.useragent.isLinux) platform = platforms.LINUX;
if (req.useragent.isLinux64) platform = platforms.LINUX_64;
}
if (!platform) return next(new Error('No platform specified and impossible to detect one'));
versions.resolve({
platform: platform,
tag: req.params.tag
})
.then(function(version) {
var platformVersion = version.platforms[platform];
if (!platformVersion) throw new Error("No download available for platform "+platform+" for version "+version.tag);
return download.stream(platformVersion.download_url, res);
})
.fail(next);
});
app.get('/download/:platform?', function (req, res, next) {
res.redirect('/download/version/latest'+(req.params.platform? '/'+req.params.platform : ''));
});
// Auto-updater
app.get('/update', function(req, res, next) {
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
var platform, tag;
Q()
.then(function() {
if (!req.query.version) throw new Error('Requires "version" parameter');
if (!req.query.platform) throw new Error('Requires "platform" parameter');
platform = platforms.detect(req.query.platform);
tag = req.query.version;
return versions.resolve({
tag: '>='+req.query.version,
platform: platform
});
})
.then(function(version) {
var status = 200;
if (version.tag == tag) status = 204;
res.status(status).send({
"url": url.resolve(fullUrl, "/download/version/"+version.tag+"/"+platform),
"name": version.tag,
"notes": version.notes,
"pub_date": version.published_at.toISOString()
});
}, function() {
res.status(204);
});
});
// Private API
if (config.api.username && config.api.password) {
app.use('/api', function (req, res, next) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.send(401);
};
var user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name === config.api.username && user.pass === config.api.password) {
return next();
} else {
return unauthorized(res);
};
});
}
app.get('/api/status', function (req, res, next) {
res.send({
uptime: (Date.now() - startTime)/1000
});
});
app.get('/api/versions', function (req, res, next) {
versions.list()
.then(function(results) {
res.send(results);
}, next);
});
app.get('/api/version/:tag', function (req, res, next) {
versions.get(req.params.tag)
.then(function(result) {
res.send(result);
}, next);
});
app.get('/api/stats/platforms', function (req, res, next) {
versions.list()
.then(function(_versions) {
var result = {};
_.each(_versions, function(version) {
_.each(version.platforms, function(platform, _platformID) {
var platformID = platforms.toType(_platformID);
result[platformID] = (result[platformID] || 0) + platform.download_count;
});
});
res.send(result);
}, next);
});
// Error handling
app.use(function(req, res, next) {
res.status(404).send("Page not found");
});
app.use(function(err, req, res, next) {
var msg = err.message || err;
var code = 500;
// Return error
res.format({
'text/plain': function(){
res.status(code).send(msg);
},
'text/html': function () {
res.status(code).send(msg);
},
'application/json': function (){
res.status(code).send({
'error': msg,
'code': code
});
}
});
});
var server = app.listen(config.port, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Listening at http://%s:%s', host, port);
});
| JavaScript | 0 | @@ -2619,16 +2619,35 @@
tus(204)
+.send('No updates')
;%0A %7D)
|
47bc35cb84ba903ca604697f3004baf2a3f8f5a2 | fix wrong jsDoc for render method | src/sap.m/src/sap/m/DynamicPageHeaderRenderer.js | src/sap.m/src/sap/m/DynamicPageHeaderRenderer.js | /*!
* ${copyright}
*/
sap.ui.define([], function () {
"use strict";
/**
* oDynamicPage Header renderer.
* @namespace
*/
var DynamicPageHeaderRenderer = {};
/**
* Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm The RenderManager that can be used for writing to the Render-Output-Buffer
* @param {sap.ui.core.Control} oPage An object representation of the control that should be rendered
*/
DynamicPageHeaderRenderer.render = function (oRm, oDynamicPageHeader) {
var aContent = oDynamicPageHeader.getContent();
// Dynamic Page Layout Header Root DOM Element.
oRm.write("<header");
oRm.writeControlData(oDynamicPageHeader);
oRm.writeAttribute("tabindex", "0");
oRm.writeAccessibilityState({
role: "region"
});
oRm.addClass("sapContrastPlus");
oRm.addClass("sapMDynamicPageHeader");
oRm.writeClasses();
oRm.write(">");
// Header Content
if (aContent.length > 0) {
oRm.write("<div");
oRm.addClass("sapMDynamicPageHeaderContent");
oRm.writeClasses();
oRm.write(">");
aContent.forEach(oRm.renderControl);
oRm.write("</div>");
if (oDynamicPageHeader.getPinnable() && !sap.ui.Device.system.phone) {
DynamicPageHeaderRenderer._renderPinUnpinArea(oDynamicPageHeader, oRm);
}
}
oRm.write("</header>");
};
DynamicPageHeaderRenderer._renderPinUnpinArea = function (oDynamicPageHeader, oRm) {
oRm.write("<div");
oRm.addClass("sapMDynamicPageHeaderPinButtonArea");
oRm.writeClasses();
oRm.write(">");
oRm.renderControl(oDynamicPageHeader._getPinButton());
oRm.write("</div>");
};
return DynamicPageHeaderRenderer;
}, /* bExport= */ true);
| JavaScript | 0.000001 | @@ -423,20 +423,33 @@
ntrol%7D o
-Page
+DynamicPageHeader
An obje
|
fd55a5beec84a9d789972767c29fea07a8c76b30 | Check if the node has already been added | src/server/graph-generation/interaction/index.js | src/server/graph-generation/interaction/index.js | const _ = require('lodash');
const pc = require('../../pathway-commons');
const logger = require('./../../logger');
const LRUCache = require('lru-cache');
const cache = require('../../cache');
const { PC_CACHE_MAX_SIZE, MAX_SIF_NODES } = require('../../../config');
let interactionType2Label = type => {
switch( type ){
case 'interacts-with':
return 'Binding';
case 'controls-state-change-of':
case 'controls-phosphorylation-of':
return 'Modification';
case 'controls-expression-of':
return 'Expression';
case 'controls-transport-of':
case 'catalysis-precedes':
return 'Other';
default:
return '';
}
};
let participantTxt2CyJson = ( parsedInteractionParts, sourceIds ) => {
let sourceName = parsedInteractionParts[0] || '';
let targetName = parsedInteractionParts[2] || '';
let isSourceQueried = sourceIds.includes(sourceName);
let isTargetQueried = sourceIds.includes(targetName);
return [
{
data: {
class: 'ball',
id: sourceName,
queried: isSourceQueried,
metric: isSourceQueried ? Number.MAX_SAFE_INTEGER : 0
}
},
{
data: {
class: 'ball',
id: targetName,
queried: isTargetQueried,
metric: isTargetQueried ? Number.MAX_SAFE_INTEGER : 0
}
}
];
};
let interactionTxt2CyJson = parsedInteractionParts => {
let participant0 = parsedInteractionParts[0];
let participant1 = parsedInteractionParts[2];
let type = parsedInteractionParts[1];
let summary = type === 'catalysis-precedes' ? `${participant0} and ${participant1} in catalysis` : `${participant0} ${type.split('-').join(' ')} ${participant1}`;
let readableType = interactionType2Label(type);
let pubmedIds = ( parsedInteractionParts[4] || '').split(';');
let mediatorIds = ( parsedInteractionParts[6] || '').split(';');
let pcIds = mediatorIds.filter( id => !id.toUpperCase().includes('REACTOME'));
let reactomeIds = mediatorIds.filter( id => id.toUpperCase().includes('REACTOME'));
return {
data: {
id: summary,
type,
source: participant0,
target: participant1,
pubmedIds,
pcIds,
reactomeIds
},
classes: readableType
};
};
let sifText2CyJson = (sifText, sourceIds) => {
let interactionsData = sifText.split('\n');
let nodeId2Json = {};
let edges = [];
interactionsData.forEach( interactionTxtLine => {
if ( !interactionTxtLine.length ) return;
let parsedInteractionParts = interactionTxtLine.split('\t');
let participantsJson = participantTxt2CyJson( parsedInteractionParts, sourceIds );
participantsJson.forEach( partcipant => nodeId2Json[partcipant.data.id] = partcipant );
let interactionJson = interactionTxt2CyJson( parsedInteractionParts );
let source = interactionJson.data.source;
let target = interactionJson.data.target;
let srcJson = nodeId2Json[source];
let tgtJson = nodeId2Json[target];
if( srcJson ){ srcJson.data.metric += 1; }
if( tgtJson ){ tgtJson.data.metric += 1; }
edges.push(interactionJson);
} );
return {
nodes: Object.values(nodeId2Json),
edges
};
};
let filterByDegree = (nodes, edges) => {
// take 50 nodes with the highest degree
// filter all nodes with degree 0
let filteredNodes = nodes.sort( (n0, n1) => {
return n1.data.metric - n0.data.metric;
} ).slice(0, MAX_SIF_NODES).filter( n => n.data.metric !== 0 );
let filteredNodeIdMap = {};
filteredNodes.forEach( node => filteredNodeIdMap[node.data.id] = true );
// filter edges that still have their source/target in the filtered node set
let filteredEdges = edges.filter( edge => {
let source = edge.data.source;
let target = edge.data.target;
// some edges may have a sorce or target filtered, we require both for
// it to be a valid edge in the network json
return filteredNodeIdMap[source] && filteredNodeIdMap[target];
});
return { nodes: filteredNodes, edges: filteredEdges };
};
let getInteractionsCyJson = (sifText, geneIds) => {
let { nodes, edges } = sifText2CyJson( sifText, geneIds );
let filteredCyJson = filterByDegree( nodes, edges );
return filteredCyJson;
};
let getInteractionsNetwork = sources => {
let uniqueGeneIds = _.uniq([].concat(sources).map( source => source.toUpperCase() ) );
let params = {
source: uniqueGeneIds
};
return pc.sifGraph( params ).then( res => {
return {
network: getInteractionsCyJson(res, uniqueGeneIds)
};
}).catch( e => {
logger.error( e );
throw e;
});
};
let pcCache = LRUCache({ max: PC_CACHE_MAX_SIZE, length: () => 1 });
module.exports = {
sifText2CyJson,
getInteractionsCyJson,
getInteractionGraphFromPC: cache(getInteractionsNetwork, pcCache)
}; | JavaScript | 0 | @@ -2647,24 +2647,25 @@
orEach( part
+i
cipant =%3E no
@@ -2661,16 +2661,73 @@
ipant =%3E
+ %7B%0A if ( !_.has(nodeId2Json, participant.data.id ) )
nodeId2
@@ -2731,24 +2731,25 @@
Id2Json%5Bpart
+i
cipant.data.
@@ -2758,23 +2758,30 @@
%5D = part
+i
cipant
-
+;%0A %7D
);%0A%0A
|
5daf897b097a35e4c9f074fe817e458d762b3ac1 | set this.hash to null by default | lib/file.js | lib/file.js | if (global.GENTLY) require = GENTLY.hijack(require);
var util = require('./util'),
WriteStream = require('fs').WriteStream,
EventEmitter = require('events').EventEmitter,
crypto = require('crypto');
function File(properties) {
EventEmitter.call(this);
this.size = 0;
this.path = null;
this.name = null;
this.type = null;
this.lastModifiedDate = null;
this._writeStream = null;
if(typeof properties === 'object') {
for (var key in properties) {
this[key] = properties[key];
}
}
if(typeof this.hash === 'string') {
this.hash = crypto.createHash(properties.hash);
}
this._backwardsCompatibility();
}
module.exports = File;
util.inherits(File, EventEmitter);
// @todo Next release: Show error messages when accessing these
File.prototype._backwardsCompatibility = function() {
var self = this;
this.__defineGetter__('length', function() {
return self.size;
});
this.__defineGetter__('filename', function() {
return self.name;
});
this.__defineGetter__('mime', function() {
return self.type;
});
};
File.prototype.open = function() {
this._writeStream = new WriteStream(this.path);
};
File.prototype.write = function(buffer, cb) {
var self = this;
this._writeStream.write(buffer, function() {
if(self.hash) {
self.hash.update(buffer);
}
self.lastModifiedDate = new Date();
self.size += buffer.length;
self.emit('progress', self.size);
cb();
});
};
File.prototype.end = function(cb) {
var self = this;
this._writeStream.end(function() {
if(self.hash) {
self.hash = self.hash.digest('hex');
}
self.emit('end');
cb();
});
};
| JavaScript | 0.000002 | @@ -335,24 +335,44 @@
ype = null;%0A
+ this.hash = null;%0A
this.lastM
@@ -427,49 +427,8 @@
%0A %0A
- if(typeof properties === 'object') %7B%0A
fo
@@ -459,18 +459,16 @@
) %7B%0A
-
this%5Bkey
@@ -488,22 +488,16 @@
s%5Bkey%5D;%0A
- %7D%0A
%7D%0A%0A i
|
020f4257fa14d7df6b1e0fe88141c0515f0d3844 | Update script.js | public/js/script.js | public/js/script.js |
$(document).ready(function() {
var modal = $('#upload-area');
modal.css('margin-top', (window.innerHeight/2) - $('#upload').height());
$('#file-dialog').on('change', function () {
var files = $(this).get(0).files;
if (files.length === 0){
return 0;
}
var formData = new FormData();
for (var index = 0; index < files.length; index++){
var file = files[index];
formData.append('files', file, file.name);
}
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log('upload successful!');
},
xhr: function () {
var xhr = new XMLHttpRequest();
// xhr.upload.addEventListener('progress', function () {
//
// });
return xhr;
}
});
});
});
function search(){
var toSearch = document.getElementById("search-id").value;
if( toSearch ==='' ){
alert("Please fill the search box...!!!!!!");
return false;
}
else
{
var url=" https://api.cognitive.microsoft.com/bing/v5.0/search?q=";
url=url+toSearch+"&count=10&offset=0&mkt=en-us&safesearch=Moderate";
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Ocp-Apim-Subscription-Key", "c9a9ed180e704db79a2419e518d5a637");
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4) {
// time to partay!!!
var response = JSON.parse(xhr.responseText);
console.log(response);
}
}
}
}
| JavaScript | 0.000002 | @@ -1754,16 +1754,23 @@
response
+.images
);%0A %7D
|
64751c3deaccb4203a25bc38b54e5c5823f69bd3 | Update the little layout of BugTracking.js (space <br/>) <br/>) | Team4of5/src/Team4of5_App/BugTracking/BugTracking.js | Team4of5/src/Team4of5_App/BugTracking/BugTracking.js | import React from 'react';
import ReactDOM from 'react-dom';
import Navbar from '../Navbar/Nav.js';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import BugTypeTable from './BugTypes.js';
import BugNotification from './BugNotification.js';
import BugTrackTableSearch from './BugTrackingToolBar.js';
class BugTracking extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<div>
<BugNotification />
</div>
<div>
<BugTypeTable />
</div>
<div>
<BugTrackTableSearch />
</div>
</div>
);
}
}
export default BugTracking;
| JavaScript | 0 | @@ -505,33 +505,60 @@
%0A %3C/div%3E%0A
+ %3Cbr/%3E%0A %3Cbr/%3E
%0A
-
%3Cdiv%3E%0A
@@ -595,25 +595,52 @@
%3C/div%3E%0A
+ %3Cbr/%3E%0A %3Cbr/%3E
%0A
-
%3Cdiv
@@ -673,24 +673,24 @@
leSearch /%3E%0A
-
%3C/di
@@ -688,24 +688,52 @@
%3C/div%3E%0A
+ %3Cbr/%3E%0A %3Cbr/%3E%0A
%3C/div%3E
|
6fc33c73d72df1b39f2f8b3c321324bf709a857d | Use hasOwnProperty to detect lastevaluatedkey | read.js | read.js | /*jshint esversion: 6 */
/* globals console, require, exports*/
'use strict';
// Load required libraries
const AWSXRay = require('aws-xray-sdk-core');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
const dynamodb = new AWS.DynamoDB.DocumentClient();
const moment = require('moment-timezone');
exports.handler = (event, context, callback) => {
console.log(event.startTime);
let startTime;
// If there is a lastupdated parameter, scan from that time
if (Number(event.lastupdated) > 1) {
console.log('Detecting lastupdated variable, ' + event.lastupdated);
startTime = Number(event.lastupdated);
} else {
startTime = 1;
}
// Set scan limit to 20 if not present or greater than 20
let limit = 20;
if (Number(event.limit) < 20) {
console.log('Detecting limit variable ' + event.limit);
limit = event.limit;
}
console.log('Scanning from greater than ' + startTime);
// Set scanning parameters
let params = {
TableName: 'impact-map',
// Only get Coordinates and Action data from the table
ProjectionExpression: 'Coordinates, #b',
// Only return items that have an Added time that is greater than startTime
FilterExpression: 'Added > :start',
ExpressionAttributeNames: {
// Set an 'alias' for the word, 'Action', because 'Action' is a reserved word in DynamoDB
'#b': 'Action'
},
ExpressionAttributeValues: {
// Set an 'alias' for startTime, called ':start'
':start': startTime
},
Limit: limit
};
if (event.exclusivestartkey.length > 1) {
console.log('exclusivestartkey detected ' + event.exclusivestartkey);
params.ExclusiveStartKey.Id = event.exclusivestartkey;
}
console.log(params);
console.log('Scanning table.');
dynamodb.scan(params, onScan);
function onScan(err, data) {
// Log error if scanning returns err
if (err) {
console.error('Unable to scan the table. Error JSON:', JSON.stringify(err, null, 2));
} else {
console.log('Scan succeeded.');
// Continue scanning if we have more items, because scan can retrieve a maximum of 1MB of data
if (typeof data.LastEvaluatedKey != 'undefined') {
console.log('LastEvaluatedKey detected');
}
// Returns the item data back to the client
console.log('Returning ' + data.Items.length + ' items to the client');
callback(null, data);
}
}
};
| JavaScript | 0 | @@ -1512,24 +1512,40 @@
if (event.
+hasOwnProperty('
exclusivesta
@@ -1553,19 +1553,44 @@
tkey
-.length %3E 1
+') && event.exclusivestartkey !== ''
) %7B%0A
|
2d4beb72de35c63200e12616f130eb10b1b9fef9 | bump version | Better_Paylocity.user.js | Better_Paylocity.user.js | // ==UserScript==
// @name Better Paylocity
// @namespace betterui
// @description Improvements to the Paylocity UI
// @include https://webtime2.paylocity.com/webtime/Employee/Timesheet
// @include https://webtime2.paylocity.com/webtime/Employee/Timesheet#
// @downloadURL https://raw.githubusercontent.com/Anthropohedron/better-paylocity/master/Better_Paylocity.user.js
// @version 0.1.1
// @grant GM_addStyle
// @grant unsafeWindow
// ==/UserScript==
(function(win, doc) {
// the page can't call functions defined in this context, so export to the
// page
function ef(fn) { return exportFunction(fn, win); }
// exported function to be called by jQuery's each
var eachWorked = ef(function eachWorked() { this.value = 9; });
// make any row with an unset "Pay Type" column default to "Worked"
function defaultWorked() {
win.$('tr.pay-type-description > td > select > option[value=0][selected]')
.parent()
.each(eachWorked);
}
// make custom Add Row button markup to be used later
var addRowBtn = win.$.parseHTML([
'<div id="myAddRowBtn" class="t-link">',
'<span class="t-sprite p-tool-add"></span>',
'Add Row',
'</div>'
].join(''))[0];
// attach handlers to the Add Row button click
win.$(addRowBtn)
.click(win.addShift)
.click(ef(defaultWorked));
// set up some CSS
GM_addStyle([
// just let the page do the scrolling
'div#TimesheetContainer { max-height: none; } ',
// make the Add Row button look good
'#myAddRowBtn {',
'background: #DEF1FA;',
'margin-top: 10px;',
'border: 1px solid;',
'padding: 3px;',
'border-radius: 8px;',
'} ',
'#myAddRowBtn .t-sprite {',
'margin-right: 3px;',
'} '
].join(''));
// default all unset rows to Worked
defaultWorked();
// wrap row selection to place the Add Row button at the associated day
var wrappedOnSelect = win.selectEntryRow;
function wrapOnSelect(row) {
// call wrapped function
var result = wrappedOnSelect(row);
// get the newly-selected row
var row = win.getSelectedEntryRow();
if (row) {
// if it's appropriate, add the Add Row button near the row
row.parents('.day-end').prev('td.day').append(addRowBtn);
} else {
// no appropriate row, so make sure the Add Row button is gone
win.$(addRowBtn).remove();
}
return result;
}
win.selectEntryRow = ef(wrapOnSelect);
})(unsafeWindow, unsafeWindow.document);
| JavaScript | 0 | @@ -401,17 +401,17 @@
0.1.
-1
+2
%0A// @gra
|
d5c15e9995004dc26c2d0713c3bde95b62fddc94 | Remove traces of jshint config | lib/assert/imgLoaded_client.js | lib/assert/imgLoaded_client.js | /* jshint browser: true */
'use strict';
// returns true if the image is loaded and decoded,
// or a number, if it didn't find one single image,
// or a helpful error if it wasn't an image,
// or the path, if it found some non-loaded image
module.exports = function imgLoaded(selector) {
function describe(elem) {
var tag = (elem.tagName || '').toLowerCase();
if (elem.id) {
tag += '#' + elem.id;
}
var classes = elem.className.replace(/^\s+|\s+$/g, '');
if (classes) {
tag += '.' + classes.replace(/\s+/g, '.');
}
return tag;
}
var imgs = document.querySelectorAll(selector);
if (imgs.length !== 1) {
return imgs.length;
}
var img = imgs[0];
if (!img.src) {
if ((img.tagName || '').match(/^img$/i)) {
return 'src-less ' + describe(img);
}
return 'non-image ' + describe(img);
}
return img.complete && img.naturalWidth ? true : img.src;
};
| JavaScript | 0.000001 | @@ -1,31 +1,4 @@
-/* jshint browser: true */%0A
'use
|
d59e52f96ad70d13f35070d70ee29b7fe8954cc9 | store hier by type | nodejs/lib/annotators/gateAnnotator.js | nodejs/lib/annotators/gateAnnotator.js | // GATE annotator
// extracts instance annotations from markup
// relative location of sensebase for libs FIXME
var sensebase = '../../../node_modules/sensebase/';
var querystring = require('querystring'), http = require('http'), cheerio = require('cheerio');
var annoLib = require(sensebase + 'lib/annotators/annotateLib'), annotations = require(sensebase + 'lib/annotations'), utils = require('../../lib/utils.js');
// local configuration
var instanceProps = utils.getProperties('./pipeline.properties');
// indicate which annotations are interesting in the properties file
var wantedAnnos = instanceProps.annotations.split(',');
var name = instanceProps.name;
// wait for annotation requests
annoLib.requestAnnotate(function(combo) {
var uri = combo.uri, html = combo.html, text = combo.text, selector = combo.selector;
GLOBAL.info(name, uri, selector, text ? text.length : 'notext');
// empty input
if (!html || html.length < 0 || !html.trim()) {
return;
}
// process retrieved annotations
markup(text, function(markedUp) {
//console.log(markedUp);
try {
var $ = cheerio.load(markedUp);
} catch (e) {
GLOBAL.error(name, e);
return;
}
var annoRows = [], candidates = {};
// do this in two passes; the first captures all annotation instances. The second adds GATE indicated instances.
// pass one: capture all instances
wantedAnnos.forEach(function(annoType) {
if (!candidates[annoType]) {
$('body').find(annoType).each(function(i, w) {
var exact = $($.html(w)).text(), attributes = $(w).attr();
// console.log('\nfound', annoType, i, { exact: exact, attr: attributes});
annoRows.push(annotations.createAnnotation({type: 'quote', annotatedBy: name, hasTarget: uri, roots: annoType, quote: exact, attributes: attributes,
ranges: annoLib.bodyInstancesFromMatches(exact, html, selector)}));
candidates[w] = 1;
});
}
});
console.log('found', annoRows.length);
// TODO determine position in GATE document of annot and choose from indexed regexes
annoLib.publishAnnotations(uri, annoRows);
});
});
// make a post request and callback results
function markup(text, callback) {
var postData = querystring.stringify({data : text});
var postOptions = {
host: instanceProps.host,
port: instanceProps.port,
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var data = '';
var postRequest = http.request(postOptions, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function() {
callback(data);
});
});
postRequest.write(postData);
}
| JavaScript | 0 | @@ -1967,27 +1967,31 @@
%7D);%0A%0A
-console.log
+ GLOBAL.info
('found'
|
f0bb198d7d70a421d0b31dcdf3c67978e4887a5c | Remove list of possible values for platformName cap (#233) | lib/basedriver/desired-caps.js | lib/basedriver/desired-caps.js | import log from './logger';
import validator from 'validate.js';
import B from 'bluebird';
let desiredCapabilityConstraints = {
platformName: {
presence: true,
isString: true,
inclusionCaseInsensitive: [
'iOS',
'Android',
'FirefoxOS',
'Windows',
'Mac',
'Tizen',
'Fake'
]
},
deviceName: {
presence: true,
isString: true
},
platformVersion: {},
newCommandTimeout: {
isNumber: true
},
automationName: {
isString: true
},
autoLaunch: {
isBoolean: true
},
udid: {
isString: true
},
orientation: {
inclusion: [
'LANDSCAPE',
'PORTRAIT'
]
},
autoWebview: {
isBoolean: true
},
noReset: {
isBoolean: true
},
fullReset: {
isBoolean: true
},
language: {
isString: true
},
locale: {
isString: true
},
eventTimings: {
isBoolean: true
},
printPageSourceOnFindFailure: {
isBoolean: true
},
};
validator.validators.isString = function (value) {
if (typeof value === 'string') {
return null;
}
if (typeof value === 'undefined') {
return null;
}
return 'must be of type string';
};
validator.validators.isNumber = function (value) {
if (typeof value === 'number') {
return null;
}
if (typeof value === 'undefined') {
return null;
}
return 'must be of type number';
};
validator.validators.isBoolean = function (value) {
if (typeof value === 'boolean') {
return null;
}
// allow a string value
if (typeof value === 'string' &&
((value.toLowerCase() === 'true' || value.toLowerCase() === 'false') ||
(value === ''))) {
log.warn('Boolean capability passed in as string. Functionality may be compromised.');
return null;
}
if (typeof value === 'undefined') {
return null;
}
return 'must be of type boolean';
};
validator.validators.isObject = function (value) {
if (typeof value === 'object') {
return null;
}
if (typeof value === 'undefined') {
return null;
}
return 'must be of type object';
};
validator.validators.deprecated = function (value, options, key) {
if (options) {
log.warn(`${key} is a deprecated capability`);
}
return null;
};
validator.validators.inclusionCaseInsensitive = function (value, options) {
if (typeof value === 'undefined') {
return null;
} else if (typeof value !== 'string') {
return 'unrecognised';
}
for (let option of options) {
if (option.toLowerCase() === value.toLowerCase()) {
return null;
}
}
return `${value} not part of ${options.toString()}`;
};
validator.promise = B;
validator.prettify = (val) => { return val; };
export { desiredCapabilityConstraints, validator };
| JavaScript | 0.000008 | @@ -185,153 +185,8 @@
ue,%0A
- inclusionCaseInsensitive: %5B%0A 'iOS',%0A 'Android',%0A 'FirefoxOS',%0A 'Windows',%0A 'Mac',%0A 'Tizen',%0A 'Fake'%0A %5D%0A
%7D,
|
afdb9ae0073b0a28b7f430e263ff2b6bfe3ee295 | Update chat.js | lib/clients/web/facets/chat.js | lib/clients/web/facets/chat.js | /**
* API Facet to make calls to methods in the chat namespace.
*
* This provides functions to call:
* - delete: {@link https://api.slack.com/methods/chat.delete|chat.delete}
* - meMessage: {@link https://api.slack.com/methods/chat.meMessage|chat.meMessage}
* - postMessage: {@link https://api.slack.com/methods/chat.postMessage|chat.postMessage}
* - update: {@link https://api.slack.com/methods/chat.update|chat.update}
*
*/
function ChatFacet(makeAPICall) {
this.name = 'chat';
this.makeAPICall = makeAPICall;
}
/**
* Deletes a message.
* @see {@link https://api.slack.com/methods/chat.delete|chat.delete}
*
* @param {?} ts - Timestamp of the message to be deleted.
* @param {?} channel - Channel containing the message to be deleted.
* @param {Object=} opts
* @param {?} opts.as_user - Pass true to delete the message as the authed user. [Bot
* users](/bot-users) in this context are considered authed users.
* @param {function=} optCb Optional callback, if not using promises.
*/
ChatFacet.prototype.delete = function delete_(ts, channel, opts, optCb) {
var requiredArgs = {
ts: ts,
channel: channel
};
return this.makeAPICall('chat.delete', requiredArgs, opts, optCb);
};
/**
* Share a me message into a channel.
* @see {@link https://api.slack.com/methods/chat.meMessage|chat.meMessage}
*
* @param {?} channel - Channel to send message to. Can be a public channel, private group or IM
* channel. Can be an encoded ID, or a name.
* @param {?} text - Text of the message to send.
* @param {function=} optCb Optional callback, if not using promises.
*/
ChatFacet.prototype.meMessage = function meMessage(channel, text, optCb) {
var requiredArgs = {
channel: channel,
text: text
};
return this.makeAPICall('chat.meMessage', requiredArgs, null, optCb);
};
/**
* Sends a message to a channel.
* @see {@link https://api.slack.com/methods/chat.postMessage|chat.postMessage}
*
* @param {?} channel - Channel, private group, or IM channel to send message to. Can be an
* encoded ID, or a name. See [below](#channels) for more details.
* @param {?} text - Text of the message to send. See below for an explanation of
* [formatting](#formatting). This field is usually required, unless you're providing only
* `attachments` instead.
* @param {Object=} opts
* @param {?} opts.parse - Change how messages are treated. Defaults to `none`. See
* [below](#formatting).
* @param {?} opts.link_names - Find and link channel names and usernames.
* @param {?} opts.attachments - Structured message attachments.
* @param {?} opts.unfurl_links - Pass true to enable unfurling of primarily text-based content.
* @param {?} opts.unfurl_media - Pass false to disable unfurling of media content.
* @param {?} opts.username - Set your bot's user name. Must be used in conjunction with `as_user`
* set to false, otherwise ignored. See [authorship](#authorship) below.
* @param {?} opts.as_user - Pass true to post the message as the authed user, instead of as a
* bot. Defaults to false. See [authorship](#authorship) below.
* @param {?} opts.icon_url - URL to an image to use as the icon for this message. Must be used in
* conjunction with `as_user` set to false, otherwise ignored. See [authorship](#authorship)
* below.
* @param {?} opts.icon_emoji - emoji to use as the icon for this message. Overrides `icon_url`.
* Must be used in conjunction with `as_user` set to false, otherwise ignored. See
* [authorship](#authorship) below.
* @param {function=} optCb Optional callback, if not using promises.
*/
ChatFacet.prototype.postMessage = function postMessage(channel, text, opts, optCb) {
var requiredArgs = {
channel: channel,
text: text
};
return this.makeAPICall('chat.postMessage', requiredArgs, opts, optCb);
};
/**
* Updates a message.
* @see {@link https://api.slack.com/methods/chat.update|chat.update}
*
* @param {?} ts - Timestamp of the message to be updated.
* @param {?} channel - Channel containing the message to be updated.
* @param {?} text - New text for the message, using the [default formatting
* rules](/docs/formatting).
* @param {Object=} opts
* @param {?} opts.attachments - Structured message attachments.
* @param {?} opts.parse - Change how messages are treated. Defaults to `client`, unlike
* `chat.postMessage`. See [below](#formatting).
* @param {?} opts.link_names - Find and link channel names and usernames. Defaults to `none`.
* This parameter should be used in conjunction with `parse`. To set `link_names` to `1`, specify
* a `parse` mode of `full`.
* @param {?} opts.as_user - Pass true to update the message as the authed user. [Bot
* users](/bot-users) in this context are considered authed users.
* @param {function=} optCb Optional callback, if not using promises.
*/
ChatFacet.prototype.update = function update(ts, channel, text, opts, optCb) {
var requiredArgs = {
ts: ts,
channel: channel,
text: text
};
return this.makeAPICall('chat.update', requiredArgs, opts, optCb);
};
/**
* Unfurl a URL within a message by defining its message attachment.
* @see {@link https://api.slack.com/methods/chat.unfurl|chat.unfurl}
*
* @param {?} ts - Timestamp of the message to be updated.
* @param {?} channel - Channel of the message to be updated.
* @param {string} unfurls - a map of URLs to structured message attachments
* @param {Boolean} userAuthRequired - Pass true to require user authorization.
* @param {function=} optCb Optional callback, if not using promises.
*/
ChatFacet.prototype.unfurl = function unfurl(ts, channel, unfurls, userAuthRequired, optCb) {
var requiredArgs = {
ts: ts,
channel: channel,
unfurls: unfurls,
user_auth_required: userAuthRequired
};
return this.makeAPICall('chat.unfurl', requiredArgs, {}, optCb);
};
module.exports = ChatFacet;
| JavaScript | 0 | @@ -5675,35 +5675,37 @@
red, optCb) %7B%0A
-var
+const
requiredArgs =
@@ -5695,32 +5695,53 @@
t requiredArgs =
+ !!userAuthRequired ?
%7B%0A ts: ts,%0A
@@ -5807,32 +5807,85 @@
quired:
-userAuthRequired
+true,%0A %7D : %7B%0A ts: ts,%0A channel: channel,%0A unfurls: unfurls,
%0A %7D;%0A%0A
|
dffec1da4e10738a46a30db608e3dcda2c62af44 | update chat.js | lib/clients/web/facets/chat.js | lib/clients/web/facets/chat.js | /**
* API Facet to make calls to methods in the chat namespace.
*
* This provides functions to call:
* - delete: {@link https://api.slack.com/methods/chat.delete|chat.delete}
* - meMessage: {@link https://api.slack.com/methods/chat.meMessage|chat.meMessage}
* - postMessage: {@link https://api.slack.com/methods/chat.postMessage|chat.postMessage}
* - update: {@link https://api.slack.com/methods/chat.update|chat.update}
*
*/
function ChatFacet(makeAPICall) {
this.name = 'chat';
this.makeAPICall = makeAPICall;
}
/**
* Deletes a message.
* @see {@link https://api.slack.com/methods/chat.delete|chat.delete}
*
* @param {?} ts - Timestamp of the message to be deleted.
* @param {?} channel - Channel containing the message to be deleted.
* @param {Object=} opts
* @param {?} opts.as_user - Pass true to delete the message as the authed user. [Bot
* users](/bot-users) in this context are considered authed users.
* @param {function=} optCb Optional callback, if not using promises.
*/
ChatFacet.prototype.delete = function delete_(ts, channel, opts, optCb) {
var requiredArgs = {
ts: ts,
channel: channel
};
return this.makeAPICall('chat.delete', requiredArgs, opts, optCb);
};
/**
* Share a me message into a channel.
* @see {@link https://api.slack.com/methods/chat.meMessage|chat.meMessage}
*
* @param {?} channel - Channel to send message to. Can be a public channel, private group or IM
* channel. Can be an encoded ID, or a name.
* @param {?} text - Text of the message to send.
* @param {function=} optCb Optional callback, if not using promises.
*/
ChatFacet.prototype.meMessage = function meMessage(channel, text, optCb) {
var requiredArgs = {
channel: channel,
text: text
};
return this.makeAPICall('chat.meMessage', requiredArgs, null, optCb);
};
/**
* Sends a message to a channel.
* @see {@link https://api.slack.com/methods/chat.postMessage|chat.postMessage}
*
* @param {?} channel - Channel, private group, or IM channel to send message to. Can be an
* encoded ID, or a name. See [below](#channels) for more details.
* @param {?} text - Text of the message to send. See below for an explanation of
* [formatting](#formatting). This field is usually required, unless you're providing only
* `attachments` instead.
* @param {Object=} opts
* @param {?} opts.parse - Change how messages are treated. Defaults to `none`. See
* [below](#formatting).
* @param {?} opts.link_names - Find and link channel names and usernames.
* @param {?} opts.attachments - Structured message attachments.
* @param {?} opts.unfurl_links - Pass true to enable unfurling of primarily text-based content.
* @param {?} opts.unfurl_media - Pass false to disable unfurling of media content.
* @param {?} opts.username - Set your bot's user name. Must be used in conjunction with `as_user`
* set to false, otherwise ignored. See [authorship](#authorship) below.
* @param {?} opts.as_user - Pass true to post the message as the authed user, instead of as a
* bot. Defaults to false. See [authorship](#authorship) below.
* @param {?} opts.icon_url - URL to an image to use as the icon for this message. Must be used in
* conjunction with `as_user` set to false, otherwise ignored. See [authorship](#authorship)
* below.
* @param {?} opts.icon_emoji - emoji to use as the icon for this message. Overrides `icon_url`.
* Must be used in conjunction with `as_user` set to false, otherwise ignored. See
* [authorship](#authorship) below.
* @param {function=} optCb Optional callback, if not using promises.
*/
ChatFacet.prototype.postMessage = function postMessage(channel, text, opts, optCb) {
var requiredArgs = {
channel: channel,
text: text
};
return this.makeAPICall('chat.postMessage', requiredArgs, opts, optCb);
};
/**
* Updates a message.
* @see {@link https://api.slack.com/methods/chat.update|chat.update}
*
* @param {?} ts - Timestamp of the message to be updated.
* @param {?} channel - Channel containing the message to be updated.
* @param {?} text - New text for the message, using the [default formatting
* rules](/docs/formatting).
* @param {Object=} opts
* @param {?} opts.attachments - Structured message attachments.
* @param {?} opts.parse - Change how messages are treated. Defaults to `client`, unlike
* `chat.postMessage`. See [below](#formatting).
* @param {?} opts.link_names - Find and link channel names and usernames. Defaults to `none`.
* This parameter should be used in conjunction with `parse`. To set `link_names` to `1`, specify
* a `parse` mode of `full`.
* @param {?} opts.as_user - Pass true to update the message as the authed user. [Bot
* users](/bot-users) in this context are considered authed users.
* @param {function=} optCb Optional callback, if not using promises.
*/
ChatFacet.prototype.update = function update(ts, channel, text, opts, optCb) {
var requiredArgs = {
ts: ts,
channel: channel,
text: text
};
return this.makeAPICall('chat.update', requiredArgs, opts, optCb);
};
/**
* Unfurl a URL within a message by defining its message attachment.
* @see {@link https://api.slack.com/methods/chat.unfurl|chat.unfurl}
*
* @param {?} ts - Timestamp of the message to be updated.
* @param {?} channel - Channel of the message to be updated.
* @param {string} unfurls - a map of URLs to structured message attachments
* @param {Boolean} userAuthRequired - Pass true to require user authorization.
* @param {function=} optCb Optional callback, if not using promises.
*/
ChatFacet.prototype.unfurl = function unfurl(ts, channel, unfurls, userAuthRequired, optCb) {
const requiredArgs = !!userAuthRequired ? {
ts: ts,
channel: channel,
unfurls: unfurls,
user_auth_required: true,
} : {
ts: ts,
channel: channel,
unfurls: unfurls,
};
return this.makeAPICall('chat.unfurl', requiredArgs, {}, optCb);
};
module.exports = ChatFacet;
| JavaScript | 0 | @@ -5447,34 +5447,60 @@
am %7B
-Boolean%7D
+Object=%7D opts%0A * @param %7B?%7D opts.
user
-AuthR
+_auth_r
equired
- P
@@ -5495,17 +5495,16 @@
equired
-
- Pass t
@@ -5679,32 +5679,20 @@
nfurls,
-userAuthRequired
+opts
, optCb)
@@ -5698,15 +5698,14 @@
) %7B%0A
+%0A
-const
+var
req
@@ -5719,29 +5719,8 @@
gs =
- !!userAuthRequired ?
%7B%0A
@@ -5776,103 +5776,8 @@
urls
-,%0A user_auth_required: true,%0A %7D : %7B%0A ts: ts,%0A channel: channel,%0A unfurls: unfurls,
%0A %7D
@@ -5838,10 +5838,12 @@
gs,
-%7B%7D
+opts
, op
|
dd0aa532e07e6d4d2b7c2ae7362a20fa89379393 | Fix refactor fail | lib/components/views/SignUp.js | lib/components/views/SignUp.js | import React, {Component, PropTypes} from 'react';
import {Link} from 'react-router';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {
Card,
FlatButton,
RaisedButton,
Snackbar,
TextField
} from 'material-ui';
import * as authActions from '../../actions/authActions';
import signupValidation from '../../validation/signupValidation';
@connect(
() => ({}),
dispatch => bindActionCreators(authActions, dispatch)
)
export default class SignUp extends Component {
static propTypes = {
signup: PropTypes.func
};
constructor(props) {
super(props);
this.state = {
email: '',
password: ''
};
}
render() {
return (
<div>
<Card style={{margin: '76px 20px',
padding: '0 20px'}}>
<h1>Sign Up</h1>
<form onSubmit={this.handleSubmit}>
<TextField
floatingLabelText="Email"
value={this.state.email}
onChange={this._updateInputState.bind(this, 'email')} />
<br/>
<TextField
floatingLabelText="Password"
hintText="Password Field"
type="password"
value={this.state.password}
onChange={this._updateInputState.bind(this, 'password')}/>
<br/>
<RaisedButton label="Sign Up" onClick={this.handleSubmit.bind(this)}/>
<p>
Have an account already?
<Link to="login">
<FlatButton label="Log In" secondary={true}/>
</Link>
</p>
</form>
</Card>
<Snackbar
ref="snackbar"
message="Invalid or Missing Username & Password. Please try again."
autoHideDuration={2000}/>
</div>
);
}
_updateInputState(key, event) {
this.setState({
[key]: event.target.value
});
}
handleSubmit(event) {
event.preventDefault();
const { email, password } = this.state;
const validation = signupValidation({
email,
password
});
if (validation.valid) {
this.props.signup(email, password);
} else {
this.refs.snackbar.show();
}
}
}
| JavaScript | 0.000006 | @@ -2168,16 +2168,17 @@
.signup(
+%7B
email, p
@@ -2184,16 +2184,17 @@
password
+%7D
);%0A %7D
|
e7e7dc32fcf5c08260f4a27315f117b93629e0f5 | Remove useless mp3s | scripts/root.js | scripts/root.js | var root = angular.module('root', ["ngResource", "mediaPlayer"])
.controller("index", ["$scope", "$resource", function ($scope, $resource) {
var artists = $resource("http://localhost:9000/api/artists");
var years = $resource('http://localhost:9000/api/artists/:artist_slug/years');
var shows = $resource('http://localhost:9000/api/artists/:artist_slug/years/:year_slug');
var recordings = $resource('http://localhost:9000/api/artists/:artist_slug/years/:year_slug/shows/:show_date');
var current_artist;
var current_year;
var current_venue;
var total_time_seconds;
window.iguanaScope = $scope;
artists.get().$promise.then(function(result) {
$scope.artists = result.data;
});
$scope.getYears = function(artist, $event) {
selectElement($event.target);
years.get({artist_slug: artist.id}).$promise.then(function(result) {
current_artist = artist;
$scope.years = result.data;
$scope.artist = current_artist.name;
// reset other lists
$scope.shows = [];
$scope.recordings = [];
});
};
$scope.getShows = function(year, $event) {
selectElement($event.target);
shows.get({artist_slug: current_artist.id, year_slug: year.year}).$promise.then(function(result) {
current_year = year;
$scope.shows = result.data.shows;
// reset other lists
$scope.recordings = [];
});
};
$scope.getRecordings = function(show, $event) {
selectElement($event.target);
recordings.get({artist_slug: current_artist.id, year_slug: current_year.year, show_date: show.display_date}).$promise.then(function(result) {
$scope.recordings = result.data[0].tracks;
current_venue = show.display_date + " — " + show.venue_name + ', ' + show.venue_city;
});
};
$scope.playSong = function(recording, $event) {
selectElement($event.target);
$scope.title = recording.title;
total_time_seconds = recording.length;
if(!$scope.audio1.playing) {
$scope.audio1.load([{ src: recording.file, type: 'audio/mp3' }, true]);
$scope.audio1.playPause();
} else {
$scope.audio1.playPause();
// temp workaround
window.setTimeout(function() {
$scope.audio1.load([{ src: recording.file, type: 'audio/mp3' }, false]);
$scope.audio1.playPause();
}, 100);
}
$scope.venue = current_venue;
var length = recording.length;
var min = Math.floor(length/60);
var sec = pad(length % 60, 2);
$scope.total_time = min + ':' + sec;
$scope.current_time = '0:00';
};
$scope.$watch("audio1.currentTime", function (newValue) {
if(newValue) {
var min = Math.floor(newValue/60);
var sec = pad(Math.floor(newValue) % 60, 2);
$scope.current_time = min + ':' + sec;
} else {
$scope.current_time = '';
}
$scope.current_time_percentage = newValue / total_time_seconds * 100 + '%';
});
$scope.nextSong = function() {
$scope.audio1.next();
};
$scope.playButton = function() {
$scope.audio1.playPause();
}
$scope.seekTo = function(timePercent) {
$scope.audio1.seek(timePercent * total_time_seconds);
}
}]);
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
function selectElement(target) {
$(target).parent().parent().children().children().removeClass('selected');
$(target).addClass('selected');
}
| JavaScript | 0.000011 | @@ -165,38 +165,56 @@
rce(%22http://
-localhost:9000
+iguana-staging.app.alecgorge.com
/api/artists
|
8f60fee09bac9db95f44a9fedc2a5be955786495 | The vendor’s name should be unique | server/app/models/food-vendor.js | server/app/models/food-vendor.js | 'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const foodVendorSchema = new Schema({
title: { type: String, required: true },
url: { type: String, required: true },
minOrderCost: { type: Number }
});
module.exports = mongoose.model('FoodVendor', foodVendorSchema);
| JavaScript | 0.999999 | @@ -239,16 +239,360 @@
%7D%0A%7D);%0A%0A
+foodVendorSchema.path('title').validate(function(title, callback) %7B%0A const Vendor = mongoose.model('FoodVendor');%0A%0A if (this.isNew %7C%7C this.isModified('title')) %7B%0A Vendor.find(%7B title %7D).exec(function(err, vendors) %7B%0A callback(!err && vendors.length === 0)%0A %7D);%0A %7D else %7B%0A callback(true);%0A %7D%0A%7D, 'Food vendor already exists');%0A%0A
module.e
|
d613efbae1abfb14ce95539594039d184932dde7 | Fix issue-1: Keep waiting if the same user joins | server/controllers/Matchmaker.js | server/controllers/Matchmaker.js | var OngoingGames = require("../models/OngoingGames");
var playerQueue = [];
exports.startGame = function(req, res) {
var player1 = req.body.username;
var game = OngoingGames.findGame(player1);
// player has ongoing game
if (game != null) {
res.json(game);
}
// Start a new game if opponent exists. Pops the last element in queue.
else if (playerQueue.length > 0) {
OngoingGames.startGame(player1, playerQueue.pop());
res.json({'message': 'Starting new game.'});
}
// If no players in queue, put this player in start of queue.
else {
playerQueue.unshift(player1);
res.json({'message': 'Waiting for opponent.'});
}
};
| JavaScript | 0.000001 | @@ -311,16 +311,52 @@
t exists
+ and opponent is not the same player
. Pops t
@@ -414,16 +414,55 @@
ngth %3E 0
+ && playerQueue.indexOf(player1) === -1
) %7B%0A
|
832efe479e68868c4da13b4e30cdd0f7beaea084 | Use correct key for accessing issueId for a vote | server/channels/vote.js | server/channels/vote.js | const { broadcastAndEmit, emit, emitError } = require('../utils');
const logger = require('../logging');
const { addVote, generatePublicVote } = require('../managers/vote');
const { getActiveGenfors } = require('../models/meeting.accessors');
const { getAnonymousUser } = require('../models/user.accessors');
const { isRegistered } = require('../managers/user');
const {
RECEIVE_VOTE: SEND_VOTE,
SUBMIT_ANONYMOUS_VOTE,
SUBMIT_REGULAR_VOTE,
USER_VOTE,
} = require('../../common/actionTypes/voting');
const checkRegistered = async (socket) => {
const user = await socket.request.user();
const { passwordHash } = socket.request.headers.cookie;
const registered = await isRegistered(user, passwordHash);
if (!registered) {
emitError(socket, new Error('Du er ikke registert'));
return false;
}
return true;
};
const submitRegularVote = async (socket, data) => {
const user = await socket.request.user();
logger.debug('Received vote', { userFullName: user.name });
if (!await checkRegistered(socket)) {
return;
}
try {
const vote = await addVote(
data.issue, user,
data.alternative, user.id,
);
logger.debug('Stored new vote. Broadcasting ...');
broadcastAndEmit(socket, SEND_VOTE, await generatePublicVote(data.issue, vote));
emit(socket, USER_VOTE, {
alternativeId: vote.alternative,
issueId: vote.question,
});
} catch (err) {
logger.error('Storing new vote failed.', err);
emitError(socket, err);
}
};
const submitAnonymousVote = async (socket, data) => {
logger.debug('Received anonymous vote');
if (!await checkRegistered(socket)) {
return;
}
const user = await socket.request.user();
const genfors = await getActiveGenfors();
const anonymousUser = await getAnonymousUser(data.passwordHash,
user.onlinewebId, genfors);
try {
const vote = await addVote(data.issue, user,
data.alternative, anonymousUser.id);
logger.debug('Stored new anonymous vote. Broadcasting ...');
broadcastAndEmit(socket, SEND_VOTE, await generatePublicVote(data.issue, vote));
emit(socket, USER_VOTE, {
alternativeId: vote.alternative,
issueId: vote.question,
});
} catch (err) {
logger.error('Storing new anonymous vote failed.', err);
emitError(socket, err);
}
};
const listener = (socket) => {
socket.on('action', async (data) => {
switch (data.type) {
case SUBMIT_REGULAR_VOTE:
submitRegularVote(socket, data);
break;
case SUBMIT_ANONYMOUS_VOTE: {
submitAnonymousVote(socket, data);
break;
}
default:
break;
}
});
};
module.exports = {
listener,
submitAnonymousVote,
submitRegularVote,
};
| JavaScript | 0 | @@ -1373,32 +1373,31 @@
sueId: vote.
-question
+issueId
,%0A %7D);%0A
@@ -2179,16 +2179,15 @@
ote.
-question
+issueId
,%0A
|
e8438ddde0bb5ae0e40adb53f6907404c475aecb | Add comments | server/config/routes.js | server/config/routes.js | module.exports = function(app, express) {
app.get('/auth/facebook', function(req, res) {
res.send('Facebook OAuth');
});
app.get('/auth/facebook/callback', function(req, res) {
res.send('Callback for Facebook OAuth');
});
app.route('/api/users')
.post(function(req, res) {
res.send('Create a new user');
})
.put(function(req, res) {
res.send('Update user info');
})
.delete(function(req, res) {
res.send('Delete the user');
});
}; | JavaScript | 0 | @@ -36,16 +36,36 @@
ess) %7B%0A%0A
+ // Facebook OAuth%0A
app.ge
@@ -97,32 +97,32 @@
ion(req, res) %7B%0A
-
res.send('Fa
@@ -139,25 +139,24 @@
th');%0A %7D);%0A
-%0A
app.get('/
@@ -253,16 +253,35 @@
%0A %7D);%0A%0A
+ // User Creation%0A
app.ro
|
8af1afb539597dab3674bd036d19ad20983abaa1 | add status route | server/config/routes.js | server/config/routes.js | var email = require('../components/messages/middleware').email
, messages = require('../components/messages/controllers')
, projects = require('../components/projects/controllers');
module.exports = function (app) {
// messages
app.post('/api/messages', email, messages.create);
// projects
app.get('/api/projects', projects.index);
app.get('/api/projects/:project', projects.show);
};
| JavaScript | 0.000001 | @@ -177,16 +177,73 @@
ollers')
+%0A , status = require('../components/status/controllers')
;%0A%0Amodul
@@ -449,12 +449,64 @@
s.show);
+%0A%0A // status%0A app.get('/api/status', status.show);
%0A%7D;%0A
|
6fb62ed76a50629c064a2efd31974326e7bfdfd3 | update static files | server/src/controller/recipes.js | server/src/controller/recipes.js | import db from '../models';
// import Sequelize from 'sequelize';
const recipes = db.recipes;
const reviews = db.reviews;
// const Op = Sequelize.Op;
/**
*
*
* @class Recipes
*/
class Recipes {
/**
*
*
* @param {any} req
* @param {any} res
* @returns
* @memberof Recipes
*/
add(req, res) {
const { recipeImage, recipeName, description, instructions, ingredients } = req.body;
return recipes
.create({
userId: req.decoded.id,
recipeImage,
recipeName,
description,
instructions,
ingredients
}).then(created => {
return res.status(201).json(created);
})
.catch((err) => {
console.log(err);
return res.status(500).json({
message: 'Some error occured!'
});
});
}
modify(req, res) {
const { recipeName, mealType, description, method, ingredients } = req.body;
let updateFields = {};
const id = req.params.recipeId;
recipes.findOne({
where: {
userId: req.decoded.id,
id: id
}
}).then(found => {
if(found) {
if (recipeName) {
updateFields.recipeName = recipeName;
}
if (mealType) {
updateFields.mealType = mealType;
}
if (description) {
updateFields.description = description;
}
if (method) {
updateFields.method = method;
}
if (ingredients) {
updateFields.ingredients = ingredients;
}
if (updateFields.length < 0 ){
return res.status(200).json({
Message: 'Nothing to update!'
});
} else {
found.update(
updateFields,
{
where: {
userId: req.decoded.id,
id: id
}
}).then((updated) => {
return res.status(200).json({
Message: 'Succesfully Updated Recipe',
updated
});
});
}
} else {
return res.status(401).json({
message: 'You cannot modify this Recipe!'
});
}
});
}
get(req, res) {
if (req.query.search) {
// lets search something
const searchQuery = req.query.search.split(' ');
let search = searchQuery.map((value) => {
return {
recipeName: {$iLike : `%${value}%`}
};
});
let ingredients = searchQuery.map((value) => {
return {
ingredients: {$iLike : `%${value}%`}
};
});
recipes.findAll({
where: {
$or:
search.concat(ingredients)
},
order: [
['id', 'DESC']
]
}).then(result => {
if (result.length <= 0) {
return res.status(404).json({
message: 'No recipe Matched your Search!'
});
}
return res.status(200).json({
result
});
});
} else if (req.query) {
const sort = req.query.sort === 'upvotes' || req.query.sort === 'downvotes' ? req.query.sort : 'upvotes';
const order = req.query.order === 'des' ? 'DESC' : 'DESC';
} else {
const limitValue = req.query.limit || 12;
const pageValue = req.query.page - 1 || 0;
return recipes
.findAndCountAll({
offset: limitValue * pageValue,
limit: limitValue,
}).then(getAllRecipes => {
if (getAllRecipes.length <= 0) {
return res.status(200).json({
Message: 'No recipes have yet been created!'
});
}
const totalCount = getAllRecipes.count;
const pageCount = Math.ceil(totalCount / limitValue);
return res.status(200).json({ totalCount, page: pageValue + 1, pageCount, getAllRecipes});
});
}
}
getOne(req, res) {
return recipes
.findOne({
where: {
id: req.params.recipeId
}
}).then(recipeDetails => {
if (recipeDetails) {
if (!req.decoded || req.decoded.id !== recipeDetails.userId) {
// updat eview
recipes.update({
views: recipeDetails.views + 1
},
{
where: {
id: req.params.recipeId
}
});
}
reviews.findAll({
where: {
recipeId: req.params.recipeId
}
}).then(recipeReviews =>{
const reviews = (recipeReviews.length <= 0)? 'No reviews yet': recipeReviews;
return res.status(200).json({
recipeDetails,
reviews: reviews
});
});
} else {
return res.status(400).json({
message: 'Recipe Not found'
});
}
});
}
getUserRecipe(req, res) {
return recipes
.findAll({
where: {
userId: (req.params.userId)? req.params.userId : req.decoded.id
}
}).then(found => {
if (found.length <= 0) {
return res.status(404).json({
message: (req.params.userId)? 'This user has not created any recipes yet!': 'You have not created any recipe Yet'
});
} else {
return res.status(200).json({
found
});
}
});
}
delete(req, res) {
const id = req.params.recipeId;
recipes.findOne({
where: {
userId: req.decoded.id,
id: id
}
}).then(found => {
if (!found) {
return res.status(404).json({
message: 'You did not created this recipe, you cannot delete it!'
});
} else {
return recipes
.destroy({
where: {
userId: req.decoded.id,
id: id
}
}).then(() => {
return res.status(200).json({
message: 'Recipe Deleted!'
});
});
}
});
}
}
export default Recipes; | JavaScript | 0.000001 | @@ -3078,16 +3078,21 @@
eq.query
+.sort
) %7B%0A
@@ -3264,22 +3264,16 @@
'DESC';%0A
-
%0A %7D e
@@ -3300,24 +3300,53 @@
limitValue =
+ (req.query.limit %3C= 0) ? 12:
req.query.l
@@ -3861,16 +3861,62 @@
tValue);
+%0A const recipes = getAllRecipes.rows;
%0A%0A
@@ -3994,29 +3994,24 @@
eCount,
-getAllR
+r
ecipes
+
%7D);%0A
|
c119c54cd53be39f6016e716f5056783d6392117 | Fix a bit of linting | chatanyara.js | chatanyara.js | /**
* Navigation and Resource Timing results.
*
* @author Juga Paazmaya <[email protected]>
* @license Licensed under the MIT license
* @version 0.2.0
* @see https://github.com/paazmaya/chatanyara.js
*/
var Chatanyara = (function main() { // eslint-disable-line no-unused-vars
'use strict';
var Kushanku = {
performance: typeof window.performance !== 'object' || window.performance,
/**
* Navigation Timing API.
*
* @see http://www.w3.org/TR/navigation-timing/
* @see http://caniuse.com/nav-timing
* @returns {boolean|object} Object with navigation timing information or false if not supported
*/
getNavigationTimings: function navTime() {
if (!this.performance || typeof this.performance.timing !== 'object') {
return false;
}
var data = {};
var timing = this.performance.timing;
// navigationStart is the first event taking place in the PerformanceTiming sequence
var navigationStart = timing.navigationStart;
// All the keys will be set to the relative time as it gives more value than the time.
for (var key in timing) {
// Only numbers are interesting
if (typeof timing[key] === 'number') {
// Value should be the time when the given event took place,
// but might be 0 if the event was not fired or was not completed.
data[key] = timing[key] === 0 ?
0 :
timing[key] - navigationStart;
}
}
/*
interface PerformanceNavigation {
const unsigned short TYPE_NAVIGATE = 0;
const unsigned short TYPE_RELOAD = 1;
const unsigned short TYPE_BACK_FORWARD = 2;
const unsigned short TYPE_RESERVED = 255;
readonly attribute unsigned short type;
readonly attribute unsigned short redirectCount;
};
*/
if (typeof this.performance.navigation === 'object') {
var nav = this.performance.navigation;
data.redirectCount = nav.redirectCount;
data.navigationType = nav.type < 3 ?
['NAVIGATE', 'RELOAD', 'BACK_FORWARD'][nav.type] :
nav.type;
}
return data;
},
/**
* Resource Timing API.
*
* @see http://www.w3.org/TR/resource-timing
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=822480
* @returns {boolean|object} Object with resource loading information or false if not supported
*/
getResourceTimings: function resTime() {
if (!this.performance || typeof this.performance.getEntriesByType !== 'function') {
return false;
}
// Convert to plain Objects
var entries = JSON.parse(JSON.stringify(this.performance.getEntriesByType('resource')));
return entries;
},
/**
* Chome only
* @returns {boolean|object} Object with memory information or false if not supported
*/
getMemoryInfo: function memInfo() {
if (!this.performance || typeof this.performance.memory !== 'object') {
return false;
}
// Convert to plain Objects
var memory = JSON.parse(JSON.stringify(this.performance.memory));
return memory;
}
};
var Sai = {
parse: function saiParse() {
return {
url: window.location.pathname,
userAgent: window.navigator.userAgent,
navigation: Kushanku.getNavigationTimings(),
resource: Kushanku.getResourceTimings(),
memory: Kushanku.getMemoryInfo()
};
}
};
return Sai;
})();
| JavaScript | 0.001647 | @@ -683,15 +683,28 @@
ion
-navTime
+getNavigationTimings
() %7B
@@ -2487,15 +2487,26 @@
ion
-resTime
+getResourceTimings
() %7B
@@ -2938,19 +2938,25 @@
unction
-mem
+getMemory
Info() %7B
@@ -3242,12 +3242,9 @@
ion
-saiP
+p
arse
|
a13fadb527e38ea41ddd7974995012fa13277ced | add mock response for getAllActions event | server/index.js | server/index.js | var io = require("socket.io").listen(31415);
io.sockets.on("connection", function (socket) {
console.log('A Client has Connected to this Server');
socket.on("message", function (data) {
console.log('Message!', data);
});
socket.on("disconnect", function (data) {
console.log("disconnecting ", data);
});
}); | JavaScript | 0 | @@ -165,15 +165,21 @@
on(%22
-message
+getAllActions
%22, f
@@ -220,23 +220,699 @@
og('
-Message!', data
+Asking all actions!', data);%0A socket.emit('defineAllActions',%0A %7B actions:%0A %5B%0A %7B%0A name: 'lights',%0A functions: %7B%0A powerControl: %7B%0A arguments: 1,%0A argumentDefinition: %5B%0A %7B%0A type: 'bool',%0A name: 'enabled'%0A %7D%0A %5D%0A %7D%0A %7D%0A %7D%0A %5D%0A %7D%0A
);%0A
|
db0659cba597ffc1802fcc34db421ba7a38added | fix profile issue | server/index.js | server/index.js | var express = require('express');
var router = express.Router();
var passport = require('passport');
var models = require('../models/');
router.get('/', function (req, res) {
'use strict';
res.render('index', {
title: 'Welcome to Lan'
});
});
router.get('/login', function (req, res) {
'use strict';
if(!req.isAuthenticated()){
res.render('login/index', {title: 'Lan Login'});
} else {
res.render('login/success', {
title: 'Already login ' + req.user.name,
uid: req.user.uid,
userName: req.user.name,
phone: req.user.phone,
alias: req.user.alias
});
}
});
router.post('/login', function (req, res) {
'use strict';
var userInfo = {
name: req.body.name,
password: req.body.password
};
models.User.findOne({where: {name: userInfo.name}}).then(function (user) {
if (!user) {
req.session.messages = 'not such user';
return res.redirect('/login');
}
user.comparePassword(userInfo.password, function (err, result) {
if (result) {
passport.authenticate('local')(req, res, function () {
req.logIn(user, function (err) {
console.log('----------------');
console.log(err);
req.session.messages = 'Login successfully';
return res.render('login/success', {
title: 'Welcome ' + user.name,
uid: user.uid,
userName: user.name,
phone: user.phone,
alias: user.alias
});
});
});
} else {
return res.sendStatus(404);
}
}
);
});
});
router.get('/logout', function (req, res) {
'use strict';
if (req.isAuthenticated()) {
req.logout();
//req.session.messages = req.i18n.__("Log out successfully");
req.session.messages = 'Log out successfully';
}
res.redirect('/');
});
router.get(/^\/users\/(.+)$/, passport.authenticate('local'), function (req, res) {
'use strict';
console.log(req.session.messages);
models.User.findOne({where: {name: req.params[0]}}).then(function (user) {
if (!user) {
return res.sendStatus(403);
}
return res.render('user/index', {
title: user.name + '\'s Profile',
user: user
});
});
});
router.post('/register', function (req, res) {
'use strict';
var userInfo = {
name: req.body.name,
password: req.body.password,
phone: req.body.phone,
alias: req.body.alias
};
models.User.build(userInfo)
.validate()
.then(function (err) {
console.log(err);
if (err) {
return res.render('user/register', {user: userInfo, title: 'Something Error', errors: err.errors});
}
models.User.create(userInfo).then(function (user, err) {
if (err) {
return res.redirect('/');
}
console.log(user.uid);
passport.authenticate('local')(req, res, function () {
res.render('success', {
title: 'Create Success,' + user.name,
account: user,
uid: user.uid
});
});
});
});
});
router.get('/register', function (req, res) {
'use strict';
res.render('user/register', {title: 'Lan Account Manager', errors: ''});
});
module.exports = router;
| JavaScript | 0.000001 | @@ -1943,40 +1943,8 @@
)$/,
- passport.authenticate('local'),
fun
@@ -1984,42 +1984,92 @@
;%0A
-console.log(req.session.messages);
+if(!req.isAuthenticated())%7B%0A res.render('login/index', %7Btitle: 'Lan Login'%7D);%0A %7D
%0A m
|
422c36d3be7f1b65f5e6c31cf2c20c730b44cc0c | Fix server --test message | cli/server.js | cli/server.js | "use strict";
/*global N*/
// 3rd-party
var async = require('async');
module.exports.parserParameters = {
version: N.runtime.version,
addHelp: true,
help: 'start fontello server',
description: 'Start fontello server'
};
module.exports.commandLineArguments = [
{
args: ['--test'],
options: {
help: 'Start server an terminates immedeately, with code 0 on init success.',
action: 'storeTrue'
}
}
];
module.exports.run = function (args, callback) {
async.series([
function (next) { N.logger.debug('Init app...'); next(); },
require('../lib/init/app'),
function (next) { N.logger.debug('Init cronjob...'); next(); },
require('../lib/init/cronjob'),
function (next) { N.logger.debug('Init server...'); next(); },
require('../lib/init/server')
], function (err) {
if (err) {
callback(err);
return;
}
// for `--test` just exit on success
if (args.test) {
process.stdout.write('\nSetver exec test OK');
process.exit(0);
}
callback();
});
};
| JavaScript | 0 | @@ -247,16 +247,17 @@
er'%0A%7D;%0A%0A
+%0A
module.e
@@ -380,16 +380,35 @@
mmed
-e
+i
ately,
+' +%0A '
with
@@ -1018,17 +1018,17 @@
te('%5CnSe
-t
+r
ver exec
@@ -1035,16 +1035,18 @@
test OK
+%5Cn
');%0A
|
1e41a7179381e4725c543e8a0d3602f0efb6abce | allow url prefix/subdirectory set w cmd line arg | server/index.js | server/index.js | #!/usr/bin/env node
"use strict";
const https = require('https');
const fs = require("fs");
const path = require("path");
const express = require("express");
const parseArgs = require("minimist");
const bodyParser = require("body-parser");
const promiseUtil = require("./promiseUtil");
const Keys = require("./Keys");
const log = require("./log");
const fileStat = promiseUtil.wrapCPS(fs.stat);
const fileRead = promiseUtil.wrapCPS(fs.readFile);
const directoryRead = promiseUtil.wrapCPS(fs.readdir);
const realpath = promiseUtil.wrapCPS(fs.realpath);
class InvalidParameter extends Error {}
class AuthError extends Error {}
const listDirectory = promiseUtil.wrapRun(function* (root, filter) {
const files = yield directoryRead(root);
const result = yield files.map(promiseUtil.wrapRun(function* (name) {
const filePath = path.join(root, name);
const stat = yield fileStat(filePath);
if (!filter || filter(name, stat)) {
return stat.isDirectory() ? {
name,
children: yield listDirectory(filePath, filter),
} : {
name,
};
}
}));
return result.filter((file) => file);
});
function validDirectoryName(name) {
return !name.startsWith(".");
}
function validFileName(name) {
return !name.startsWith(".") && name.endsWith(".gpg");
}
function validFilePath(filePath) {
const splitted = filePath.split(path.sep);
return Boolean(
splitted.length &&
splitted.slice(0, -1).every(validDirectoryName) &&
validFileName(splitted[splitted.length - 1])
);
}
function filterFiles(name, stat) {
return (
stat.isDirectory() ? validDirectoryName(name) :
stat.isFile() ? validFileName(name) :
false
);
}
const getGPGId = promiseUtil.wrapRun(function* (rootPath) {
const stat = yield fileStat(rootPath);
if (stat.isDirectory()) {
const gpgIdPath = path.resolve(rootPath, ".gpg-id");
let gpgStat;
try {
gpgStat = yield fileStat(gpgIdPath);
}
catch (e) {
// Ignore ENOENT errors, just check for parent directory
if (e.code !== "ENOENT") {
log.error(e);
}
}
if (gpgStat && gpgStat.isFile()) {
return (yield fileRead(gpgIdPath, { encoding: "utf-8" })).trim();
}
}
const parentPath = path.resolve(rootPath, "..");
if (rootPath === parentPath) throw new Error("No .gpg-id found");
return getGPGId(parentPath);
});
const auth = promiseUtil.wrapRun(function* (conf, requestPath, passphrase) {
const gpgId = yield getGPGId(requestPath || conf.passwordStorePath);
if (!(yield conf.keys.verify(gpgId, passphrase))) {
throw new AuthError(`Bad passphrase`);
}
return gpgId;
});
function apiRouter(conf) {
const router = express.Router();
router.use(bodyParser.json());
function sendError(res, error) {
res.json({
error: {
type: error.constructor.name,
message: error.message,
},
});
}
function wrap(gen) {
return promiseUtil.wrapRun(function* (req, res, next) {
try {
yield* gen(req, res, next);
}
catch (error) {
log.debug(error);
sendError(res, error);
}
});
}
const getSecurePath = promiseUtil.wrapRun(function* (requestPath) {
try {
if (!Array.isArray(requestPath)) return;
if (requestPath.some((p) => typeof p !== "string")) return;
const filePath = yield realpath(path.resolve(
conf.passwordStorePath,
path.join(...requestPath)
));
// Make sure the path is inside passwordStorePath and isn't in a dotted directory/file
if (validFilePath(path.relative(conf.passwordStorePath, filePath))) return filePath;
}
catch (e) {
log.debug(e);
}
});
router.use(wrap(function* (req, res, next) {
if (!req.body) throw new InvalidParameter("No request body");
if (!req.body.passphrase) throw new InvalidParameter("No passphrase");
req.auth = (requestPath) => auth(conf, requestPath, req.body.passphrase);
next();
}));
router.post("/list", wrap(function* (req, res) {
yield req.auth();
res.json(yield listDirectory(conf.passwordStorePath, filterFiles));
}));
router.post("/get", wrap(function* (req, res) {
const filePath = yield getSecurePath(req.body.path);
// Always authenticate. We shouldn't throw any exception related to the file path before
// authentication, as it could be a privacy leak (= an attacker could craft queries to check if
// a file exists)
yield req.auth(filePath);
if (!filePath) throw new InvalidParameter("Invalid path parameter");
const rawContent = yield fileRead(filePath);
const content = yield conf.keys.decrypt(rawContent, req.body.passphrase);
if (!content.length) throw new Error("The file seems empty");
res.json(content[0].toString());
}));
return router;
}
function launchApp(conf) {
const app = express();
app.use(express.static(path.join(__dirname, "..", "dist")));
app.use("/api", apiRouter(conf));
app.httpsListen = function() {
var server = https.createServer({
key: fs.readFileSync(args.key),
cert: fs.readFileSync(args.cert)
}, this);
return server.listen.apply(server, arguments);
};
app.httpsListen(conf.port, "localhost", function () {
const address = this.address();
log.info`Server listening on https://${address.address}:${address.port}`;
});
}
const args = parseArgs(process.argv, {
alias: {
debug: [ "d" ],
store: [ "s" ],
port: [ "p" ],
key: [ "k" ],
cert: [ "c" ]
},
boolean: [ "debug" ],
});
promiseUtil.run(function* () {
const passwordStorePath = yield realpath(args.store || path.join(process.env.HOME, ".password-store"));
const passwordStoreStat = yield fileStat(passwordStorePath);
if (!passwordStoreStat.isDirectory()) throw new Error(`${passwordStorePath} is not a directory`);
const keys = new Keys();
yield args._.slice(2).map((key) => keys.addFromFile(key));
log.setLevel(args.debug ? log.DEBUG : log.INFO);
launchApp({
passwordStorePath,
keys,
port: args.port || 3000,
});
})
.catch(log.error);
| JavaScript | 0.000009 | @@ -4896,16 +4896,36 @@
app.use(
+args.urlpre %7C%7C %22/%22,
express.
@@ -4979,16 +4979,38 @@
app.use(
+(args.urlpre %7C%7C %22%22) +
%22/api%22,
@@ -5418,16 +5418,30 @@
ss.port%7D
+$%7Bargs.urlpre%7D
%60;%0A %7D);
@@ -5586,16 +5586,37 @@
t: %5B %22c%22
+ %5D,%0A urlpre: %5B %22u%22
%5D%0A %7D,%0A
|
a2bcfb5537f053cd516e8b7bbb09c364d4c60789 | build bump | sites/newspring/mobile-config.js | sites/newspring/mobile-config.js | App.info({
id: 'cc.newspring.newspringapp',
name: 'NewSpring',
description: 'App for NewSpring Church',
author: 'NewSpring Church',
email: '[email protected]',
website: 'https://newspring.cc',
version: '0.0.3',
buildNumber: '92'
});
App.icons({
// iOS
'iphone_2x': 'assets/icons/ios/[email protected]',
'iphone_3x': 'assets/icons/ios/[email protected]',
'ipad': 'assets/icons/ios/icon-76x76.png',
'ipad_2x': 'assets/icons/ios/[email protected]',
'ipad_pro': 'assets/icons/ios/[email protected]',
'ios_settings': 'assets/icons/ios/icon-29x29.png',
'ios_settings_2x': 'assets/icons/ios/[email protected]',
'ios_settings_3x': 'assets/icons/ios/[email protected]',
'ios_spotlight': 'assets/icons/ios/icon-40x40.png',
'ios_spotlight_2x': 'assets/icons/ios/[email protected]',
// Android
'android_mdpi': 'assets/icons/android/icon-48x48-mdpi.png',
'android_hdpi': 'assets/icons/android/icon-72x72-hdpi.png',
'android_xhdpi': 'assets/icons/android/icon-96x96-xhdpi.png',
'android_xxhdpi': 'assets/icons/android/icon-144x144-xxhdpi.png',
'android_xxxhdpi': 'assets/icons/android/icon-192x192-xxxhpdi.png'
});
App.launchScreens({
// iOS
'iphone_2x': 'assets/splash/ios/[email protected]',
'iphone5': 'assets/splash/ios/[email protected]',
'iphone6': 'assets/splash/ios/splash-667h.png',
'iphone6p_portrait': 'assets/splash/ios/splash-1242h-portrait.png',
'iphone6p_landscape': 'assets/splash/ios/splash-1242h-landscape.png',
'ipad_portrait': 'assets/splash/ios/splash-768x1024.png',
'ipad_portrait_2x': 'assets/splash/ios/[email protected]',
'ipad_landscape': 'assets/splash/ios/splash-1024x768.png',
'ipad_landscape_2x': 'assets/splash/ios/[email protected]',
// Android
'android_mdpi_portrait': 'assets/splash/android/splash-320x470.png',
'android_mdpi_landscape': 'assets/splash/android/splash-470x320.png',
'android_hdpi_portrait': 'assets/splash/android/splash-480x640.png',
'android_hdpi_landscape': 'assets/splash/android/splash-640x480.png',
'android_xhdpi_portrait': 'assets/splash/android/splash-720x960.png',
'android_xhdpi_landscape': 'assets/splash/android/splash-960x720.png',
'android_xxhdpi_portrait': 'assets/splash/android/splash-1080x1440.png',
'android_xxhdpi_landscape': 'assets/splash/android/splash-1440x1080.png'
});
App.accessRule('*');
App.setPreference('EnableBitcode', false);
App.setPreference('ShowSplashScreenSpinner', false);
App.setPreference('SplashMaintainAspectRatio', true);
App.setPreference("StatusBarBackgroundColor", "#202020");
App.setPreference("StatusBarStyle", "lightcontent");
| JavaScript | 0 | @@ -234,17 +234,17 @@
mber: '9
-2
+3
'%0A%7D);%0A%0AA
|
ceb8f6cc92fa90ed12ee79ff12d5a82b165ba0f5 | add new cluster to seed | seed.js | seed.js | var User = require('./models/user_model');
var Cluster = require('./models/cluster_model');
var ApiCache = require('./models/api_cache_model');
var ListingCache = require('./models/listing_cache_model');
var async = require('async');
var db = require('./database');
console.log('First, removing everything');
async.each([User, Cluster, ApiCache, ListingCache], function(c, cb) {
c.remove({}, cb);
}, function() {
var users = {};
async.each(['jackfranklin', 'oj206', 'bob'], function(name, cb) {
User.createWithToken({ redditName: name }, function(e, user) {
console.log('CREATED USER:', user.redditName, 'ID:', user.id);
users[name] = user;
cb();
});
}, function() {
var clusters = [
new Cluster({name: 'coding', subreddits: ['vim', 'angularjs', 'swift'], owner: users.jackfranklin, admins: [users.oj206], public: true }),
new Cluster({name: 'lol', subreddits: ['funny', 'tifu'], owner: users.oj206, admins: [], public: false }),
new Cluster({name: 'football', subreddits: ['nufc', 'soccer'], owner: users.jackfranklin, admins: [], subscribers: [users.bob], public: true }),
new Cluster({name: 'nerd', subreddits: ['apple', 'gaming'], owner: users.oj206, admins: [users.jackfranklin], subscribers: [users.bob], public: true }),
new Cluster({name: 'talesfrom', subreddits: ['talesfromtechsupport', 'retail'], owner: users.oj206, admins: [], subscribers: [users.jackfranklin], public: true }),
];
async.each(clusters, function(c, cb) {
c.save(function(e, cluster) {
console.log('CREATED CLUSTER:', cluster.name, 'OWNER:', cluster.owner, 'ADMINS', cluster.admins, 'SUBS', cluster.subscribers, 'PUBLIC:', cluster.public, 'SUBREDDITS', cluster.subreddits);
cb();
});
}, function() {
db.close();
});
});
});
| JavaScript | 0.000001 | @@ -1279,32 +1279,155 @@
ublic: true %7D),%0A
+ new Cluster(%7Bname: 'random', subreddits: %5B'mufc'%5D, owner: users.oj206, admins: %5B%5D, subscribers: %5B%5D, public: true %7D),%0A
new Cluste
|
871629e79ea3de25a66a99271b29e8f7e1c4ea6e | missing s | services/wit.js | services/wit.js | 'use strict'
var Config = require('../config')
var FB = require('../connectors/facebook')
var Wit = require('node-wit').Wit
var request = require('request')
var firstEntityValue = function (entities, entity) {
var val = entities && entities[entity] &&
Array.isArray(entities[entity]) &&
entities[entity].length > 0 &&
entities[entity][0].value
if (!val) {
return null
}
return typeof val === 'object' ? val.value : val
}
var actions = {
send(request, response) {
return new Promise(function(resolve, reject) {
var id = request.context._fbid_;
console.log(JSON.stringify(response),JSON.stringify(request));
if (reponse.quickreplies) {
FB.newQuickReply(id, response.text, response.quickreplies)
} else if (response.text) {
if (checkURL(message)) {
FB.newImage(id, response.text)
} else {
FB.newMessage(id, response.text)
}
}
return resolve();
})
},
say ({sessionId, context, message}) {
// Bot testing mode, run cb() and return
console.log('SAY WANTS TO TALK TO:', context)
console.log('SAY HAS SOMETHING TO SAY:', message)
if (checkURL(message)) {
FB.newImage(context._fbid_, message)
} else {
FB.newMessage(context._fbid_, message)
}
return Promise.resolve(context)
},
merge({sessionId, context, entities, message}) {
// Reset variables
// delete context.suffix
// delete context.name
// Retrive name
// var name = firstEntityValue(entities, 'name')
// if (name) {
// context.name = name
// }
console.log('call merge')
var new_context = {}
// var ord_type = firstEntityValue(entities, 'order_type')
// if (ord_type == 'product') {
// context.product = ord_type
// delete context.printing
// delete context.ask
// }
// else if (ord_type == 'printing') {
// context.printing = ord_type
// delete context.product
// delete context.ask
// }
// else
// {
// context.ask = ord_type
// delete context.product
// delete context.printing
// }
var name = firstEntityValue(entities, 'name')
if (name) {
new_context.name = name
}
var sex = firstEntityValue(entities, 'sex')
if (sex) {
new_context.sex = sex
}
// Reset the cutepics story
return Promise.resolve(context);
},
error({sessionId, context}) {
console.log(error.message)
},
// list of functions Wit.ai can execute
sayHello({sessionId, context}) {
if (context.sex == 'male') {
context.suffix = 'ครับ'
}
else
{
context.suffix = 'ค่ะ'
}
context.name = 'อาม'
return Promise.resolve(context)
}
}
// SETUP THE WIT.AI SERVICE
var getWit = function () {
console.log('GRABBING WIT')
return new Wit({accessToken: Config.WIT_TOKEN, actions, apiVersion: "20170325"})
}
module.exports = {
getWit: getWit,
}
// BOT TESTING MODE
if (require.main === module) {
console.log('Bot testing mode!')
var client = getWit()
client.interactive()
}
// GET WEATHER FROM API
var getWeather = function (location) {
return new Promise(function (resolve, reject) {
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22'+ location +'%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys'
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
var jsonData = JSON.parse(body)
var forecast = jsonData.query.results.channel.item.forecast[0].text
console.log('WEATHER API SAYS....', jsonData.query.results.channel.item.forecast[0].text)
return forecast
}
})
})
}
// CHECK IF URL IS AN IMAGE FILE
var checkURL = function (url) {
return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
}
// LIST OF ALL PICS
var allPics = {
corgis: [
'http://i.imgur.com/uYyICl0.jpeg',
'http://i.imgur.com/useIJl6.jpeg',
'http://i.imgur.com/LD242xr.jpeg',
'http://i.imgur.com/Q7vn2vS.jpeg',
'http://i.imgur.com/ZTmF9jm.jpeg',
'http://i.imgur.com/jJlWH6x.jpeg',
'http://i.imgur.com/ZYUakqg.jpeg',
'http://i.imgur.com/RxoU9o9.jpeg',
],
racoons: [
'http://i.imgur.com/zCC3npm.jpeg',
'http://i.imgur.com/OvxavBY.jpeg',
'http://i.imgur.com/Z6oAGRu.jpeg',
'http://i.imgur.com/uAlg8Hl.jpeg',
'http://i.imgur.com/q0O0xYm.jpeg',
'http://i.imgur.com/BrhxR5a.jpeg',
'http://i.imgur.com/05hlAWU.jpeg',
'http://i.imgur.com/HAeMnSq.jpeg',
],
default: [
'http://blog.uprinting.com/wp-content/uploads/2011/09/Cute-Baby-Pictures-29.jpg',
],
};
| JavaScript | 0.999823 | @@ -651,16 +651,17 @@
%09%09if (re
+s
ponse.qu
|
ea3182e9de3d830fd77121b0bd559960bfc209a9 | improve messaging | GameOfLife/gameoflife.js | GameOfLife/gameoflife.js | "use strict";
var assert = require('assert');
var LIVE = 1;
var DEAD = 0;
var cellState = function(currentCellState, numberOfAliveNeighbours) {
var twoOrThreeNeighbours = numberOfAliveNeighbours === 2 ||
numberOfAliveNeighbours === 3;
if (numberOfAliveNeighbours < 2 || numberOfAliveNeighbours > 3) {
return DEAD;
}
else if (currentCellState === LIVE && twoOrThreeNeighbours) {
return LIVE;
}
else if (currentCellState === DEAD && numberOfAliveNeighbours === 3) {
return LIVE;
}
};
describe('Game of life', function() {
describe('cell', function() {
it('fewer than two neighbours dies', function() {
assert.equal(DEAD, cellState(LIVE,1));
});
it('more than 3 alive cells dies', function() {
assert.equal(DEAD, cellState(LIVE,4));
});
it('live cells with 2 or 3 neighbours live on', function() {
assert.equal(LIVE, cellState(LIVE,2));
assert.equal(LIVE, cellState(LIVE,3));
});
it('dead cells with exactly 3 neighbours live', function() {
assert.equal(LIVE, cellState(DEAD,3));
});
it('should be defined for all input types', function() {
for (var i=0;i<=8;++i) {
assert(undefined !== cellState(DEAD,i));
assert(undefined !== cellState(LIVE,i));
}
});
});
});
| JavaScript | 0.00039 | @@ -1242,16 +1242,49 @@
(DEAD,i)
+, 'dead with ' + i + 'neighbours'
);%0A
@@ -1324,16 +1324,49 @@
(LIVE,i)
+, 'live with ' + i + 'neighbours'
);%0A
|
2b4617a754635ae5e5a294eac16368d903901393 | Fix indentation | GitHubSourceTree.user.js | GitHubSourceTree.user.js | // ==UserScript==
// @name GitHubSourceTree
// @namespace http://really-serious.biz/
// @version 1.0.1
// @description Adds a "Clone in SourceTree" button to github pages
// @respository https://github.com/jamesgarfield/GitHubSourceTree
// @match https://*github.com/*
// @copyright 2014+, James Garfield
// ==/UserScript==
(function(){
const $ = document.querySelectorAll.bind(document);
const gitHubNode = $(".clone-options + a")[0]
if (!gitHubNode) {
return;
}
const parentNode = gitHubNode.parentNode;
const insertBeforeNode = gitHubNode.nextSibling;
const gitURL = $(".clone-url-box .js-url-field")[0].value
var sourceTreeNode = gitHubNode.cloneNode();
sourceTreeNode.href = 'sourcetree://cloneRepo/' + gitURL;
sourceTreeNode.innerHTML = '<span class="octicon octicon-device-desktop"></span>Clone in SourceTree';
parentNode.insertBefore(sourceTreeNode, insertBeforeNode);
})()
| JavaScript | 0.017244 | @@ -104,17 +104,17 @@
1.0.
-1
+2
%0A// @des
@@ -344,17 +344,20 @@
tion()%7B%0A
-%09
+
const $
|
a05570d6416279d4324b41797dcc015dff11ec50 | test spelling | test.js | test.js | var assert = require('assert');
var five = require('./');
assert.equal(5, five(), 'Five should give you five');
assert.notEqual(6, five(), 'Five should not give you not five');
assert.equal('⁵', five.upHigh(), 'An up high five should be a superscripted 5');
assert.equal('₅', five.downLow(), 'A down low five should be a subscripted 5');
assert.equal('V', five.roman(), 'A roman five should be a V');
assert.equal('خمسة', five.arabic(), 'A arabic five should be خمسة');
assert.equal('pet', five.croatian(), 'A croatian five should be pet');
assert.equal('pět', five.czech(), 'A czech five should be pět');
assert.equal('Five', five.english(), 'A english five should be Five');
assert.equal('cinq', five.french(), 'A french five should be cinq');
assert.equal('fünf', five.german(), 'A german five should be fünf');
assert.equal('cúig', five.irish(), 'A irish five should be cúig');
assert.equal('таван', five.mongolian(), 'A mongolian five should be таван');
assert.equal('pięć', five.polish(), 'A polish five should be pięć');
assert.equal('pet', five.slovenian(), 'A slovenian five should be pet');
assert.equal('fem', five.swedish(), 'A swedish five should be fem');
assert.equal('ห้า', five.thai(), 'A thai five should be ห้า');
assert.equal('tahlapi', five.choctaw(), 'A choctaw five should be tahlapi');
assert.equal('ivefay', five.piglatin(), 'A piglatin five should be ivefay');
assert.equal('di-di-di-di-dit', five.morseCode(), 'A five in morse code should be di-di-di-di-dit');
assert.equal('101', five.binary(), 'A binary five should be 101');
assert.equal('5', five.octal(), 'An octal five should be 5');
var now = new Date().valueOf();
var slowFive = five.tooSlow();
var finishes = new Date().valueOf();
assert.equal(5, slowFive, 'A too slow five should still be five');
assert.ok((finishes - now) > 500, 'A too slow five should take longer than 500 milliseconds to be returned, blocking execution and generally being a bad idea');
assert.equal(["Juwan Howard","Ray Jackson","Jimmy King","Jalen Rose","Chris Weber"],five.fab(),'A fab five should be the 1991-1993 Michigan Mens Basketball Team');
assert.equal(JSON.stringify([5, 5, 5]), JSON.stringify(five.map([1, 2, 3])));
assert.equal(5, five.reduce([1, 2, 3]));
process.exit(0);
| JavaScript | 0.000134 | @@ -2029,16 +2029,17 @@
Weber%22%5D,
+
five.fab
@@ -2041,16 +2041,17 @@
e.fab(),
+
'A fab f
|
858be8428637a6541bd498d972a712bbc34ea4a1 | test coverage | test.js | test.js | const test = require('tape')
const reduce = require('./')
const Promise = require('any-promise')
test('promise-reduce should assert input types', function (t) {
t.plan(1)
t.throws(reduce.bind(null, 123))
})
test('promise-reduce should accept a single val', function (t) {
t.plan(1)
const res = Promise.resolve(2)
.then(reduce(reduceFn, 3))
.then(checkFn)
function reduceFn(prev, next) {
return prev + next
}
function checkFn(val) {
t.equal(5, val)
}
})
test('promise-reduce should reduce a fn', function (t) {
t.plan(1)
const res = Promise.resolve([1, 2, 3])
.then(reduce(reduceFn, 0))
.then(checkFn)
function reduceFn(prev, next) {
return prev + next
}
function checkFn(val) {
t.equal(6, val)
}
})
test('should pass reducer arguments to callback', function(t) {
const arrTest = [1, 2]
const res = Promise.resolve(arrTest)
.then(reduce(reduceFn, 0))
.then(checkFn)
function reduceFn(prev, next, index, arr) {
t.equal(4, arguments.length)
t.equal(arrTest, arr)
return new Promise(function (resolve) {
setTimeout(function () {
resolve(prev + next)
}, 1)
})
}
function checkFn(val) {
t.equal(3, val)
t.end()
}
})
test('should not continue until last iteration has been resolved', function (t) {
t.plan(1)
const res = Promise.resolve([1, 2, 3])
.then(reduce(reduceFn, 0))
.then(checkFn)
function reduceFn(prev, next) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(prev + next)
}, 1)
})
}
function checkFn(val) {
t.equal(6, val)
}
})
test('should not call callback when initial value is undefined and iterable contains one item', function (t) {
t.plan(1)
const res = Promise.resolve([1])
.then(reduce(reduceFn, undefined))
.then(checkFn)
function reduceFn(prev, next) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(prev + next)
}, 1)
})
}
function checkFn(val) {
t.equal(1, val, 'should return the item in iterable')
}
})
test('should not call callback when iterable is empty', function (t) {
t.plan(1)
const res = Promise.resolve([])
.then(reduce(reduceFn, 10))
.then(checkFn)
function reduceFn(prev, next) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(prev + next)
}, 1)
})
}
function checkFn(val) {
t.equal(10, val, 'should return initial value')
}
})
| JavaScript | 0.000201 | @@ -1825,24 +1825,29 @@
(reduce(
-reduceFn
+function() %7B%7D
, undefi
@@ -1876,170 +1876,8 @@
n)%0A%0A
- function reduceFn(prev, next) %7B%0A return new Promise(function (resolve) %7B%0A setTimeout(function () %7B%0A resolve(prev + next)%0A %7D, 1)%0A %7D)%0A %7D%0A%0A
fu
@@ -2098,24 +2098,29 @@
(reduce(
-reduceFn
+function() %7B%7D
, 10))%0A
@@ -2142,170 +2142,8 @@
n)%0A%0A
- function reduceFn(prev, next) %7B%0A return new Promise(function (resolve) %7B%0A setTimeout(function () %7B%0A resolve(prev + next)%0A %7D, 1)%0A %7D)%0A %7D%0A%0A
fu
|
323a5651003984c8f2cb7da1b6f6c8e9d6b38f84 | update tests | test.js | test.js | import test from 'ava';
import mvg from '.';
test('Load station', async t => {
const station = await mvg.getStation(953);
const expectedStationInfo = {
type: 'station',
latitude: 48.108379,
longitude: 11.663822,
id: 953,
place: 'München',
name: 'Feldbergstraße',
hasLiveData: true,
hasZoomData: false,
products: ['b'],
lines: {
tram: [],
nachttram: [],
sbahn: [],
ubahn: [],
bus: [],
nachtbus: [],
otherlines: []
}
};
t.deepEqual(station, expectedStationInfo);
});
| JavaScript | 0.000001 | @@ -353,11 +353,30 @@
: %5B'
-b'%5D
+BUS'%5D,%0A link: 'FBE'
,%0A
|
93bfd985a6a552de9340ee2937589ce1833ba784 | Remove del dependency. | test.js | test.js | 'use strict';
var del = require('del');
var path = require('path');
var helpers = require('yeoman-generator').test;
describe(require('./package.json').name, function () {
beforeEach(function (cb) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
cb(err);
return;
}
this.generator = helpers.createGenerator('postcss:app', ['../app']);
cb();
}.bind(this));
});
it('generates expected files', function (cb) {
var expected = [
'.editorconfig',
'.gitignore',
'.jshintrc',
'.npmignore',
'.travis.yml',
'index.js',
'LICENSE-MIT',
'package.json',
'README.md',
'test.js'
];
helpers.mockPrompt(this.generator, {
pluginName: 'postcss-superb',
pluginDescription: 'test description',
githubName: 'test',
authorUrl: 'http://test.com'
});
this.generator.run(function () {
helpers.assertFile(expected);
cb();
});
});
});
| JavaScript | 0 | @@ -12,34 +12,8 @@
';%0A%0A
-var del = require('del');%0A
var
|
c7f893203d72da300bc58b726e59da78534c7a97 | fix hints in test | test.js | test.js | var assert = require('assert');
var expect = require('chai').expect;
var nodePkg = require('./package.json');
var bowerPkg = require('./bower.json');
var frpc = require('./frpc');
var testDate = "1987-12-22T16:20:29.000Z";
var method = "method";
var params = [
123, // int
true, // bool
false, // bool
(100).toFixed(2), // double
"Name", // string
new Date(testDate), // datetime
101 >> 1, // binary
567188429000, // positive
-567188429000, // negative
{ // struct
name: "David",
surname: "Rus",
date: new Date(testDate)
},
[0, 1, "text"], // array
null // null
];
var testDataBase64 = "yhECAWgGbWV0aG9kOHsRECAGMTAwLjAwIAROYW1lKADNm84h6ihoeTA4MjzImBAPhETImBAPhFADBG5hbWUgBURhdmlkB3N1cm5hbWUgA1J1cwRkYXRlKADNm84h6ihoeTBYA0AAOAEgBHRleHRg";
var testDataBuffer = new Buffer(testDataBase64, 'base64');
before(function() {
// Force UTC as a local timezone
Date.prototype.real_getTimezoneOffset = Date.prototype.getTimezoneOffset;
Date.prototype.real_getHours = Date.prototype.getHours;
Date.prototype.real_getMinutes = Date.prototype.getMinutes;
Date.prototype.getHours = function() {
var offset = parseInt(this.real_getTimezoneOffset() / 60);
return this.real_getHours() + offset;
};
Date.prototype.getMinutes = function() {
var offset = this.real_getTimezoneOffset() % 60;
return this.real_getMinutes() + offset;
};
Date.prototype.getTimezoneOffset = function() {
return 0;
};
});
describe('node-fastrpc', function() {
describe('metadata', function() {
it('bower.json vs. package.json', function() {
assert.equal(nodePkg.name, bowerPkg.name);
assert.equal(nodePkg.version, bowerPkg.version);
assert.equal(nodePkg.description, bowerPkg.description);
assert.equal(nodePkg.license, bowerPkg.license);
assert.equal(nodePkg.main, bowerPkg.main);
});
});
describe('methods', function(){
it('serializeCall()', function(){
var bin = frpc.serializeCall(method, params);
var data = new Buffer(bin);
expect(data).to.deep.equal(testDataBuffer);
});
it('parse()', function(){
var data = frpc.parse(testDataBuffer);
expect(data.method).to.be.equal(method);
expect(JSON.stringify(data.params)).to.deep.equal(JSON.stringify(params));
});
});
});
| JavaScript | 0.00002 | @@ -409,25 +409,25 @@
-(
100
-).toFixed(2),
+,
@@ -564,16 +564,16 @@
-101 %3E%3E 1
+%5B69, 96%5D
,
@@ -1001,45 +1001,49 @@
HsRE
-CAGMTAwLjAwIAROYW1lKADNm84h6ihoeTA4Mj
+BgAAAAAAABZQCAETmFtZSj8zZvOIeqoaHkwMAJFYD
zImB
@@ -1101,26 +1101,26 @@
XRlK
-AD
+Pz
Nm84h6
-i
+q
hoeTBYA
-0A
+zg
AOAE
@@ -2335,32 +2335,33 @@
ods', function()
+
%7B%0A it('se
@@ -2378,32 +2378,33 @@
l()', function()
+
%7B%0A va
@@ -2444,16 +2444,45 @@
, params
+, %7B'3':'float', '6':'binary'%7D
);%0A
@@ -2617,16 +2617,17 @@
nction()
+
%7B%0A
|
738341e8e8e7777693ab6b400d13c40da46a1f33 | order for arguments of assert.equals | test.js | test.js | var sanitize = require('./index.js');
var assert = require('assert');
var express = require('express');
var superagent = require('superagent');
describe('sanitize', function() {
it('should remove fields that start with $ from objects', function() {
assert.equal(0, Object.keys(sanitize({ $gt: 5 })).length);
var o = sanitize({ $gt: 5, a: 1 });
assert.equal(1, Object.keys(o).length);
assert.equal('a', Object.keys(o)[0]);
assert.equal(1, o.a);
});
it('should do nothing for numbers and strings', function() {
assert.equal(1, sanitize(1));
assert.equal('a', sanitize('a'));
});
it('should do nothing for arrays', function() {
assert.deepEqual([1, 2, 3], sanitize([1, 2, 3]));
});
it('shouldnt be fooled by non-POJOs', function() {
var Clazz = function() {
this.$gt = 5;
this.a = 1;
};
var o = sanitize(new Clazz());
assert.equal(1, Object.keys(o).length);
assert.equal('a', Object.keys(o)[0]);
assert.equal(1, o.a);
});
it('should remove nested fields', function () {
var obj = { username: { $ne: null }};
assert.deepEqual(sanitize(obj), { username: {} });
var issue3 = { "foo": { "bar": { "$ref": "foo" } } };
assert.deepEqual(sanitize(issue3), { foo: { bar: {} } })
});
it('should do nothing for null or undefined', function () {
assert.equal(null, sanitize(null));
assert.equal(undefined, sanitize(undefined));
assert.deepEqual(sanitize({ 'a': null }), { 'a': null });
});
});
describe('sanitize express integration', function() {
var app;
var server;
beforeEach(function() {
app = express();
app.use(require('body-parser').urlencoded({extended: true}));
app.use(require('body-parser').json());
server = app.listen(8081);
});
afterEach(function() {
server.close();
});
it('should sensibly sanitize query params', function(done) {
app.get('/test', function(req, res) {
assert.equal(0, Object.keys(sanitize(req.query.username)).length);
done();
});
superagent.get('http://localhost:8081/test?username[$gt]=', function(){});
});
it('should sensibly sanitize body JSON', function(done) {
app.post('/test', function(req, res) {
var clean = sanitize(req.body.username);
assert.equal(1, Object.keys(clean).length);
assert.equal('a', Object.keys(clean)[0]);
assert.equal(1, clean.a);
assert.deepEqual([1, 2, 3], req.body.arr);
done();
});
superagent.post('http://localhost:8081/test').send({
username: { $gt: "", a: 1 },
arr: [1, 2, 3]
}).end();
});
});
| JavaScript | 0.000001 | @@ -237,32 +237,56 @@
', function() %7B%0A
+ // %7B $gt: 5 %7D -%3E %7B%7D%0A
assert.equal
@@ -278,35 +278,32 @@
assert.equal(
-0,
Object.keys(sani
@@ -330,161 +330,183 @@
ngth
+, 0
);%0A
-%0A
-var o = sanitize(%7B $gt: 5, a: 1 %7D);%0A assert.equal(1, Object.keys(o).length);%0A assert.equal('a', Object.keys(o)%5B0%5D);%0A assert.equal(1, o.a
+// %7B $gt: 5, a: 1 %7D -%3E %7B a: 1 %7D%0A assert.deepEqual(sanitize(%7B $gt: 5, a: 1 %7D), %7B a: 1 %7D);%0A // %7B $gt: '' %7D -%3E %7B%7D%0A assert.deepEqual(sanitize(%7B '$gt': '' %7D), %7B%7D
);%0A
@@ -591,19 +591,16 @@
t.equal(
-1,
sanitize
@@ -602,16 +602,19 @@
itize(1)
+, 1
);%0A a
@@ -625,21 +625,16 @@
t.equal(
-'a',
sanitize
@@ -638,16 +638,21 @@
ize('a')
+, 'a'
);%0A %7D);
@@ -724,27 +724,16 @@
epEqual(
-%5B1, 2, 3%5D,
sanitize
@@ -743,16 +743,27 @@
, 2, 3%5D)
+, %5B1, 2, 3%5D
);%0A %7D);
@@ -942,106 +942,29 @@
ert.
-e
+deepE
qual(
-1, Object.keys(o).length);%0A assert.equal('a', Object.keys(o)%5B0%5D);%0A assert.equal(1, o.a
+o, %7B a: 1 %7D
);%0A
@@ -1923,11 +1923,8 @@
ual(
-0,
Obje
@@ -1959,32 +1959,35 @@
sername)).length
+, 0
);%0A done();
@@ -2249,126 +2249,38 @@
ert.
-equal(1, Object.keys(clean).length);%0A assert.equal('a', Object.keys(clean)%5B0%5D);%0A assert.equal(1, clean.a
+deepEqual(clean, %7B 'a': 1 %7D
);%0A
-%0A
@@ -2302,19 +2302,8 @@
ual(
-%5B1, 2, 3%5D,
req.
@@ -2310,20 +2310,30 @@
body.arr
+, %5B1, 2, 3%5D
);%0A
-%0A
do
|
1c35b46cb7612bce06264a470aa022b8eb8ea0ab | test for xo binary since eslint is not used anymore | test.js | test.js | import {join} from 'path';
import test from 'ava';
import concat from 'stream-string';
import spawnShell from './';
test('Use shell to run commands', async t => {
const p = spawnShell('echo "it works"', {
stdio: [0, 'pipe', 2]
});
const output = await concat(p.stdout);
t.is(output, 'it works\n');
});
test('Returned ChildProcess has a exitPromise prop that resolve with process exit code', async t => {
const p = spawnShell('exit 1');
const exitCode = await p.exitPromise;
t.is(exitCode, 1);
});
test('Returned ChildProcess exitPromise is rejected on spawn errors', async t => {
const p = spawnShell('', {shell: 'unknown'});
const err = await t.throws(p.exitPromise);
t.is(err.code, 'ENOENT');
});
test('inject your package `node_modules/.bin` directory in path', async t => {
const p = spawnShell('which eslint', {
stdio: [0, 'pipe', 2],
shell: 'sh'
});
const output = await concat(p.stdout);
t.is(output, join(__dirname, '/node_modules/.bin/eslint\n'));
});
| JavaScript | 0 | @@ -818,22 +818,18 @@
('which
-eslint
+xo
', %7B%0A%09%09s
@@ -964,14 +964,10 @@
bin/
-eslint
+xo
%5Cn')
|
cfd9cb4c7ef2e63f268c475cfd99120a1a4ddf53 | make test run | test.js | test.js | var Transform = require('stream').Transform
, test = require('tape')
, bufferedTransform = require('./stream')
, collectData = function (stream, callback) {
var data = []
stream.on('data', function (chunk) {
data.push(chunk)
})
stream.once('end', function () {
callback(null, data)
})
}
test('stream with one chunk and one data block', function (t) {
t.plan(4)
var stream = new Transform()
stream._transform = bufferedTransform(
function (chunks, callback) {
t.equal(chunks.length, 1, 'correct number of chunks')
t.deepEqual(chunks[0], new Buffer([ 1, 2, 3, 4, 5 ]))
this.push(chunks[0])
callback()
}
)
collectData(stream, function (err, data) {
t.equal(data.length, 1, 'correct chunks emitted')
t.deepEqual(data[0], new Buffer([ 1, 2, 3, 4, 5 ]))
t.end()
})
stream.write(new Buffer([
// size
5, 0, 0, 0,
// data
1, 2, 3, 4, 5
]))
stream.end()
})
test('stream with 1 byte chunks', function (t) {
var stream = new Transform()
, count = 0
, expected = [
new Buffer([ 1, 2, 3 ])
, new Buffer([ 4, 7, 1, 1 ])
, new Buffer([ 9 ])
]
stream._transform = bufferedTransform(
function (chunks, callback) {
var self = this
t.equal(chunks.length, 1, 'correct number of chunks')
t.deepEqual(chunks[0], expected[count])
count++
chunks.forEach(function (chunk) {
self.push(chunk)
})
callback()
}
)
collectData(stream, function (err, data) {
t.equal(data.length, 3, 'correct chunks emitted')
t.deepEqual(data[0], new Buffer([ 1, 2, 3 ]))
t.deepEqual(data[1], new Buffer([ 4, 7, 1, 1 ]))
t.deepEqual(data[2], new Buffer([ 9 ]))
t.end()
})
;[
// size
3, 0, 0, 0,
// data
1, 2, 3,
// size
4, 0, 0, 0,
// data
4, 7, 1, 1,
// size
1, 0, 0, 0,
9
].forEach(function (num) {
stream.write(new Buffer([ num ]))
})
stream.end()
})
test('stream with chunks of different lengths', function (t) {
var stream = new Transform()
, count = 0
, expected = [
new Buffer([ 1, 2, 3 ])
, new Buffer([ 4, 7, 1, 1 ])
, new Buffer([ 9 ])
]
, input = [
// size
3, 0, 0, 0,
// data
1, 2, 3,
// size
4, 0, 0, 0,
// data
4, 7, 1, 1,
// size
1, 0, 0, 0,
9
]
stream._transform = bufferedTransform(
function (chunks, callback) {
var self = this
t.equal(chunks.length, 1, 'correct number of chunks')
t.deepEqual(chunks[0], expected[count])
count++
chunks.forEach(function (chunk) {
self.push(chunk)
})
callback()
}
)
collectData(stream, function (err, data) {
t.equal(data.length, 3, 'correct chunks emitted')
t.deepEqual(data[0], new Buffer([ 1, 2, 3 ]))
t.deepEqual(data[1], new Buffer([ 4, 7, 1, 1 ]))
t.deepEqual(data[2], new Buffer([ 9 ]))
t.end()
})
for(var i = 0; i + 4 < input.length; i += 4)
stream.write(new Buffer(input.slice(i, i + 4)))
stream.write(new Buffer(input.slice(i)))
stream.end()
})
test('stream with one chunk with multiple data blocks', function (t) {
var stream = new Transform()
stream._transform = bufferedTransform(
function (chunks, callback) {
var self = this
t.equal(chunks.length, 3, 'correct number of chunks')
t.deepEqual(chunks[0], new Buffer([ 1, 2, 3 ]))
t.deepEqual(chunks[1], new Buffer([ 4, 7, 1, 1 ]))
t.deepEqual(chunks[2], new Buffer([ 9 ]))
chunks.forEach(function (chunk) {
self.push(chunk)
})
callback()
}
)
collectData(stream, function (err, data) {
t.equal(data.length, 3, 'correct chunks emitted')
t.deepEqual(data[0], new Buffer([ 1, 2, 3 ]))
t.deepEqual(data[1], new Buffer([ 4, 7, 1, 1 ]))
t.deepEqual(data[2], new Buffer([ 9 ]))
t.end()
})
stream.write(new Buffer([
// size
3, 0, 0, 0,
// data
1, 2, 3,
// size
4, 0, 0, 0,
// data
4, 7, 1, 1,
// size
1, 0, 0, 0,
9
]))
stream.end()
}) | JavaScript | 0.999597 | @@ -100,21 +100,33 @@
uire('./
-strea
+buffered-transfor
m')%0A%0A ,
|
657ef147ea6b1b59d6c24481a8bc6801a7fdf922 | test now computes hashes in prepare stage | test.js | test.js | /**
* DiscordForge - a plugin system for Discord.
* Copyright (C) 2017 DiscordForge Development
*
* 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 3 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
const assert = require('assert');
const fs = require('fs');
const {fork} = require('child_process');
const os = require('os');
const path = require('path');
const dforgeDir = path.join(os.homedir(), '.discordforge');
const checksum = require('checksum');
describe('Files', () => {
it('should have bootstrap.js', () => {
if (fs.existsSync('bootstrap.js') === false)
throw new Error('File missing.');
});
it('should have index.js', () => {
if (fs.existsSync('index.js') === false)
throw new Error('File missing.');
});
it('should have modloader.js', () => {
if (fs.existsSync('modloader.js') === false)
throw new Error('File missing.');
});
it('should have setup.js', () => {
if (fs.existsSync('setup.js') === false)
throw new Error('File missing.');
});
it('should have LICENSE', () => {
if (fs.existsSync('LICENSE') === false)
throw new Error('File missing.');
});
});
describe('Setup', () => {
before(function(done) {
this.timeout(60000);
console.log('\nThis test requires the setup script to be executed first. We will now install DiscordForge as if the end user is installing it.\n[Timeout: 1 minute]\n');
let setup = fork('setup.js');
setup.on('exit', (code) => {
if (code !== 0)
throw new Error(`Setup exited with code ${code}`);
console.log('\nDone installing. We will now continue with testing.\n');
done();
});
});
it('should have made a directory in the home directory', () => {
if (fs.existsSync(dforgeDir) === false)
throw new Error('Directory missing.');
});
it('should have made a plugins directory', () => {
if (fs.existsSync(path.join(dforgeDir, 'plugins')) === false)
throw new Error('Directory missing.');
});
it('should have made a modloader directory', () => {
if (fs.existsSync(path.join(dforgeDir, 'modloader')) === false)
throw new Error('Directory missing.');
});
it('should have made a modloader.js', () => {
if (fs.existsSync(path.join(dforgeDir, 'modloader', 'modloader.js')) === false)
throw new Error('File missing.');
});
it('should have made an exact copy of the modloader', () => {
let sumCurrent, sumCopy;
checksum.file(path.join(dforgeDir, 'modloader', 'modloader.js'), (err, sum) => {
sumCopy = sum;
});
checksum.file('modloader.js', (err, sum) => {
sumCurrent = sum;
});
assert.equal(sumCurrent, sumCopy);
});
}); | JavaScript | 0 | @@ -1662,16 +1662,42 @@
() =%3E %7B%0A
+%09let sumCurrent, sumCopy;%0A
%09before(
@@ -1809,16 +1809,48 @@
ed first
+, and file hashes to be computed
. We wil
@@ -2115,41 +2115,278 @@
ng.
-We will now continue with testing
+Now creating hashes.%5Cn');%0A%09%09%09checksum.file(path.join(dforgeDir, 'modloader', 'modloader.js'), (err, sum) =%3E %7B%0A%09%09%09%09sumCopy = sum;%0A%09%09%09%7D);%0A%09%09%09checksum.file('modloader.js', (err, sum) =%3E %7B%0A%09%09%09%09sumCurrent = sum;%0A%09%09%09%7D);%0A%09%09%09console.log('Created hashes. Testing may now continue
.%5Cn'
@@ -3133,217 +3133,8 @@
%3E %7B%0A
-%09%09let sumCurrent, sumCopy;%0A%09%09checksum.file(path.join(dforgeDir, 'modloader', 'modloader.js'), (err, sum) =%3E %7B%0A%09%09%09sumCopy = sum;%0A%09%09%7D);%0A%09%09checksum.file('modloader.js', (err, sum) =%3E %7B%0A%09%09%09sumCurrent = sum;%0A%09%09%7D);%0A
%09%09as
|
deefc10ea7e401ec3d7892c377c29062d8ca47da | update `emit end` test | test.js | test.js | 'use strict';
/* deps: mocha */
var assert = require('assert');
var minimist = require('minimist');
var plugins = require('./');
var cli;
describe('minimist', function () {
beforeEach(function () {
cli = plugins(minimist);
});
it('should throw if `minimist` not function', function (done) {
function fixture () {
plugins(123);
}
assert.throws(fixture, TypeError);
assert.throws(fixture, /expect `minimist` be function/);
done();
});
it('should parse arguments without any plugins:', function (done) {
cli.parse(['--a', '--b'], function (err, argv) {
assert.equal(argv.a, true);
assert.equal(argv.b, true);
done();
});
});
it('should chain plugins:', function () {
cli.use(function () {
return function (argv) {
argv.foo = 'bar';
};
})
.use(function () {
return function (argv) {
argv.baz = 'quux';
};
});
cli.parse(['--a', '--b'], function (err, argv) {
assert.equal(argv.foo === 'bar', true);
assert.equal(argv.baz === 'quux', true);
assert.equal(argv.a === true, true);
assert.equal(argv.b === true, true);
done();
});
});
it('should expose args on the `argv` object:', function (done) {
cli.parse(['a', 'b', 'c'], function (err, res) {
assert.deepEqual(res._, ['a', 'b', 'c']);
done();
});
});
it('should expose options on the `argv` object:', function (done) {
cli.parse(['a', 'b', 'c', '--foo=bar'], function (err, res) {
assert.equal(res.foo, 'bar');
done();
});
});
it('should emit `end` after all args are emitted:', function (done) {
var i = 0;
function set(key, value) {
return function (cli) {
return function (argv, next) {
argv[key] = value;
next(null, argv);
};
};
}
cli.use(set('aaa', 'bbb'))
cli.use(set('ccc', 'ddd'))
cli.use(set('eee', 'fff'))
cli.on('end', function (argv) {
i++;
});
cli.parse(['a', 'b', 'c', '--foo=bar'], function (err, argv) {
assert.equal(i, 1);
assert.equal(argv.aaa, 'bbb');
assert.equal(argv.ccc, 'ddd');
assert.equal(argv.eee, 'fff');
done();
});
});
it('should done callback be optional', function (done) {
var _cli = cli.parse(['a', 'b']);
assert.equal(typeof _cli.minimist, 'function');
done();
});
});
| JavaScript | 0 | @@ -2005,24 +2005,135 @@
on (argv) %7B%0A
+ assert.equal(argv.aaa, 'bbb');%0A assert.equal(argv.ccc, 'ddd');%0A assert.equal(argv.eee, 'fff');%0A
i++;%0A
|
eff00849e440da2c9498c1e7f71073cb48657e33 | fix tests :white_check_mark: | test.js | test.js | 'use strict'
const test = require('tape')
const sortBy = require('lodash.sortby')
const autocomplete = require('.')
test('autocomplete returns an array', (t) => {
t.plan(2)
t.ok(Array.isArray(autocomplete('', 3)))
t.ok(Array.isArray(autocomplete('foo', 3)))
})
test('autocomplete returns an empty array for an empty query', (t) => {
t.plan(1)
const results = autocomplete('', 3)
t.equal(results.length, 0)
})
test('autocomplete sorts by score', (t) => {
t.plan(1)
const results = autocomplete('statio', 3)
t.deepEqual(results, sortBy(results, 'score').reverse())
})
test('autocomplete limits the number of results', (t) => {
t.plan(1)
t.equal(autocomplete('statio', 1).length, 1)
})
test('gives reasonable results', (t) => {
const r0 = autocomplete('U Seestr.', 1)[0]
t.ok(r0)
t.equal((r0 || {}).id, '900000009103')
const r1 = autocomplete('S Heerstr.', 1)[0]
t.ok(r1)
t.equal((r1 || {}).id, '900000026105')
const r2 = autocomplete('kotti', 1, true)[0]
t.ok(r2)
t.equal((r2 || {}).id, '900000013102')
const r3 = autocomplete('S+U Alexanderplatz', 1, true, false)[0]
t.ok(r3)
t.equal((r3 || {}).id, '900000100003')
t.end()
})
| JavaScript | 0 | @@ -675,16 +675,17 @@
('statio
+n
', 1).le
|
134fcb59ea74c618f3cdd3ae21afe9629433caf5 | Add test for missing id, closes #13 | test.js | test.js | 'use strict'
// setup
import test from 'ava'
import scrud from './index'
import axios from 'axios'
import getScrud from 'get-scrud'
const allowOrigins = ['localhost']
const postBody = {
first: 'andrew',
last: 'carpenter',
zip: 37601,
email: '[email protected]'
}
const basePath = '/api'
const port = 8092
const apiOpts = {host: 'localhost', port, basePath, timeout: '10s'}
const putBody = {zip: 37615}
const logger = () => {}
const opts = {
port,
base: basePath,
namespace: 'scrud',
allowOrigins,
logger,
setScrudHeader: true,
jsonwebtoken: {
secret: `SomeRandomAstString`,
algorithm: `HS256`,
issuer: `SCRUD`,
audience: `client`,
expiresIn: 1800
}
}
Object.assign(opts, require('./../_secrets/scrud/config.json'))
const { sendData } = scrud
// globals
let id, apiCall, jwt
// tests
test.before(async () => {
await scrud.register('member')
await scrud.start(opts)
jwt = await scrud.genToken({some: 'stuffs'})
apiCall = getScrud(Object.assign({jwt}, apiOpts))
})
test.serial('CREATE', async (assert) => {
// create first so that we can expect data in other actions
let c = await apiCall('member', 'create', postBody)
id = c.id
assert.truthy(id)
})
test.serial('SEARCH', async (assert) => {
let s = await apiCall('member', 'search', {first: 'andrew'})
assert.true(Array.isArray(s) && s.length > 0)
})
test.serial('READ', async (assert) => {
let r = await apiCall('member', 'read', id)
assert.is(r.zip, '37601')
})
test.serial('UPDATE', async (assert) => {
let u = await apiCall('member', 'update', id, putBody)
assert.is(u.zip, '37615')
})
test.serial('DELETE', async (assert) => {
await assert.notThrows(apiCall('member', 'delete', id))
})
test.serial('regession: body parses gracefully', async (assert) => {
let url = `http://localhost:${port}${basePath}/member/${id}`
let headers = {Authorization: `Bearer ${jwt}`}
await assert.notThrows(axios({method: 'PUT', url, data: 'u', headers}))
})
test.skip('close ends pg client (not really testable)', async (assert) => {
let url = `http://localhost:${port}${basePath}/member?first=andrew`
await assert.throws(axios({method: 'GET', url, timeout: 3}))
})
test('register throws with no name', async (assert) => {
await assert.throws(scrud.register(), Error, 'register throws with no name')
})
test('register returns resource object', async (assert) => {
let resource = await scrud.register('profile')
assert.truthy(resource, 'resource is defined')
assert.truthy(resource.hasOwnProperty('name'), 'resource has name')
assert.is(resource.name, 'profile')
})
test(`exported resource DB helpers work as expected`, async (assert) => {
let locId = (await scrud.insert('member', {params: {zip: 37615}})).id
assert.is((await scrud.findAll('member', {params: {id: locId}}))[0].zip, '37615')
await assert.notThrows(scrud.save('member', {id: locId, params: {zip: '37610'}}))
assert.is((await scrud.find('member', {id: locId, params: {}})).zip, '37610')
await assert.notThrows(scrud.destroy('member', {id: locId, params: {}}))
})
test(`exported SCRUD helpers work as expected`, async (assert) => {
let locId = (await scrud.create('member', {params: {zip: 37615}})).id
assert.is((await scrud.search('member', {params: {id: locId}}))[0].zip, '37615')
await assert.notThrows(scrud.update('member', {id: locId, params: {zip: 37610}}))
assert.is((await scrud.read('member', {id: locId, params: {}})).zip, '37610')
await assert.notThrows(scrud.delete('member', {id: locId, params: {}}))
})
test(`basePth and path edge cases are handled properly`, async (assert) => {
let hdl = (req, res) => Promise.resolve(sendData(res, 'test'))
let handlers = {search: hdl, create: hdl, read: hdl, update: hdl, delete: hdl}
await scrud.register('api', handlers)
let headers = {Authorization: `Bearer ${jwt}`}
let res
res = await axios(`http://localhost:${port}${basePath}/api/1`, {headers})
assert.is(res.headers.scrud, 'api:read')
res = await axios(`http://localhost:${port}${basePath}/api/1?j=2`, {headers})
assert.is(res.headers.scrud, 'api:read')
res = await axios(`http://localhost:${port}${basePath}/api/ `, {headers})
assert.is(res.headers.scrud, 'api:search')
let enc = encodeURIComponent(`?a=b&c[]=._*j&d=1/1/18&e=f?k`)
res = await axios(`http://localhost:${port}${basePath}/api${enc} `, {headers})
assert.is(res.headers.scrud, 'api:search')
})
| JavaScript | 0 | @@ -1714,24 +1714,277 @@
', id))%0A%7D)%0A%0A
+test.serial('missing resource id returns 404', async (assert) =%3E %7B%0A let url = %60http://localhost:$%7Bport%7D$%7BbasePath%7D/member/%60%0A let headers = %7BAuthorization: %60Bearer $%7Bjwt%7D%60%7D%0A await assert.throws(axios(%7Bmethod: 'PUT', url, data: putBody, headers%7D))%0A%7D)%0A%0A
test.serial(
@@ -2234,221 +2234,8 @@
%7D)%0A%0A
-test.skip('close ends pg client (not really testable)', async (assert) =%3E %7B%0A let url = %60http://localhost:$%7Bport%7D$%7BbasePath%7D/member?first=andrew%60%0A await assert.throws(axios(%7Bmethod: 'GET', url, timeout: 3%7D))%0A%7D)%0A%0A
test
|
e3a50604d310d4907d11f6d59b157fdd785a14cb | rename test description, oops | test.js | test.js | import test from 'ava';
import linkExtractor from './index';
test('linkExtractor function exists', t => {
t.is(typeof linkExtractor, 'function');
});
test('takeScreenshot takes 1 arguments', t => {
t.is(linkExtractor.length, 1);
});
| JavaScript | 0.000003 | @@ -157,22 +157,21 @@
st('
-takeScreenshot
+linkExtractor
tak
|
8c1f13bf6bd5a78c9b07f9aebac43507272c56f2 | fix test case for nvm in node v0.10 | test.js | test.js | 'use strict';
/* deps: mocha */
var assert = require('assert');
var paths = require('./');
var path = require('path');
describe('order', function() {
var testCase1 = paths(__dirname);
it('should return an array of directories:', function() {
assert.ok(testCase1.length > 1);
assert.ok(Array.isArray(testCase1));
});
it('./global-paths/test/node_modules', function() {
assert.equal(testCase1[0], path.resolve(__dirname, 'node_modules'));
});
var indexRootNpm;
it('/node_modules', function() {
indexRootNpm = testCase1.indexOf(path.resolve('/node_modules'));
assert.ok(indexRootNpm >= 1);
});
if(!process.env.NODE_PATH) {
if(process.platform === 'win32') {
it('%APPDATA%\\Roaming\\npm\\node_modules', function() {
var indexAppData;
for(var i = indexRootNpm + 1; i < testCase1.length; i++) {
if(/\\npm\\node_modules$/.test(testCase1[i])) {
indexAppData = i;
}
}
assert.ok(testCase1.length > indexAppData);
});
} else {
var indexLib;
it('/usr/lib/node_modules', function() {
indexLib = testCase1.indexOf('/usr/lib/node_modules');
assert.ok(indexLib > indexRootNpm);
assert.ok(testCase1.length > indexLib);
});
if(process.env.NVM_BIN) {
it('nvm', function() {
var indexNvm;
for(var i = indexRootNpm + 1; i < testCase1.length; i++) {
if(/nvm\/versions\/node\/v[\d\.]+\/lib\/node_modules$/.test(testCase1[i])) {
indexNvm = i;
} else {
}
}
assert.ok(indexNvm < indexLib);
});
}
}
}
it('./global-paths', function() {
indexRootNpm = testCase1.indexOf(path.resolve('/node_modules'));
assert.equal(testCase1[testCase1.length - 1], __dirname);
});
});
| JavaScript | 0.000001 | @@ -1284,48 +1284,19 @@
i
-f(process.env.NVM_BIN) %7B%0A it('nvm
+t('bin path
', f
@@ -1319,144 +1319,77 @@
-
var
+b
in
-dexNvm;%0A for(var i = indexRootNpm + 1; i %3C testCase1.length; i++) %7B%0A if(/nvm%5C/versions%5C/node%5C/v%5B%5Cd%5C.%5D+%5C
+Nvm = testCase1.indexOf(path.resolve(process.execPath, '..
/lib
-%5C
/nod
@@ -1401,110 +1401,13 @@
ules
-$/.test(testCase1%5Bi%5D)) %7B%0A indexNvm = i;%0A %7D else %7B%0A %7D%0A %7D%0A
+'));%0A
@@ -1420,21 +1420,19 @@
sert.ok(
+b
in
-dex
Nvm %3C in
@@ -1450,22 +1450,12 @@
-
-
%7D);%0A
- %7D%0A
|
c1d24b39f0585c3bc0c7a1d8acaa0a9b22e9e1c0 | Reformat complex functions in tests | test.js | test.js | /* global describe */
/* global it */
/* global expect */
var λ = require('./lambada');
var numbers = [[-1], [0], [1], [Math.PI], [0.1], [142857], [Infinity]];
var pairs = [[0, 0], [Math.PI, -Math.SQRT2], [1, 1], [-1, 0], [100/7, -200/13]];
var triplets = [[0, 0, 0], [Math.PI, -Math.SQRT2, 100], [1, 3, 2], [100/7, -200/13, 400/Math.E]];
function compareFunctions(f, g, domain) {
domain.forEach(function (args) {
expect(f.apply(null, args)).toBe(g.apply(null, args));
});
}
describe('lambada', function () {
it('should be a function', function () {
expect(typeof λ).toBe('function');
});
it("passes Functional Javascript's tests", function () {
expect(λ('x -> x + 1')(1)).toBe(2);
expect(λ('x y -> x + 2*y')(1, 2)).toBe(5);
expect(λ('x, y -> x + 2*y')(1, 2)).toBe(5);
expect(λ('_ + 1')(1)).toBe(2);
expect(λ('/2')(4)).toBe(2);
expect(λ('2/')(4)).toBe(0.5);
expect(λ('/')(2,4)).toBe(0.5);
expect(λ('x + 1')(1)).toBe(2);
expect(λ('x + 2*y')(1, 2)).toBe(5);
expect(λ('y + 2*x')(1, 2)).toBe(5);
expect(λ('x -> y -> x + 2*y')(1)(2)).toBe(5);
});
it('creates a unary function for a simple expression', function () {
var f = λ('3 + x');
expect(typeof f).toBe('function');
compareFunctions(f, function (x) { return 3 + x; }, numbers);
});
it('creates a binary function for a simple expression', function () {
var f = λ('x + 2 * y');
expect(typeof f).toBe('function');
compareFunctions(f, function (x, y) { return x + 2 * y; }, pairs);
});
it('creates a function for a binary operator', function () {
var f = λ('+');
expect(typeof f).toBe('function');
compareFunctions(f, function (x, y) { return x + y; }, pairs);
});
it('creates a function for a partially applied postfix binary operator', function () {
var f = λ('3-');
expect(typeof f).toBe('function');
compareFunctions(f, function (x) { return 3 - x; }, numbers);
});
it('creates a function for a partially applied postfix binary operator', function () {
var f = λ('/5');
expect(typeof f).toBe('function');
compareFunctions(f, function (x) { return x / 5; }, numbers);
});
it('caches functions', function () {
var f = λ('x -> 2 * x + 5');
var g = λ('x -> 2 * x + 5');
expect(typeof f).toBe('function');
expect(typeof g).toBe('function');
expect(f).toBe(g);
});
it('returns a function unchanged', function () {
var f = function () {};
var g = λ(f);
expect(f).toBe(g);
});
it('supports dot something as an operation', function () {
var f = λ('.foo');
var obj = { foo: 5, bar: 6, baz: 7 };
expect(f(obj)).toBe(5);
});
});
describe('lambada.sequence', function () {
it('exists and is a function', function () {
expect(λ.sequence).toBeDefined();
expect(typeof λ.sequence).toBe('function');
});
it('applies unary functions from left to right', function () {
var f = λ.sequence('+2', '*3', '4-');
var g = function(x) { return 4 - ((x + 2) * 3); };
compareFunctions(f, g, numbers);
});
it('handles regular functions correctly', function () {
var f = λ.sequence('*100', Math.floor, '/10');
var g = function (x) { return Math.floor(x * 100) / 10; };
compareFunctions(f, g, numbers);
});
it('can accept a non-unary function as a first argument', function () {
var f = λ.sequence(Math.max, '/100');
var g = function () { return Math.max.apply(null, Array.prototype.slice.call(arguments)) / 100; };
compareFunctions(f, g, triplets);
});
});
describe('lambada.compose', function () {
it('exists and is a function', function () {
expect(λ.compose).toBeDefined();
expect(typeof λ.compose).toBe('function');
});
it('applies unary functions from right to left', function () {
var f = λ.compose('+2', '*3', '4-');
var g = function(x) { return ((4 - x) * 3) + 2; };
compareFunctions(f, g, numbers);
});
it('handles regular functions correctly', function () {
var f = λ.compose(Math.exp, '*2', Math.abs);
var g = function (x) { return Math.exp(2 * Math.abs(x)); };
compareFunctions(f, g, numbers);
});
it('can accept a non-unary function as a last argument', function () {
var f = λ.compose(Math.floor, Math.pow);
var g = function () { return Math.floor(Math.pow.apply(null, Array.prototype.slice.call(arguments))); };
compareFunctions(f, g, pairs);
});
});
| JavaScript | 0 | @@ -3666,32 +3666,44 @@
= function () %7B
+%0A
return Math.max
@@ -3760,16 +3760,24 @@
) / 100;
+%0A
%7D;%0A
@@ -4624,16 +4624,28 @@
ion () %7B
+%0A
return
@@ -4716,16 +4716,24 @@
ents)));
+%0A
%7D;%0A
|
c4079082ff58da4361141fa182412aaea6bf54e5 | rename key | test.js | test.js | try {
var dotenv = require('dotenv');
dotenv.load({silent: true});
} catch (error) {
console.log(error);
}
var webdriver = require('selenium-webdriver'),
username = process.env.SAUCE_NAME,
accessKey = process.env.SAUCE_KEY,
driver;
//TODO - Test on more plaforms ...
driver = new webdriver.Builder().
withCapabilities({
'browserName': 'chrome',
'platform': 'Windows XP',
'version': '43.0',
'username': username,
'accessKey': accessKey,
'name': "Minesweeper"
}).
usingServer("http://" + username + ":" + accessKey +
"@ondemand.saucelabs.com:80/wd/hub").
build();
//TODO - Rewrite to use Mocha ...
driver.getSession().then(function (session) {
var id = session.id_;
var SauceLabs = require("saucelabs");
var saucelabs = new SauceLabs({
username: username,
password: accessKey
});
driver.get("https://minesweeper-objects.mybluemix.net/");
console.log("Starting tests ...");
driver.getTitle().then(function (title) {
console.log("title is: " + title);
var passed = title === "Minesweeper";
var done = function () {
console.log("done: " + passed);
};
//console.log(id);
driver.quit();
saucelabs.updateJob(id, {
name: title,
passed: passed
}, done);
});
});
| JavaScript | 0.000027 | @@ -184,16 +184,20 @@
v.SAUCE_
+USER
NAME,%0A
@@ -228,16 +228,23 @@
v.SAUCE_
+ACCESS_
KEY,%0A
|
7dd2a51b24cdf08accf2b02bcaffe562a36fc735 | fix tests | test.js | test.js | 'use strict';
var test = require('ava');
var childProcess = require('child_process');
test(function (t) {
t.plan(2);
childProcess.execFile('./cli.js', ['--cwd=fixture'], {
cwd: __dirname
}, function (err, stdout) {
t.error(err);
t.is(stdout.trim(), __dirname);
});
});
| JavaScript | 0.000001 | @@ -84,16 +84,19 @@
);%0A%0Atest
+.cb
(functio
@@ -222,17 +222,19 @@
) %7B%0A%09%09t.
-e
+ifE
rror(err
@@ -270,16 +270,27 @@
rname);%0A
+%09%09t.end();%0A
%09%7D);%0A%7D);
|
da5b66d30a8455099673afb8dd97d8ddb063074f | Add failing test for #36 | test.js | test.js | import test from 'ava';
import m from '.';
test('replace comments with whitespace', t => {
t.is(m('//comment\n{"a":"b"}'), ' \n{"a":"b"}');
t.is(m('/*//comment*/{"a":"b"}'), ' {"a":"b"}');
t.is(m('{"a":"b"//comment\n}'), '{"a":"b" \n}');
t.is(m('{"a":"b"/*comment*/}'), '{"a":"b" }');
t.is(m('{"a"/*\n\n\ncomment\r\n*/:"b"}'), '{"a" \n\n\n \r\n :"b"}');
t.is(m('/*!\n * comment\n */\n{"a":"b"}'), ' \n \n \n{"a":"b"}');
t.is(m('{/*comment*/"a":"b"}'), '{ "a":"b"}');
});
test('remove comments', t => {
const opts = {whitespace: false};
t.is(m('//comment\n{"a":"b"}', opts), '\n{"a":"b"}');
t.is(m('/*//comment*/{"a":"b"}', opts), '{"a":"b"}');
t.is(m('{"a":"b"//comment\n}', opts), '{"a":"b"\n}');
t.is(m('{"a":"b"/*comment*/}', opts), '{"a":"b"}');
t.is(m('{"a"/*\n\n\ncomment\r\n*/:"b"}', opts), '{"a":"b"}');
t.is(m('/*!\n * comment\n */\n{"a":"b"}', opts), '\n{"a":"b"}');
t.is(m('{/*comment*/"a":"b"}', opts), '{"a":"b"}');
});
test('doesn\'t strip comments inside strings', t => {
t.is(m('{"a":"b//c"}'), '{"a":"b//c"}');
t.is(m('{"a":"b/*c*/"}'), '{"a":"b/*c*/"}');
t.is(m('{"/*a":"b"}'), '{"/*a":"b"}');
t.is(m('{"\\"/*a":"b"}'), '{"\\"/*a":"b"}');
});
test('consider escaped slashes when checking for escaped string quote', t => {
t.is(m('{"\\\\":"https://foobar.com"}'), '{"\\\\":"https://foobar.com"}');
t.is(m('{"foo\\"":"https://foobar.com"}'), '{"foo\\"":"https://foobar.com"}');
});
test('line endings - no comments', t => {
t.is(m('{"a":"b"\n}'), '{"a":"b"\n}');
t.is(m('{"a":"b"\r\n}'), '{"a":"b"\r\n}');
});
test('line endings - single line comment', t => {
t.is(m('{"a":"b"//c\n}'), '{"a":"b" \n}');
t.is(m('{"a":"b"//c\r\n}'), '{"a":"b" \r\n}');
});
test('line endings - single line block comment', t => {
t.is(m('{"a":"b"/*c*/\n}'), '{"a":"b" \n}');
t.is(m('{"a":"b"/*c*/\r\n}'), '{"a":"b" \r\n}');
});
test('line endings - multi line block comment', t => {
t.is(m('{"a":"b",/*c\nc2*/"x":"y"\n}'), '{"a":"b", \n "x":"y"\n}');
t.is(m('{"a":"b",/*c\r\nc2*/"x":"y"\r\n}'), '{"a":"b", \r\n "x":"y"\r\n}');
});
test('line endings - works at EOF', t => {
const opts = {whitespace: false};
t.is(m('{\r\n\t"a":"b"\r\n} //EOF'), '{\r\n\t"a":"b"\r\n} ');
t.is(m('{\r\n\t"a":"b"\r\n} //EOF', opts), '{\r\n\t"a":"b"\r\n} ');
});
| JavaScript | 0.000001 | @@ -2360,16 +2360,284 @@
b%22%5Cr%5Cn%7D ');%0A%7D);%0A
+%0Atest.failing('handles weird escaping', t =%3E %7B%0A%09// eslint-disable-next-line no-useless-escape%0A%09t.is(m('%7B%22x%22:%22x %5C%22sed -e %5C%5C%5C%22s/%5E.%5C%5C%5C%5C%7B46%5C%5C%5C%5C%7DT//%5C%5C%5C%22 -e %5C%5C%5C%22s/#033/%5C%5C%5C%5Cx1b/g%5C%5C%5C%22%5C%22%22%7D'), '%7B%22x%22:%22x %5C%22sed -e %5C%5C%5C%22s/%5E.%5C%5C%5C%5C%7B46%5C%5C%5C%5C%7DT//%5C%5C%5C%22 -e %5C%5C%5C%22s/#033/%5C%5C%5C%5Cx1b/g%5C%5C%5C%22%5C%22%22%7D');%0A%7D);%0A
|
a7e9f46061093e0a789c3be8069264f596ab2416 | Add simple cyclic test | test.js | test.js | var vows = require('vows')
, toposort = require('./index')
, assert = require('assert')
var suite = vows.describe('toposort')
suite.addBatch(
{ 'acyclic graphs':
{ topic: function() {
return toposort(
[ ["3", '2']
, ["2", "1"]
, ["6", "5"]
, ["5", "2"]
, ["5", "4"]
])
/*(read downwards)
6 3
| |
5->2
| |
4 1
*/
}
, 'should be sorted correctly': function(er, result) {
assert.instanceOf(result, Array)
var failed = [], passed
;[ [ '3','6','5','2','1','4' ]
, [ '3','6','5','2','4','1' ]
, [ '6','3','5','2','1','4' ]
, [ '6','5','3','2','1','4' ]
, [ '6','5','3','2','4','1' ]
, [ '6','5', '4','3','2','1' ]
].forEach(function(solution) {
try {
assert.deepEqual(result, solution)
passed = true
}catch (e) {
failed.push(e)
}
})
if (!passed) {
console.log(failed)
throw failed[0];
}
}
}
, 'cyclic graphs':
{ topic: function() {
return toposort(
[ ["foo", 'bar']
, ["bar", "ron"]
, ["john", "bar"]
, ["tom", "john"]
, ["ron", "tom"]// cyclic dependecy
])
}
, 'should throw an exception': function(_, val) {
assert.instanceOf(val, Error)
}
}
, 'triangular dependency':
{ topic: function() {
return toposort([['a', 'b'], ['a', 'c'], ['b', 'c']]);
}
, 'shouldn\'t throw an error': function(er, result) {
assert.deepEqual(result, ['a', 'b', 'c'])
}
}
})
.run(null, function() {
(suite.results.broken+suite.results.errored) > 0 && process.exit(1)
}) | JavaScript | 0.000016 | @@ -1030,16 +1030,275 @@
%0A %7D%0A, '
+simple cyclic graphs':%0A %7B topic: function() %7B%0A return toposort(%0A %5B %5B%22foo%22, 'bar'%5D%0A , %5B%22bar%22, %22foo%22%5D// cyclic dependecy%0A %5D)%0A %7D%0A , 'should throw an exception': function(_, val) %7B%0A assert.instanceOf(val, Error)%0A %7D%0A %7D%0A, 'complex
cyclic g
|
c3647550a89cdc0db7b1429186ff2b6333fdce62 | add test data | test.js | test.js | console.log("Package Script Test....");
function test() {
require('./pkgscript.js').spawn([
{
command: "npm",
args: ["--version"]
}
]);
}
test(); | JavaScript | 0.000006 | @@ -160,16 +160,97 @@
rsion%22%5D%0A
+ %7D,%0A %7B%0A command: %22npm%22,%0A args: %5B%22--version%22%5D%0A
|
906af157d40b7be8d87a7d817c8609dc92e363d7 | add some tests | test.js | test.js | import test from 'ava';
import shell from 'shelljs';
import m from './';
shell.config.silent = true;
test('mock and unmock git bla', async t => {
const log = 'mocking git bla!';
const unmock = await m(`console.log('${log}')`, 'bla');
let actual = shell.exec('git bla').stdout;
t.is(log + '\n', actual);
actual = shell.exec('git').stdout;
t.not(log + '\n', actual);
unmock();
actual = shell.exec('git bla').stdout;
t.not(log + '\n', actual);
});
test('mock and unmock git --no-pager bla', async t => {
const log = 'mocking git bla!';
const unmock = await m(`console.log('${log}')`, 'bla');
let actual = shell.exec('git --no-pager bla').stdout;
t.is(log + '\n', actual);
actual = shell.exec('git').stdout;
t.not(log + '\n', actual);
unmock();
actual = shell.exec('git --no-pager bla').stdout;
t.not(log + '\n', actual);
});
test('mocking bar does not affect foo', async t => {
const fooLog = 'mocking foo!';
await m(`console.log('${fooLog}')`, 'foo');
const barLog = 'mocking bar!';
await m(`console.log('${barLog}')`, 'bar');
const barActual = shell.exec('git bar').stdout;
t.is(barLog + '\n', barActual);
const fooActual = shell.exec('git foo').stdout;
t.is(fooLog + '\n', fooActual);
});
test('mocking git', async t => {
const log = 'mocking git!';
const unmock = await m(`console.log('${log}')`);
let actual = shell.exec('git').stdout;
t.is(log + '\n', actual);
actual = shell.exec('git foo').stdout;
t.is(log + '\n', actual);
unmock();
actual = shell.exec('git').stdout;
t.not(log + '\n', actual);
});
| JavaScript | 0.000001 | @@ -1050,22 +1050,97 @@
ar');%0A%0A%09
-const
+let barActual = shell.exec('git bar').stdout;%0A%09t.is(barLog + '%5Cn', barActual);%0A%0A%09
barActua
@@ -1151,32 +1151,43 @@
shell.exec('git
+--no-pager
bar').stdout;%0A%09t
@@ -1219,22 +1219,97 @@
ual);%0A%0A%09
-const
+let fooActual = shell.exec('git foo').stdout;%0A%09t.is(fooLog + '%5Cn', fooActual);%0A%0A%09
fooActua
@@ -1320,32 +1320,43 @@
shell.exec('git
+--no-pager
foo').stdout;%0A%09t
@@ -1381,24 +1381,87 @@
fooActual);
+%0A%0A%09let stderr = shell.exec('git log').stderr;%0A%09t.falsy(stderr);
%0A%7D);%0A%0Atest('
@@ -1695,32 +1695,111 @@
'%5Cn', actual);%0A%0A
+%09actual = shell.exec('git --no-pager log').stdout;%0A%09t.is(log + '%5Cn', actual);%0A%0A
%09unmock();%0A%09actu
|
1e91686162543586a66eb6ebc2b70f0d476004fd | update test | test.js | test.js | 'use strict';
var assert = require('assert');
var gutil = require('gulp-util');
var markdown = require('./');
it('should compile Markdown to HTML', function (cb) {
var stream = markdown();
stream.once('data', function (file) {
assert.equal(file.relative, 'fixture.html');
assert.equal(file.contents.toString(), '<p><em>foo</em></p>\n');
});
stream.on('end', cb);
stream.write(new gutil.File({
path: 'fixture.md',
contents: new Buffer('*foo*')
}));
stream.end();
});
| JavaScript | 0.000001 | @@ -273,16 +273,19 @@
ml');%0A%09%09
+//
assert.e
|
04f2b5467967bac49caeb9847729ce62705444f4 | Update points in test.js to 2.0.0 | test.js | test.js | var aggregate = require('./');
var test = require('tape');
var polygon = require('turf-polygon');
var point = require('turf-point');
var featurecollection = require('turf-featurecollection');
test('aggregate', function(t){
var poly1 = polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]);
var poly2 = polygon([[[10,0],[20,10],[20,20],[20,0],[10,0]]]);
var polyFC = featurecollection([poly1, poly2]);
var pt1 = point(5,5, {population: 200});
var pt2 = point(1,3, {population: 600});
var pt3 = point(14,2, {population: 100});
var pt4 = point(13,1, {population: 200});
var pt5 = point(19,7, {population: 300});
var ptFC = featurecollection([pt1, pt2, pt3, pt4, pt5]);
var aggregations = [
{
aggregation: 'sum',
inField: 'population',
outField: 'pop_sum'
},
{
aggregation: 'average',
inField: 'population',
outField: 'pop_avg'
},
{
aggregation: 'median',
inField: 'population',
outField: 'pop_median'
},
{
aggregation: 'min',
inField: 'population',
outField: 'pop_min'
},
{
aggregation: 'max',
inField: 'population',
outField: 'pop_max'
},
{
aggregation: 'deviation',
inField: 'population',
outField: 'pop_deviation'
},
{
aggregation: 'variance',
inField: 'population',
outField: 'pop_variance'
},
{
aggregation: 'count',
inField: '',
outField: 'point_count'
}
];
var aggregated = aggregate(polyFC, ptFC, aggregations);
t.equal(aggregated.features[0].properties.pop_sum, 800);
t.equal(aggregated.features[1].properties.pop_sum, 600);
t.equal(aggregated.features[0].properties.pop_avg, 400);
t.equal(aggregated.features[1].properties.pop_avg, 200);
t.equal(aggregated.features[0].properties.pop_median, 400);
t.equal(aggregated.features[1].properties.pop_median, 200);
t.equal(aggregated.features[0].properties.pop_min, 200);
t.equal(aggregated.features[1].properties.pop_min, 100);
t.equal(aggregated.features[0].properties.pop_max, 600);
t.equal(aggregated.features[1].properties.pop_max, 300);
t.ok(aggregated.features[0].properties.pop_deviation);
t.ok(aggregated.features[1].properties.pop_deviation);
t.ok(aggregated.features[0].properties.pop_variance);
t.ok(aggregated.features[1].properties.pop_variance);
t.end();
});
| JavaScript | 0 | @@ -417,11 +417,13 @@
int(
+%5B
5,5
+%5D
, %7Bp
@@ -462,11 +462,13 @@
int(
+%5B
1,3
+%5D
, %7Bp
@@ -507,12 +507,14 @@
int(
+%5B
14,2
+%5D
, %7Bp
@@ -553,12 +553,14 @@
int(
+%5B
13,1
+%5D
, %7Bp
@@ -599,12 +599,14 @@
int(
+%5B
19,7
+%5D
, %7Bp
|
e9e07ab54c814ec390dc4680a654cca370942dff | fix undefined check so that we can hash the string 'undefined' (#31) | test.js | test.js | var md5 = require('./md5.js');
var assert = require('assert');
describe('md5', function () {
it('should throw an error for `undefined`', function() {
assert.throws(function() {
md5(undefined);
});
});
it('should throw an error for `null`', function() {
assert.throws(function() {
md5(null);
});
});
it('should return the expected MD5 hash for "message"', function() {
assert.equal('78e731027d8fd50ed642340b7c9a63b3', md5('message'));
});
it('should not return the same hash for random numbers twice', function() {
var msg1 = Math.floor((Math.random() * 100000) + 1) + (new Date).getTime();
var msg2 = Math.floor((Math.random() * 100000) + 1) + (new Date).getTime();
if (msg1 !== msg2) {
assert.notEqual(md5(msg1), md5(msg2));
} else {
assert.equal(md5(msg1), md5(msg1));
}
});
it('should support Node.js Buffers', function() {
var buffer = new Buffer('message áßäöü', 'utf8');
assert.equal(md5(buffer), md5('message áßäöü'));
})
it('should be able to use a binary encoded string', function() {
var hash1 = md5('abc', { asString: true });
var hash2 = md5(hash1 + 'a', { asString: true, encoding : 'binary' });
var hash3 = md5(hash1 + 'a', { encoding : 'binary' });
assert.equal(hash3, '131f0ac52813044f5110e4aec638c169');
});
});
| JavaScript | 0.00257 | @@ -120,17 +120,19 @@
ror for
-%60
+an
undefine
@@ -132,17 +132,22 @@
ndefined
-%60
+ value
', funct
@@ -214,32 +214,183 @@
%0A %7D);%0A %7D);%0A%0A
+ it('should allow the hashing of the string %60undefined%60', function() %7B%0A assert.equal('5e543256c480ac577d30f76f9120eb74', md5('undefined'));%0A %7D);%0A%0A
it('should thr
|
2c96e579dc1b4e52a5a09b65377872c93c05b7b4 | fix issue 32 | vein.js | vein.js | /**
* vein.js - version 0.3
*
* by Danny Povolotski ([email protected])
**/
!function (name, definition) {
if (typeof module != 'undefined') module.exports = definition()
else if (typeof define == 'function' && define.amd) define(name, definition)
else this[name] = definition()
}('vein', function () {
var vein = function(){};
// Kudos to: http://youmightnotneedjquery.com/
var extend = function(out) {
out = out || {};
for (var i = 1; i < arguments.length; i++) {
if (!arguments[i])
continue;
for (var key in arguments[i]) {
if (arguments[i].hasOwnProperty(key))
out[key] = arguments[i][key];
}
}
return out;
};
var findOrDeleteBySelector = function(selector, stylesheet, css){
var matches = [],
rules = stylesheet[ document.all ? 'rules' : 'cssRules' ],
selectorCompare = selector.replace(/\s/g,''),
ri, rl;
// Since there could theoretically be multiple versions of the same rule,
// we will first iterate
for(ri = 0, rl = rules.length; ri < rl; ri++) {
if(
// regular style selector
(rules[ri].selectorText === selector) ||
// for media queries, remove spaces and see if the query matches
(rules[ri].type === 4 && rules[ri].cssText.replace(/\s/g,'').substring(0, selectorCompare.length) == selectorCompare)
) {
if(css === null) {
// If we set css to null, let's delete that ruleset altogether
stylesheet.deleteRule(ri);
}
else {
// Otherwise - we push it into the matches array
matches.push(rules[ri]);
}
}
}
return matches;
};
var cssToString = function(css){
cssArray = [];
for(property in css) {
if (css.hasOwnProperty(property)) {
cssArray.push(property + ': ' + css[property] + ';');
}
}
cssText = cssArray.join('');
return cssText;
};
// Get the stylesheet we use to inject stuff or create it if it doesn't exist yet
vein.getStylesheet = function() {
var self = this,
si, sl;
if(!self.element || !document.getElementById('vein')) {
self.element = document.createElement("style");
self.element.setAttribute('type', 'text/css');
self.element.setAttribute('id', 'vein');
document.getElementsByTagName("head")[0].appendChild(self.element);
self.stylesheet = self.element.sheet;
}
return self.stylesheet;
};
var getRulesFromStylesheet = function(stylesheet){
return stylesheet[ document.all ? 'rules' : 'cssRules' ];
}
var insertRule = function(selector, cssText, stylesheet){
var rules = getRulesFromStylesheet(stylesheet);
if(stylesheet.insertRule) {
// Supported by all modern browsers
stylesheet.insertRule(selector + '{' + cssText + '}', rules.length);
} else {
// Old IE compatability
stylesheet.addRule(selector, cssText, rules.length);
}
};
// Let's inject some CSS. We can supply an array (or string) of selectors, and an object
// with CSS value and property pairs.
vein.inject = function(selectors, css, options) {
options = extend({}, options);
var self = this,
stylesheet = options.stylesheet || self.getStylesheet(),
rules = getRulesFromStylesheet(stylesheet),
si, sl, query, matches, cssText, property, mi, ml, qi, ql;
if(typeof selectors === 'string') {
selectors = [selectors];
}
for(si = 0, sl = selectors.length; si < sl; si++) {
if(typeof selectors[si] === 'object' && stylesheet.insertRule){
for(query in selectors[si]) {
matches = findOrDeleteBySelector(query, stylesheet, css);
if(matches.length === 0){
cssText = cssToString(css);
for(qi = 0, ql = selectors[si][query].length; qi < ql; qi++) {
insertRule(query, selectors[si][query][qi] + '{' + cssText + '}', stylesheet);
}
} else {
for(mi = 0, ml = matches.length; mi < ml; mi++) {
self.inject(selectors[si][query], css, {stylesheet: matches[mi]});
}
}
}
} else {
matches = findOrDeleteBySelector(selectors[si], stylesheet, css);
// If all we wanted is to delete that ruleset, we're done here
if(css === null) return;
// If no rulesets have been found for the selector, we will create it below
if(matches.length === 0) {
cssText = cssToString(css);
insertRule(selectors[si], cssText, stylesheet);
}
// Otherwise, we're just going to modify the property
else {
for(mi = 0, ml = matches.length; mi < ml; mi++) {
for(property in css) {
if (css.hasOwnProperty(property)) {
// TODO: Implement priority
if(matches[mi].style.setProperty) {
matches[mi].style.setProperty(property, css[property], '');
} else {
//IE8
matches[mi].style.setAttribute(property, css[property], '');
}
}
}
}
}
}
}
return self;
};
return vein;
});
| JavaScript | 0.000001 | @@ -831,16 +831,46 @@
s = %5B%5D,%0A
+ rulesDelete = %5B%5D,%0A
@@ -1672,29 +1672,24 @@
-stylesheet.deleteRule
+rulesDelete.push
(ri)
@@ -1880,32 +1880,158 @@
%7D%0A %7D%0A%0A
+ for (ri = 0, rl = rulesDelete.length; ri %3C rl; ri++) %7B%0A stylesheet.deleteRule(rulesDelete%5Bri%5D);%0A %7D%0A%0A
return m
|
531c90747ca2ec66030bbfec68802598dca68816 | remove Div from config.js | .storybook/config.js | .storybook/config.js | import React from 'react';
import {configure, addDecorator, getStorybook, setAddon} from '@storybook/react';
import {Div} from 'glamorous';
import createPercyAddon from '@percy-io/percy-storybook';
import {fontFamily, fontSize} from '../src/styles';
global.__PATH_PREFIX__ = ''; // eslint-disable-line no-underscore-dangle
const {percyAddon, serializeStories} = createPercyAddon();
setAddon(percyAddon);
addDecorator(story => (
<Div css={{fontFamily, fontSize}}>
{story()}
</Div>
));
function loadStories() {
const req = require.context('../src', true, /stories.js$/);
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
serializeStories(getStorybook);
| JavaScript | 0.000003 | @@ -106,39 +106,8 @@
t';%0A
-import %7BDiv%7D from 'glamorous';%0A
impo
@@ -439,17 +439,17 @@
=%3E (%0A %3C
-D
+d
iv css=%7B
@@ -491,17 +491,17 @@
()%7D%0A %3C/
-D
+d
iv%3E%0A));%0A
|
3f2ec113c84f1fe18157e6fd6376c967214f3775 | initialize compose in storybook config | .storybook/config.js | .storybook/config.js | /* global __STORYBOOK_CLIENT_API__ */
/**
* External dependencies
*/
import React from 'react';
import { addDecorator, configure } from '@storybook/react';
/**
* WordPress dependencies
*/
import { createHigherOrderComponent } from '@wordpress/compose';
import {
Component,
createRef,
Fragment,
createElement,
createPortal,
} from '@wordpress/element';
import { __, sprintf, setLocaleData } from '@wordpress/i18n';
import {
getQueryString,
addQueryArgs,
} from '@wordpress/url';
import lodash from 'lodash';
import {
addFilter,
removeFilter,
addAction,
doAction,
applyFilters,
removeAction,
removeAllFilters,
} from '@wordpress/hooks';
/**
* Internal dependencies
*/
import '../dist/assets/css/wpdashboard.css';
import '../dist/assets/css/adminbar.css';
import '../dist/assets/css/admin.css';
import '../vendor/johnpbloch/wordpress-core/wp-admin/css/common.css';
import '../vendor/johnpbloch/wordpress-core/wp-admin/css/dashboard.css';
import '../vendor/johnpbloch/wordpress-core/wp-admin/css/edit.css';
import '../vendor/johnpbloch/wordpress-core/wp-admin/css/forms.css';
import { googlesitekit as dashboardData } from '../.storybook/data/wp-admin-admin.php-page=googlesitekit-dashboard-googlesitekit';
// Default Data.
const googlesitekit = dashboardData;
// Setup.
const wp = {};
wp.element = wp.element || {};
wp.i18n = wp.i18n || {};
wp.hooks = wp.hooks || {};
wp.url = {
getQueryString,
addQueryArgs,
};
wp.compose.createHigherOrderComponent = createHigherOrderComponent;
wp.hooks.addFilter = addFilter;
wp.hooks.removeFilter = removeFilter;
wp.hooks.addAction = addAction;
wp.hooks.doAction = doAction;
wp.hooks.applyFilters = applyFilters;
wp.hooks.removeAction = removeAction;
wp.hooks.removeAllFilters = removeAllFilters;
wp.element.Component = Component;
wp.element.createRef = createRef;
wp.element.Fragment = Fragment;
wp.element.createElement = createElement;
wp.element.createPortal = createPortal;
wp.i18n.__ = __ || {};
wp.i18n.setLocaleData = setLocaleData || {};
wp.i18n.sprintf = sprintf || {};
window.wp = window.wp || wp;
window.React = React;
window.lodash = lodash;
window.googlesitekit = window.googlesitekit || googlesitekit;
window.googlesitekit.setup = window.googlesitekit.setup || googlesitekit.setup;
window.googlesitekit.admin = window.googlesitekit.admin || googlesitekit.admin;
window.googlesitekit.modules = window.googlesitekit.modules || googlesitekit.modules;
window.googlesitekit.admin.assetsRoot = '/assets/';
window.googlesitekit.isStorybook = true;
window.wp.apiFetch = ( vars ) => {
const matches = vars.path.match( '/google-site-kit/v1/modules/(.*)/data/(.*[^/])' );
if ( window.googlesitekit.modules[ matches[ 1 ] ][ matches[ 2 ] ] ) {
return Promise.resolve( window.googlesitekit.modules[ matches[ 1 ] ][ matches[ 2 ] ] );
}
return {
then: () => {
return {
catch: () => false,
};
},
};
};
// Global Decorator.
addDecorator( ( story ) => <div className="googlesitekit-plugin-preview">
<div className="googlesitekit-plugin">{ story() }</div>
</div> );
const req = require.context( '../stories', true, /\.stories\.js$/ );
function loadStories() {
req.keys().forEach( ( filename ) => req( filename ) );
}
configure( loadStories, module );
// TODO Would be nice if this wrote to a file. This logs our Storybook data to the browser console. Currently it gets put in .storybook/storybook-data and used in tests/backstop/scenarios.js.
// eslint-disable-next-line no-console
console.log( '__STORYBOOK_CLIENT_API__.raw()', __STORYBOOK_CLIENT_API__.raw() );
| JavaScript | 0.000002 | @@ -1427,16 +1427,33 @@
rgs,%0A%7D;%0A
+wp.compose = %7B%7D;%0A
wp.compo
|
a4e24f17619d4e643a328b2cb6afdd6720706a14 | fix lint errors | .storybook/config.js | .storybook/config.js | import { configure } from '@storybook/react';
function loadStories() {
require('../stories');
}
configure(loadStories, module);
| JavaScript | 0.000037 | @@ -1,17 +1,16 @@
import %7B
-
configur
@@ -10,17 +10,16 @@
onfigure
-
%7D from '
@@ -62,13 +62,16 @@
ries
+
() %7B%0A
+
re
|
3b2502932af664fe376a7268b1ca99ead4e947df | move clear screen function into game.js | shared/Utils.js | shared/Utils.js | var Utils = {
// returns a random integer between min and max
// via: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FMath%2Frandom
randBetween: function(min, max, floating) {
if (floating) {
return Math.random() * (max - min + 1) + min;
} else {
return Math.floor(Math.random() * (max - min + 1) + min);
}
},
// mixin function, gives objects new functons from other objects
mixin: function(to, from) {
for (var prop in from.prototype) {
if (! to.prototype[prop]) {
to.prototype[prop] = from.prototype[prop];
}
}
},
linearTween: function(delta, current, target, duration, thresh) {
// taken from: http://jessefreeman.com/game-dev/intro-to-math-for-game-development/
var change = target - current;
thresh = thresh || 0.01;
if (Math.abs(change) < thresh) return target;
return change * delta / duration + current;
},
clearCanvas: function() {
return context.clearRect(0, 0, canvas.width, canvas.height);
},
createSessionId: function(sessionId, days) {
// via:
// http://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie
var date = new Date();
days = days || 7;
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
var data = "sessionId=" + sessionId;
var cookie = [data, ';', expires, "; path=/"];
document.cookie = cookie.join('');
},
readSessionId: function() {
if (document.cookie.length && document.cookie.match(/sessionId/)) {
var matches = document.cookie.match(/sessionId=(\w+-\w+-\w+-\w+-\w+)/);
return matches ? matches[1] : undefined;
}
},
eraseSessionId: function() {
this.createSessionId("");
}
};
if (typeof module !== 'undefined') module.exports = Utils;
| JavaScript | 0.000001 | @@ -1026,107 +1026,8 @@
%7D,%0A%0A
- clearCanvas: function() %7B%0A return context.clearRect(0, 0, canvas.width, canvas.height);%0A %7D,%0A%0A
cr
|
467887bdad2e0a7d84da1a265afd5d095be41e07 | Increase number of visible birthdays | homedisplay/info_birthdays/static/js/birthdays.js | homedisplay/info_birthdays/static/js/birthdays.js | var Birthdays = function(elem, use_date, options) {
options = options || {};
options.interval = options.interval || SLOW_UPDATE;
options.showdate = options.showdate || false;
options.maxitems = options.maxitems || 100000;
var parent_elem = $(elem), this_date = use_date, update_interval, wait_sync, current_item = 0, items_in_current = 0;
parent_elem = parent_elem.slice(0, 1);
function onReceiveItemWS(message) {
processData(message);
}
function clearDates() {
$(elem).find("li").remove();
items_in_current = 0;
current_item = 0;
parent_elem = $(elem).slice(current_item, 1);
}
function compareBirthdays(a, b) {
if (a.birthday_sort < b.birthday_sort) {
return -1;
}
if (a.birthday_sort > b.birthday_sort) {
return 1;
}
return 0;
}
function formatSortString(da) {
da = moment(da);
var m = da.month();
if (m < 10) {
m = "0" + m;
}
var d = da.date();
if (d < 10) {
d = "0" + d;
}
return "" + m + d;
}
function processData(data) {
clearDates();
var now, now_str, data_sortable = [];
now = moment().subtract(1, "days");
now_str = formatSortString(now);
$.each(data, function() {
var a, sort_string, prefix;
a = moment(this.fields.birthday);
sort_string = formatSortString(a);
this.birthday_moment = a;
prefix = "0";
this.next_year = false;
if (sort_string < now_str) {
prefix = "1";
this.next_year = true;
}
this.birthday_sort = prefix + sort_string;
data_sortable.push(this);
});
data_sortable.sort(compareBirthdays);
$.each(data_sortable, function() {
var name = this.fields.name, age = "", b, date = "", extra = "";
if (this.fields.nickname) {
name = this.fields.nickname;
}
if (this.fields.valid_year) {
b = moment(this.birthday_moment);
b = b.year(now.year());
if (this.next_year) {
b = b.add(1, "year");
}
age = (" (" + this.birthday_moment.from(b) + ")").replace(" sitten", "");
}
if (options.showdate) {
date = " - " + this.birthday_moment.date() + "." + (this.birthday_moment.month() + 1)+".";
if (this.fields.valid_year) {
date += this.birthday_moment.year();
}
}
if (items_in_current > options.maxitems) {
current_item += 1;
if (current_item > 3) {
return false;
}
parent_elem = $(elem).slice(current_item, current_item + 1);
items_in_current = 0;
}
items_in_current += 1;
if (this_date == "tomorrow") {
extra = "(huomenna)";
}
parent_elem.append("<li><i class='fa-li fa fa-birthday-cake'></i> "+name+date+age+extra+"</li>");
});
}
function update() {
$.get("/homecontroller/birthdays/get_json/"+this_date, function(data) {
processData(data);
});
}
function startInterval() {
var now = new Date(), minutes, wait_time;
stopInterval();
update();
update_interval = setInterval(update, options.interval);
ws_generic.register("birthdays_" + this_date, onReceiveItemWS);
ge_refresh.register("birthdays_" + this_date, update);
}
function stopInterval() {
if (update_interval) {
update_interval = clearInterval(update_interval);
}
ws_generic.deRegister("birthdays_" + this_date);
ge_refresh.deRegister("birthdays_" + this_date);
}
this.startInterval = startInterval;
this.stopInterval = stopInterval;
};
var birthdays_today, birthdays_tomorrow, birthdays_all;
$(document).ready(function() {
birthdays_today = new Birthdays("#today .list-birthdays .fa-ul", "today");
birthdays_tomorrow = new Birthdays("#tomorrow .list-birthdays .fa-ul", "tomorrow");
birthdays_all = new Birthdays("#birthdays-list-all .fa-ul", "all", {interval: 60 * 60 * 1000, showdate: true, maxitems: 38});
birthdays_today.startInterval();
birthdays_tomorrow.startInterval();
birthdays_all.startInterval();
$(".main-button-box .birthdays").on("click", function () {
content_switch.switchContent("#birthdays-list-all");
});
$("#birthdays-list-all .close").on("click", function() {
content_switch.switchContent("#main-content");
});
});
| JavaScript | 0.000035 | @@ -3929,10 +3929,10 @@
ms:
-38
+45
%7D);%0A
|
f568a100920e256a1571b048bfbe393702755157 | fix calculation of an indicator | hsph/_design/views/cati_performance_report/map.js | hsph/_design/views/cati_performance_report/map.js | function(doc) {
//!code util/emit_array.js
//!code util/hsph.js
if (!isHSPHBirthCase(doc)) {
return;
}
function datePlusDays(string, daysToAdd) {
var newDate = new Date(string);
newDate.setDate(newDate.getDate() + daysToAdd);
return newDate;
}
function differenceInDays(time1, time2) {
return Math.floor((time1 - time2) / (24 * 3600 * 1000));
}
function daysSinceEpoch(date) {
return Math.floor(date.getTime() / (24 * 3600 * 1000));
}
function hasPhoneNumber(doc) {
return (doc.phone_mother_number || doc.phone_husband_number ||
doc.phone_asha_number || doc.phone_house_number);
}
// get last follow up time from case actions
var firstFollowUpTime = false,
lastFollowUpTime = false;
for (var i in doc.actions) {
var action = doc.actions[i],
properties = action.updated_unknown_properties;
for (var prop in action.updated_known_properties) {
properties[prop] = action.updated_known_properties[prop];
}
if (typeof properties.follow_up_type !== 'undefined') {
var time = (new Date(action.date)).getTime();
if (!firstFollowUpTime) {
firstFollowUpTime = time;
}
if (!lastFollowUpTime || time > lastFollowUpTime) {
lastFollowUpTime = time;
}
}
}
// calculate indicators
var data = {},
openedOn = datePlusDays(doc.opened_on, 0).getTime(),
filterDatePlus11 = datePlusDays(doc.filter_date, 11).getTime(),
filterDatePlus13 = datePlusDays(doc.filter_date, 13).getTime();
data.followedUp = (doc.follow_up_type === 'followed_up');
data.noFollowUpAfter4Days = !!(hasPhoneNumber(doc) &&
(!firstFollowUpTime || filterDatePlus11 < firstFollowUpTime) &&
doc.filter_date
);
data.transferredToManager = (doc.follow_up_type === 'direct_to_call_center_manager');
data.transferredToField = (doc.follow_up_type === 'field_follow_up');
data.notClosedOrTransferredAfter13Days = !!(hasPhoneNumber(doc) &&
!(doc.closed_on || data.transferredToManager || data.transferredToField) &&
doc.filter_date
);
data.workingDays = [];
for (var i in doc.actions) {
var days = daysSinceEpoch(new Date(doc.actions[i].date));
if (data.workingDays.indexOf(days) === -1) {
data.workingDays.push();
}
}
data.followUpTime = lastFollowUpTime ?
differenceInDays(lastFollowUpTime, openedOn) : null;
emit_array([doc.user_id], [doc.opened_on], data, {
noFollowUpAfter4Days: [doc.filter_date || 0],
notClosedOrTransferredAfter13Days: [doc.filter_date || 0]
});
}
| JavaScript | 0.000004 | @@ -2198,16 +2198,52 @@
+(!lastFollowUpTime %7C%7C %0A (
!(doc.cl
@@ -2306,16 +2306,69 @@
ToField)
+ %7C%7C%0A filterDatePlus13 %3C lastFollowUpTime))
&&%0A
|
c9d9f886a37d24efe9cdabe2818f81fac30fbe0a | build algorithm update | build.js | build.js | var fs = require('fs')
var path = require('path')
var gulp = require('gulp')
var concat = require('gulp-concat')
path.delimiter = "/"
var javascriptSource = [];
var cssSource = [];
(function lookIntoFolder(dir){
var folderContent = fs.readdirSync( path.resolve(__dirname, dir) )
folderContent.forEach(function( filename ){
var filepath = "./"+ dir+"/"+ filename
filepath = filepath.replace(/\\/gi, "/")
var stat = fs.lstatSync( filepath )
if(stat.isFile()){
var extension = filename.split('.')[1]
if(extension == "js"){
javascriptSource.push(filepath)
}else if(extension == "css"){
cssSource.push(filepath)
}
}else if(stat.isDirectory()){
lookIntoFolder(dir+"/"+filename)
}
})
})("src")
console.log(javascriptSource, cssSource)
gulp.src(javascriptSource)
.pipe(concat('caretaker.js'))
.pipe(gulp.dest("dist") )
gulp.src(cssSource)
.pipe(concat('caretaker.css'))
.pipe(gulp.dest("dist"))
| JavaScript | 0.000001 | @@ -132,86 +132,74 @@
/%22%0A%0A
-var javascriptSource = %5B%5D;%0Avar cssSource = %5B%5D;%0A(function lookIntoFolder(dir)%7B%0A
+function lookIntoFolder(dir, intendedExtension)%7B%0A%09var sources = %5B%5D
%0A%09va
@@ -516,97 +516,39 @@
==
-%22js%22)%7B%0A%09%09%09%09javascriptSource.push(filepath)%0A%09%09%09%7Delse if(extension == %22css%22
+intendedExtension
)%7B%0A%09%09%09%09
-cssS
+s
ource
+s
.pus
@@ -599,16 +599,41 @@
())%7B%0A%09%09%09
+var sourcesInDirectory =
lookInto
@@ -659,202 +659,804 @@
name
-)%0A%09%09%7D%0A%09%7D)%0A%0A%7D)(%22src%22)%0A%0Aconsole.log(javascriptSource, cssSource)%0A%0Agulp.src(javascriptSource)%0A%09.pipe(concat('caretaker.js'))%0A%09.pipe(gulp.dest(%22dist%22) )%0A%0Agulp.src(cssSource)%0A%09.pipe(concat('caretaker
+, intendedExtension)%0A%09%09%09sources = sources.concat(sourcesInDirectory)%0A%09%09%7D%0A%09%7D)%0A%09return sources%0A%7D%0A%0Avar javascriptSource = lookIntoFolder(%22src%22, %22js%22)%0Avar cssSource = lookIntoFolder(%22src%22, %22css%22)%0A%0Avar javascriptExtensionSource = lookIntoFolder(%22src_extension%22, %22js%22)%0Avar cssExtensionSource = lookIntoFolder(%22src_extension%22, %22css%22)%0A%0Aconsole.log(%22Main Files:%22, javascriptSource, cssSource)%0Aconsole.log(%22Extension Files:%22, javascriptExtensionSource, cssExtensionSource)%0A%0Agulp.src(javascriptSource)%0A%09.pipe(concat('caretaker.js'))%0A%09.pipe(gulp.dest(%22dist%22) )%0A%0Agulp.src(cssSource)%0A%09.pipe(concat('caretaker.css'))%0A%09.pipe(gulp.dest(%22dist%22))%0A%0Agulp.src(javascriptExtensionSource)%0A%09.pipe(concat('caretaker.extension.js'))%0A%09.pipe(gulp.dest(%22dist%22))%0A%0Agulp.src(cssExtensionSource)%0A%09.pipe(concat('caretaker.extension
.css
|
ca30dbe5c02599cc4c1cbee4c85e74e4fa32f9b8 | Fix spec. | src/app/battle/character.srv.spec.js | src/app/battle/character.srv.spec.js | describe('factory: Character', function () {
beforeEach(module('marvel.app'));
beforeEach(inject(function () {
}));
describe('On initialization', function () {
it('should load the character data', inject(function ($rootScope, $q, Character, BattleApi) {
function getSuccessfulPromise() {
var defer = $q.defer();
defer.resolve({
data: {
results: [
{
id: 100,
name: 'foo',
thumbnail: {
path: 'http://foo',
extension: 'jpg'
}
}
]
}
});
return defer.promise;
}
spyOn(BattleApi, 'findCharacterByOffset').andReturn(getSuccessfulPromise());
var character = new Character(0);
$rootScope.$apply();
expect(character.offset).toBe(0);
expect(character.loaded).toBe(true);
expect(character.id).toBe(100);
expect(character.name).toBe('foo');
expect(character.picture).toBe('http://foo.jpg');
}));
});
}); | JavaScript | 0 | @@ -1036,16 +1036,54 @@
cter(0);
+%0A character.loadByOffset();
%0A%0A
|
158ae45cebfb1f711c52c0effe788771ec1a3e4d | change scr | App/js/services/graphics-engine.js | App/js/services/graphics-engine.js | /*Original Game File - functions to help with displaying the game*/
angular.module("gameApp")
.factory("graphicsEngineService", ["globalSettings", "coordinateSystem", function (globalSettings, coordinateSystem) {
"use strict";
return {
initialise: function (canvasContext, graphicsFile) {
this.spriteWidth = globalSettings.spriteSize;
this.spriteHeight = globalSettings.spriteSize;
this.canvas = canvasContext;
this.spriteSheet = new Image();
this.spriteSheet.src = graphicsFile;
},
convertGameXCoordinateToPixels: function (x) {
return x * globalSettings.spriteSize;
},
convertGameYCoordinateToPixels: function (y) {
return (y * globalSettings.spriteSize) + globalSettings.scoreBoardArea;
},
blankScreen: function () {
var img = new Image;
img.src = "http://i.imgur.com/tRbwjj7.png";
var pat = this.canvas.createPattern(img, "repeat");
this.canvas.rect(0, 0, 450, 400);
this.canvas.fillStyle = pat;
this.canvas.fill();
//this.canvas.fillStyle = globalSettings.gameBoardBackgroundColour;
this.canvas.fillRect(0, 0, globalSettings.gameBoardWidth * this.spriteWidth, globalSettings.scoreBoardArea + (globalSettings.gameBoardHeight * this.spriteHeight));
},
drawText: function (coordSystem, x, y, text, colour, font) {
if (coordSystem === coordinateSystem.world) {
x = this.convertGameXCoordinateToPixels(x);
y = this.convertGameYCoordinateToPixels(y);
}
/*
var img = new Image;
img.src = "../../images/bg.png";
var pat = this.canvas.createPattern(img, "no-repeat");
this.canvas.rect(0, 0, 100, 10);
this.canvas.fillStyle = pat;
this.canvas.fill();
*/
this.canvas.font = font;
this.canvas.fillText(text, x, y)
},
drawImage: function (coordSystem, x, y, image) {
if (coordSystem === coordinateSystem.world) {
x = this.convertGameXCoordinateToPixels(x);
y = this.convertGameYCoordinateToPixels(y);
}
this.canvas.drawImage(
this.spriteSheet,
this.spriteWidth * (image % globalSettings.spriteSheetWidth),
this.spriteHeight * Math.floor(image / globalSettings.spriteSheetWidth),
this.spriteWidth,
this.spriteHeight,
x,
y,
this.spriteWidth,
this.spriteHeight);
}
}
}]); | JavaScript | 0.000001 | @@ -1030,10 +1030,8 @@
p://
-i.
imgu
@@ -1040,19 +1040,15 @@
com/
-tRbwjj7.png
+QThBTyI
%22;%0D%0A
@@ -2100,32 +2100,52 @@
llStyle = pat;%0D%0A
+ */%0D%0A
@@ -2171,14 +2171,8 @@
%0D%0A%0D%0A
-*/%0D%0A%0D%0A
|
e54522895d266cc305088e39958840f71d46e5ae | Add mobile signaling support + debugging | signal/index.js | signal/index.js | var _ = require('lodash-node')
var users = []
var sessions = {}
exports.register = function (server, options, next) {
var io = require('socket.io')(server.select('signal').listener)
io.on('connection', function (socket) {
socket.on('register', function (data) {
if (_.findIndex(users, { socket: socket.id }) !== -1) {
socket.emit('register_error', { message: 'You are already registered.' })
return
}
users.push({
socket: socket.id,
session: data.session
})
if (data.isInitiator) {
sessions[data.session] = {
initiator: socket.id,
users: []
}
}
sessions[data.session].users.push({ socket: socket.id })
socket.emit('registered', {
socket: socket.id,
session: data.session,
users: sessions[data.session].users
})
console.log('- ' + socket.id + ' registered, session ' + data.session)
})
socket.on('invite', function (data) {
var user = _.find(users, { socket: socket.id })
if (!user) { return }
var target = _.find(users, { socket: data.target })
if (!target) { return }
io.to(target.socket).emit('invited', {
id: socket.id
})
})
socket.on('message', function (data) {
var user = _.find(users, { socket: socket.id })
if (!user) { return }
var target = _.find(users, { socket: data.target })
if (!target) { return }
io.to(target.socket).emit('message', {
id: socket.id,
message: data.message
})
})
socket.on('disconnect', function () {
var index = _.findIndex(users, { socket: socket.id })
if (index !== -1) {
var session = users[index].session
var seindex = _.findIndex(sessions[session].users, { socket: socket.id })
users.splice(index, 1)
sessions[session].users.splice(seindex, 1)
_.forEach(sessions[session].users, function (user, n) {
io.to(user.socket).emit('leave', {
id: socket.id
})
})
console.log('- ' + socket.id + ' disconnected.')
}
})
})
next()
}
exports.register.attributes = {
name: 'olive-signal'
}
| JavaScript | 0 | @@ -221,16 +221,69 @@
ocket) %7B
+%0A console.log('- ' + socket.id + ' has connected')
%0A%0A so
@@ -570,24 +570,122 @@
n%0A %7D)%0A%0A
+ // For mobile%0A if (!sessions%5Bdata.session%5D) %7B%0A data.isInitiator = true%0A %7D%0A%0A
if (da
@@ -803,24 +803,25 @@
%7D%0A %7D%0A
+%0A
sessio
@@ -1384,32 +1384,97 @@
cket.id%0A %7D)
+%0A%0A console.log('- ' + socket.id + ' invited ' + data.target)
%0A %7D)%0A%0A soc
@@ -1779,24 +1779,24 @@
message%0A
-
%7D)
%0A %7D)%0A
@@ -1783,24 +1783,129 @@
age%0A %7D)
+%0A%0A console.log('- ' + socket.id + ' sent message to ' + data.target)%0A console.log(data.message)
%0A %7D)%0A%0A
|
9bac8da85ab224ad8ee03c1e01e11ab7f39ea3d3 | Simplify code with _.result | core/src/main/web/app/utils/basic/commonui.js | core/src/main/web/app/utils/basic/commonui.js | /*
* Copyright 2014 TWO SIGMA OPEN SOURCE, 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
*
* 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.
*/
/**
* Module bk.commonUi
* This module is the general store of low level UI directives, which should be separated out or
* potentially found equivalent in 3rd party libraries.
*/
(function() {
'use strict';
var module = angular.module('bk.commonUi', []);
module.directive('onCtrlEnter', function() {
return {
link: function(scope, element, attrs) {
element.bind("keyup", function(event) {
if (event.ctrlKey && event.keyCode === 13) { // ctrl + enter
scope.$apply(attrs.onCtrlEnter);
}
});
}
};
});
module.directive('eatClick', function() {
return function(scope, element, attrs) {
element.click(function(event) {
event.preventDefault();
});
};
});
module.directive('focusStart', function() {
return {
link: function(scope, element, attrs) {
Q.fcall(function() {
element.focus();
});
}
};
});
module.directive('bkcell', function() {
return {
restrict: 'C',
link: function(scope, element, attrs) {
element.mouseover(function(event) {
element.addClass("cell-bracket-selected");
event.stopPropagation();
});
element.mouseout(function(event) {
element.removeClass("cell-bracket-selected");
event.stopPropagation();
});
}
};
});
module.directive('bkShow', function() { // like ngShow, but animated
return {
link: function(scope, element, attrs) {
var expression = attrs.bkShow;
scope.$watch(expression, function(newValue, oldValue) {
if (newValue) {
element.stop(true, true).slideDown(200);
} else {
element.stop(true, true).slideUp(200);
}
});
}
};
});
module.directive('bkHide', function() { // like ngShow, but animated
return {
link: function(scope, element, attrs) {
var expression = attrs.bkHide;
scope.$watch(expression, function(newValue, oldValue) {
if (newValue) {
element.stop(true, true).slideUp(200);
} else {
element.stop(true, true).slideDown(200);
}
});
}
};
});
module.directive('bkDropdownMenu', function() {
return {
restrict: 'E',
template: '<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">' +
'<li ng-repeat="item in getMenuItems()" ng-class="getItemClass(item)">' +
'<a href="#" tabindex="-1" ng-click="runAction(item)" ng-class="getAClass(item)" title="{{item.tooltip}}" eat-click>' +
'<i class="icon-ok" ng-show="isMenuItemChecked(item)"> </i> ' +
'{{getName(item)}}' +
'</a>' +
// XXX - the submenu needs to be hacked to be as wide as the parent
// otherwise there is a gap and you can't hit the submenu. BEAKER-433
'<ul class="dropdown-menu">' +
'<li ng-repeat="subitem in getSubItems(item)" ng-class="getItemClass(subitem)">' +
'<a href="#" tabindex="-1" ng-click="runAction(subitem)" ng-class="getAClass(subitem)" title="{{subitem.tooltip}}" eat-click>' +
'<i class="icon-ok" ng-show="isMenuItemChecked(subitem)"> </i> ' +
'{{getName(subitem)}}' +
'</a>' +
'</li>' +
'</ul>' +
'</li>' +
'</ul>',
scope: {
"menuItems": "=",
// Classes to be added to any submenu item. Used for adding
// pull-left to menus that are on the far right (e.g. bkcellmenu).
submenuClasses: '@'
},
replace: true,
controller: function($scope) {
var isItemDisabled = function(item) {
if (_.isFunction(item.disabled)) {
return item.disabled();
}
return item.disabled;
};
$scope.getMenuItems = function() {
if (_.isFunction($scope.menuItems)) {
return $scope.menuItems();
} else {
return $scope.menuItems;
}
};
$scope.getAClass = function(item) {
var result = [];
if (isItemDisabled(item)) {
result.push("disabled-link");
} else if (item.items && item.items.length <= 1 && item.autoReduce) {
if (item.items.length === 0) {
result.push("disabled-link");
} else if (item.items.length === 1) {
if (isItemDisabled(item.items[0])) {
result.push("disabled-link");
}
}
}
return result.join(" ");
};
$scope.getItemClass = function(item) {
var result = [];
if (item.type === "divider") {
result.push("divider");
} else if (item.type === "submenu" || item.items) {
if (item.items && item.items.length <= 1 && item.autoReduce) {
} else {
result.push("dropdown-submenu");
// Add any extra submenu classes. (e.g. to specify if it should be left or right).
if ($scope.submenuClasses) {
_.each(
$scope.submenuClasses.split(' '),
function(elt) {
result.push(elt);
}
);
}
}
}
return result.join(" ");
};
$scope.runAction = function(item) {
if (item.items && item.items.length === 1 && item.autoReduce) {
item.items[0].action();
} else {
item.action();
}
};
$scope.getName = function(item) {
var name = "";
if (item.items && item.items.length === 1 && item.autoReduce) {
if (item.items[0].reducedName) {
name = item.items[0].reducedName;
} else {
name = item.items[0].name;
}
} else {
name = item.name;
}
if (_.isFunction(name)) {
name = name();
}
return name;
};
$scope.isMenuItemChecked = function(item) {
if (item.isChecked) {
if (_.isFunction(item.isChecked)) {
return item.isChecked();
} else {
return item.isChecked;
}
}
return false;
};
$scope.getSubItems = function(parentItem) {
if (_.isFunction(parentItem.items)) {
return parentItem.items();
}
return parentItem.items;
};
},
link: function(scope, element, attrs) {
}
};
});
module.directive('bkEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.bkEnter);
});
event.preventDefault();
}
});
};
});
})();
| JavaScript | 0.999998 | @@ -4529,130 +4529,33 @@
-if (_.isFunction($scope.menuItems)) %7B%0A return $scope.menuItems();%0A %7D else %7B%0A return
+return _.result(
$scope
-.
+, '
menu
@@ -4559,29 +4559,19 @@
enuItems
-;%0A %7D
+');
%0A
|
9f9cfe11ee274aadd749b0acbb951fbd4519eb7d | fix to support flac in firefox | scripts/app/app.js | scripts/app/app.js | "use strict";
// Create the AudioContext to use in the app
var audioCtx = new window.AudioContext();
// Load app when everything else has loaded
window.onload = function() {
var app = new App();
app.loadDefault();
};
/**
* Audio visualiser. Uses Web Audio API and Three.js
* Initializes values and starts listening to the UI
*/
var App = function() {
this.audioHandler = null;
this.threeVis = null;
this.analyser = audioCtx.createAnalyser();
this.analyser.connect(audioCtx.destination);
this.analyser.minDecibels = -100;
this.analyser.maxDecibels = -20;
this.analyser.smoothingTimeConstant = 0.9;
this.analyser.fftSize = 2048;
// Listen to the browse button
var fileUpload = document.getElementById("fileUpload");
var self = this;
fileUpload.addEventListener("change", function() {
self.loadUploadedFile(fileUpload.files[0]);
});
// Listen to the default button
var loadDefaultBtn = document.getElementById("loadDefaultBtn");
loadDefaultBtn.addEventListener("click", function() {
self.loadDefault();
});
};
/**
* Load a user uploaded file
* @param {File} file The uploaded file
*/
App.prototype.loadUploadedFile = function(file) {
var reader = new FileReader();
var that = this;
reader.onload = function(e) {
// If flac, use aurora.js and flac.js to decode
if (file.type === "audio/flac") {
var asset = AV.Asset.fromBuffer(e.target.result);
/*
Decode the flac file to a Float32Array containing interleaved
PCM audio and pass it to the specified function
*/
asset.decodeToBuffer(function(buffer) {
window.console.log("Audio decoded.");
/* Copy the interleaved PCM audio from the Float32Array to a new AudioBuffer */
var audioBuffer = audioCtx.createBuffer(2, buffer.length, audioCtx.sampleRate);
var leftChannel = audioBuffer.getChannelData(0);
var rightChannel = audioBuffer.getChannelData(1);
var inputIndex = 0;
for (var i = 0; i < buffer.length;) {
leftChannel[inputIndex] = buffer[i++];
rightChannel[inputIndex] = buffer[i++];
inputIndex++;
}
var array = [];
array[0] = audioBuffer;
that.finishedLoading(array);
});
// Else use the AudioContext to decode. Supported formats depends on the browser
} else {
audioCtx.decodeAudioData(e.target.result, function(buffer) {
window.console.log("Audio decoded.");
var array = [];
array[0] = buffer;
that.finishedLoading(array);
});
}
};
reader.readAsArrayBuffer(file);
};
App.prototype.loadDefault = function() {
var that = this;
var bufferLoader = new BufferLoader(audioCtx, [
"sounds/default.mp3",
],
that.finishedLoading.bind(that)
);
bufferLoader.load();
};
/**
* Handles the decoded AudioBuffers.
* Sets up the AudioHandler and visualiser the first time the function is called.
* Also sets up the play button listener.
* A bit flawed to do it this way, but hey, it works
*
* @param {Array} bufferList Array containing the AudioBuffers
* @return {void}
*/
App.prototype.finishedLoading = function(bufferList) {
if (this.audioHandler === null) {
this.audioHandler = new AudioHandler(this.analyser, bufferList[0]);
var tempAudio = this.audioHandler;
this.threeVis = new ThreeVis(this.analyser);
var toggle = document.getElementById("toggle");
var togglespan = document.getElementById("togglespan");
toggle.addEventListener("click", function() {
tempAudio.togglePlayback();
if (togglespan.className == "glyphicon glyphicon-play")
togglespan.className = "glyphicon glyphicon-pause";
else
togglespan.className = "glyphicon glyphicon-play";
});
} else {
this.audioHandler.changeBuffer(bufferList[0]);
}
};
| JavaScript | 0 | @@ -1384,16 +1384,43 @@
decode%0A
+ console.log(file);%0A
@@ -1449,16 +1449,49 @@
io/flac%22
+ %7C%7C file.type === 'audio/x-flac'
) %7B%0A
|
c4ea61c303a3e9b554f1bc7e6cda7ee927b05c2b | Remove more content from the wikipedia article, that we dont want. | webtasks/wikipedia-article-extract.js | webtasks/wikipedia-article-extract.js | const jsdom = require('jsdom');
const f = (context, cb) => {
const wikipediaUrl = context.data['article-url'];
jsdom.env({
url: `${ wikipediaUrl }?printable=yes`,
scripts: ['http://code.jquery.com/jquery.js'],
done: (err, window) => {
const $ = window.$;
$('script').remove(); // remove all scripts
$('.thumb').remove(); // remove all images
$('#toc').remove(); // remove the TOC
$('.mw-editsection').remove(); // remove the edit controls
$('.reference').remove(); // remove all foot notes
$('table').remove(); // inline tables are useless
cb(null, $('#mw-content-text').text());
}
});
};
module.exports = f;
| JavaScript | 0 | @@ -594,16 +594,169 @@
seless%0A%0A
+ // remove content at the bottom which we dont need%0A $('.printfooter').remove();%0A $('#catlinks').remove();%0A $('noscript').remove();%0A%0A
cb
|
10cd6b1318af66b17fb08e6fec05c3b54a793211 | version 1.0.0 | better-prettydate.js | better-prettydate.js | /**
* @file better-prettydate.js
* @version 1.0.0 2013-07-10T21:26:33
* @overview Enhances time element to update text in realtime
* @copyright Maksim Chemerisuk 2013
* @license MIT
* @see https://github.com/chemerisuk/better-prettydate
*/
(function(DOM, undefined) {
"use strict";
// Inspired by jquery-prettydate:
// http://bassistance.de/jquery-plugins/jquery-plugin-prettydate/
var I18N_NOW = "prettydate-now",
I18N_MINUTE = "prettydate-minute",
I18N_MINUTES = "prettydate-minutes",
I18N_HOUR = "prettydate-hour",
I18N_HOURS = "prettydate-hours",
I18N_YESTERDAY = "prettydate-yesterday",
I18N_DAYS = "prettydate-days",
I18N_WEEK = "prettydate-week",
I18N_WEEKS = "prettydate-weeks",
I18N_MONTH = "prettydate-month",
I18N_MONTHS = "prettydate-months",
I18N_YEAR = "prettydate-year",
I18N_YEARS = "prettydate-years";
DOM.extend("time[datetime]", {
constructor: function() {
// use bind to store context inside of _refreshDate
this.bind("_refreshDate")._refreshDate();
},
getDate: (function() {
// https://github.com/csnover/js-iso8601/blob/master/iso8601.js
var rES5ts = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/,
// Indexes in a rES5ts match list that are required for Date.UTC,
// Use in a loop to replace undefined with 0 (otherwise Date.UTC would give NaN)
dateUrcReqIndx = [1, 4, 5, 6, 7, 10, 11];
return function() {
var i, k, minutesOffset = 0,
m = rES5ts.exec(this.get("datetime"));
if (!m) throw "Invalid ISO String";
for (i = 0; (k = dateUrcReqIndx[i]); i += 1) {
m[k] = +m[k] || 0;
}
// Undefined days and months are allowed
m[2] = +m[2] || 1;
m[3] = +m[3] || 1;
if (m[8] !== "Z" && m[9] !== undefined) {
minutesOffset = m[10] * 60 + m[11];
if (m[9] === "+") minutesOffset = 0 - minutesOffset;
}
return Date.UTC(m[1], m[2] - 1, m[3], m[4], m[5] + minutesOffset, m[6], m[7]);
};
}()),
setDate: (function() {
var pad = function(value) { return ("00" + value).slice(-2); };
return function(value) {
var result = value.getUTCFullYear() +
"-" + pad( value.getUTCMonth() + 1 ) +
"-" + pad( value.getUTCDate() ) +
"T" + pad( value.getUTCHours() ) +
":" + pad( value.getUTCMinutes() ) +
":" + pad( value.getUTCSeconds() ) +
"." + String( (value.getUTCMilliseconds() / 1000).toFixed(3) ).slice(2, 5) +
"Z";
this.set("datetime", result)._refreshDate();
return this;
};
}()),
_refreshDate: function() {
var diff = (new Date() - this.getDate()) / 1000,
dayDiff = Math.floor(diff / 86400),
value = 1,
i18nKey;
if (dayDiff === 0) {
if (diff < 60) i18nKey = I18N_NOW;
else if (diff < 120) i18nKey = I18N_MINUTE;
else if (diff < 3600) { i18nKey = I18N_MINUTES; value = Math.floor(diff / 60); }
else if (diff < 7200) { i18nKey = I18N_HOUR; }
else if (diff < 86400) { i18nKey = I18N_HOURS; value = Math.floor(diff / 3600); }
} else if (dayDiff === 1) { i18nKey = I18N_YESTERDAY; }
else if (dayDiff < 7) { i18nKey = I18N_DAYS; value = dayDiff; }
else if (dayDiff < 8) { i18nKey = I18N_WEEK; }
else if (dayDiff < 14) { i18nKey = I18N_DAYS; value = dayDiff; }
else if (dayDiff < 30) { i18nKey = I18N_WEEKS; value = Math.ceil(dayDiff / 7); }
else if (dayDiff < 32) { i18nKey = I18N_MONTH; }
else if (dayDiff < 363) { i18nKey = I18N_MONTHS; value = Math.ceil(dayDiff / 31); }
else if (dayDiff <= 380) { i18nKey = I18N_YEAR; }
else if (dayDiff > 380) { i18nKey = I18N_YEARS; value = Math.ceil(dayDiff / 365); }
// protect from internal inserted content + trigger reflow in IE8
this.set({ "data-i18n": i18nKey, "data-prettydate": value }).set("");
// schedule next update
setTimeout(this._refreshDate, (dayDiff > 0 ? 86400 : (diff < 3600 ? 60 : 3600)) * 1000);
}
});
}(window.DOM));
| JavaScript | 0.000002 | @@ -64,12 +64,12 @@
21:2
-6:33
+7:44
%0A *
|
634b1df62ae5456c540e179b376253b684e483af | enhance removeLine func | generators/utils.js | generators/utils.js | 'use strict';
const path = require('path');
const fs = require('fs-extra');
const chalk = require('chalk');
const _ = require('lodash')
const beautify = require('js-beautify').js_beautify;
const jsBeautifyOptions = { indent_size: 2, preserve_newlines: false, end_with_newline: true };
// Defining Markers
exports.COMPONENT_MARKER = '// Add new components above';
exports.SERVICE_MARKER = '// Add new services above';
exports.PAGE_MARKER = '// Add new pages above';
exports.DIRECTIVE_MARKER = '// Add new directives above';
exports.COMPONENT_NESTED_MARKER = '// Add new nested components above';
exports.SERVICE_NESTED_MARKER = '// Add new nested services above';
exports.DIRECTIVE_NESTED_MARKER = '// Add new nested directives above';
exports.IMPORT_MODULE_MARKER = '// Add module imports above';
exports.IMPORT_STYLE_MARKER = '// Add style imports above';
exports.IMPORT_DIRECTIVE_MARKER = '// Add directive imports above';
exports.IMPORT_SERVICE_MARKER = '// Add service imports above';
exports.IMPORT_DEPENDENCY_MARKER = '// Add module dependencies above';
exports.ADD_DIRECTIVE_TOMODULE_MARKER = '// Add directive to module above';
exports.ADD_SERVICE_TOMODULE_MARKER = '// Add service to module above';
exports.MAIN_SCSS_MARKER = '// Add Main SCSS Above';
exports.ROUTE_MARKER = '// Add new routes above';
exports.STATE_MARKER = '// Add new states above';
exports.DOCS_ASSETS_PATH = '/docs/docs-assets';
exports.DOCS_STORAGE_FILENAME = 'docs.json';
// Defining utility functions
/*
* writes a line to a file before a marker
* takes as inputs the file name, line to add, marker, and full path
*/
exports.addToFile = function(filename,lineToAdd,beforeMarker,fullpathI){
try {
let fullPath = path.resolve(fullpathI,filename);
let fileSrc = fs.readFileSync(fullPath,'utf8');
let indexOf = fileSrc.indexOf(beforeMarker);
let lineStart = fileSrc.substring(0,indexOf).lastIndexOf('\n') + 1;
let indent = fileSrc.substring(lineStart,indexOf);
fileSrc = fileSrc.substring(0,indexOf) + lineToAdd + "\n" + indent + fileSrc.substring(indexOf);
fs.writeFileSync(fullPath,fileSrc);
// console.log('Written data to files');
} catch(e) {
console.log('Could not write data to files');
throw e;
}
};
exports.removeLineFromFile = function(filename,lineToRemove, fullpathI, indent, fullLine){
try {
let fullPath = path.resolve(fullpathI,filename);
let fileSrc = fs.readFileSync(fullPath,'utf8');
let indexOf = fileSrc.indexOf(lineToRemove);
if(indexOf===-1){
throw new Error('line not found');
}
let topHalf = fileSrc.substring(0,indexOf);
topHalf = topHalf.substring(0, topHalf.lastIndexOf('\n'))
let bottomHalf = fileSrc.substring(indexOf);
fileSrc = topHalf + bottomHalf.substring(bottomHalf.indexOf('\n'));
// fileSrc = beautify(fileSrc, jsBeautifyOptions);
fs.writeFileSync(fullPath,fileSrc);
// console.log('Written data to files');
} catch(e) {
console.log('Could not remove data from files');
throw e;
}
};
/*
* checks if a given path exists synchronously
*/
exports.existsSync = function(path){
return fs.existsSync(path);
};
exports.isHasPackage = function (obj) {
return _.isObject(obj) && obj.package && obj.import !== false;
}
exports.stripPackageName = function (pkgName) {
let regexp = /(.*?)@/;
let match = pkgName.match(regexp);
if (match) {
return match[1];
}
return pkgName;
}
exports.deleteDirRecursive = function(path) {
if (fs.existsSync(path)) {
fs.readdirSync(path).forEach(function(file, index) {
var curPath = path + "/" + file;
if (fs.lstatSync(curPath).isDirectory()) { // recurse
exports.deleteDirRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}else{
console.log("invalid path: " + path + " was not deleted.");
}
};
| JavaScript | 0.000004 | @@ -2690,23 +2690,34 @@
+let
topHalf
+IndexOf
= topHa
@@ -2723,21 +2723,30 @@
alf.
-substring(0,
+lastIndexOf('%5Cn')!=-1?
topH
@@ -2766,17 +2766,88 @@
Of('%5Cn')
-)
+:topHalf.length;%0A topHalf = topHalf.substring(0, topHalfIndexOf);
%0A
|
749ed249336b9aa1eae655516aee5d5ffbcfc0c8 | Return the parsed message from command. | plugins/command.js | plugins/command.js | /* Description:
* Generic command parsing and dispatch.
*
* Dependencies:
* None
*
* Configuration:
* None
*
* Author:
* mythmon
*
* Takes messages that look like "foo bar=baz qux" and converts them to
* `sendMessage('foo', {bar: baz, _args: ['qux']})`
*
* Special processing: if the first space-separated part of the string
* looks like a url, this will make a content message like
* `sendMessage('content', {url: <theurl>, type: 'url', <any extra args>})
*/
var url = require('url');
module.exports = function(corsica) {
corsica.on('command', function(args) {
var tokens = parser(args.raw);
var msgType = tokens[0];
var parsedUrl = url.parse(tokens[0]);
var msg = {
raw: args.raw,
_args: [],
};
tokens.slice(1).forEach(function(token) {
if (token.indexOf('=') > -1) {
var parts = token.split('=');
msg[parts[0]] = parts.slice(1).join('=');
} else {
msg._args.push(token);
}
});
if (parsedUrl.protocol) {
// Found a url, special case.
msg.url = tokens[0];
msg.type = 'url';
msgType = 'content';
}
return corsica.sendMessage(msgType, msg)
.then(function (msg) {
if (msg.response) {
args._response = msg._response;
}
return args;
});
});
};
function parser(str) {
var tokens = [];
var quotes = false;
var curToken = '';
function _push() {
if (curToken) {
tokens.push(curToken);
}
curToken = '';
}
for (var i = 0; i < str.length; i++) {
if (str[i] === '\\') {
i++;
curToken += str[i];
} else {
if (quotes) {
if (str[i] === '"') {
quotes = false;
_push();
} else {
curToken += str[i];
}
} else {
if (str[i] === '"') {
quotes = true;
} else if (str[i] === ' ') {
_push();
} else {
curToken += str[i];
}
}
}
}
_push();
return tokens;
}
module.exports.parser = parser;
| JavaScript | 0.000858 | @@ -579,20 +579,19 @@
unction(
-args
+msg
) %7B%0A%0A
@@ -611,20 +611,19 @@
parser(
-args
+msg
.raw);%0A
@@ -701,63 +701,22 @@
-var msg = %7B%0A raw: args.raw,%0A
+msg.
_args
-:
+ =
%5B%5D
-,%0A %7D
;%0A
@@ -1106,34 +1106,19 @@
-return corsica.sendMessage
+console.log
(msg
@@ -1131,146 +1131,54 @@
msg)
-%0A
+;%0A%0A
-.then(function (msg) %7B%0A if (msg.response) %7B%0A args._response = msg._response;%0A %7D%0A return args;%0A %7D
+return corsica.sendMessage(msgType, msg
);%0A
|
cf6cc3461dbe98486e08ddc41d4c0eb6aab713b0 | Fix gender definition not exists in zh-Hant-TW. | src/types/person/definitions/zh-Hant-TW/index.js | src/types/person/definitions/zh-Hant-TW/index.js | export {default as name} from './name';
export {default as firstName} from './firstName';
export {default as lastName} from './lastName';
| JavaScript | 0.998692 | @@ -29,24 +29,68 @@
m './name';%0A
+export %7Bdefault as gender%7D from './gender';%0A
export %7Bdefa
|
37a93c26e472d2692edb76dd078ce6ca08dcfdef | comment the current line, if no selection | plugins/comment.js | plugins/comment.js |
//do something else here to inject script for the language of the file.
//for example...
// js is //
// bash is #
// ini is ;
// I spend most of my time editing js, though.
// so I'll leave that for when it's more important.
function comment (line) {
return '//' + line
}
function uncomment (line) {
return isCommented(line) ? line.replace('//', '') : line
}
function isCommented (line) {
var r = /^\s*\/\//.test(line)
console.error('COMMENTED?', r, line)
return r
}
module.exports = function (doc, keys) {
var rc = this.config
keys.on('keypress', function (ch, key) {
if('k' == key.name && key.ctrl && doc.marks) {
var m = doc.marks[0]
var M = doc.marks[1]
//first decide if we will comment or uncomment.
//uncomment, if the lines all have comments at the start.
//else, comment.
var commented = true
for(var i = m.y; i <= M.y; i++)
if(!isCommented(doc.lines[i]))
commented = false
for(var i = m.y; i <= M.y; i++)
doc.updateLine(i,
(commented ? uncomment : comment) (doc.lines[i])
)
}
})
}
| JavaScript | 0 | @@ -228,16 +228,50 @@
portant.
+%0A// don't comment out empty lines?
%0A%0Afuncti
@@ -469,43 +469,25 @@
ine)
-%0A console.error('COMMENTED?', r,
+ %7C%7C /%5E%5Cs*$/.test(
line
@@ -649,79 +649,282 @@
ctrl
- && doc.marks) %7B%0A var m = doc.marks%5B0%5D%0A var M = doc.marks%5B1%5D%0A
+) %7B%0A if(!doc.marks)%0A doc.start().mark().down().mark().up().move()%0A var m = doc.marks%5B0%5D%0A var M = doc.marks%5B1%5D%0A var from = m.y%0A //only indent do not comment the last line if the cursor is at 0%0A var to = M.x %7C%7C M.y == m.y ? M.y : M.y - 1
%0A
@@ -1103,37 +1103,37 @@
for(var i =
-m.y
+from
; i %3C=
-M.y
+to
; i++)%0A
@@ -1217,21 +1217,21 @@
i =
-m.y
+from
; i %3C=
-M.y
+to
; i+
|
b4d67860dcecdaea849ea85855bd4a50e683f5ae | replace local file with /dev/stdin, comment out unneeded variables | scripts/cleanup.js | scripts/cleanup.js | // cleanup.js
/*
* MIT license http://opensource.org/licenses/MIT
*
* Copyright (c) 2015 Eric Elliott
* Original author of this script: [email protected]
*/
var fs = require("fs");
var doclistPath = '/Users/sperberx/dev/essential-javascript-links/misc/';
var doclistName = 'README-short1';
var doclistAddon = '-new';
var doclistExtension = '.md';
/*
files I'm testing with
/Users/sperberx/dev/essential-javascript-links/misc/some-wrong-apos.md
/Users/sperberx/dev/essential-javascript-links/README.md
/Users/sperberx/dev/essential-javascript-links/misc/README-ee.md
/Users/sperberx/dev/essential-javascript-links/misc/README-short1.md
*/
// identify each type of change, particularly for the apostrophe, since global change (e.g., /.'./g or /(\w|\d)'(\w|\d)/g) is just too risky
// By making only known changes, stray apostrophes and quotes can be located easily
// not yet defined: single quotes within double quotes
var replacements = [
{ searchFor: /'d\b/g, replaceWith: "’d"}, // I'd
{ searchFor: /'ll\b/g, replaceWith: "’ll"}, // you'll
{ searchFor: /'m\b/g, replaceWith: "’m"}, // I'm
{ searchFor: /'re\b/g, replaceWith: "’re"}, // you're
{ searchFor: /'s\b/g, replaceWith: "’s"}, // it's
{ searchFor: /'t\b/g, replaceWith: "’t"}, // don't
{ searchFor: /'ve\b/g, replaceWith: "’ve"}, // I've
{ searchFor: /O'R/g, replaceWith: "O’R"}, // O'Reilly
{ searchFor: /",/g, replaceWith: ',”'}, // comma outside quote mark
{ searchFor: /"\./g, replaceWith: '.”'}, // period outside quote mark (transpose only)
{ searchFor: /"\b/g, replaceWith: '“'}, // open quote (eg, precedes a 'word boundary')
{ searchFor: /\b"/g, replaceWith: '”'}, // close quote (eg, is preceded by a 'word boundary') needs to be set to follow punctuation as well
{ searchFor: / - /g, replaceWith: " — "} // em dash
];
/* store components of path */
var pathAndFile = doclistPath + doclistName + doclistExtension; // /Users/sperberx/dev/essential-javascript-links/README.md
var pathAndFileNew = doclistPath + doclistName+ doclistAddon + doclistExtension; // /Users/sperberx/dev/essential-javascript-links/README-new.md
var aFile = fs.readFile(pathAndFile, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
// for each object in the replacements array, go through the document and make the replacement
function cleanUp(someFile) {
replacements.forEach(function(replacement) {
someFile = someFile.replace(replacement.searchFor, replacement.replaceWith);
})
return someFile;
}
var result = cleanUp(data);
console.log(result);
console.log('got result back');
// fs.writeFile(pathAndFileNew, result, function (err) {
// if (err) throw err;
// console.log('It\'s saved!');
// });
});
| JavaScript | 0 | @@ -184,16 +184,19 @@
(%22fs%22);%0A
+//
var docl
@@ -261,16 +261,19 @@
misc/';%0A
+//
var docl
@@ -299,16 +299,19 @@
hort1';%0A
+//
var docl
@@ -329,16 +329,19 @@
'-new';%0A
+//
var docl
@@ -1945,16 +1945,19 @@
ath */%0A
+//
var path
@@ -2076,16 +2076,19 @@
ADME.md%0A
+//
var path
@@ -2253,27 +2253,28 @@
eadFile(
-pathAndFile
+'/dev/stdin'
, 'utf8'
@@ -2726,16 +2726,18 @@
esult);%0A
+//
cons
|
5cd9a51f7faa4b7f8d1f8cf0cd4cdafb63366929 | support null or undefined | get-constructors.js | get-constructors.js | // get-constructors.js
this.constructors = function () {
'use strict';
try {
names('Object', Object);
names('Array', Array);
names('Error', Error);
names('RegExp', RegExp);
names('String', String);
names('Number', Number);
names('Boolean', Boolean);
names('Function', Function);
names('Empty', Function.prototype);
} catch (err) {}
// names(name, fn)
function names(name, fn) {
if (fn.name !== name)
fn.name = name;
}
// getProto(obj)
var getProto = Object.getPrototypeOf ? Object.getPrototypeOf :
Object.prototype.__proto__ ?
function getProto(obj) { return obj.__proto__; } :
function getProto(obj) {
var ctor = obj.constructor;
if (typeof ctor === 'function') {
if (ctor.prototype !== obj)
return ctor.prototype;
if (typeof ctor['super'] === 'function')
return ctor['super'].prototype;
if (typeof ctor.super_ === 'function')
return ctor.super_.prototype;
}
return obj.__proto__;
};
// constructors([obj])
function constructors(obj) {
// supports: getter and normal function
if (arguments.length === 0) obj = this;
// convert to object from primitives
if (obj != null && typeof obj !== 'object' && typeof obj !== 'function')
obj = Object(obj);
if (obj === Array) return [Array, Function.prototype];
if (obj === Error) return [Error, Function.prototype];
if (obj === RegExp) return [RegExp, Function.prototype];
if (obj === Object) return [Object, Function.prototype];
if (obj === String) return [String, Function.prototype];
if (obj === Number) return [Number, Function.prototype];
if (obj === Boolean) return [Boolean, Function.prototype];
if (obj === Function) return [Function, Function.prototype];
if (obj.constructor === Array) return [Array, Object];
if (obj.constructor === Error) return [Error, Object];
if (obj.constructor === RegExp) return [RegExp, Object];
if (obj.constructor === Object) return [Object];
if (obj.constructor === String) return [String, Object];
if (obj.constructor === Number) return [Number, Object];
if (obj.constructor === Boolean) return [Boolean, Object];
var classes = [];
if (obj instanceof Function) {
// for Class/constructor
for (; obj; obj = (obj['super'] || obj.super_ || getProto(obj)))
if (typeof obj === 'function')
classes.push(obj);
if (classes.length === 0 ||
classes[classes.length - 1] !== Function.prototype)
classes.push(Function.prototype);
}
else {
var saveObj = obj;
// for instance/object
for (; obj; obj = getProto(obj)) {
if (obj.hasOwnProperty) {
if (obj.hasOwnProperty('constructor'))
classes.push(obj.constructor);
}
else if (obj.constructor) {
if (classes.length === 0 ||
classes[classes.length - 1] !== obj.constructor)
classes.push(obj.constructor);
}
}
if (classes.length === 0 &&
typeof saveObj.constructor === 'function')
classes = [saveObj.constructor];
if (classes.length === 0 ||
classes[classes.length - 1] !== Object)
classes.push(Object);
}
return classes;
}
// extendPrototype([ctor])
constructors.extendPrototype = function extendPrototype(ctor) {
ctor = ctor || Object;
if (ctor.prototype.constructors !== constructors)
ctor.prototype.constructors = constructors;
return this;
};
// defProp(obj, prop, propDesc)
var defProp = function (obj) {
if (!Object.defineProperty) return null;
try {
Object.defineProperty(obj, 'prop', {value: 'str'});
return obj.prop === 'str' ? Object.defineProperty : null;
} catch (err) { return null; }
} ({});
// defGetter(obj, prop, getter)
var defGetter = defProp ?
function defGetter(obj, prop, getter) {
return defProp(obj, prop, {get: getter}); } :
Object.prototype.__defineGetter__ ?
function defGetter(obj, prop, getter) {
return obj.__defineGetter__(prop, getter); } :
function defGetter(obj, prop, getter) {};
// fnameRegExp: function name regular expression
var fnameRegExp = /^\s*function\s*\**\s*([^\(\s]*)[\S\s]+$/im;
// Function.prototype.name for ie
if (!Function.prototype.hasOwnProperty('name'))
defGetter(Function.prototype, 'name',
function nameOfFunction() {
return ('' + this).replace(fnameRegExp, '$1') || undefined; });
constructors.constructors = constructors;
// module.exports
if (typeof module === 'object' && module.exports)
module.exports = constructors;
return constructors;
}();
| JavaScript | 0.000002 | @@ -1821,32 +1821,39 @@
pe%5D;%0A if (obj
+ && obj
.constructor ===
@@ -1887,32 +1887,39 @@
ct%5D;%0A if (obj
+ && obj
.constructor ===
@@ -1953,32 +1953,39 @@
ct%5D;%0A if (obj
+ && obj
.constructor ===
@@ -2021,32 +2021,39 @@
ct%5D;%0A if (obj
+ && obj
.constructor ===
@@ -2081,32 +2081,39 @@
ct%5D;%0A if (obj
+ && obj
.constructor ===
@@ -2149,32 +2149,39 @@
ct%5D;%0A if (obj
+ && obj
.constructor ===
@@ -2217,32 +2217,39 @@
ct%5D;%0A if (obj
+ && obj
.constructor ===
@@ -3143,16 +3143,27 @@
+ saveObj &&
typeof
|
a9429b40a209d3648b3b2a19d10456174f05a7ef | Allow for (slow) translation between languages | src/common/i18n.js | src/common/i18n.js | import sha1 from 'sha1';
import zhTw from './translations/zh_TW/i10n.json';
import de from './translations/de_DE/i10n.json';
import id from './translations/id_ID/i10n.json';
import zhCn from './translations/zh_CN/i10n.json';
import it from './translations/it_IT/i10n.json';
import vi from './translations/vi_VN/i10n.json';
import pl from './translations/pl_PL/i10n.json';
import ru from './translations/ru_RU/i10n.json';
import pt from './translations/pt_PT/i10n.json';
import es from './translations/es_ES/i10n.json';
import fr from './translations/fr_FR/i10n.json';
import en from './translations/en/i10n.json';
import ach from './translations/ach_UG/i10n.json';
export const supportedLanguages = {
zh_tw: zhTw,
de,
id,
zh_cn: zhCn,
it,
vi,
pl,
ru,
pt,
es,
fr,
en,
ach,
};
const fallbackLang = en;
let translation = {};
const t = key => (key in translation ? translation[key] : fallbackLang[key]);
export const init = lang => {
translation = supportedLanguages[lang];
};
export const translate = str => (str && t(sha1(str))) || str;
export const xml = dom => {
const categories = Array.from(dom.getElementsByTagName('category') || []);
categories.forEach(child => {
const text = child.getAttribute('i18n-text');
if (text) {
child.setAttribute('name', translate(text));
}
xml(child);
});
return dom;
};
| JavaScript | 0.000031 | @@ -1090,16 +1090,541 @@
%7C str;%0A%0A
+export const translateLangToLang = (str, fromLang, toLang) =%3E %7B%0A if (supportedLanguages%5BfromLang%5D) %7B%0A const hashIndex = Object.values(supportedLanguages%5BfromLang%5D).findIndex(translatedStr =%3E str === translatedStr);%0A if (hashIndex !== -1) %7B%0A const hash = Object.keys(supportedLanguages%5BfromLang%5D)%5BhashIndex%5D;%0A const translatedStr = supportedLanguages%5BtoLang%5D%5Bhash%5D;%0A if (translatedStr) %7B%0A return translatedStr;%0A %7D%0A %7D%0A %7D%0A return str;%0A%7D;%0A%0A
export c
|
6b2961676a206999fe15296d732b951eaaeb9cca | enhance logging on DOM querying | src/common/init.js | src/common/init.js |
/**
* Initialize the plugin and respond with a promise
*/
export function ui5Initialize(debug) {
if(debug)
jQuery.sap.log.setLevel(jQuery.sap.log.Level.DEBUG);
new Promise(resolve => sap.ui.getCore().attachInit(() => {
new sap.m.BusyIndicator().placeAt("indicator");
resolve();
}));
}
export function ui5SetTheme(name, path) {
sap.ui.getCore().applyTheme(name, path);
}
export function findUi5DialogElement(name){
return document.body.querySelector(`[ui5-dialog-id="${name}"]`);
}
export function getUi5DialogElement(name) {
try {
return document.body.querySelector(`[ui5-dialog-id="${name}"]`).au.controller.viewModel.UIElement;
}
catch (exc) {
return null;
}
} | JavaScript | 0.000001 | @@ -430,17 +430,67 @@
ame)%7B%0A
+console.log(%60querying %5Bui5-dialog-id=%22$%7Bname%7D%22%5D%60);
%0A
-
return
@@ -603,16 +603,71 @@
try %7B%0A
+ console.log(%60querying %5Bui5-dialog-id=%22$%7Bname%7D%22%5D%60);%0A
retu
@@ -765,16 +765,16 @@
nt;%0A %7D%0A
-
catch
@@ -781,16 +781,38 @@
(exc) %7B%0A
+ console.log(exc);%0A
retu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.