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
|
---|---|---|---|---|---|---|---|
4df37e4b922ffbc170a69e93647e64f22dbaa7ca
|
Correct event binding from popover-close to popover-content
|
scripts/views/popover-view.js
|
scripts/views/popover-view.js
|
/**
* Popover View Usage Example
* This is a block helper so it can be used like so:
*
* {{#view App.PopoverView title="Test Title"}}
* Hover over me.
* <div class="popover-content" style="display:none;">
* This is the contention popover content. View Id: {{view.elementId}}
* </div>
* {{/view}}
*
* You may also specify the parameter dataTrigger as being 'hover', 'click' is default:
* {{#view App.PopoverView title="Test Title" dataTrigger="hover"}}
*
*/
App.PopoverView = Ember.View.extend({
classNames: ['inline-block', 'tooltip-container', 'popover-container'],
classNameBindings: ['customId'],
tagName: 'div',
attributeBindings: ['title', 'dataTrigger:data-trigger', 'dataHtml:data-html','dataSelector:data-selector', 'dataContainer:data-container', 'dataPlacement:data-placement', 'dataContent:data-content', 'displayFlag', 'trigger', 'dataToggle:data-toggle'],
toggle: false,
dataTrigger: 'click',
popoverContent: function() {
var self = this;
var $content = $('.' + self.get('customId') + ' > ' + '.popover-content');
return $content.html();
/*
return function() {
var $content = $('#' + self.get('elementId') + ' > ' + '.popover-content');
console.log('content.html', $content.html());
return $content.html();
}
*/
}.property('customId', 'toggle'),
popoverArguments: function() {
return {
container: 'body',
html: true,
trigger: 'manual',
content: this.get('popoverContent'),
template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"> </h3> <div class="popover-close"> <button type="button" class="close">×</button> </div> <div class="popover-content"><p></p></div></div></div>'
}
}.property('popoverContent', 'customId'),
mouseEnter: function (event) {
//hide all other popovers
$(".popover").remove();
this.set('toggle', true);
$('.' + this.get('customId')).popover(this.get('popoverArguments')).popover('show');
$('.popover-close').on('click', function (e) {
$(".popover").remove();
});
$('.popover-close').on('mouseleave', function (e) {
$(".popover").remove();
});
},
reloadObserver: function(event) {
if (this.get('toggle')) {
Ember.run.scheduleOnce('afterRender', this, function() {
$('.' + this.get('customId')).popover(this.get('popoverArguments')).popover('show');
});
}
}.observes('controller.vcpus'),
init: function() {
this.set('customId', App.uuid());
var self = this;
Ember.run.schedule('afterRender', this, function() {
$('body').on('click', function (e) {
if (!$(e.target).hasClass('popover-content') && !($(e.target).parents().hasClass('popover-content')) ) {
$('.' + self.get('customId')).popover(self.get('popoverArguments')).popover('hide');
}
});
});
this._super();
}
});
|
JavaScript
| 0 |
@@ -2126,28 +2126,30 @@
('.popover-c
-lose
+ontent
').on('mouse
|
6ef0fb6d95a7dff6e89182649e294c6ebb26fa07
|
Fix cancel uploading action
|
src/apps/Syncano/Actions/Hosting.js
|
src/apps/Syncano/Actions/Hosting.js
|
import _ from 'lodash';
import bluebird from 'bluebird';
let stopUploading = false;
export default {
list() {
this.NewLibConnection
.Hosting
.please()
.list()
.ordering('desc')
.then(this.completed)
.catch(this.failure);
},
create(params) {
this.NewLibConnection
.Hosting
.please()
.create(params)
.then((createdHosting) => {
if (params.is_default) {
return this.NewLibConnection
.Hosting
.please()
.setDefault({ id: createdHosting.id })
.then(this.completed)
.catch(this.failure);
}
return this.completed(createdHosting);
})
.catch(this.failure);
},
update(id, params) {
this.NewLibConnection
.Hosting
.please()
.update({ id }, params)
.then((updatedHosting) => {
if (params.is_default) {
return this.NewLibConnection
.Hosting
.please()
.setDefault({ id: updatedHosting.id })
.then(this.completed)
.catch(this.failure);
}
return this.completed(updatedHosting);
})
.catch(this.failure);
},
remove(items) {
const promises = _.map(items, (item) => this.NewLibConnection.Hosting.please().delete({ id: item.id }));
this.Promise
.all(promises)
.then(this.completed)
.catch(this.failure);
},
cancelUploading() {
stopUploading = true;
},
uploadFiles(hostingId, files) {
const all = this.NewLibConnection.HostingFile.please().all({ hostingId }, { ordering: 'desc' });
all.on('stop', (fetchedFiles) => {
bluebird.mapSeries(files, (file, currentFileIndex) => {
const lastFileIndex = files.length - 1;
const isFinished = currentFileIndex === lastFileIndex;
const fileToUpdate = _.find(fetchedFiles, { path: file.path });
const payload = { file: this.NewLibConnection.file(file), path: file.path };
const errorCallback = ({ errors, message }) => {
this.failure(
{
isFinished,
currentFileIndex,
lastFileIndex
},
{
file,
errors,
message
}
);
};
if (stopUploading) {
if (currentFileIndex === lastFileIndex) {
stopUploading = false;
return this.completed({
isFinished: true,
isCanceled: true
});
}
return true;
}
if (fileToUpdate) {
return this.NewLibConnection
.HostingFile
.please()
.update({ id: fileToUpdate.id, hostingId }, payload)
.then(() => this.completed({
isFinished,
currentFileIndex,
lastFileIndex
}))
.catch(errorCallback);
}
return this.NewLibConnection
.HostingFile
.please()
.upload({ hostingId }, payload)
.then(() => this.completed({
isFinished,
currentFileIndex,
lastFileIndex
}))
.catch(errorCallback);
});
});
},
listFiles(hostingId) {
const data = {};
const all = this.NewLibConnection.HostingFile.please().all({ hostingId }, { ordering: 'desc' });
all.on('stop', (files) => {
data.files = files;
this.NewLibConnection
.Hosting
.please()
.get({ id: hostingId })
.then((hostingDetails) => {
data.hostingDetails = hostingDetails;
this.completed(data);
})
.catch(this.failure);
});
},
removeFiles(files, hostingId) {
const lastFileIndex = files.length - 1;
bluebird.mapSeries(files, (file, currentFileIndex) => {
const hasNextFile = files.length > currentFileIndex + 1;
return this.NewLibConnection
.HostingFile
.please()
.delete({ hostingId, id: file.id })
.then(() => this.completed({
isFinished: !hasNextFile,
currentFileIndex,
lastFileIndex
}))
.catch(this.failure);
});
},
publish(id) {
this.NewLibConnection
.Hosting
.please()
.setDefault({ id })
.then(this.completed)
.catch(this.failure);
}
};
|
JavaScript
| 0 |
@@ -1616,32 +1616,65 @@
ring: 'desc' %7D);
+%0A let cancelFileIndex = false;
%0A%0A all.on('st
@@ -2555,31 +2555,220 @@
ed: true
-%0A %7D)
+,%0A currentFileIndex: cancelFileIndex,%0A lastFileIndex: cancelFileIndex%0A %7D);%0A %7D%0A if (!cancelFileIndex) %7B%0A cancelFileIndex = currentFileIndex
;%0A
|
2004133758bce649ed09d9be8dc8fb2990e94f4a
|
Add method to send message to all channels
|
plugins/BotPlug.js
|
plugins/BotPlug.js
|
'use strict';
class BotPlug {
constructor( bot ) {
this.bot = bot;
this.aliasList = {
gustin : 'gust1n',
sälen : 'theseal',
jwilsson : 'mcgurk'
};
this.names = {};
this.setupNameDetection();
}
setupNameDetection(){
this.bot.addListener( 'names', ( channel, nicks ) => {
this.names[ channel ] = [];
for( let name in nicks ){
this.names[ channel ].push( name.toLowerCase() );
}
} );
this.bot.addListener( 'join', ( channel, nick ) => {
if( this.names[ channel ] ){
this.names[ channel ].push( nick.toLowerCase() );
}
} );
this.bot.addListener( 'quit', ( nick, reason, channels ) => {
for( let i = 0; i < channels.length; i = i + 1 ){
let channel = channels[ i ];
if( this.names[ channel ] ){
this.names[ channel ].splice( this.names[ channel ].indexOf( nick ), 1 );
}
}
} );
this.bot.addListener( 'part', ( channel, nick ) => {
if( this.names[ channel ] ){
this.names[ channel ].splice( this.names[ channel ].indexOf( nick ), 1 );
}
} );
this.bot.addListener( 'kick', ( channel, nick ) => {
if( this.names[ channel ] ){
this.names[ channel ].splice( this.names[ channel ].indexOf( nick ), 1 );
}
} );
this.bot.addListener( 'kill', ( nick, reason, channels ) => {
for( let i = 0; i < channels.length; i = i + 1 ){
let channel = channels[ i ];
if( this.names[ channel ] ){
this.names[ channel ].splice( this.names[ channel ].indexOf( nick ), 1 );
}
}
} );
this.bot.addListener( 'nick', ( oldnick, newnick, channels ) => {
for( let i = 0; i < channels.length; i = i + 1 ){
let channel = channels[ i ];
if( this.names[ channel ] ){
this.names[ channel ][ this.names[ channel ].indexOf( oldnick ) ] = newnick.toLowerCase();
}
}
} );
}
sendMessageToChannel( channel, message ) {
this.bot.say( channel, message.trim() );
}
detectMessage( callback ){
// callback gets called with nick, text, message
for( let channel in this.bot.opt.channels ){
if( this.bot.opt.channels.hasOwnProperty( channel ) ){
this.bot.addListener( 'message' + this.bot.opt.channels[ channel ], callback );
}
}
}
detectMessageToUser( callback ){
this.detectMessage( ( nick, text, message ) => {
let usersInMessage = this.checkIfMessageToUser( nick, message.args[ 0 ], text );
if( usersInMessage.length > 0 ){
callback( usersInMessage, nick, text );
}
});
}
checkIfMessageToUser( from, channel, message ){
let formattedMessage = message.toLowerCase();
let namesInMessage = [];
let formattedFrom = from.toLowerCase();
let validNamesInMessage = [];
// Add any user that might be in the channel
for( let i = 0; i < this.names[ channel ].length; i = i + 1 ){
if( formattedMessage.indexOf( this.names[ channel ][ i ] ) > -1 ){
if( namesInMessage.indexOf( this.names[ channel ][ i ] ) === -1 ){
namesInMessage.push( this.names[ channel ][ i ] );
}
}
}
// Add some aliases
for( let name in this.aliasList ){
if( formattedMessage.indexOf( name ) !== -1 ){
if( namesInMessage.indexOf( name ) === -1 ){
namesInMessage.push( this.aliasList[ name ] );
}
}
}
// Remove the sender if it's there
for( let i = 0; i < namesInMessage.length; i = i + 1 ){
if( namesInMessage[ i ] === formattedFrom ){
console.log( 'Found a message from ' + from + ' with ' + from + ' in it, skipping that user.' );
} else {
validNamesInMessage.push( namesInMessage[ i ] );
}
}
return validNamesInMessage;
}
}
module.exports = BotPlug;
|
JavaScript
| 0 |
@@ -2285,24 +2285,231 @@
%7D );%0A %7D%0A%0A
+ sendMessageToAllChannels( message )%7B%0A for( let i = 0; i %3C this.bot.opt.channels.length; i = i + 1 )%7B%0A this.sendMessageToChannel( this.bot.opt.channels%5B i %5D, message );%0A %7D%0A %7D%0A%0A
sendMess
|
9af07949e997e8f7bae3ab3b406ba78dff6737fc
|
Update a test name
|
test/unit/containers/DiscoverContainer_test.js
|
test/unit/containers/DiscoverContainer_test.js
|
import { expect } from '../../spec_helper'
import { stubJSONStore } from '../../stubs'
import { sortCategories } from '../../../src/selectors'
import {
loadCategoryPosts,
loadDiscoverPosts,
loadDiscoverUsers,
getCategories,
} from '../../../src/actions/discover'
import {
generateTabs,
getStreamAction,
shouldContainerUpdate,
} from '../../../src/containers/DiscoverContainer'
describe('DiscoverContainer', () => {
context('#getStreamAction', () => {
it('returns the correct stream action for featured and recommended', () => {
const realAction = loadCategoryPosts()
const featuredAction = getStreamAction('featured')
const recommendedAction = getStreamAction('recommended')
expect(featuredAction).to.deep.equal(realAction)
expect(recommendedAction).to.deep.equal(realAction)
})
it('returns the correct stream action for recent', () => {
const realAction = loadDiscoverPosts('recent')
const testAction = getStreamAction('recent')
expect(testAction).to.deep.equal(realAction)
})
it('returns the correct stream action for trending', () => {
const realAction = loadDiscoverUsers('trending')
const testAction = getStreamAction('trending')
expect(testAction).to.deep.equal(realAction)
})
it('returns the correct stream action for all', () => {
const realAction = getCategories()
const testAction = getStreamAction('all')
expect(testAction).to.deep.equal(realAction)
})
})
context('#generateTabs', () => {
it('returns the correct stream action for featured and recommended', () => {
const json = stubJSONStore()
const categories = json.categories
const keys = Object.keys(categories)
let primary = []
let secondary = []
let tertiary = []
keys.forEach((key) => {
const category = categories[key]
switch (category.level) {
case 'primary':
primary.push(category)
break
case 'secondary':
secondary.push(category)
break
case 'tertiary':
tertiary.push(category)
break
default:
break
}
})
primary = primary.sort(sortCategories)
secondary = secondary.sort(sortCategories)
tertiary = tertiary.sort(sortCategories)
const tabs = generateTabs(primary, secondary, tertiary)
expect(tabs[0]).to.have.property('children', 'Featured')
expect(tabs[0]).to.have.property('to', '/discover')
expect(tabs[1]).to.have.property('children', 'Trending')
expect(tabs[1]).to.have.property('to', '/discover/trending')
expect(tabs[2]).to.have.property('children', 'Recent')
expect(tabs[2]).to.have.property('to', '/discover/recent')
expect(tabs[3]).to.have.property('kind', 'divider')
expect(tabs[4]).to.have.property('children', 'Art')
expect(tabs[4]).to.have.property('to', '/discover/art')
expect(tabs[5]).to.have.property('children', 'Design')
expect(tabs[5]).to.have.property('to', '/discover/design')
expect(tabs[6]).to.have.property('children', 'Photography')
expect(tabs[6]).to.have.property('to', '/discover/photography')
expect(tabs[7]).to.have.property('children', 'Architecture')
expect(tabs[7]).to.have.property('to', '/discover/architecture')
expect(tabs[8]).to.have.property('children', 'Interviews')
expect(tabs[8]).to.have.property('to', '/discover/interviews')
expect(tabs[9]).to.have.property('children', 'Collage')
expect(tabs[9]).to.have.property('to', '/discover/collage')
})
})
context('#shouldSearchContainerUpdate', () => {
it('returns the correct stream action for discover', () => {
const thisProps = {
coverDPI: 'xhdpi',
isBeaconActive: true,
isLoggedIn: true,
location: 'location',
params: 'Params',
pageTitle: 'PageTitle',
primary: ['primary0', 'primary1', 'primary2'],
secondary: ['secondary0', 'secondary1', 'secondary2'],
tertiary: ['tertiary0', 'tertiary1', 'tertiary2'],
}
const sameProps = {
coverDPI: 'xhdpi',
isBeaconActive: true,
isLoggedIn: true,
location: 'location',
params: 'Params',
pageTitle: 'PageTitle',
primary: ['primary0', 'primary1', 'primary2'],
secondary: ['secondary0', 'secondary1', 'secondary2'],
tertiary: ['tertiary0', 'tertiary1', 'tertiary2'],
}
const nextProps = {
coverDPI: 'xhdpi',
isBeaconActive: false,
isLoggedIn: true,
location: 'location',
params: 'Params2',
pageTitle: 'PageTitle',
primary: ['primary0', 'primary1', 'primary2'],
secondary: ['secondary0', 'secondary1', 'secondary2'],
tertiary: ['tertiary0', 'tertiary1', 'tertiary2'],
}
const lastProps = {
coverDPI: 'xhdpi',
isBeaconActive: false,
isLoggedIn: true,
location: 'location',
params: 'Params2',
pageTitle: 'PageTitle',
primary: ['primary00', 'primary01', 'primary02'],
secondary: ['secondary00', 'secondary01', 'secondary02'],
tertiary: ['tertiary00', 'tertiary01', 'tertiary02'],
}
const shouldSameUpdate = shouldContainerUpdate(thisProps, sameProps)
const shouldNextUpdate = shouldContainerUpdate(thisProps, nextProps)
const shouldLastUpdate = shouldContainerUpdate(nextProps, lastProps)
expect(shouldSameUpdate).to.be.false
expect(shouldNextUpdate).to.be.true
expect(shouldLastUpdate).to.be.true
})
})
})
|
JavaScript
| 0.00009 |
@@ -3664,14 +3664,8 @@
ould
-Search
Cont
|
7dcd8fef16b38b4781a329bedbd89bd5e273983e
|
Fix tooltip position when legend displayed
|
src/assets/facette/js/chart/rect.js
|
src/assets/facette/js/chart/rect.js
|
chart.fn.drawBackgroundRect = function() {
var $$ = this;
$$.bgRect = $$.svg.append('rect')
.attr('class', 'chart-background')
.attr('width', $$.width)
.attr('height', $$.height);
};
chart.fn.drawZoomRect = function() {
var $$ = this;
if (!$$.config.zoom.enabled) {
return;
}
// Initialize zoom rectangle
$$.zoomRect = $$.areaGroup.append('rect')
.attr('class', 'chart-zoom')
.attr('width', 0)
.attr('height', $$.height - ($$.titleGroup ? $$.titleGroup.node().getBBox().height : 0) - 2 * $$.config.padding)
.style('display', 'none');
$$.zoomOrigin = null;
$$.zoomActive = false;
$$.zoomCancelled = false;
};
chart.fn.resetZoomRect = function() {
var $$ = this;
// Detach key event
d3.select(document.body).on('keydown', null);
// Reset zoom selection
$$.zoomOrigin = null;
$$.zoomActive = false;
$$.zoomCancelled = false;
$$.zoomRect
.attr('x', 0)
.attr('width', 0)
.style('display', 'none');
// Restore cursor line
$$.cursorLine.style('display', 'block');
};
chart.fn.drawEventRect = function() {
var $$ = this;
var dateBisect = d3.bisector(function(a) { return a[0] * 1000; }).left,
rectWidth = $$.areaGroup.node().getBBox().width,
rectHeight = $$.height - ($$.titleGroup ? $$.titleGroup.node().getBBox().height : 0) - 2 * $$.config.padding,
tooltipPosYStick = false,
tooltipDelta = $$.yAxisGroup.node().getBBox().width + $$.config.padding;
$$.areaGroup.append('rect')
.attr('class', 'chart-event')
.attr('fill', 'transparent')
.attr('width', rectWidth)
.attr('height', rectHeight)
.on('dragstart', function() {
d3.event.preventDefault();
d3.event.stopPropagation();
})
.on('mouseout', function() {
tooltipPosYStick = false;
// Hide tooltip and cursor line
$$.cursorLine.style('display', 'none');
$$.toggleTooltip(false);
if ($$.config.events.cursorMove) {
$$.config.events.cursorMove(null);
}
})
.on('mousedown', function() {
if ($$.config.zoom.onStart) {
$$.config.zoom.onStart();
}
// Attach key event
d3.select(document.body).on('keydown', function() {
if (d3.event.which == 27) { // <Escape>
$$.zoomCancelled = true;
$$.resetZoomRect();
}
});
// Initialize zoom selection
$$.zoomOrigin = d3.mouse(this)[0];
$$.zoomActive = true;
$$.zoomRect.style('display', 'block');
// Hide cursor line during selection
$$.cursorLine.style('display', 'none');
})
.on('mouseup', function() {
// Execute callback
if (!$$.zoomCancelled && $$.config.zoom.onSelect) {
var start = $$.xScale.invert(parseInt($$.zoomRect.attr('x'), 10)),
end = $$.xScale.invert(parseInt($$.zoomRect.attr('x'), 10) +
parseInt($$.zoomRect.attr('width'), 10));
var startTime = start.getTime(),
endTime = end.getTime();
if (!isNaN(startTime) && !isNaN(endTime) && startTime !== endTime) {
$$.config.zoom.onSelect(start, end);
}
}
$$.resetZoomRect();
})
.on('mousemove', function() {
var mouse = d3.mouse(this);
// Set cursor line position
if (!$$.tooltipEnabled) {
$$.cursorLine.style('display', 'block');
}
$$.cursorLine
.attr('x1', mouse[0])
.attr('x2', mouse[0]);
if ($$.config.events.cursorMove) {
$$.config.events.cursorMove($$.xScale.invert(mouse[0]));
}
if ($$.tooltipLocked) {
return;
}
// Set tooltip content
var data = {
date: $$.xScale.invert(mouse[0]),
values: []
};
$$.config.series.forEach(function(series, idx) {
var idxPlot = series.plots ? dateBisect(series.plots, data.date, 1) : -1;
data.values[idx] = {
name: series.name,
value: idxPlot != -1 ? series.plots[idxPlot] : null
};
});
$$.updateTooltip(data);
// Set tooltip position
var tooltipPosX = mouse[0] + tooltipDelta,
tooltipPosXKey = 'left',
tooltipPosY = tooltipPosYStick ? 0 : rectHeight + $$.config.padding - mouse[1],
tooltipPosYKey = tooltipPosYStick ? 'top' : 'bottom',
tooltipWidth = $$.tooltipGroup.node().clientWidth;
// Update zoom selection if active
if ($$.zoomActive) {
$$.zoomRect
.attr('x', Math.min($$.zoomOrigin, mouse[0]))
.attr('width', Math.abs(mouse[0] - $$.zoomOrigin));
}
// Show tooltip and cursor line
if (!$$.tooltipEnabled) {
$$.toggleTooltip(true);
}
// Update tooltip position
if (tooltipPosX + tooltipWidth > rectWidth) {
tooltipPosX = Math.abs(mouse[0] - rectWidth) + $$.config.padding;
tooltipPosXKey = 'right';
$$.tooltipGroup.style('left', null);
} else {
if ($$.yLegend) {
tooltipPosX += $$.config.padding;
}
$$.tooltipGroup.style('right', null);
}
if (!tooltipPosYStick) {
var tooltipPosYDelta = $$.tooltipGroup.node().getBoundingClientRect().top;
if (tooltipPosYDelta < 0) {
tooltipPosY = 0;
tooltipPosYKey = 'top';
tooltipPosYStick = true;
$$.tooltipGroup.style('bottom', null);
} else {
$$.tooltipGroup.style('top', null);
}
}
$$.tooltipGroup
.style(tooltipPosXKey, tooltipPosX + 'px')
.style(tooltipPosYKey, tooltipPosY + 'px');
});
};
|
JavaScript
| 0.000001 |
@@ -5001,16 +5001,156 @@
Width;%0A%0A
+ if ($$.legendGroup) %7B%0A tooltipPosY += $$.legendGroup.node().getBBox().height + $$.config.padding;%0A %7D%0A%0A
|
de9760d86f3e9bdb3bbbb03312662da3c33e75d9
|
Add invalid test using `consistent` option value
|
lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-fenced-code-marker/test/fixtures/invalid.js
|
lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-fenced-code-marker/test/fixtures/invalid.js
|
'use strict';
// VARIABLES //
var invalid;
var test;
// MAIN //
// Create our test cases:
invalid = [];
test = {
'code': [
'/**',
'* Beep boop.',
'*',
'* ~~~javascript',
'* y = x;',
'* ~~~',
'*/',
'function beep() {',
' console.log( "boop" );',
'}'
].join( '\n' ),
'errors': [
{
'message': 'Fenced code should use ` as a marker',
'type': null
}
]
};
invalid.push( test );
test = {
'code': [
'/**',
'* Beep boop.',
'*',
'* ~~~javascript',
'* y = x;',
'* ~~~',
'*/',
'function beep() {',
' console.log( "boop" );',
'}'
].join( '\n' ),
'options': [ '`' ],
'errors': [
{
'message': 'Fenced code should use ` as a marker',
'type': null
}
]
};
invalid.push( test );
test = {
'code': [
'/**',
'* Beep _boop_.',
'*',
'* ```javascript',
'* y = x;',
'* ```',
'*/',
'function beep() {',
' console.log( "boop" );',
'}'
].join( '\n' ),
'options': [ '~' ],
'errors': [
{
'message': 'Fenced code should use ~ as a marker',
'type': null
}
]
};
invalid.push( test );
// EXPORTS //
module.exports = invalid;
|
JavaScript
| 0.000012 |
@@ -1065,16 +1065,407 @@
est );%0A%0A
+test = %7B%0A%09'code': %5B%0A%09%09'/**',%0A%09%09'* Beep _boop_.',%0A%09%09'*',%0A%09%09'* ~~~javascript',%0A%09%09'* y = x;',%0A%09%09'* ~~~',%0A%09%09'*',%0A%09%09'* %60%60%60javascript',%0A%09%09'* y = x;',%0A%09%09'* %60%60%60',%0A%09%09'*/',%0A%09%09'function beep() %7B',%0A%09%09' console.log( %22boop%22 );',%0A%09%09'%7D'%0A%09%5D.join( '%5Cn' ),%0A%09'options': %5B 'consistent' %5D,%0A%09'errors': %5B%0A%09%09%7B%0A%09%09%09'message': 'Fenced code should use ~ as a marker',%0A%09%09%09'type': null%0A%09%09%7D%0A%09%5D%0A%7D;%0Ainvalid.push( test );%0A%0A
%0A// EXPO
|
b4260cfb91766b4e113254562ce5283bddb5950e
|
refactor toward next test
|
server/03-stack/stack.spec.js
|
server/03-stack/stack.spec.js
|
describe('the stack spec', () => {
it('shows the infrastructure works', () => {
true.should.be.true();
});
const makeStack = () => {
return {
isEmpty: () => true,
size: () => 0
};
};
const stack = {
isEmpty: () => true,
size: () => 0
};
describe('a stack should', () => {
it('start empty', () => {
stack.isEmpty().should.be.true();
});
it('start with stack size 0', () => {
stack.size().should.equal(0);
});
it('not be empty when pushed');
it('leave stack size 1 when pushed');
it('leave stack empty when pushed and popped');
it('leave stack size 0 when pushed and popped');
it('overflow');
it('underflow');
it('pop the same one pushed');
it('pop the same two pushed');
it('accept only positive capacity');
});
}
);
|
JavaScript
| 0.000001 |
@@ -212,20 +212,18 @@
%7D;%0A%0A
-cons
+le
t stack
|
943204dc50393bb22a5cabad088c6abdf0e28d55
|
Fix object is not a function error in omxviewer
|
server/configure-socket-io.js
|
server/configure-socket-io.js
|
var socketio = require('socket.io');
function configureSocketIo(server, repo) {
var io = socketio.listen(server);
// If this is a raspberry pi viewer.
var viewerMode = process.argv[2] ? process.argv[2].toLowerCase() : 'none';
if(viewerMode === 'omx' || viewerMode == '-omx') {
console.log('omxplayer viewer enabled');
var omxViewer = require('./omx-viewer')();
}
io.on('connection', function(socket) {
console.log('connection made');
socket.on('disconnect', function() {
console.log('user disconnected');
});
socket.on('select video', function(args) {
console.log('select video');
console.log(args);
//socket.broadcast.emit('select video');
var videoDetails = repo.loadVideoDetails(args.videoId);
socket.broadcast.emit('video selected', videoDetails);
if(omxViewer) {
omxViewer.videoSelected(videoDetails);
socket.broadcast.emit('video playing');
}
console.log('video selected');
});
socket.on('play video', function(args) {
console.log('play video');
socket.broadcast.emit('play video');
if(omxViewer) {
omxViewer.play(args);
socket.broadcast.emit('video playing');
}
});
socket.on('video playing', function(args) {
console.log('video playing');
socket.broadcast.emit('video playing');
});
socket.on('pause video', function(args) {
console.log('pause video');
socket.broadcast.emit('pause video');
if(omxViewer) {
omxViewer.pause(args);
socket.broadcast.emit('video paused');
}
});
socket.on('video paused', function(args) {
console.log('video paused');
socket.broadcast.emit('video paused');
});
socket.on('stop video', function(args) {
console.log('stop video');
socket.broadcast.emit('stop video');
if(omxViewer) {
omxViewer.stop(args);
socket.broadcast.emit('video stopped');
}
});
socket.on('video stopped', function(args) {
console.log('video stopped');
socket.broadcast.emit('video stopped');
});
socket.on('seek video', function(args) {
console.log('seek video');
console.log(args);
socket.broadcast.emit('seek video', args);
if(omxViewer) {
omxViewer.seek(args);
socket.broadcast.emit('video seeked');
}
});
socket.on('video seeked', function(args) {
console.log('video seeked');
socket.broadcast.emit('video seeked');
});
socket.on('jump video', function(args) {
console.log('jump video');
console.log(args);
socket.broadcast.emit('jump video', args);
if(omxViewer) {
omxViewer.jump(args);
socket.broadcast.emit('video jumped');
}
});
socket.on('video jumped', function(args) {
console.log('video jumped');
socket.broadcast.emit('video jumped');
});
});
}
module.exports = configureSocketIo;
|
JavaScript
| 0.000395 |
@@ -384,18 +384,16 @@
viewer')
-()
;%0A %7D%0A
|
04b638a893952ff7d818b7913904132b21b768d5
|
Fix error
|
apps/marketplace/index.js
|
apps/marketplace/index.js
|
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import Banner from 'shared/Banner/Banner'
import Header from './components/Header/Header'
import AUFooter from './components/Footer/AUFooter'
import configureStore from './store'
import RootContainer from './routes'
import { fetchAuth } from './actions/appActions'
import './main.scss'
const store = configureStore()
store.dispatch(fetchAuth())
const App = () => (
<Provider store={store}>
<BrowserRouter>
<div id="Application">
<header role="banner">
<Banner />
<Header />
</header>
<main id="content" role="region" aria-live="polite">
<div className="container">
<div className="row">
<div className="col-xs-12">
<RootContainer />
</div>
</div>
</div>
</main>
<AUFooter />
</div>
</BrowserRouter>
</Provider>
)
ReactDOM.render(<App />, document.getElementById('root'))
|
JavaScript
| 0.000004 |
@@ -222,23 +222,16 @@
s/Header
-/Header
'%0Aimport
|
e901a01be1c46ca4a207a07f0132911c9e9acd42
|
Fix react-tap-event-plugin issue
|
src/client/entryPoint/app-client.js
|
src/client/entryPoint/app-client.js
|
'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import AppRoutes from '../components/AppRoutes';
import 'jquery';
// var injectTapEventPlugin = require('react-tap-event-plugin');
import './less/style.less';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
// injectTapEventPlugin();
//Needed for React Developer Tools
window.React = React;
window.onload = () => {
ReactDOM.render(<AppRoutes/>, document.getElementById('main'));
};
|
JavaScript
| 0.000015 |
@@ -140,14 +140,14 @@
';%0A%0A
-// var
+import
inj
@@ -168,18 +168,13 @@
gin
-= require(
+from
'rea
@@ -193,17 +193,16 @@
-plugin'
-)
;%0A%0Aimpor
@@ -296,19 +296,16 @@
/988941%0A
-//
injectTa
|
a98445143d6e1c67a1cb9e2c9a4be2740fa7e325
|
remove more actionTypes for comment
|
src/comments/commentsActionTypes.js
|
src/comments/commentsActionTypes.js
|
export const GET_COMMENTS = 'GET_COMMENTS';
export const GET_COMMENTS_START = 'GET_COMMENTS_START';
export const GET_COMMENTS_SUCCESS = 'GET_COMMENTS_SUCCESS';
export const GET_COMMENTS_ERROR = 'GET_COMMENTS_ERROR';
export const GET_MORE_COMMENTS = 'GET_MORE_COMMENTS';
export const GET_MORE_COMMENTS_START = 'GET_MORE_COMMENTS_START';
export const GET_MORE_COMMENTS_SUCCESS = 'GET_MORE_COMMENTS_SUCCESS';
export const GET_MORE_COMMENTS_ERROR = 'GET_MORE_COMMENTS_ERROR';
export const SHOW_MORE_COMMENTS = 'SHOW_MORE_COMMENTS';
export const SEND_COMMENT = 'SEND_COMMENT';
export const SEND_COMMENT_START = 'SEND_COMMENT_START';
export const SEND_COMMENT_SUCCESS = 'SEND_COMMENT_SUCCESS';
export const SEND_COMMENT_ERROR = 'SEND_COMMENT_ERROR';
export const OPEN_COMMENTING_DRAFT = 'OPEN_COMMENTING_DRAFT';
export const UPDATE_COMMENTING_DRAFT = 'UPDATE_COMMENTING_DRAFT';
export const CLOSE_COMMENTING_DRAFT = 'CLOSE_COMMENTING_DRAFT';
|
JavaScript
| 0 |
@@ -214,265 +214,8 @@
';%0A%0A
-export const GET_MORE_COMMENTS = 'GET_MORE_COMMENTS';%0Aexport const GET_MORE_COMMENTS_START = 'GET_MORE_COMMENTS_START';%0Aexport const GET_MORE_COMMENTS_SUCCESS = 'GET_MORE_COMMENTS_SUCCESS';%0Aexport const GET_MORE_COMMENTS_ERROR = 'GET_MORE_COMMENTS_ERROR';%0A%0A
expo
|
5dba978146c2e9d9dc911277305ae42537b6791b
|
Fix missing slash in Navigation, breaking the page when clicked.
|
src/common/components/Navigation.js
|
src/common/components/Navigation.js
|
import React from 'react';
import Relay from 'react-relay';
import ActionLockOpen from 'material-ui/svg-icons/action/lock-open';
import Avatar from 'material-ui/Avatar';
import { Menu, MenuItem } from 'material-ui/Menu';
import IconButton from 'material-ui/IconButton';
import Popover from 'material-ui/Popover';
import NavigationMenu from 'material-ui/svg-icons/navigation/menu';
import RaisedButton from 'material-ui/RaisedButton';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import { fullWhite, lightBlue900 } from 'material-ui/styles/colors';
import { Link } from 'react-router';
import theme from '../theme';
class Navigation extends React.Component {
static propTypes = {
viewer: React.PropTypes.object,
organization: React.PropTypes.object,
//socket: React.PropTypes.object,
}
static childContextTypes = {
muiTheme: React.PropTypes.object.isRequired,
};
state = {
open: false,
}
getChildContext() {
return { muiTheme: getMuiTheme(theme) };
}
handleOpen = (event) => {
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget,
});
}
handleClose = () => {
this.setState({
open: false,
});
}
render() {
const viewer = this.props.viewer;
const org = this.props.organization;
const isMember = org.isMember;
const logo = (
<Link
to="/"
onClick={this.handleClose}
style={{
padding: '19px 10px 20px 9px',
}}
>
<img
src="/img/logo.wh.svg"
alt="Nidarholm-logo"
style={{
height: 70,
width: 196,
paddingTop: 4,
marginBottom: -16,
}}
/>
</Link>
);
return (
<div style={{ backgroundColor: lightBlue900 }}>
<div className="flex-menu-desktop">
<nav
className="flex-menu"
style={{
display: 'flex',
flexWrap: 'wrap',
minWidth: 300,
width: '100%',
justifyContent: 'space-between',
}}
>
<div style={{ flexBasis: 'auto' }}>
{logo}
</div>
<div
style={{
display: 'flex',
flexWrap: 'wrap',
flexGrow: 1,
justifyContent: 'flex-start',
alignItems: 'center',
}}
>
<Link to="/om" style={{ color: 'white' }}>
Om oss
</Link>
<Link to="/projects" style={{ color: 'white' }}>
Konserter
</Link>
<Link to="/members" style={{ color: 'white' }}>
Medlemmer
</Link>
<Link to="/stott-oss" style={{ color: 'white' }}>
Støtt oss
</Link>
</div>
<div
style={{
display: 'flex',
flexWrap: 'wrap',
flexGrow: 1,
justifyContent: 'flex-end',
alignItems: 'center',
}}
>
{isMember
? <Link to="/files">Filer</Link>
: null
}
{isMember
? <Link to="/pages">Sider</Link>
: null
}
{isMember
? <Link to="/events">Aktiviteter</Link>
: null
}
{isMember
? <Link to="/music">Notearkiv</Link>
: null
}
{viewer
? <Link
to={`/users/${viewer.id}`}
style={{
display: 'flex',
alignItems: 'center',
margin: '-5px 0',
color: 'white',
}}
>
<Avatar
src={viewer.profilePicturePath}
style={{ margin: '0 5px' }}
/>
<span>{viewer.name}</span>
</Link>
: <Link
to="/login"
style={{
padding: 0,
margin: '12px 15px 12px 10px',
}}
>
<RaisedButton
label="Logg inn"
icon={<ActionLockOpen />}
/>
</Link>
}
</div>
</nav>
</div>
<div className="flex-menu-mobile">
<div style={{ flexGrow: 1 }}>
{logo}
</div>
<div>
{this.props.viewer ? <Link to={`/users/${viewer.id}`}>
<Avatar
src={viewer.profilePicturePath}
/>
</Link>
: <Link to="/login">
<RaisedButton
style={{ minWidth: 44, marginLeft: 10 }}
icon={<ActionLockOpen />}
/>
</Link>
}
</div>
<div>
<IconButton
className="flex-menu-handler"
onClick={this.handleOpen}
touch
>
<NavigationMenu color={fullWhite} />
</IconButton>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
targetOrigin={{ horizontal: 'right', vertical: 'top' }}
onRequestClose={this.handleClose}
>
<nav
className="flex-menu"
style={{
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-around',
width: '100%',
backgroundColor: lightBlue900,
}}
>
<Menu>
<MenuItem>
<Link
to="about"
onClick={this.handleClose}
>
Om oss
</Link>
</MenuItem>
<MenuItem>
<Link
to="/projects"
onClick={this.handleClose}
>
Konserter
</Link>
</MenuItem>
<MenuItem>
<Link
to="/members"
onClick={this.handleClose}
>
Medlemmer
</Link>
</MenuItem>
<MenuItem>
<Link
to="/stott-oss"
onClick={this.handleClose}
>
Støtt oss
</Link>
</MenuItem>
</Menu>
{isMember
? <Menu>
{isMember
? <MenuItem>
<Link to="/files" onClick={this.handleClose}>
Filer
</Link>
</MenuItem>
: null
}
{isMember
? <MenuItem>
<Link to="/pages" onClick={this.handleClose}>
Sider
</Link>
</MenuItem>
: null
}
{isMember
? <MenuItem>
<Link to="/events" onClick={this.handleClose}>
Aktiviteter
</Link>
</MenuItem>
: null
}
{isMember
? <MenuItem>
<Link to="/music" onClick={this.handleClose}>
Notearkiv
</Link>
</MenuItem>
: null
}
</Menu>
: null
}
</nav>
</Popover>
</div>
</div>
</div>
);
}
}
export default Relay.createContainer(Navigation, {
fragments: {
organization: () => Relay.QL`
fragment on Organization {
id
isMember,
}`,
viewer: () => Relay.QL`
fragment on User {
id,
name,
profilePicturePath,
}`,
},
});
|
JavaScript
| 0 |
@@ -8491,16 +8491,17 @@
to=%22
+/
about%22%0A
|
6cb4b3cad60ee232a1eaa4df760f120e43765e79
|
Improve padding of donation form
|
src/components/donate/DonateForm.js
|
src/components/donate/DonateForm.js
|
import React, { Component } from 'react'
import {
Box,
LargeButton,
Button,
Flex,
Heading,
Icon,
Input,
Label,
Text
} from '@hackclub/design-system'
import { CLIENT_URL, PUBLIC_STRIPE_KEY } from 'constants'
import { toNumber } from 'lodash'
import api from 'api'
const Secure = Flex.extend`
position: absolute;
top: 0;
right: 0;
align-items: center;
justify-content: flex-end;
text-align: right;
`
const amounts = [10, 20, 40, 100]
const AmountsGrid = Box.extend`
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: ${({ theme }) => theme.space[3]}px;
input[type='radio'] {
display: none;
&:checked + label {
background-color: ${({ theme }) => theme.colors.blue[7]} !important;
}
}
input[type='number'] {
text-align: center;
border-radius: ${({ theme }) => theme.pill};
grid-column: 2 / span 2;
}
`
const Amount = Button.withComponent('label').extend`
border-radius: ${({ theme }) => theme.pill};
`
const Option = ({ amount, ...props }) => [
<input
type="radio"
id={`amount[${amount}]`}
name="amount"
value={amount}
key={`input[${amount}]`}
{...props}
/>,
<Amount bg="info" htmlFor={`amount[${amount}]`} key={`label[${amount}]`}>
<Text.span>${amount}</Text.span>
</Amount>
]
const Other = Input.extend`
color: ${({ theme }) => theme.colors.black};
::placeholder {
color: ${({ theme }) => theme.colors.muted};
}
`
class DonateForm extends Component {
state = {
loading: true,
stripeLoading: true,
amount: 20,
recurring: true
}
componentWillUnmount() {
if (this.stripeHandler) {
this.stripeHandler.close()
}
}
render() {
const { custom, recurring, amount } = this.state
return (
<Box align="center" style={{ position: 'relative' }}>
<Box bg="primary" color="white" mx={[-3, -4]} pb={3} mb={3}>
<Secure p={2} mr={[-3, -4]}>
<Text f={0} color="red.1" caps bold>
Secure
</Text>
<Icon size={16} name="lock" color="red.1" ml={2} />
</Secure>
<Heading.h2 mt={[-3, -4]} pt={3} px={3} f={5}>
Become a patron
</Heading.h2>
<Text color="snow" mt={1} f={1}>
Just $3 supports a student for a month
</Text>
</Box>
<Flex align="center" justify="center" color="black">
<Text f={3} bold>
Select an amount
</Text>
<Text.span mx={2} children="—" />
<Label>
<input
name="recurring"
type="checkbox"
style={{
WebkitAppearance: 'checkbox',
MozAppearance: 'checkbox',
appearance: 'checkbox'
}}
checked={recurring}
onChange={this.handleRecurringChange}
/>
<Text.span f={2} ml={1}>
monthly?
</Text.span>
</Label>
</Flex>
<AmountsGrid w={1} mt={3} mb={4}>
{amounts.map(amount => (
<Option
amount={amount}
onChange={e => this.handleAmountChange(amount)}
key={amount}
/>
))}
<Other
type="number"
placeholder="Other"
onChange={e => this.handleAmountChange(e.target.value)}
/>
</AmountsGrid>
<Text color="slate" mb={3} f={1}>
Our recommended donation is $20/month
</Text>
<LargeButton
onClick={e => this.startStripe(e)}
children={this.buttonText()}
w={1}
/>
</Box>
)
}
loadStripe = onload => {
if (!window.StripeCheckout) {
const script = document.createElement('script')
script.onload = () => {
onload()
}
script.src = 'https://checkout.stripe.com/checkout.js'
document.head.appendChild(script)
} else {
onload()
}
}
startStripe = e => {
this.loadStripe(() => {
this.stripeHandler = window.StripeCheckout.configure({
key: PUBLIC_STRIPE_KEY,
image: `${CLIENT_URL}/twitter-avatar.png`,
locale: 'auto',
amount: this.amountInCents(),
token: this.handleToken
})
this.setState({
stripeLoading: false,
// loading needs to be explicitly set false so component will render in 'loaded' state.
loading: false
})
this.onStripeUpdate(e)
})
}
onStripeUpdate = e => {
this.stripeHandler.open({
name: 'Hack Club',
description: this.state.recurring
? 'Monthly contribution to Hack Club'
: 'One-time contribution to Hack Club',
panelLabel: 'Donate',
allowRememberMe: false
})
e.preventDefault()
}
handleToken = token => {
this.setState({ loading: true })
const data = new FormData()
data.append('stripe_email', token.email)
data.append('stripe_token', token.id)
data.append('recurring', this.state.recurring)
data.append('amount', this.amountInCents())
this.setState({ status: 'loading' })
api
.post('v1/donations', { data })
.then(data => {
if (data.donation_successful) {
this.setState({ status: 'done' })
} else {
this.setState({ status: 'error' })
}
})
.catch(() => {
this.setState({ status: 'error' })
})
}
handleAmountChange = a => {
const amount = toNumber(a || 1)
this.setState({ amount })
}
handleRecurringChange = v => {
this.setState({ recurring: v.target.checked })
}
buttonText() {
switch (this.state.status) {
case 'done':
return 'Thank you 😊'
case 'loading':
return 'One moment…'
case 'error':
return 'Something went wrong!'
default:
const msg = `Donate $${this.state.amount}`
return this.state.recurring ? `${msg} a month` : msg
}
}
setAmount = amount => v => {
this.setState({ amount, custom: false })
}
amountInCents = () => this.state.amount * 100
}
export default DonateForm
|
JavaScript
| 0 |
@@ -1879,17 +1879,17 @@
4%5D%7D pb=%7B
-3
+4
%7D mb=%7B3%7D
@@ -2143,17 +2143,17 @@
4%5D%7D pt=%7B
-3
+4
%7D px=%7B3%7D
|
69158a8cc7b2deb536c808b180bfa75276d184c7
|
change responsiveness level for finances
|
src/components/finances/finances.js
|
src/components/finances/finances.js
|
import React, { Component } from 'react'
import Bills from './bills'
import Payments from './payments'
import FinanceNavmenu from './finance_navmenu'
class Finances extends Component {
render() {
return (
<article className="finances col-sm-9">
<FinanceNavmenu />
{this.props.children}
</article>
)
}
}
export default Finances
|
JavaScript
| 0 |
@@ -249,10 +249,10 @@
col-
-s
m
+d
-9%22%3E
|
f9f9c093b4f8ea784ec2657f9222e1b582461a78
|
comment cleanup
|
src/components/form/SubmitButton.js
|
src/components/form/SubmitButton.js
|
// dependencies
//
import React from 'react';
import classnames from 'classnames';
// @TODO a generic button which is not wired into the form `isValid` state
/**
* The SubmitButton component
* @param {String} children The label to display in the button
* @param {String} style The style with which to display the button
* @param {Function} onClick The `onClick` handler for the button
* @param {Boolean} isValid A flag indicating whether the form to which this
* button is attached is valid
* @return {React.Element} The React element describing this component
*/
const SubmitButton = ({ children, style, onClick }, { isValid }) => (
<button
className={classnames('btn', {
'btn-danger': style === 'danger' || style === 'error',
'btn-warning': style === 'warning' || style === 'warn',
'btn-info': style === 'info',
'btn-success': style === 'success' || style === 'ok',
'btn-default': !style,
})}
disabled={!isValid}
onClick={onClick}
>
{children || 'Submit'}
</button>
);
// define the property types for the component
//
SubmitButton.propTypes = {
style: React.PropTypes.string,
onClick: React.PropTypes.func,
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.node),
React.PropTypes.node,
]),
};
// define the context types for values received from higher up the food chain
//
SubmitButton.contextTypes = {
isValid: React.PropTypes.bool,
};
// export the component
//
export default SubmitButton;
|
JavaScript
| 0 |
@@ -436,18 +436,81 @@
lag
-indicating
+(from the parent Form's context) indicating%0A *
whe
@@ -536,21 +536,38 @@
ich this
+ button is attached
%0A *
-
@@ -584,34 +584,17 @@
-button is attached
+
is vali
|
0451123acb987f53bfaaa6719881a404519fc7f9
|
comment cleanup
|
src/components/form/SubmitButton.js
|
src/components/form/SubmitButton.js
|
// npm dependencies
//
import React from 'react';
import classnames from 'classnames';
/**
* The SubmitButton component
* @param {String} children The label to display in the button
* @param {String} name The name for the component
* @param {String} style The style with which to display the button
* @param {Function} onClick The `onClick` handler for the button
* @param {Boolean} isValid A flag (from the parent Form's context) indicating
* whether the form to which this button is attached
* is valid
* @return {React.Element} The React element describing this component
*/
class SubmitButton extends React.Component {
constructor(props) {
super(props);
this.state = {
disabled: props.disabled,
};
}
componentWillReceiveProps(newProps) {
if (this.state.disabled !== !!newProps.disabled) {
this.setState({ disabled: !!newProps.disabled });
}
}
render() {
return (
<button
name={this.props.name}
className={classnames('btn', {
'btn-danger': this.props.style === 'danger' || this.props.style === 'error',
'btn-warning': this.props.style === 'warning' || this.props.style === 'warn',
'btn-info': this.props.style === 'info',
'btn-success': this.props.style === 'success' || this.props.style === 'ok',
'btn-default': !this.props.style,
})}
disabled={!this.context.isValid || !!this.state.disabled}
onClick={this.props.onClick}
>
{this.props.children || 'Submit'}
</button>
);
}
}
// define the property types for the component
//
SubmitButton.propTypes = {
/** A flag indicated whether this button is disabled */
disabled: React.PropTypes.boolean,
/** The name for the component */
name: React.PropTypes.string,
/** The style with which to display the button */
style: React.PropTypes.oneOf(
['danger', 'error', 'warning', 'warn', 'info', 'success', 'ok']
),
/** The `onClick` handler for the button */
onClick: React.PropTypes.func,
/** The child(ren) of this component */
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.node),
React.PropTypes.node,
]),
};
// define the context types for values received from higher up the food chain
//
SubmitButton.contextTypes = {
isValid: React.PropTypes.bool,
};
// export the component
//
export default SubmitButton;
|
JavaScript
| 0 |
@@ -712,172 +712,558 @@
-constructor(props) %7B%0A super(props);%0A%0A this.state = %7B%0A disabled: props.disabled,%0A %7D;%0A %7D%0A%0A componentWillReceiveProps(newProps) %7B
+/**%0A * Construct the SubmitButton instance%0A * @param %7BObject%7D props The component properties%0A */%0A constructor(props) %7B%0A super(props);%0A%0A // initialize the component state%0A //%0A this.state = %7B%0A disabled: props.disabled,%0A %7D;%0A %7D%0A%0A /**%0A * Handle new props for the component%0A * @param %7BObject%7D newProps The new property values%0A */%0A componentWillReceiveProps(newProps) %7B%0A // has the disabled flag state changed? if so, update the component%0A // state%0A //
%0A
@@ -1393,24 +1393,119 @@
%7D%0A %7D%0A%0A
+ /**%0A * Render the component%0A * @return %7BReact.Element%7D The React component%0A */%0A
render()
|
85fd8fd6bb679d9499f4b77859e7e0ffa68bcb4d
|
Switch x axis to minute
|
src/components/pres/Moisture/Day.js
|
src/components/pres/Moisture/Day.js
|
import React from 'react';
import { Line } from 'react-chartjs-2';
export default function Day({ days }) {
const items = days.day || [];
if (days.loading) {
return (
<p>Loading...</p>
);
}
const data = {
labels: items.map((d) => d.date, []),
datasets: [{
label: 'Moisture',
fill: true,
data: items.map((d) => d.moisture, []),
}],
};
return (
<div className="widget">
<div className="widget-body">
<Line data={data} />
</div>
</div>
);
}
|
JavaScript
| 0.000001 |
@@ -384,16 +384,111 @@
,%0A %7D;%0A%0A
+ const options = %7B%0A scales: %7B%0A xAxes: %5B%7B%0A type: 'time',%0A %7D%5D,%0A %7D,%0A %7D;%0A%0A
return
@@ -580,16 +580,34 @@
a=%7Bdata%7D
+ options=%7Boptions%7D
/%3E%0A
|
48563d681904294c2c8e3d0e90b5853bc69917d9
|
Use site-wide page styling
|
src/components/user/user-profile.js
|
src/components/user/user-profile.js
|
import React from 'react';
import { Paper, AppBar, Tabs, Tab } from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles';
import { user } from '@openchemistry/girder-ui';
const StyledTabs = withStyles({
indicator: {
display: 'flex',
justifyContent: 'center',
backgroundColor: 'transparent',
'& > div': {
width: '100%',
backgroundColor: '#ffffff',
},
},
})(props => <Tabs {...props} TabIndicatorProps={{ children: <div /> }} />);
export default function UserProfile() {
const [value, setValue] = React.useState(0);
let scopeOptions = ['read', 'write'];
function handleChange(event, newValue) {
setValue(newValue);
}
return (
<Paper style={{margin:'10px'}}>
<AppBar position="static">
<StyledTabs value={value} onChange={handleChange}>
<Tab label='Profile' />
<Tab label='API Keys' />
</StyledTabs>
</AppBar>
<div hidden={value !== 0}>
<user.BasicInfo />
</div>
<div hidden={value !== 1}>
<user.ApiKeys scopeOptions={scopeOptions}/>
</div>
</Paper>
);
}
|
JavaScript
| 0 |
@@ -53,16 +53,28 @@
abs, Tab
+, Typography
%7D from
@@ -150,16 +150,91 @@
yles';%0A%0A
+import PageHead from '../page-head';%0Aimport PageBody from '../page-body';%0A%0A
import %7B
@@ -275,17 +275,16 @@
r-ui';%0A%0A
-%0A
const St
@@ -790,52 +790,340 @@
%3C
-Paper style=%7B%7Bmargin:'10px'%7D%7D%3E%0A %3CAppBar
+div%3E%0A %3CPageHead%3E%0A %3CTypography color=%22inherit%22 gutterBottom variant=%22display1%22%3E%0A User Settings%0A %3C/Typography%3E%0A %3CTypography variant=%22subheading%22 paragraph color=%22inherit%22%3E%0A %3C/Typography%3E%0A %3C/PageHead%3E%0A %3CPageBody%3E%0A %3CPaper%3E%0A %3CAppBar style=%7B%7BbackgroundColor:%22#37474F%22%7D%7D
pos
@@ -1138,16 +1138,20 @@
tatic%22%3E%0A
+
@@ -1203,32 +1203,36 @@
nge%7D%3E%0A
+
+
%3CTab label='Prof
@@ -1241,32 +1241,36 @@
e' /%3E%0A
+
+
%3CTab label='API
@@ -1286,16 +1286,20 @@
+
%3C/Styled
@@ -1310,16 +1310,20 @@
%3E%0A
+
+
%3C/AppBar
@@ -1324,16 +1324,20 @@
AppBar%3E%0A
+
%3Cd
@@ -1365,24 +1365,28 @@
0%7D%3E%0A
+
%3Cuser.BasicI
@@ -1394,31 +1394,39 @@
fo /%3E%0A
+
+
%3C/div%3E%0A
+
%3Cdiv h
@@ -1446,16 +1446,20 @@
!== 1%7D%3E%0A
+
@@ -1504,24 +1504,28 @@
ns%7D/%3E%0A
+
+
%3C/div%3E%0A %3C
@@ -1519,24 +1519,28 @@
%3C/div%3E%0A
+
+
%3C/Paper%3E%0A )
@@ -1540,10 +1540,40 @@
er%3E%0A
+ %3C/PageBody%3E%0A %3C/div%3E%0A
);%0A%7D
+%0A
|
93d9f3b8f18a4c3e20c86f17ca40acf6540b495f
|
use angular window to redirect
|
src/controllers/certificate-edit.js
|
src/controllers/certificate-edit.js
|
/* global app:true */
((angular, app) => { 'use strict';
const controller = 'CertificateEditController';
if (typeof app === 'undefined') throw (controller + ': app is undefined');
app.controller(controller, ['$scope', '$routeParams', 'ajax', 'viewFactory', 'toast',
function ($scope, $routeParams, ajax, viewFactory, toast) {
$scope.certId = $routeParams.certificateId;
$scope.formInput = {};
$scope.sniList = [];
viewFactory.title = 'Edit Certificate';
ajax.get({ resource: '/certificates/' + $scope.certId }).then(function (response) {
$scope.formInput.certificate = response.data.cert;
$scope.formInput.privateKey = response.data.key;
$scope.sniList = (typeof response.data.snis === 'object'
&& Array.isArray(response.data.snis)) ? response.data.snis : [];
viewFactory.deleteAction = {target: 'Certificate', url: '/certificates/' + $scope.certId, redirect: '#!/certificates'};
}, function (response) {
toast.error('Could not load certificate details');
if (response && response.status === 404) window.location.href = '#!/certificates';
});
var formEdit = angular.element('form#formEdit');
var formSNIs = angular.element('form#formSNIs');
formEdit.on('submit', (event) => {
event.preventDefault();
var payload = {};
if ($scope.formInput.certificate.trim().length > 10) {
payload.cert = $scope.formInput.certificate;
} else {
formEdit.find('textarea[name="certificate"]').focus();
return false;
}
if ($scope.formInput.privateKey.trim().length > 10) {
payload.key = $scope.formInput.privateKey;
} else {
formEdit.find('textarea[name="privateKey"]').focus();
return false;
}
ajax.patch({
resource: '/certificates/' + $scope.certId,
data: payload
}).then(() => {
toast.success('Certificate updated');
}, (response) => {
toast.error(response.data);
});
return false;
});
formSNIs.on('submit', (event) => {
event.preventDefault();
let hostInput = formSNIs.children('div.hpadding-10.pad-top-10').children('input[name="host"]');
let payload = {};
if (hostInput.val().trim().length <= 0) {
return false;
}
payload.name = hostInput.val();
payload.ssl_certificate_id = $scope.certId;
ajax.post({
resource: '/snis/',
data: payload
}).then(function () {
toast.success('New host name added');
$scope.sniList.push(hostInput.val());
hostInput.val('');
}, function (response) {
toast.error(response.data);
});
});
angular.element('span#btnAddSNI').on('click', function () {
formSNIs.slideToggle(300);
});
}]);
})(window.angular, app);
|
JavaScript
| 0.000001 |
@@ -16,16 +16,25 @@
rue */%0A(
+function
(angular
@@ -39,19 +39,16 @@
ar, app)
- =%3E
%7B 'use
@@ -109,17 +109,16 @@
oller';%0A
-%0A
if (
@@ -221,16 +221,27 @@
oller, %5B
+'$window',
'$scope'
@@ -308,16 +308,25 @@
nction (
+$window,
$scope,
@@ -368,16 +368,65 @@
ast) %7B%0A%0A
+ viewFactory.title = 'Edit Certificate';%0A%0A
@@ -534,57 +534,8 @@
%5D;%0A%0A
- viewFactory.title = 'Edit Certificate';%0A%0A
@@ -938,16 +938,33 @@
tion = %7B
+%0A
target:
@@ -977,16 +977,32 @@
ficate',
+%0A
url: '/
@@ -1032,16 +1032,32 @@
.certId,
+%0A
redirec
@@ -1076,16 +1076,29 @@
ficates'
+%0A
%7D;%0A%0A
@@ -1110,32 +1110,24 @@
, function (
-response
) %7B%0A
@@ -1177,25 +1177,24 @@
details');%0A
-%0A
@@ -1197,49 +1197,9 @@
-if (response && response.status === 404)
+$
wind
@@ -1253,27 +1253,27 @@
);%0A%0A
-var
+let
formEdit =
@@ -1308,21 +1308,9 @@
it')
-;%0A var
+,
for
@@ -1377,32 +1377,41 @@
on('submit',
+ function
(event)
=%3E %7B%0A
@@ -1390,35 +1390,32 @@
function (event)
- =%3E
%7B%0A e
@@ -1454,11 +1454,11 @@
-var
+let
pay
@@ -2136,13 +2136,18 @@
hen(
-() =%3E
+function()
%7B%0A
@@ -2214,16 +2214,25 @@
%7D,
+ function
(respon
@@ -2234,19 +2234,16 @@
esponse)
- =%3E
%7B%0A
@@ -2366,24 +2366,33 @@
submit',
+ function
(event)
=%3E %7B%0A
@@ -2387,11 +2387,8 @@
ent)
- =%3E
%7B%0A
|
e1976ec748999aa0d48f5ac456902e906e8a5051
|
Prevent 0-length phrases
|
yipsum.js
|
yipsum.js
|
var sourceWords = [
// Variations on fur
'fur',
'furry',
'furre',
'furries',
// Conventions
'con',
'convention',
'anthrocon',
'AC',
'Further Confusion',
'FC',
'Midwest Fur Fest',
'MFF',
// Fursuiting
'fursuit',
'suiter',
'headless',
'ruining the magic',
// Various
'popufur',
'feesh',
// Art
'commission',
'stream',
'sketch',
'sketch stream',
'icon',
// Chat
'furnet',
'anthrochat',
'FurryMUCK',
'SPR',
'taps',
'tapestries',
'furcadia',
// Websites
'furnation',
'Yerf!',
'VCL',
'FA',
'FurAffinity',
'SoFurry',
'Weasyl',
'InkBunny',
'Wikifur',
// Species
'sergal',
'fox',
'wolf',
'husky',
'cat',
// Noises
'yap',
'yip',
'bark',
'mew',
'meow',
'growl',
'murr',
// Verbs
'wiggle',
'scritch',
'pet',
];
$(document).ready(function() {
result = '';
_(5).times(function(paragraph) {
result += '<p>';
_(7).times(function(sentence) {
_(Math.floor((Math.random() * 10) / 3) + 1).times(function(phrase) {
_(Math.floor(Math.random() * 10)).times(function(word) {
sourceWord = _.sample(sourceWords);
if (phrase === 0 && word === 0) {
sourceWord = sourceWord.charAt(0).toUpperCase() + sourceWord.slice(1);
}
result += sourceWord + ' ';
});
result = result.slice(0, result.length - 1) + ', ';
});
result = result.slice(0, result.length - 2) + '. ';
});
result += '</p>';
});
$('#yipsum').html(result);
});
|
JavaScript
| 0.999997 |
@@ -1083,16 +1083,20 @@
() * 10)
+ + 1
).times(
|
72dc834d56b010607a8699a3e4da9b9a5abd87c9
|
Fix bug with levels being equal on same tile
|
src/game/Generators/genCreatures.js
|
src/game/Generators/genCreatures.js
|
import CreaturesJSON from "../db/Creatures.json";
const creatures = new Map(Object.entries(CreaturesJSON));
class Creature {
constructor(level, creature) {
this.name = creature.name;
this.level = level;
this.symbol = creature.attributes.healthBar;
// this.items = getItems(this.name);
this.attr = creature.attributes;
}
}
const genCreatures = (playerLevel = 1) => {
let tileCreatures = [];
let level = Math.ceil(Math.random() * playerLevel * 1.5);
creatures.forEach(c => {
if (Math.random() < c.attributes.spawnChance) {
tileCreatures.push(new Creature(level, c));
}
});
return tileCreatures;
}
export default genCreatures;
|
JavaScript
| 0 |
@@ -416,68 +416,8 @@
%5B%5D;%0A
- let level = Math.ceil(Math.random() * playerLevel * 1.5);%0A
cr
@@ -529,21 +529,60 @@
reature(
-level
+Math.ceil(Math.random() * playerLevel * 1.5)
, c));%0A
|
098a23560ff10ae9e68e8bf9367f3ad3b1e51ee7
|
Load analytics with the main bundle
|
assets/javascript/main.js
|
assets/javascript/main.js
|
import supports from './supports';
const POLYFILL_PATH = process.env.SBF_PUBLIC_PATH + 'polyfills.js';
/**
* The main script entry point for the site. Initalizes all the sub modules
* analytics tracking, and the service worker.
* @param {?Error} err Present if an error occurred loading the polyfills.
*/
function main(err) {
// Add an `is-legacy` class on browsers that don't supports flexbox.
if (!supports.flexbox()) {
let div = document.createElement('div');
div.className = 'Error';
div.innerHTML = `Your browser does not support Flexbox.
Parts of this site may not appear as expected.`;
document.body.insertBefore(div, document.body.firstChild);
}
System.import('./analytics').then((analytics) => {
analytics.init();
if (err) {
analytics.trackError(err);
}
});
}
/**
* The primary site feature detect. Determines whether polyfills are needed.
* @return {boolean} True if the browser supports all required features and
* no polyfills are needed.
*/
function browserSupportsAllFeatures() {
return !!(window.Promise && window.Symbol);
}
/**
* Creates a new `<script>` element for the passed `src`, and invokes the
* passed callback once done.
* @param {string} src The src attribute for the script.
* @param {!Function<?Error>} done A callback to be invoked once the script has
* loaded, if an error occurs loading the script the function is invoked
* with the error object.
*/
function loadScript(src, done) {
const js = document.createElement('script');
js.src = src;
js.onload = () => done();
js.onerror = () => done(new Error('Failed to load script ' + src));
document.head.appendChild(js);
}
if (browserSupportsAllFeatures()) {
main();
} else {
loadScript(POLYFILL_PATH, main);
}
|
JavaScript
| 0 |
@@ -1,12 +1,54 @@
+import * as analytics from './analytics';%0A
import suppo
@@ -71,17 +71,16 @@
orts';%0A%0A
-%0A
const PO
@@ -747,138 +747,23 @@
%0A%0A
-System.import('./analytics').then((analytics) =%3E %7B%0A analytics.init();%0A if (err) %7B%0A analytics.trackError(err);%0A %7D%0A %7D
+analytics.init(
);%0A%7D
|
bd5d76bb4f9e6286cf61112eac9386d3ce546a48
|
Remove left over console log
|
assets/js/participants.js
|
assets/js/participants.js
|
(function(){
var $wrapper_div = document.querySelector('#participant-management');
var phone_icon_url = chrome.extension.getURL('assets/img/phone_icon.png');
var phone_img_src = '<img class="phoneicon" src="' + phone_icon_url + '" alt="Edit phone number">';
// =======================================================================
// DOM helper functions
// =======================================================================
var reload_phone_icons = function(){
var $player_lis = $wrapper_div.querySelectorAll('.participant-model');
each_$($player_lis, function($e){
var has_phone_icon = !!$e.querySelector('.phoneicon');
if(!has_phone_icon){
var $pencil_icon = $e.querySelector('.icon-pencil');
console.log('$pencil_icon ',$pencil_icon );
$pencil_icon.insertAdjacentHTML('beforebegin', phone_img_src);
}
});
};
var remove_phone_form = function(){
var $phone_input_form = $wrapper_div.querySelector('#phone_submit');
if($phone_input_form)
$phone_input_form.parentElement.removeChild($phone_input_form);
};
var close_edit_form = function(){
var $edit_form = $wrapper_div.querySelector('form[style$="block;"]');
if($edit_form)
$edit_form.style.display = 'none';
};
var display_phone_alert = function(template, context){
var $alert_info = document.querySelector('.alert');
if($alert_info)
$alert_info.parentElement.removeChild($alert_info);
var phone_alert_html = ghetto_render_template(template, context);
$wrapper_div.insertAdjacentHTML('beforeBegin', phone_alert_html);
};
// =======================================================================
// Event handlers
// =======================================================================
dynamic_child_bind($wrapper_div, '.phoneicon', 'click', function($e){
close_edit_form();
var $parent_li = get_parent($e, 3);
var player_name = $parent_li.firstElementChild.getAttribute('title');
var $phone_input_form = $wrapper_div.querySelector('#phone_submit');
if($phone_input_form){
var forms_player_name = $phone_input_form.children[1].getAttribute('value');
remove_phone_form();
var should_toggle_and_stop = player_name == forms_player_name;
if(should_toggle_and_stop)
return;
}
with_player_phones([player_name], function(data){
var $btn_controls = $parent_li.querySelector('.participant-controls');
var phone_form_html = ghetto_render_template('save_phone', {
'player': player_name,
'phone': data[player_name] || ''
});
$btn_controls.insertAdjacentHTML('afterend', phone_form_html);
});
});
// Having the normal edit form and the phone edit form open at the same time
// seems to cause data loss.
dynamic_child_bind($wrapper_div, '.icon-pencil', 'click', function($e){
remove_phone_form();
});
// Account for player names changing. Phone numbers should still match up.
dynamic_global_bind($wrapper_div, 'li form', 'submit', function($e){
var $player_li = get_parent($e, 1);
var $player_name_input = $player_li.querySelector('.inline-participant_name');
var old_player_name = $player_li.firstElementChild.getAttribute('title');
var new_player_name = $player_name_input.value;
if(new_player_name == old_player_name)
return;
// This is a contest to see how many race conditions I can fit into one
// extension. I think I'm winning.
setTimeout(function(){
var $alert_box = $player_li.querySelector('.error-message');
var name_taken = $alert_box.textContent;
if(name_taken)
return;
with_player_phones([old_player_name], function(data){
var phone_number = data[old_player_name] || '';
if(phone_number){
set_player_phone(new_player_name, phone_number);
set_player_phone(old_player_name, '');
}
});
}, 500);
});
dynamic_global_bind($wrapper_div, '#phone_input', 'keyup', function($e, evt){
var enter_key_pressed = evt.keyCode == ENTER_KEYCODE;
if(!enter_key_pressed)
return;
var player_name = $wrapper_div.querySelector('#player_name').value;
var phone_number = $e.value;
// Blank is valid and indicates deletion, so we don't want to confuse this
// with blank after stripping non numeric characters
if(phone_number !== ""){
phone_number = $e.value.replace(/\D+/g, '');
// Naive US phone validation
if(phone_number.length != 10){
display_phone_alert('phone_error', {'number': $e.value });
return;
}
}
set_player_phone(player_name, phone_number, function(){
var $phone_input_form = $wrapper_div.querySelector('#phone_submit');
$phone_input_form.parentElement.removeChild($phone_input_form);
var template = phone_number === '' ? 'phone_deleted': 'phone_added';
display_phone_alert(template, {'player': player_name });
});
});
// =======================================================================
// onload commands
// =======================================================================
reload_phone_icons();
setInterval(function(){
reload_phone_icons();
}, 2000);
})();
|
JavaScript
| 0 |
@@ -738,64 +738,8 @@
');%0A
- console.log('$pencil_icon ',$pencil_icon );%0A
|
89404d2fdbed0c9db41ade5d27fddfabf1b7baf6
|
fix unmountTimeout
|
src/js/SGoogleMapMarkerComponent.js
|
src/js/SGoogleMapMarkerComponent.js
|
import SGoogleMapComponentBase from 'coffeekraken-s-google-map-component-base'
import __whenAttribute from 'coffeekraken-sugar/js/dom/whenAttribute'
/**
* @name SGoogleMapMarkerComponent
* @extends SGoogleMapComponentBase
* Provide a nice webcomponent wrapper around the google map marker api.
*
* @example html
* <s-google-map center="{lat: -25.363, lng: 131.044}">
* <s-google-map-marker position="{lat: -25.363, lng: 131.044}">
* </s-google-map-marker>
* </s-google-map>
* @see https://www.npmjs.com/package/google-maps
* @see https://developers.google.com/maps/documentation/javascript/
* @author Olivier Bossel <[email protected]>
*/
export default class SGoogleMapMarkerComponent extends SGoogleMapComponentBase {
/**
* Default props
* @definition SWebComponent.defaultProps
* @protected
*/
static get defaultProps() {
return {
/**
* @name Google Map Marker API
* Support all the google map marker API properties
* @prop
* @type {Google.Map.Marker}
* @see https://developers.google.com/maps/documentation/javascript/3.exp/reference#MarkerOptions Google Map Marker Options
*/
};
}
/**
* Mount dependencies
* @definition SWebComponent.mountDependencies
* @protected
*/
static get mountDependencies() {
return [function() {
return __whenAttribute(this.parentNode, 'inited');
}];
}
/**
* Physical props
* @definition SWebComponent.physicalProps
* @protected
*/
static get physicalProps() {
return [];
}
/**
* Should accept component props
* @definition SWebComponent.shouldComponentAcceptProp
* @protected
*/
shouldComponentAcceptProp(prop) {
return true;
}
/**
* Component will mount
* @definition SWebComponent.componentWillMount
* @protected
*/
componentWillMount() {
super.componentWillMount();
}
/**
* Mount component
* @definition SWebComponent.componentMount
* @protected
*/
componentMount() {
super.componentMount();
// save reference to the parent node to dispatch an event when unmounted
this._parentNode = this.parentNode;
// get the map instance to use for this marker.
// this is grabed from the parent node that need to be a google-map component
if ( ! this.map) {
throw `The "${this._componentNameDash}" component has to be a direct child of a "SGoogleMapComponent"`;
}
// add the marker to the map
// load the map api
if ( ! this._marker) {
this._initMarker();
} else {
this._marker.setMap(this.map);
}
// dispatch an event to notify the new marker
this.dispatchComponentEvent('new-google-map-marker', this._marker);
}
/**
* Component unmount
* @definition SWebComponent.componentUnmount
* @protected
*/
componentUnmount() {
super.componentUnmount();
// remove the marker from the map
if (this._marker) {
this._marker.setMap(null);
}
// dispatch an event to notify the new marker
this.dispatchComponentEvent('remove-google-map-marker', this._marker, this._parentNode);
}
/**
* Component will receive props
* @definition SWebComponent.componentWillReceiveProps
* @protected
*/
componentWillReceiveProps(nextProps, previousProps) {
if ( ! this._marker) return;
this._marker.setOptions(nextProps);
}
/**
* Render the component
* Here goes the code that reflect the this.props state on the actual html element
* @definition SWebComponent.render
* @protected
*/
render() {
super.render();
}
/**
* Init the marker
*/
_initMarker() {
this._marker = new this.google.maps.Marker(this.props);
this._marker.setMap(this.map);
// set the component as inited
// used by the markers to init when the map is ok
this.setAttribute('inited', true);
}
/**
* Access the google map instance
* @type {Google.Map}
*/
get map() {
return this.parentNode.map;
}
/**
* Access the google map marker instance
* @type {Google.Map.Marker}
*/
get marker() {
return this._marker;
}
}
|
JavaScript
| 0.000003 |
@@ -874,16 +874,132 @@
turn %7B%0A%0A
+%09%09%09// set the unmout timeout to 0 to avoid unwanted delays when adding and removing markers%0A%09%09%09unmountTimeout : 0,%0A%0A
%09%09%09/**%0A%09
|
4f8f1ba354299b0f1b03ba744d21b8f2f8011119
|
Check if elements exists before adding unread class
|
src/js/modules/discussion-topics.js
|
src/js/modules/discussion-topics.js
|
this.mmooc = this.mmooc || {};
this.mmooc.discussionTopics = function () {
return {
setDiscussionTopicPubDate: function(discussionTopic) {
var formattedDate = mmooc.util.formattedDate(discussionTopic.posted_at);
var pubDate = $("<div class='publication-date'>" + formattedDate + "</div>");
$(pubDate).prependTo('#discussion_topic .discussion-header-right');
},
alterDiscussionReadStateLook: function() {
var self = this;
$('body').on('click', '.read-unread-button', function (){
$(this).toggleClass('read');
$(this).closest(".entry-content").siblings(".discussion-read-state-btn").click();
self.toggleReadUnreadButton($(this));
});
var checkExist = setInterval(function() {
if ($('.discussion-read-state-btn').length) {
clearInterval(checkExist);
var readUnreadButton = $("<div class='read-unread-button'>Marker som lest</div>");
readUnreadButton.appendTo('.discussion_entry .entry-header');
self.toggleReadUnreadButton($(this).closest(".discussion_entry").find("read-unread-button"));
}
}, 100);
},
toggleReadUnreadButton: function(button) {
$(".discussion-read-state-btn").each(function(index) {
var button = $(this).siblings(".entry-content").find(".read-unread-button");
if($(this).parent().hasClass("unread")) {
button.text('Marker som lest');
button.addClass('read');
}
else {
button.text('Marker som ulest');
button.removeClass('read');
}
});
},
setDiscussionsListUnreadClass: function() {
var wait = setInterval(function() {
clearInterval(wait);
$("#open-discussions .ig-list .discussion").each(function() {
var unread = $(this).find('.new-items').text();
if(unread.indexOf('0') == -1) {
$(this).addClass('unread');
}
});
}, 800);
},
insertSearchButton: function() {
$('.index_view_filter_form').append('<button class="btn btn-discussion-search">');
}
};
}();
|
JavaScript
| 0 |
@@ -1936,19 +1936,25 @@
var
-wai
+checkExis
t = setI
@@ -1966,32 +1966,104 @@
al(function() %7B%0A
+ if ($(%22#open-discussions .ig-list .discussion%22).length) %7B%0A
clea
@@ -2076,15 +2076,23 @@
val(
-wai
+checkExis
t);%0A
+
@@ -2171,24 +2171,26 @@
+
var unread =
@@ -2221,24 +2221,26 @@
s').text();%0A
+
@@ -2281,32 +2281,34 @@
+
$(this).addClass
@@ -2325,34 +2325,38 @@
;%0A
-%7D%0A
+ %7D%0A
%7D);%0A
@@ -2347,32 +2347,46 @@
%7D);%0A
+ %7D%0A
%7D, 800
@@ -2386,9 +2386,9 @@
%7D,
-8
+1
00);
@@ -2533,26 +2533,16 @@
rch%22%3E');
-%0A
%0A
|
8afada94833b0262fae99cc6e6f6819b49c71a62
|
Fix type
|
src/js/sparql/documented-queries.js
|
src/js/sparql/documented-queries.js
|
import queries from './queries'
const {
GSBPMDescription
} = queries
export default {
GSBPMDescription: {
descr: 'Retrieve a globale description of the GSBPM',
whatWeGet: 'phases',
results: {
phase: 'phase (uri)',
phaseLabel: 'phase label',
subprocess: 'subprocess (uri)',
subprocessLabel: 'subprocess label'
},
params: [],
queryBuilder: GSBPMDescription
}
}
|
JavaScript
| 0.000002 |
@@ -134,17 +134,16 @@
a global
-e
descrip
|
5279c542a204c049f6d0f7f7d62f5e44d690ecc2
|
Use of js-tokeniser
|
backend/tokeniser.test.js
|
backend/tokeniser.test.js
|
/*eslint-env mocha */
const should = require('should') // eslint-disable-line no-unused-vars
const tokeniser = require('js-tokeniser')
const rules = require('./rules')
describe('Tokeniser', () => {
it('should recognise comments', done => {
let result = tokeniser('// abc', rules)
result.should.be.an.array
result.length.should.equal(1)
result[0].type.should.equal('comment')
result[0].matches[0].should.equal('// abc')
done()
})
it('should recognise definitions', done => {
let result = tokeniser('Name = Test\nAuthor = "Bob Sherman"', rules)
result[0].type.should.equal('definition')
result[1].type.should.equal('definition')
result[0].matches[1].should.equal('Name')
result[0].matches[2].should.equal('Test')
result[1].matches[1].should.equal('Author')
result[1].matches[2].should.equal('"Bob Sherman"')
done()
})
it('should recognise arrays', done => {
let result = tokeniser('abc [\n\tx = 1\n]', rules)
result.should.be.an.array
result.length.should.equal(3)
result[0].type.should.equal('arrayStart')
result[0].matches[0].should.equal('abc [')
result[0].matches[1].should.equal('abc')
result[2].type.should.equal('arrayEnd')
result[2].matches[0].trim().should.equal(']')
done()
})
it('should recognise objects', done => {
let result = tokeniser('abc {\n\tx = 1\n}', rules)
result.should.be.an.array
result.length.should.equal(3)
result[0].type.should.equal('objectStart')
result[0].matches[0].should.equal('abc {')
result[0].matches[1].should.equal('abc')
result[2].type.should.equal('objectEnd')
result[2].matches[0].trim().should.equal('}')
done()
})
it('should recognise objects in an array', done => {
let result = tokeniser('Array[\n\t{\n\t}\n]', rules)
result.length.should.equal(4)
result[0].type.should.equal('arrayStart')
result[1].type.should.equal('objectStart')
result[2].type.should.equal('objectEnd')
result[3].type.should.equal('arrayEnd')
result[0].matches[0].should.equal('Array[')
result[0].matches[1].should.equal('Array')
result[1].matches[0].should.equal('\n\t{')
result[1].matches[1].should.equal('')
result[2].matches[0].should.equal('\n\t}')
result[3].matches[0].should.equal('\n]')
done()
})
it('should recognise arrays in an array', done => {
let result = tokeniser('Array[\n\t[\n\t]\n]', rules)
result.length.should.equal(4)
result[0].type.should.equal('arrayStart')
result[1].type.should.equal('arrayStart')
result[2].type.should.equal('arrayEnd')
result[3].type.should.equal('arrayEnd')
result[0].matches[0].should.equal('Array[')
result[0].matches[1].should.equal('Array')
result[1].matches[0].should.equal('\n\t[')
result[1].matches[1].should.equal('')
result[2].matches[0].should.equal('\n\t]')
result[3].matches[0].should.equal('\n]')
done()
})
it('should recognise literals in an array', done => {
let result = tokeniser('abc [1, 2, 3]', rules)
result.should.be.an.array
result.length.should.equal(3)
result[0].type.should.equal('arrayStart')
result[0].matches[0].should.equal('abc [')
result[0].matches[1].should.equal('abc')
result[2].type.should.equal('arrayEnd')
result[2].matches[0].trim().should.equal(']')
done()
})
})
|
JavaScript
| 0.000001 |
@@ -3173,24 +3173,25 @@
n%5D')%0A
+
done()%0A %7D
|
c5ad514dd1ecdf057c5f0f5e7522b7e40534692b
|
Use different arity in benchmark to avoid deopt
|
bench/fork-performance.js
|
bench/fork-performance.js
|
/**
* Fork Performance Benchmark
* Measures the cost of forking a repo. This is a good indicator of
* start up time for complicated trees.
*/
'use strict'
const { Microcosm } = require('../build/microcosm.min')
const time = require('microtime')
const SIZES = [
100,
5000,
15000,
30000
]
console.log('\nConducting fork benchmark...\n')
var action = 'test'
var Domain = {
getInitialState: () => 0,
register() {
return {
[action]: (n) => n + 1
}
}
}
var results = SIZES.map(function (SIZE) {
var repo = new Microcosm()
repo.addDomain('one', Domain)
var then = time.now()
for (var i = 0; i < SIZE; i++) {
repo.fork().on('change', () => {})
}
var setup = (time.now() - then) / 1000
then = time.now()
repo.push(action, 1)
var push = (time.now() - then) / 1000
return {
'Count' : SIZE.toLocaleString(),
'Setup' : setup.toLocaleString() + 'ms',
'Push' : push.toLocaleString() + 'ms'
}
})
/**
* Finally, report our findings.
*/
require('console.table')
console.table(results)
|
JavaScript
| 0 |
@@ -458,19 +458,22 @@
%5D: (
-n
+a, b
) =%3E
-n + 1
+a + b
%0A
|
5328e8a2757e8c7f6e0fedf57230d930d3fe43fd
|
Add extension point to add properties to event
|
src/clients/appinsights/AppInsightsClient.js
|
src/clients/appinsights/AppInsightsClient.js
|
const appInsightsKey = process.env.FORTIS_SERVICES_APPINSIGHTS_KEY;
let client;
let consoleLog = console.log;
let consoleError = console.error;
let consoleWarn = console.warn;
const TRACE_LEVEL_INFO = 1;
const TRACE_LEVEL_WARNING = 2;
const TRACE_LEVEL_ERROR = 3;
function setup() {
if (appInsightsKey) {
const appInsights = require('applicationinsights');
appInsights.setup(appInsightsKey);
appInsights.start();
client = appInsights.getClient(appInsightsKey);
console.log = trackTrace(TRACE_LEVEL_INFO, consoleLog);
console.warn = trackTrace(TRACE_LEVEL_WARNING, consoleWarn);
console.error = trackTrace(TRACE_LEVEL_ERROR, consoleError);
}
}
function trackTrace(level, localLogger) {
return (message) => {
if (client) {
client.trackTrace(message, level);
}
localLogger(message);
};
}
function trackDependency(promiseFunc, dependencyName, callName) {
if (!client) return promiseFunc;
function dependencyTracker(...args) {
return new Promise((resolve, reject) => {
const start = new Date();
promiseFunc(...args)
.then(returnValue => {
const duration = new Date() - start;
const success = true;
client.trackDependency(dependencyName, callName, duration, success);
resolve(returnValue);
})
.catch(err => {
const duration = new Date() - start;
const success = false;
client.trackDependency(dependencyName, callName, duration, success);
reject(err);
});
});
}
return dependencyTracker;
}
function trackEvent(promiseFunc, eventName) {
if (!client) return promiseFunc;
function eventTracker(...args) {
return new Promise((resolve, reject) => {
const start = new Date();
promiseFunc(...args)
.then(returnValue => {
const duration = new Date() - start;
const success = true;
client.trackEvent(eventName, { duration: duration, success: success });
resolve(returnValue);
})
.catch(err => {
const duration = new Date() - start;
const success = false;
client.trackEvent(eventName, { duration: duration, success: success });
reject(err);
});
});
}
return eventTracker;
}
module.exports = {
trackDependency: trackDependency,
trackEvent: trackEvent,
setup: setup
};
|
JavaScript
| 0 |
@@ -1592,24 +1592,40 @@
c, eventName
+, extraPropsFunc
) %7B%0A if (!c
@@ -1642,32 +1642,137 @@
urn promiseFunc;
+%0A extraPropsFunc = extraPropsFunc %7C%7C ((returnValue, err) =%3E (%7B%7D)); // eslint-disable-line no-unused-vars
%0A%0A function eve
@@ -1932,32 +1932,89 @@
%7B%0A const
+props = extraPropsFunc(returnValue, null);%0A props.
duration = new D
@@ -2028,38 +2028,38 @@
start;%0A
-const
+props.
success = true;%0A
@@ -2099,48 +2099,13 @@
me,
-%7B duration: duration, success: success %7D
+props
);%0A
@@ -2170,32 +2170,81 @@
%7B%0A const
+props = extraPropsFunc(null, err);%0A props.
duration = new D
@@ -2258,38 +2258,38 @@
start;%0A
-const
+props.
success = false;
@@ -2330,48 +2330,13 @@
me,
-%7B duration: duration, success: success %7D
+props
);%0A
|
ab94a8f1639e8c8f5eb4214fa1c4d4d8dac2fb93
|
Add paging mode route
|
examples/express/express.js
|
examples/express/express.js
|
'use strict'
const path = require('path')
const express = require('express')
const hackernews = require('../../')
const app = express()
const news = hackernews()
const watchmode = process.argv.includes('--watch')
const index = `
<ul>
<li><a href="/stories/top">top</a></li>
<li><a href="/stories/new">new</a></li>
<li><a href="/stories/best">best</a></li>
<li><a href="/stories/ask">ask</a></li>
<li><a href="/stories/show">show</a></li>
<li><a href="/stories/job">job</a></li>
<li><a href="/users/jl">users/jl</a></li>
<li><a href="/maxitem">maxitem</a></li>
<li><a href="/updates">updates</a></li>
</ui>`
app.get('/', (req, res) => {
res.send(index)
})
app.get('/stories/:type', (req, res) => {
news.stories(req.params.type).then(data => res.send(data))
})
app.get('/users/:id', (req, res) => {
news.user(req.params.id).then(data => res.send(data))
})
app.get('/maxitem', (req, res) => {
news.maxItem().then(data => res.send(`maxitem: ${data}`))
})
app.get('/updates', (req, res) => {
news.update().then(data => res.send(data))
})
app.use('/hackernews', express.static(path.join(path.resolve(__dirname, '../'))))
Promise.resolve(watchmode && news.watch()).then(() => {
app.listen(3000, () => {
console.log(`server has started with ${watchmode ? 'watch' : 'fetch'} mode`)
})
})
|
JavaScript
| 0.000001 |
@@ -262,32 +262,98 @@
p%22%3Etop%3C/a%3E%3C/li%3E%0A
+%09%3Cli%3E%3Ca href=%22/stories/top?page=1&count=1%22%3Etop at page 1%3C/a%3E%3C/li%3E%0A
%09%3Cli%3E%3Ca href=%22/s
@@ -766,24 +766,49 @@
, res) =%3E %7B%0A
+%09console.log(req.query);%0A
%09news.storie
@@ -824,16 +824,71 @@
ams.type
+, %7B%0A%09%09page: req.query.page,%0A%09%09count: req.query.count%0A%09%7D
).then(d
|
2648985f2cd50ad42f2f9d4d9642696fc2d022bb
|
update API call
|
get-contributors.js
|
get-contributors.js
|
#!/usr/bin/env node
/**
* Usage:
* ./get-contributors.js "project"
*
* Example:
* ./get-contributors.js macbre/phantomas
*/
var api = require('github'),
log = require('npmlog'),
format = require('util').format,
github;
var argv = process.argv.slice(2),
user = argv[0].split('/')[0],
project = argv[0].split('/')[1];
log.info('GIT', 'Getting contributors of %s/%s', user, project);
github = new api({
version: "3.0.0",
});
github.repos.getContributors({
user: user,
repo: project
}, function(err, contributors) {
if (err) {
log.error('API', '#%d: %s', err.code, err.message);
return;
}
log.info('API', 'Got %d contributor(s)', contributors.length);
var ret = [];
contributors.forEach(function(contributor) {
ret.push(
format('%s (https://github.com/%s)',
contributor.login,
contributor.login
));
});
console.log(ret.join("\n"));
});
|
JavaScript
| 0 |
@@ -464,18 +464,19 @@
tors(%7B%0A%09
-us
+own
er: user
|
7d594d5857f9730048ae79cf931e25a78c466677
|
Remove obsolete variable
|
view/dbjs/form-section-base-get-legacy.js
|
view/dbjs/form-section-base-get-legacy.js
|
'use strict';
var forEach = require('es5-ext/object/for-each')
, normalizeOptions = require('es5-ext/object/normalize-options')
, d = require('d')
, generateId = require('time-uuid')
, resolvePropertyPath = require('dbjs/_setup/utils/resolve-property-path')
, db = require('mano').db
, ns = require('mano').domjs.ns;
/*
return object of form:
{
controls: ids || undefined,
legacy: lagacyScript || undefined
}
*/
module.exports = Object.defineProperty(db.FormSectionBase.prototype, 'getLegacy',
d(function (formId/*, options */) {
var result, legacyData, options = Object(arguments[1]), self, master;
master = options.master || this.master;
result = {};
result.controls = {};
self = this;
this.constructor.propertyNames.forEach(function (item, propName) {
var val, id, resolved, formFieldPath, propOptions;
resolved = resolvePropertyPath(master, propName);
formFieldPath = resolved.object.__id__ + '/' + resolved.key;
if (self.inputOptions.has(propName)) {
propOptions = normalizeOptions(self.inputOptions.get(propName));
forEach(propOptions, function (value, name) {
if (typeof value !== 'function') return;
if (!value.isOptionResolver) return;
propOptions[name] = value.call(this);
});
result.controls[formFieldPath] = propOptions;
}
val = resolved.object.getDescriptor(db.Object.getApplicablePropName(resolved.key)
)._value_;
if (typeof val !== 'function') {
return;
}
if (!legacyData) {
legacyData = [];
}
id = 'input-' + generateId();
legacyData.push({ id: id, constraint: val, sKeyPath: propName });
result.controls[formFieldPath] = normalizeOptions(result.controls[formFieldPath], { id: id });
}, this);
if (legacyData) {
result.legacy = ns.legacy('formSectionStateHelper', formId, master.__id__,
legacyData, options.legacyEntityProto);
}
return result;
}));
|
JavaScript
| 0.023758 |
@@ -642,14 +642,8 @@
1%5D),
- self,
mas
@@ -732,23 +732,8 @@
%7B%7D;%0A
-%09%09self = this;%0A
%09%09th
@@ -975,20 +975,20 @@
%0A%09%09%09if (
-self
+this
.inputOp
@@ -1049,12 +1049,12 @@
ons(
-self
+this
.inp
|
61c8ce4464e58172a89182397bfaef3ead64d14d
|
Test session ending
|
connect.js
|
connect.js
|
var alexa = require('alexa-app');
var request = require('request-promise');
var express = require('express');
var express_app = express();
var app = new alexa.app('connect');
app.express({ expressApp: express_app });
app.intent('PlayIntent', {
"utterances": [
"play",
"resume",
"continue"
]
},
function (req, res) {
request.put("https://api.spotify.com/v1/me/player/play").auth(null, null, true, req.sessionDetails.accessToken);
res.say('Playing');
}
);
app.intent('PauseIntent', {
"utterances": [
"pause"
]
},
function (req, res) {
request.put("https://api.spotify.com/v1/me/player/pause").auth(null, null, true, req.sessionDetails.accessToken);
res.say('Paused');
}
);
app.intent('GetDevicesIntent', {
"utterances": [
"devices",
"list"
]
},
function (req, res) {
return request.get({
url: "https://api.spotify.com/v1/me/player/devices",
auth: {
"bearer": req.sessionDetails.accessToken
},
json: true
})
.then(function (body) {
var devices = body.devices || [];
var deviceNames = [];
res.say("I found these devices:");
for (var i = 0; i < devices.length; i++) {
deviceNames.push((i + 1) + ". " + devices[i].name);
devices[i].number = (i + 1);
}
res.say(deviceNames.slice(0, deviceNames.length - 1).join(', ') + ", and " + deviceNames.slice(-1));
req.getSession().set("devices", devices);
})
.catch(function (err) {
console.error('error:', err.message);
});
}
);
app.intent('DevicePlayIntent', {
"slots": {
"DEVICENUMBER": "AMAZON.NUMBER"
},
"utterances": [
"play on {-|DEVICENUMBER}",
"play on number {-|DEVICENUMBER}",
"play on device {-|DEVICENUMBER}",
"play on device number {-|DEVICENUMBER}"
]
},
function (req, res) {
if (req.hasSession()) {
if (req.slot("DEVICENUMBER")) {
var deviceNumber = req.slot("DEVICENUMBER");
var devices = req.getSession().get("devices") || [];
var deviceId, deviceName;
for (var i = 0; i < devices.length; i++) {
if (devices[i].number == deviceNumber) {
deviceId = devices[i].id;
deviceName = devices[i].name;
}
}
res.say("Device " + deviceNumber + ": " + deviceName);
}
}
});
express_app.use(express.static(__dirname));
express_app.get('/', function (req, res) {
res.redirect('https://github.com/thorpelawrence/alexa-spotify-connect');
});
var port = process.env.PORT || 8888;
console.log("Listening on port " + port);
express_app.listen(port);
module.exports = app;
|
JavaScript
| 0.000001 |
@@ -1270,16 +1270,24 @@
d these
+connect
devices:
@@ -1663,16 +1663,61 @@
vices);%0A
+ res.shouldEndSession(false);%0A
|
138b8cc669f274ed09337ea1cf5aa6937a1cf0ab
|
Update example phantomwebintro (#14545)
|
examples/phantomwebintro.js
|
examples/phantomwebintro.js
|
// Read the Phantom webpage '#intro' element text using jQuery and "includeJs"
"use strict";
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.open("http://phantomjs.org/", function(status) {
if (status === "success") {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
console.log("$(\".explanation\").text() -> " + $(".explanation").text());
});
phantom.exit(0);
});
} else {
phantom.exit(1);
}
});
|
JavaScript
| 0 |
@@ -26,14 +26,16 @@
ge '
-#intro
+.version
' el
@@ -354,13 +354,13 @@
ery/
-1.6.1
+3.1.0
/jqu
@@ -416,32 +416,78 @@
te(function() %7B%0A
+ // lastest version on the web%0A
@@ -503,25 +503,25 @@
og(%22$(%5C%22
-.explanat
+span.vers
ion%5C%22).t
@@ -540,17 +540,17 @@
$(%22
-.explanat
+span.vers
ion%22
|
01a94507b7da914116e38b181918c53adf1ae862
|
update regex and external path
|
content.js
|
content.js
|
(() => {
const $title = document.querySelector('.js-issue-title');
if (!$title) {
return;
}
chrome.storage.local.get('inlineLinks', (options) => {
let title = $title.innerHTML.replace(/(<a[^>]+>|⬆︎|<\/a>)/g, '');
title.match(/#\d+(?=[\],\s\d#]*\])/g).forEach((tag) => {
const url = `https://www.pivotaltracker.com/story/show/${tag.match(/\d+/)}`;
const attrs = `href="${url}" target="_blank"`;
const replacement = options.inlineLinks === false ?
`${tag}<a ${attrs}>⬆︎</a>` :
`<a ${attrs}>${tag}</a>`;
title = title.replace(tag, replacement);
});
$title.innerHTML = title;
});
})();
|
JavaScript
| 0 |
@@ -245,11 +245,20 @@
ch(/
-#%5Cd
+%5Ba-zA-Z0-9-%5D
+(?=
@@ -325,60 +325,46 @@
s://
-www.pivotaltracker.com/story/show/$%7Btag.match(/%5Cd+/)
+nextcapital.atlassian.net/browse/$%7Btag
%7D%60;%0A
|
8dcb9e13d1cf54e53f5c24fc3a51aed2221d2c58
|
fix 1 typo
|
examples/shared_testconf.js
|
examples/shared_testconf.js
|
var config = {
job_basename: require('path').basename(process.cwd()) + '_' + process.env.TRAVIS_JOB_ID,
sauceSeleniumAddress: 'localhost:4445/wd/hub',
sauceUser: process.env.SAUCE_USERNAME,
sauceKey: process.env.SAUCE_ACCESS_KEY,
browsers: [
{browserName: 'chrome'},
{browserName: 'firefox'},
{browserName: 'safari', version: 7, platform: 'OS X 10.9'},
{browserName: 'safari', version: 6, platform: 'OS X 10.8'},
{browserName: 'internet explorer', version: 11, platform: 'Windows 8.1'},
{browserName: 'internet explorer', version: 10, platform: 'Windows 8'},
{browserName: 'internet explorer', version: 9, platform: 'Windows 7'},
{browserName: 'Android', version:'4.4', platform: 'Linux'},
{browserName: 'Android', version:'4.1', platform: 'Linux'},
{browserName: 'Android', version:'4.0', platform: 'Linux'},
{browserName: 'iphone', deviceName: 'iPhone Simulator', version:'8.1', platform: 'OS X 10.9'},
{browserName: 'iphone', deviceName: 'iPhone Simulator', version:'8.0', platform: 'OS X 10.9'},
{browserName: 'iphone', deviceName: 'iPhone Simulator', version:'7.1', platform: 'OS X 10.9'},
{browserName: 'iphone', deviceName: 'Phone Simulator', version:'6.1', platform: 'OS X 10.8'},
{browserName: 'ipad', version:'8.1', platform: 'OS X 10.9'},
{browserName: 'ipad', version:'8.0', platform: 'OS X 10.9'},
{browserName: 'ipad', version:'7.1', platform: 'OS X 10.9'},
{browserName: 'ipad', version:'6.1', platform: 'OS X 10.8'}
],
specs: [process.cwd() + '/spec.js'],
baseUrl: 'http://localhost:3000/',
// This enable testing on none angular pages without test code change.
onPrepare: function () {
element = browser.element;
browser.ignoreSynchronization = true;
},
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000
}
};
config.multiCapabilities = config.browsers.map(function (cfg) {
cfg.build = config.job_basename;
cfg['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
cfg.name = 'FluxEx browser test for example: ' + config.job_basename;
cfg.public = 'public';
cfg.tags = [process.env.TRAVIS_JOB_ID, process.env.TRAVIS_COMMIT, 'fluxex'];
return cfg;
});
module.exports.config = config;
|
JavaScript
| 0.000017 |
@@ -1193,16 +1193,17 @@
eName: '
+i
Phone Si
|
7021f759c85d7efb63cb6043d1a68189e35da422
|
Add rpc-port to the user login token
|
api/user.js
|
api/user.js
|
var api = require('express').Router()
, config = require('../lib/config')
, db = require('ezseed-database').db.user
, jwt = require('express-jwt')
, prettyBytes = require('pretty-bytes')
, debug = require('debug')('ezseed:api')
, logger = require('ezseed-logger')('api')
jwt.sign = require('jsonwebtoken').sign
api
.use(
jwt({ secret: config.secret }).unless({ path: ['/api/login'] })
)
.use(function(err, req, res, next) {
if(err.name === 'UnauthorizedError') {
logger.error(err)
return res.status(401).end()
}
next()
})
.post('/login', function(req, res) {
db.login(req.body, function(err, user) {
if(err) {
return res.send({error: err}).status(401).end()
} else {
user.prettySize = prettyBytes(user.spaceLeft)
user.token = jwt.sign(user, config.secret)
return res.json(user)
}
})
})
/** Protected methods **/
.get('/-', function(req, res) {
//get user paths
db.paths(req.user.id, function(err, user) {
user.prettySize = prettyBytes(user.spaceLeft)
return res.json(user)
})
})
.get('/-/files', function(req, res) {
var types = ['others', 'movies', 'albums']
if(req.query.type && types.indexOf(req.query.type) === -1)
return res.status(500).send({error: req.params.type+' is not a valid type'}).end()
if(req.query.match)
req.query.match = JSON.parse(req.query.match)
debug("Files", req.query)
//need params, limit, dateUpdate, paths, type !
db.files(req.user.id, req.query, function(err, paths) {
if(req.query.type) {
var files = {}
files[req.query.type] = []
} else {
var files = {movies: [], albums: [], others: []}
}
paths.paths.forEach(function(path) {
for(var i in files) {
for(var j in path[i]) {
files[i].push(path[i][j])
}
}
})
return res.json(files)
})
})
.get('/-/refresh', function(req, res) {
db.paths(req.user.id, function(err, user) {
process.watcher.client.call('refresh', user.paths, function(err, update) {
if(err) {
res.status(500).send({error: err})
} else {
res.json(update)
}
})
})
})
// Mainly used for debugging
.get('/-/reset', function(req,res) {
db.reset(req.user.id, function(err, paths) {
if(err) {
logger.error(err)
}
process.watcher.client.call('refresh', paths.paths, function(err, update) {
if(err) {
res.status(500).send({error: err})
} else {
res.json(update)
}
})
})
})
.get('/-/size', function(req, res) {
var size = {
movies: 0,
albums: 0,
others: 0
}, total = 0
var opts = req.params.default ? {default: req.user.default_path} : {}
db.files(req.user.id, opts, function(err, files) {
if(!files)
return res.status(500).end()
files.paths.forEach(function(p) {
if(!req.params.path || req.params.paths.indexOf(p._id) !== -1 || req.params.paths.indexOf(p._id) !== -1) {
for(var i in size) {
p[i].forEach(function(files) {
files[require('ezseed-database').helpers.filename(i)].forEach(function(file) {
size[i] += file.size
})
})
total += size[i]
}
}
})
size.total = total
var pretty = {}
//converting bytes to pretty version
for(var i in size) {
pretty[i] = {
percent: size[i] / total * 100,
bytes: size[i],
pretty: prettyBytes(size[i])
}
}
return res.json(pretty)
})
})
module.exports = api
|
JavaScript
| 0 |
@@ -113,16 +113,63 @@
db.user%0A
+ , p = require('path')%0A , fs = require('fs')%0A
, jwt
@@ -861,16 +861,240 @@
ecret) %0A
+%0A if(user.client == 'transmission') %7B%0A var transmission = JSON.parse(fs.readFileSync(p.join(config.home, user.username, '.settings.'+user.username+'.json')))%0A user.port = transmission%5B'rpc-port'%5D%0A %7D%0A%0A
re
|
023dec86037a7fade22eb7199f53edafda07c25c
|
update backends of mostomessages, status and frame
|
backends.js
|
backends.js
|
var mbc = require('mbc-common'),
search_options = mbc.config.Search,
collections = mbc.config.Common.Collections,
backboneio = require('backbone.io'),
middleware = new mbc.iobackends().get_middleware()
;
module.exports = function (db) {
var backends = {
app: {
use: [backboneio.middleware.configStore()]
},
transform: {
use: [middleware.uuid],
mongo: {
db: db,
collection: collections.Transforms,
opts: { search: search_options.Transforms },
}},
media: {
redis: true,
mongo: {
db: db,
collection: collections.Medias,
opts: { search: search_options.Medias },
}},
piece: {
use: [middleware.uuid],
mongo: {
db: db,
collection: collections.Pieces,
opts: { search: search_options.Pieces },
}},
list: {
use: [middleware.uuid, middleware.tmpId],
mongo: {
db: db,
collection: collections.Lists,
opts: { search: search_options.Lists },
}},
sched: {
use: [middleware.uuid, middleware.publishJSON],
mongo: {
db: db,
collection: collections.Scheds,
opts: { search: search_options.Scheds },
}},
status: {
use: [middleware.uuid],
mongo: {
db: db,
collection: collections.Status,
opts: { search: search_options.Status },
}},
frame: {
use: [backboneio.middleware.memoryStore(db, 'progress', {})],
},
mostomessages: {
mongo: {
db: db,
collection: collections.Mostomessages,
opts: { search: search_options.Mostomessages },
}},
sketch: {
use: [middleware.uuid],
mongo: {
db: db,
collection: collections.Sketchs,
opts: { search: search_options.Sketchs },
}},
user: {
use: [middleware.uuid],
mongo: {
db: db,
collection: collections.Auth,
}},
transcodestatus: {
use: [middleware.debug],
redis: true,
store: backboneio.middleware.memoryStore(db, 'transcode_status', {}),
},
transcode: {
use: [middleware.debug],
redis: true,
mongo: {
db: db,
collection: collections.Transcoding,
}},
};
return backends;
};
|
JavaScript
| 0 |
@@ -1552,32 +1552,57 @@
ddleware.uuid%5D,%0A
+ redis: true,%0A
mong
@@ -1772,38 +1772,64 @@
: %7B%0A
-us
+redis: true,%0A stor
e:
-%5B
backboneio.middl
@@ -1865,17 +1865,16 @@
ss', %7B%7D)
-%5D
,%0A
@@ -1899,24 +1899,49 @@
messages: %7B%0A
+ redis: true,%0A
|
4a97ef3d48d7d99444225eff2b07b2f6a1fb248f
|
Clean up convert.js code style
|
convert.js
|
convert.js
|
module.exports = function convert (keys, values) {
var reverse = { }
var full = { }
var i
for (i = keys.length; i--;) {
full[keys[i].toUpperCase()] = values[i].toUpperCase()
full[keys[i]] = values[i]
}
for (i in full) {
reverse[full[i]] = i
}
return {
fromEn: function (str) {
return str.replace(/./g, function (ch) {
return full[ch] || ch
})
},
toEn: function (str) {
return str.replace(/./g, function (ch) {
return reverse[ch] || ch
})
}
}
}
|
JavaScript
| 0.000032 |
@@ -26,17 +26,16 @@
convert
-
(keys, v
@@ -56,25 +56,24 @@
reverse = %7B
-
%7D%0A var full
@@ -76,17 +76,16 @@
full = %7B
-
%7D%0A var
@@ -115,16 +115,17 @@
th; i--;
+
) %7B%0A
|
a3d136ab5c9e0f40fcec7dbde12ecec0b9df9202
|
Replace references to the highlight rule's function name.
|
convert.js
|
convert.js
|
var fs = require('fs');
var dot = require('dot');
function fetchHighlightRules(aceSheet) {
var lines = (''+aceSheet).split('\n');
var beforeStart = true; // Before the start of the function we fetch.
var beforeEnd = true;
var result = 'function() {\n';
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (beforeStart) {
if (line.match(/HighlightRules = function/)) {
beforeStart = false;
}
} else if (beforeEnd) {
if (line.match(/^oop\.inherits/)) {
beforeEnd = false;
} else {
// Indent it properly.
result += ' ' + line + '\n';
}
} else { break; }
}
return result;
}
var modeConf = {};
// Read all arguments.
// eg, ./ace2cm asciidoc ./asciidoc_highlight_rules.js '{"textRules":false}'
// The mode name is first.
modeConf.modeName = process.argv[2] || 'mode';
modeConf.rules = fetchHighlightRules(fs.readFileSync(process.argv[3]));
// Defaults.
modeConf.textRules = true;
modeConf.mixedMode = false;
// The last argument is a JSON object.
function addOtherConf(modeConf, otherConf) {
for (var key in otherConf) {
modeConf[key] = otherConf[key];
}
}
addOtherConf(modeConf, JSON.parse(process.argv[4]));
// Fetch the template.
var template = ''+fs.readFileSync('mode-template.js');
dot.templateSettings.strip = false;
process.stdout.write(dot.template(template)(modeConf));
|
JavaScript
| 0 |
@@ -223,16 +223,88 @@
= true;%0A
+ var functionName = ''; // Name of the real *HighlightRules function.%0A
var re
@@ -328,16 +328,16 @@
) %7B%5Cn';%0A
-
for (v
@@ -468,24 +468,97 @@
nction/)) %7B%0A
+ functionName = line.match(/ (%5Ba-zA-Z%5C$_%5D+HighlightRules) =/)%5B1%5D;%0A
befo
@@ -725,16 +725,16 @@
operly.%0A
-
@@ -754,16 +754,56 @@
' + line
+.replace(functionName, 'HighlightRules')
+ '%5Cn';
|
c09750335756415533cbd9848e1b099538efbe5a
|
Fix options extend
|
cordova.js
|
cordova.js
|
// The pushApi is just an Event emitter
Push = new EventEmitter();
Push.setBadge = function(count) {
// Helper
var pushNotification = window.plugins.pushNotification;
// If the set application badge is available
if (typeof pushNotification.setApplicationIconBadgeNumber == 'function') {
// Set the badge
pushNotification.setApplicationIconBadgeNumber(function(result) {
// Success callback
Push.emit('badge', result);
}, function(err) {
// Error callback
Push.emit('error', { type: 'badge', error: err });
}, count);
}
};
// handle APNS notifications for iOS
onNotificationAPN = function(e) {
if (e.alert) {
// navigator.notification.vibrate(500);
// navigator.notification.alert(e.alert);
}
if (e.sound) {
// var snd = new Media(e.sound);
// snd.play();
}
if (e.badge) {
// XXX: Test if this allows the server to set the badge
Push.setBadge(e.badge);
}
// e.sound, e.badge, e.alert
Push.emit('startup', e);
};
// handle GCM notifications for Android
onNotificationGCM = function(e) {
var pushNotification = window.plugins.pushNotification;
switch( e.event ) {
case 'registered':
if ( e.regid.length > 0 ) {
Push.emit('token', { gcm: ''+e.regid } );
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if (e.foreground)
{
// if the notification contains a soundname, play it.
// var my_media = new Media("/android_asset/www/"+e.soundname);
// my_media.play();
} else {
// navigator.notification.vibrate(500);
// navigator.notification.alert(e.payload.message);
}
// e.foreground, e.foreground, Coldstart or background
Push.emit('startup', e);
// e.payload.message, e.payload.msgcnt, e.msg, e.soundname
break;
case 'error':
// e.msg
Push.emit('error', { type: 'gcm.cordova', error: e });
break;
}
};
Push.init = function(options) {
var self = this;
// Clean up options, make sure the pushId
if (options.gcm && !options.gcm.pushId)
throw new Error('Push.initPush gcm got no pushId');
// Set default options - these are needed for apn?
options = {
badge: (options.badge !== false),
sound: (options.sound !== false),
alert: (options.alert !== false)
};
// Initialize on ready
document.addEventListener('deviceready', function() {
var pushNotification = window.plugins.pushNotification;
if (device.platform == 'android' || device.platform == 'Android') {
try {
if (options.gcm && options.gcm.pushId) {
pushNotification.register(function(result) {
// Emit registered
self.emit('register', result);
}, function(error) {
// Emit error
self.emit('error', { type: 'gcm.cordova', error: error });
}, {
'senderID': ''+options.gcm.pushId,
'ecb': 'onNotificationGCM'
});
} else {
// throw new Error('senderID not set in options, required on android');
console.warn('WARNING: Push.init, No gcm.pushId set on android');
}
} catch(err) {
// console.log('There was an error starting up push');
// console.log('Error description: ' + err.message);
self.emit('error', { type: 'gcm.cordova', error: err.message });
}
} else {
try {
pushNotification.register(function(token) {
// Got apn / ios token
self.emit('token', { apn: token });
}, function(error) {
// Emit error
self.emit('error', { type: 'apn.cordova', error: error });
}, {
'badge': ''+options.badge,
'sound': ''+options.sound,
'alert': ''+options.alert,
'ecb': 'onNotificationAPN'
}); // required!
} catch(err) {
// console.log('There was an error starting up push');
// console.log('Error description: ' + err.message);
self.emit('error', { type: 'apn.cordova', error: err.message });
}
}
}, true);
}; // EO Push
|
JavaScript
| 0.000002 |
@@ -2368,16 +2368,25 @@
tions =
+_.extend(
%7B%0A ba
@@ -2495,16 +2495,26 @@
lse)%0A %7D
+, options)
;%0A%0A /
|
6a9dfdec12a61ae3c3be5710148b3c1c6b20503c
|
Add new life event
|
app/app.js
|
app/app.js
|
/* global angular */
angular.module('app', ['templates', 'ngDialog'])
.controller('AppController', ['$scope', 'ngDialog', function($scope, ngDialog) {
$scope.toDo = [
{
'name': 'Get A Job',
'where': 'Your Company',
'job': true,
'draggable': true
}
];
$scope.inProgress = [
{
'name': 'Web Developer',
'where': 'TrackInsight',
'job': true,
'avatar': true
}
];
$scope.done = [
{
'name': 'Web Developer',
'where': 'Amadeus IT Group',
'job': true
},
{
'name': 'Certified ScrumMaster',
'where': 'ScrumAlliance',
'certification': true
},
{
'name': 'Certified Java SE 7 Programmer',
'where': 'Oracle',
'certification': true
},
{
'name': 'Web Developer',
'where': 'Freelance',
'job': true
},
{
'name': 'Software Engineering Intern',
'where': 'Thales Alenia Space',
'job': true
},
{
'name': 'Web Developer Intern',
'where': 'Koris International',
'job': true
},
{
'name': 'Tutor Of Mathematics',
'where': 'Complétude',
'job': true
},
{
'name': 'Engineer\'s Degree, Computer Science',
'where': 'Polytech Nice-Sophia',
'school': true
},
{
'name': '1-year Exchange, Computer Science',
'where': 'Western University',
'school': true
}
];
$scope.onDrop = function(task) {
$scope.toDo = [];
$scope.inProgress.unshift(task);
$scope.$apply();
ngDialog.openConfirm({
templateUrl: 'modal.html',
className: 'ngdialog-theme-plain'
});
};
}])
.directive('postit', ['$document', function($document) {
return {
restrict: 'E',
replace: true,
templateUrl: 'task.html',
scope: {
task: '=',
avatar: '='
},
link: function(scope, el) {
if(scope.task.draggable) {
var getTaskType = function(task) {
if(task.job) return 'job';
if(task.school) return 'school';
if(task.certification) return 'certification';
};
var inprogress = angular.element($document[0].querySelector('.inprogress'));
el.attr('draggable', true);
el.bind('dragstart', function(e) {
var task = {
'name': scope.task.name,
'where': scope.task.where
};
task[getTaskType(scope.task)] = true;
e.dataTransfer.setData('text', JSON.stringify(task));
inprogress.addClass('dragInProgress');
});
el.bind('dragend', function() {
inprogress.removeClass('dragInProgress');
});
}
}
};
}])
.directive('onDrop', function() {
return {
restrict: 'A',
scope: {
onDrop: '&'
},
link: function(scope, el) {
var dropElement = angular.element(el[0].querySelector('#dropTarget'));
dropElement.bind('dragover', function(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
});
dropElement.bind('dragenter', function(e) {
angular.element(e.target).addClass('over');
});
dropElement.bind('dragleave', function(e) {
angular.element(e.target).removeClass('over');
});
dropElement.bind('drop', function(e) {
e.preventDefault();
e.stopPropagation();
el.removeClass('dragInProgress');
var task = JSON.parse(e.dataTransfer.getData('text'));
task.avatar = true;
scope.onDrop({'task': task});
});
}
};
});
|
JavaScript
| 0.999999 |
@@ -328,32 +328,30 @@
name': 'Web
-Develope
+Creato
r',%0A 'w
@@ -362,20 +362,17 @@
': '
-TrackInsight
+Freelance
',%0A
@@ -414,32 +414,32 @@
rue%0A %7D%0A %5D;%0A%0A
-
$scope.done =
@@ -469,32 +469,125 @@
Web Developer',%0A
+ 'where': 'TrackInsight',%0A 'job': true%0A %7D,%0A %7B%0A 'name': 'Web Developer',%0A
'where': '
|
802e405f1a3786a59968fc3463610edcaeb61f1e
|
fix for notify that got unmerged
|
admin/server.js
|
admin/server.js
|
var express = require('express');
var bodyParser = require('body-parser');
var sendNotification = require('./fireBase/notification.js');
var app = express();
app.use(bodyParser.json());
var queue = [];
var notificationTimers = [];
var numberOfMonitors = 5;
var notificationTimeoutInMinutes = 5;
app.set('port', (process.env.PORT || 5000));
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.use('/dist', express.static(__dirname + '/dist'));
app.get('/', function(request, response) {
response.sendFile(__dirname + '/index.html');
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
app.post('/notify', function(request, response) {
sendNotification(request.body.token);
response.json({a: 'hello'});
});
app.get('/testInitData', function(request, response){
for (var i=0;i < (numberOfMonitors+2);i++) {
requestMonitor({
id: '3300876' + i + i + i,
phone: '050777877' + i + i + i,
fullName: 'Pregnant lady ' +i
});
}
response.json(queue);
});
/*
Get entire queue ordered by who is called next
*/
app.get('/queue', function(request, response){
response.json(queue);
});
/*
Return indication whether there is an available chair
*/
app.get('/queue/status', function(request, response){
let isAvailable = { isAvailable: (queue.length-1 < numberOfMonitors)};
response.json(isAvailable);
});
/*
Add a new user to the end of the queue
*/
app.post('/queue', function(request, response) {
var newRequest = request.body;
if (getFromQueueByID(newRequest.id) !== null) {
response.status(405).send({ error: "User " + newRequest.id+ " already registered." });
return;
};
requestMonitor(newRequest);
response.json(newRequest);
});
/*
Clears the entire queue and all timers.
*/
app.delete('/queue', function(request, response){
queue = [];
for (id in notificationTimers) {
clearTimeout(notificationTimers[id]);
delete notificationTimers[id];
}
notificationTimers = [];
response.json(queue);
});
/*
Update the queue configuration. Set the numberOfMonitors and notificationTimeoutInMinutes parameters
*/
app.put('/queue/config', function(request, response){
let configData = request.body;
if(configData.numberOfMonitors !== undefined) {
numberOfMonitors = configData.numberOfMonitors;
}
if(configData.notificationTimeoutInMinutes !== undefined) {
notificationTimeoutInMinutes = configData.notificationTimeoutInMinutes;
}
response.json({});
});
/*
Removes a user from the queue
*/
app.delete('/queue/:id', function(request, response){
let id = request.params.id;
deleteUser(id);
response.json({});
});
/*
Move user a place up in the queue
*/
app.put('/queue/up/:id', function(request, response){
let id = request.params.id;
for (index in queue) {
if (queue[index].id === id) {
if (index == 0) {
break;
} else {
let user = queue[index];
// remove from queue
queue.splice(index,1);
// add back to queue
queue.splice(index-1, 0, user);
}
}
}
response.json(queue);
});
/*
Move user to the top of the queue
*/
app.put('/queue/top/:id', function(request, response){
let id = request.params.id;
for (index in queue) {
if (queue[index].id === id) {
if (index == 0) {
break;
} else {
let user = queue[index];
// remove from queue
queue.splice(index,1);
// add back to queue
queue.splice(0, 0, user);
}
}
}
response.json(queue);
});
/*
Move user down in queue
*/
app.put('/queue/down/:id', function(request, response){
let id = request.params.id;
for (index in queue) {
if (queue[index].id === id) {
if (index == queue.length-1) {
break;
} else {
let user = queue[index];
// remove from queue
queue.splice(index,1);
// add back to queue
queue.splice(index+1, 0, user);
}
}
}
response.json(queue);
});
/*
Get first user that has not been notified from queue queue and notify
*/
app.put('/queue/notify', function(request, response){
// find first user without notification time
let user = {};
for (index in queue) {
if (queue[index].notificationTime === undefined) {
user = queue[index];
notifyUser(user);
}
}
response.json(queue);
});
/****************************************************************************
* M E T H O D S
*****************************************************************************/
/*
Send a request for a monitor, returns true if available and false if queued
*/
function requestMonitor(user) {
user.registrationTime = new Date();
queue.push(user);
if (queue.length-1 < numberOfMonitors) {
startTimerUser(user);
return true;
}
return false;
}
/*
Removes the user properly, both the timeout of the notification and from the queue
*/
function deleteUser(id) {
// removing timeout in case we have it
if (notificationTimers[id]) {
clearTimeout(notificationTimers[id]);
delete notificationTimers[id];
}
for (index in queue) {
if (queue[index].id === id) {
queue.splice(index,1);
break;
}
}
}
/*
Starts the timer for the user to get to the monitor. sets the end time on the user objectp
*/
function startTimerUser(user) {
let endTime = new Date();
user.notificationTime = new Date(endTime.setMinutes(endTime.getMinutes() + 5));
let timeout = setTimeout(timeOutDelete, notificationTimeoutInMinutes * 60 * 1000, user.id);
notificationTimers[user.id] = timeout;
}
/*
// TODO - use for push notification
*/
function notifyUser(user) {
startTimerUser(user);
console.log('notifying user ' + JSON.stringify(user) + '...')
}
/*
Callback from the timeout
*/
function timeOutDelete(id) {
deleteUser(id);
}
/*
Get the user from the queue by ID
*/
function getFromQueueByID(id) {
for (index in queue) {
if (queue[index].id === id) {
return queue[index];
}
}
return null;
}
|
JavaScript
| 0 |
@@ -5020,32 +5020,48 @@
tifyUser(user);%0A
+%09 break;%0A
%7D%0A %7D%0A
|
c817baab9eb7a7da76c5743b7f2c4c249d5396fa
|
add usage of react-router
|
app/app.js
|
app/app.js
|
/**
* Main entrance of the app.
**/
import React from 'react'
import ReactDOM from 'react-dom'
const App = ({ title = 'Hello, World!' }) => (
<div>{title}</div>
)
App.propTypes = {
title: React.PropTypes.string,
}
ReactDOM.render(<App title="Hello from Pyssion in AnYang, again!" />, document.getElementById('app'))
|
JavaScript
| 0.000001 |
@@ -88,16 +88,77 @@
act-dom'
+%0Aimport %7B Router, Route, browserHistory %7D from 'react-router'
%0A%0Aconst
@@ -280,76 +280,143 @@
%0A%7D%0A%0A
-ReactDOM.render(%3CApp title=%22Hello from Pyssion in AnYang, again!%22 /%3E
+const AppRouter = (%0A %3CRouter history=%7BbrowserHistory%7D%3E%0A %3CRoute path=%22/%22 component=%7BApp%7D /%3E%0A %3C/Router%3E%0A)%0A%0AReactDOM.render(AppRouter
, do
@@ -445,8 +445,9 @@
'app'))%0A
+%0A
|
df82e186753ce4552d99e1f96bcb54579f2ae3ab
|
make regexes case insenitive
|
app/app.js
|
app/app.js
|
'use strict';
const TelegramBot = require('node-telegram-bot-api');
const bot_api_token = process.env.BOT_API_TOKEN;
const tgBot = new TelegramBot(bot_api_token, { polling: true });
const CronJob = require('cron').CronJob;
const Parser = require('./SVPageParser');
const Subscriptions = require('./subscriptions');
/* Daily cronjob to notify subscribers*/
try {
new CronJob('00 10 * * 1-5', function () {
console.log('Cron job started');
notifySubscribers();
}, null, true,'Europe/Zurich');
} catch(ex) {
console.log("cron pattern not valid");
}
/* Routes */
tgBot.onText(/\/get(Today)?$/mg,getTodayHandler);
tgBot.onText(/\/getDaily/,getDailyHandler);
tgBot.onText(/\/getPartTime/,getPartTimeHandler);
tgBot.onText(/\/start/,startHandler);
tgBot.onText(/\/stop/,cancelSubscriptionsHandler);
tgBot.onText(/\/cancel/,cancelSubscriptionsHandler);
tgBot.onText(/\/(get)?source/mg,getSourceHandler);
/* Handlers */
function sendTodaysMenu(chatId) {
const url = 'http://siemens.sv-restaurant.ch/de/menuplan.html';
const parser = new Parser();
parser.parse(url, function (markdownText) {
tgBot.sendMessage(chatId, markdownText, {parse_mode: 'Markdown'});
});
}
function getTodayHandler(message) {
let chatId = message.chat.id;
sendTodaysMenu(chatId);
}
function getDailyHandler(message) {
let chat = message.chat;
let chatId = message.chat.id;
const subscriptions = new Subscriptions();
subscriptions.add(chat,function () {
let markdownText = "*Successfully added you to the daily subscriber list* \n" +
"I will send you the menu at 10:00am from now on. \n" +
"You can send me /stop to quit that.";
tgBot.sendMessage(chatId,markdownText,{ parse_mode: 'Markdown'});
});
}
function getPartTimeHandler(message) {
let chatId = message.chat.id;
let markdownText = "This feature is not implemented yet.";
tgBot.sendMessage(chatId,markdownText,{ parse_mode: 'Markdown'});
}
function cancelSubscriptionsHandler(message) {
let chat = message.chat;
let chatId = message.chat.id;
const subscriptions = new Subscriptions();
subscriptions.remove(chat,function () {
let markdownText = "*Successfully removed you from the daily subscriber list* \n" +
"I will no longer bother you with daily updates.";
tgBot.sendMessage(chatId,markdownText,{ parse_mode: 'Markdown'});
});
}
function startHandler(message) {
let chatId = message.chat.id;
var markdownText = 'Hello! \n' +
'I can send you the menu for the SV restaurant in Zug. \n' +
'try /get or /getDaily (for daily updates)';
tgBot.sendMessage(chatId,markdownText,{ parse_mode: 'Markdown'});
}
function notifySubscribers() {
var subscriptions = new Subscriptions();
console.log("notify Subscribers called");
subscriptions.forAll(function (subscriber) {
sendTodaysMenu(subscriber.id);
});
}
function getSourceHandler(message){
let chatId = message.chat.id;
let markdownText = 'This bot is written by Fabio Zuber utilizing Node.js.\n' +
'The code is open source. Feel free to check it out on [GitHub](https://github.com/Sirius-A/sv-restaurant-zug-bot).';
tgBot.sendMessage(chatId,markdownText,{ parse_mode: 'Markdown'});
}
|
JavaScript
| 0.001567 |
@@ -615,16 +615,17 @@
ay)?$/mg
+i
,getToda
@@ -660,16 +660,17 @@
etDaily/
+i
,getDail
@@ -708,16 +708,17 @@
artTime/
+i
,getPart
@@ -753,16 +753,17 @@
%5C/start/
+i
,startHa
@@ -791,16 +791,17 @@
/%5C/stop/
+i
,cancelS
@@ -845,16 +845,17 @@
/cancel/
+i
,cancelS
@@ -907,16 +907,17 @@
ource/mg
+i
,getSour
|
9077d08fee6f80fd1ebb4bcb470aeefbdba4aaf4
|
fix bug in expire delete job
|
app/app.js
|
app/app.js
|
// Module dependencies
var express = require('express');
var strftime = require('strftime');
var _ = require('underscore');
var path = require('path');
var http = require('http');
var util = require('util');
// Internal modules
var routes = require('./routes');
var api = require('./routes/api');
var mid = require('./middlewares.js');
var store = require('./lib/store.js');
var tcpsrv = require('./lib/tcpsrv.js');
var ConnectStore = require('./lib/connect-store.js')(express);
// Initialisation of express
var app = express();
// Configuration
var public_path = path.join(__dirname, './public');
var config = require('../config.json');
var brush = require('../brush.json');
app.configure(function () {
// Setup view tempates
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.locals.pretty = true;
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
store: new ConnectStore,
secret: config.session.secret,
cookie: { maxAge: config.session.maxAge }
}));
app.use(express.static(public_path));
// compile the less stylesheet to a css
app.use(require('less-middleware')({ src: public_path }));
// show awesome error messages
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
// setup locals / view/request helpers
app.use(function (req, res, next) {
res.locals.domain = req.headers.host;
res.locals.url = function (args, hash) {
var url = req.protocol + '://' + req.headers.host + '/' + args.join('/');
if (typeof hash != 'undefined' && hash != null && hash != '') {
url += '#' + hash;
}
if (url.charAt(0) != '/' && url.indexOf('http') !== 0)
url = '/' + url;
return url;
};
res.locals.config = config;
res.locals.brush = brush;
res.locals.strftime = strftime;
res.locals.session = req.session;
// set session default values:
_.defaults(req.session, config.session.defaults);
next();
});
});
// sets a timer to delete expired pastes every 5 minutes
setInterval(function () {
console.log('delete expired pastes');
Paste.deleteExpired(function (err) {
if (err != null) console.error(err);
});
}, 15 * 60 * 1000);
// setup routes
app.get ('/' , routes.index);
app.get ('/list' , routes.list);
app.get ('/create' , routes.createPasteForm);
app.post('/create' , routes.createPaste);
app.get ('/:id.:format?/:file?', routes.readPaste);
app.get ('/update/:id/:secret' , routes.updatePasteForm);
app.post('/update' , routes.updatePaste);
app.get ('/delete/:id/:secret' , routes.deletePasteForm);
app.post('/delete' , routes.deletePaste);
app.post('/settings' , routes.settings);
app.get ('/about' , routes.about);
// setup REST API routes
app.get ('/api/1/paste' , api.list);
app.get ('/api/1/paste/:id' , api.readPaste);
app.post('/api/1/paste' , api.createPaste);
app.put ('/api/1/paste/:id' , api.updatePaste);
app.delete('/api/1/paste/:id' , api.deletePaste);
app.get ('*' , routes.notFound);
// Error messages all redirect to create
app.use(function (err, req, res, next) {
console.log('\n');
console.log('AN ERROR OCCURED :: ' + req.ip + ' :: ' + req.originalUrl);
console.log(' ========================================================= ');
console.log(err.stack);
console.log('\n');
res.render('create', {notice: err});
});
// start the express server
http.createServer(app).listen(config.server.port, config.server.bind, function() {
console.log('Express server listening on port ' + config.server.port);
});
// start the TCP server, for netcat/telnet posting;)
tcpsrv.create();
|
JavaScript
| 0 |
@@ -473,24 +473,73 @@
(express);%0A%0A
+var Paste = require('./models/paste.js').Paste;%0A%0A
// Initialis
|
f0a6476cf8c086a3d9d4dbbeef289cd05f2f3dcd
|
Update app.js
|
app/app.js
|
app/app.js
|
(function () {
'use strict';
angular
.module('DeezerKids', [
// Angular modules.
'ngRoute',
'ngCookies',
'ngAnimate',
'ngMaterial',
'ngMessages'
])
.config(config)
.run(run);
config.$inject = ['$routeProvider', '$locationProvider', '$mdDateLocaleProvider', '$mdThemingProvider'];
function config($routeProvider, $locationProvider, $mdDateLocaleProvider, $mdThemingProvider) {
$routeProvider.otherwise({
redirectTo: '/startup'
});
$mdDateLocaleProvider.months = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
$mdDateLocaleProvider.shortMonths = ['Jan', 'Feb', 'Mrz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'];
$mdDateLocaleProvider.days = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
$mdDateLocaleProvider.shortDays = ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'];
// Can change week display to start on Monday.
$mdDateLocaleProvider.firstDayOfWeek = 1;
// Example uses moment.js to parse and format dates.
$mdDateLocaleProvider.parseDate = function (dateString) {
var m = moment(dateString, 'DD.MM.YYYY', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
$mdDateLocaleProvider.formatDate = function (date) {
return moment(date).format('DD.MM.YYYY');
};
$mdDateLocaleProvider.monthHeaderFormatter = function (date) {
return $mdDateLocaleProvider.shortMonths[date.getMonth()] + ' ' + date.getFullYear();
};
// In addition to date display, date components also need localized messages
// for aria-labels for screen-reader users.
$mdDateLocaleProvider.weekNumberFormatter = function (weekNumber) {
return 'Woche ' + weekNumber;
};
$mdDateLocaleProvider.msgCalendar = 'Kalender';
$mdDateLocaleProvider.msgOpenCalendar = 'Kalender öffnen';
$mdThemingProvider
.theme('default')
.primaryPalette('green')
.accentPalette('blue-grey');
}
run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];
function run($rootScope, $location, $cookieStore, $http) {
// keep user logged in after page refresh
$rootScope.globals = $cookieStore.get('globals') || {};
$rootScope.$on('$locationChangeStart', function (event, next, current) {
// redirect to startup procedure if no mode is set
var restrictedPage = $.inArray($location.path(), ['/startup']) === -1;
//var mode = false;
var mode = $rootScope.globals.mode;
if (restrictedPage && !mode) {
$location.path('/startup');
}
});
}
})();
|
JavaScript
| 0.000002 |
@@ -388,16 +388,30 @@
rovider'
+, '$rootScope'
%5D;%0A%0A
@@ -502,16 +502,28 @@
Provider
+, $rootScope
) %7B%0A
@@ -2292,22 +2292,63 @@
grey');%0A
+ %0A $rootScope.mode = null;%0A
%7D%0A
-
%0A run
@@ -2526,32 +2526,34 @@
refresh%0A
+//
$rootScope.globa
@@ -2832,40 +2832,8 @@
-1;%0A
- //var mode = false;%0A
@@ -2866,16 +2866,8 @@
ope.
-globals.
mode
@@ -2906,13 +2906,20 @@
&&
-!
mode
+ == null
) %7B%0A
|
e0f9b1c4d04221f9df132507a129e53f4007ae93
|
Use broadcast for parent-children communication
|
app/app.js
|
app/app.js
|
'use strict';
var errorSound = "http://www.soundjay.com/button/sounds/button-10.mp3";
var startSound = "http://www.soundjay.com/misc/bell-ringing-05.mp3";
var victoryCount = 3;
var victorySeq = [3, 1, 0, 2, 3, 1, 0, 2];
// n: number, z: 0
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 isPrefix(a, b) {
var p = b.slice(0, a.length);
var isSame = (a.length == p.length) && a.every(function(element, index) {
return element === p[index];
});
return isSame;
}
function genSeq(len, min, max) {
var seq = [];
for (var i = 0; i < len; i++) {
seq.push(Math.floor(Math.random() * max));
}
return seq;
}
function sleepPromise(ms) {
return new Promise(function(resolve) {
setTimeout(resolve, ms);
});
}
function playSoundPromise(url) {
return new Promise(function(resolve, reject) {
var audio = new Audio();
audio.preload = "auto";
audio.autoplay = true;
audio.onerror = reject;
audio.onended = resolve;
audio.src = url
});
}
var quad = Vue.extend({
template: '#quad-template',
props: ['qid', 'soundUrl'],
data: function() {
return {
lightened: false,
}
},
methods: {
play: function() {
this.lighten().then(this.darken);
this.$dispatch('quad-played', this.qid);
},
lighten: function() {
this.lightened = true
this.$parent.countDisplay = pad(this.$parent.count, 2);
return playSoundPromise(this.soundUrl);
},
darken: function() {
this.lightened = false
}
}
});
var main = new Vue({
el: '#main',
data: {
'isStrict': false,
'isOn': false,
'count': 0,
'latency': 500,
'countDisplay': '--',
'blink': false,
'showedSeq': [],
'playedSeq': [],
'generatedSeq': [],
'quads': []
},
components: {
'quad': quad
},
methods: {
showSeq: function() {
console.log("showSeq");
var sequence = Promise.resolve();
for (var i = 0; i < this.generatedSeq.length; i++) {
var child = this.quads[this.generatedSeq[i]];
sequence = sequence.then(sleepPromise.bind(null, this.latency))
.then(child.lighten)
.then(child.darken)
.then(function(showedSeq, qid) {
showedSeq.push(qid);
}.bind(null, this.showedSeq, child.qid));
}
return sequence;
},
nextSeq: function() {
console.log("nextSeq");
if (this.isOn) {
this.count ++;
this.countDisplay = pad(this.count, 2);
this.showedSeq = [];
this.playedSeq = [];
this.generatedSeq = genSeq(this.count, 0, this.quads.length);
return this.showSeq();
}
},
toggleStrict: function() {
if (this.isOn) {
this.isStrict = !this.isStrict;
}
},
reset: function() {
this.count = 0;
this.countDisplay = '--';
this.showedSeq = [];
this.playedSeq = [];
this.generatedSeq = [];
this.blink = false;
this.latency = 500;
this.quads = this.$children.sort(function(a, b){
return a.qid - b.qid;
})
},
start: function() {
if (this.isOn) {
this.reset();
playSoundPromise(startSound).then(this.nextSeq);
}
},
toggleOn: function() {
this.reset();
this.isStrict = false;
this.isOn = !this.isOn;
},
quadPlayed: function(qid) {
if (this.isOn) {
this.playedSeq.push(qid);
// check array contains
console.log(this.playedSeq);
if (isPrefix(this.playedSeq, this.showedSeq)) {
if (this.playedSeq.length === this.showedSeq.length) {
if (this.count === victoryCount) {
this.generatedSeq = victorySeq;
this.blink = true;
this.latency = 0;
sleepPromise(500)
.then(this.showSeq)
.then(sleepPromise.bind(null, 3000))
.then(this.start);
} else {
sleepPromise(2000).then(this.nextSeq);
}
}
} else {
console.log("Error!");
var that = this;
this.blink = true;
this.playedSeq = [];
this.showedSeq = [];
this.countDisplay = '!!';
sleepPromise(300)
.then(playSoundPromise.bind(null, errorSound))
.then(sleepPromise.bind(null, 2000))
.then(function(){
that.blink = false;
if (that.isStrict) {
that.start();
} else {
that.showSeq();
}
});
}
}
}
}
});
|
JavaScript
| 0.000001 |
@@ -1293,32 +1293,59 @@
ghtened: false,%0A
+ enabled: true,%0A
%7D%0A %7D,
@@ -1334,24 +1334,24 @@
,%0A %7D%0A
-
%7D,%0A m
@@ -1379,32 +1379,68 @@
y: function() %7B%0A
+ if (this.enabled) %7B%0A
this
@@ -1469,16 +1469,20 @@
arken);%0A
+
@@ -1522,24 +1522,38 @@
this.qid);%0A
+ %7D%0A
%7D,%0A
@@ -1812,32 +1812,214 @@
false%0A %7D%0A
+ %7D,%0A events: %7B%0A 'disable-quad': function() %7B%0A this.enabled = false;%0A %7D,%0A 'enable-quad': function() %7B%0A this.enabled = true;%0A %7D%0A
%7D%0A%7D);%0A%0Avar m
@@ -2439,24 +2439,69 @@
%22showSeq%22);%0A
+ this.$broadcast('disable-quad');%0A
@@ -2968,32 +2968,32 @@
;%0A %7D%0A
-
retu
@@ -3003,16 +3003,64 @@
sequence
+.then(this.$broadcast.bind(this, 'enable-quad'))
;%0A
|
2c6089e70f0ed76b42a6c17f03d46d72e5674cc3
|
Edit config for editor
|
app/app.js
|
app/app.js
|
var editor = ace.edit("game-rb-editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/ruby");
editor.getSession().setTabSize(2);
editor.getSession().setUseSoftTabs(true);
var toggleConnectionStatus = function(display) {
var connStatus = document.getElementById('conn-status');
connStatus.innerHTML = display;
};
var addToTerminal = function(value, type) {
var classes = 'outputs outputs-' + type;
value = value.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\n/g, '<br>');
terminalOutputs.innerHTML += '<p class="' + classes + '">' + value + '</p>';
terminalInput.scrollIntoView();
};
var handleterminalInput = function(event) {
var key = event.which || event.keyCode;
if (key == 13) {
event.preventDefault();
socket.emit('terminalInput', { input: terminalInput.value });
addToTerminal(terminalInput.value, 'input');
terminalInput.value = '';
}
};
var handleFileRun = function() {
var currentFileContent = editor.getValue();
socket.emit('fileInput', { input: currentFileContent });
addToTerminal('Running game...', 'input');
};
var socket = io('http://localhost:8888/ruby'),
terminal = document.getElementById('terminal'),
terminalOutputs = document.getElementById('terminal-outputs'),
terminalInput = document.getElementById('terminal-input'),
sourceActionSave = document.getElementById('source-action-save'),
sourceActionRun = document.getElementById('source-action-run');
terminal.addEventListener('click', function(e) { terminalInput.focus() }, false);
sourceActionSave.addEventListener('click', function(e) { alert('Files saved!') }, false );
sourceActionRun.addEventListener('click', handleFileRun, false);
socket.on('connect', function() {
toggleConnectionStatus('<span class="success">Server Connected</span>');
terminalInput.addEventListener('keypress', handleterminalInput, false);
});
socket.on('disconnect', function() {
toggleConnectionStatus('<span class="warning">Server Disconnected</span>');
terminalInput.removeEventListener('keypress', handleterminalInput, false);
});
socket.on('ready', function(data) {
window.console.log(data);
addToTerminal(data.output, 'welcome');
handleFileRun();
});
socket.on('terminalOutput', function(data) {
window.console.log(data);
addToTerminal(data.output, 'output');
});
|
JavaScript
| 0.000003 |
@@ -68,24 +68,68 @@
/monokai%22);%0A
+editor.getSession().setFoldStyle('manual');%0A
editor.getSe
@@ -238,16 +238,156 @@
s(true);
+%0Aeditor.setDisplayIndentGuides(true);%0Aeditor.setHighlightActiveLine(true);%0Aeditor.setShowPrintMargin(false);%0Aeditor.setShowInvisibles(true);
%0A%0Avar to
|
b6c1f6ff66967ac1f7384b9b4987f139ccbd8903
|
Improve react example
|
examples/react/src/airbrake.js
|
examples/react/src/airbrake.js
|
import React, { Component } from 'react';
import AirbrakeClient from 'airbrake-js';
let airbrakeClient;
export function notify(err) {
if (!airbrakeClient) {
airbrakeClient = new AirbrakeClient({
projectId: 1,
projectKey: 'FIXME'
});
}
airbrakeClient.notify(err);
}
export default class AirbrakeComponent extends Component {
render() {
try {
return this.unsafeRender();
} catch (err) {
notify(err);
return <p>{String(err)}</p>;
}
}
unsafeRender() {
throw new Error('Abstract method unsafeRender not implemented');
}
}
|
JavaScript
| 0.000006 |
@@ -283,16 +283,84 @@
ify(err)
+.catch(function(err) %7B%0A console.warn('notify failed:', err);%0A %7D)
;%0A%7D%0A%0Aexp
|
327763cc82d367d07d154fc2d7a55e5052d2e859
|
Add stars to example
|
examples/symbol-atlas-webgl.js
|
examples/symbol-atlas-webgl.js
|
goog.require('ol.Feature');
goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.geom.Point');
goog.require('ol.layer.Vector');
goog.require('ol.source.Vector');
goog.require('ol.style.AtlasManager');
goog.require('ol.style.Circle');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
goog.require('ol.style.Style');
var atlasManager = new ol.style.AtlasManager({
maxSize: ol.has.WEBGL_MAX_TEXTURE_SIZE});
var symbolInfo = [{
opacity: 1.0,
scale: 1.0,
fillColor: 'rgba(255, 153, 0, 0.4)',
strokeColor: 'rgba(255, 204, 0, 0.2)'
}, {
opacity: 0.75,
scale: 1.25,
fillColor: 'rgba(70, 80, 224, 0.4)',
strokeColor: 'rgba(12, 21, 138, 0.2)'
}, {
opacity: 0.5,
scale: 1.5,
fillColor: 'rgba(66, 150, 79, 0.4)',
strokeColor: 'rgba(20, 99, 32, 0.2)'
}, {
opacity: 1.0,
scale: 1.0,
fillColor: 'rgba(176, 61, 35, 0.4)',
strokeColor: 'rgba(145, 43, 20, 0.2)'
}];
var radiuses = [3, 6, 9, 15, 19, 25];
var symbolCount = symbolInfo.length * radiuses.length;
var symbols = [];
var i, j;
for (i = 0; i < symbolInfo.length; ++i) {
var info = symbolInfo[i];
for (j = 0; j < radiuses.length; ++j) {
symbols.push(new ol.style.Circle({
opacity: info.opacity,
scale: info.scale,
radius: radiuses[j],
fill: new ol.style.Fill({
color: info.fillColor
}),
stroke: new ol.style.Stroke({
color: info.strokeColor,
width: 1
}),
// by passing the atlas manager to the symbol,
// the symbol will be added to an atlas
atlasManager: atlasManager
}));
}
}
var featureCount = 30000;
var features = new Array(featureCount);
var feature, geometry;
var e = 25000000;
for (i = 0; i < featureCount; ++i) {
geometry = new ol.geom.Point(
[2 * e * Math.random() - e, 2 * e * Math.random() - e]);
feature = new ol.Feature(geometry);
feature.setStyle(
new ol.style.Style({
image: symbols[i % (symbolCount - 1)]
})
);
features[i] = feature;
}
var vectorSource = new ol.source.Vector({
features: features
});
var vector = new ol.layer.Vector({
source: vectorSource
});
// Use the "webgl" renderer by default.
var renderer = exampleNS.getRendererFromQueryString();
if (!renderer) {
renderer = 'webgl';
}
var map = new ol.Map({
renderer: renderer,
layers: [vector],
target: document.getElementById('map'),
view: new ol.View({
center: [0, 0],
zoom: 3
})
});
|
JavaScript
| 0.000036 |
@@ -267,24 +267,63 @@
yle.Fill');%0A
+goog.require('ol.style.RegularShape');%0A
goog.require
@@ -339,24 +339,24 @@
e.Stroke');%0A
-
goog.require
@@ -423,16 +423,118 @@
nager(%7B%0A
+ // we increase the default size so that all symbols fit into%0A // a single atlas image%0A size: 512,%0A
maxSiz
@@ -1138,16 +1138,20 @@
s.length
+ * 2
;%0Avar sy
@@ -1284,16 +1284,37 @@
++j) %7B%0A
+ // circle symbol%0A
symb
@@ -1733,16 +1733,441 @@
%7D));
+%0A%0A // star symbol%0A symbols.push(new ol.style.RegularShape(%7B%0A points: 8,%0A opacity: info.opacity,%0A scale: info.scale,%0A radius: radiuses%5Bj%5D,%0A radius2: radiuses%5Bj%5D * 0.7,%0A angle: 1.4,%0A fill: new ol.style.Fill(%7B%0A color: info.fillColor%0A %7D),%0A stroke: new ol.style.Stroke(%7B%0A color: info.strokeColor,%0A width: 1%0A %7D),%0A atlasManager: atlasManager%0A %7D));
%0A %7D%0A%7D%0A%0A
@@ -3004,17 +3004,17 @@
zoom:
-3
+4
%0A %7D)%0A%7D)
|
3691087d5e2f08a3da6e0eba35353edc65b36fa4
|
Add lint config to add-domains script
|
scripts/add-domains.js
|
scripts/add-domains.js
|
#!/usr/bin/env node
if (process.argv.includes('--help') || process.argv.includes('-h')) {
console.info(`Usage: ${__filename.slice(__dirname.length + 1)} [-h|--help] [--dry]`);
process.exit(0);
}
const isDry = process.argv.includes('--dry');
const fs = require('fs');
process.env.ENABLE_PROVIDER_DOMAINS = 'true';
const config = require('../config/environment')(process.env.EMBER_ENV);
const {providers} = config.PREPRINTS;
const hostsFileName = '/etc/hosts';
const hostIP = '127.0.0.1';
const hostsFile = fs.readFileSync(hostsFileName, {encoding: 'utf8'});
const sectionHeader = '## EMBER-PREPRINTS ##\n';
const sectionFooter = '\n## /EMBER-PREPRINTS ##';
const rgx = new RegExp(`(?:${sectionHeader})(.|\\s)*(?:${sectionFooter})`, 'm');
const domainProviders = providers
.slice(1)
.filter(provider => provider.domain)
.map(provider => {
provider.domain = provider.domain.replace(/:.*$/, '');
return provider;
});
const maxLength = domainProviders
.map(provider => provider.domain.length)
.reduce((acc, val) => acc < val ? val : acc, 0);
const lines = domainProviders
.map(provider => `${hostIP}\t${provider.domain}${' '.repeat(maxLength - provider.domain.length)}\t# ${provider.id}`)
.join('\n');
const section = `${sectionHeader}${lines}${sectionFooter}`;
const resultFile = rgx.test(hostsFile) ? hostsFile.replace(rgx, section) : `${hostsFile}\n\n${section}`;
console.info(`Resulting file:\n${resultFile}`);
if (isDry) {
console.log('!!! DRY RUN, File not written !!!');
process.exit(0);
}
fs.writeFileSync(hostsFileName, resultFile, {encoding: 'utf8'});
|
JavaScript
| 0.000001 |
@@ -14,16 +14,103 @@
v node%0A%0A
+/* eslint-env node */%0A/* eslint no-console: %5B%22error%22, %7B allow: %5B%22info%22, %22warn%22%5D %7D%5D */%0A%0A
if (proc
@@ -1585,11 +1585,12 @@
ole.
-log
+warn
('!!
|
4fa616a0646b11c883d460b06b80bae2fd1d3984
|
change scatter backplane acrosss to use ciecam02
|
imports/3d/drawBackplane.js
|
imports/3d/drawBackplane.js
|
import THREE from 'three';
import { _ } from 'meteor/underscore';
import * as d3scale from 'd3-scale';
import * as d3shape from 'd3-shape';
import * as d3color from 'd3-color';
const d3 = { ...d3scale, ...d3color, ...d3shape };
export function drawBackplane(ctx, options) {
const defaults = {
textColor: d3.hcl(0, 0, 100),
fontSize: 20,
fontFace: 'Arial',
};
const props = { ...defaults, ...options };
ctx.font = `${props.fontSize}px ${props.fontFace}`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const xScale = d3.scaleLinear().domain([0, 360]).range([0, ctx.canvas.width]);
const yScale = d3.scaleLinear().domain([0, 100]).range([0, ctx.canvas.height]);
const nh = 24;
const nv = 10;
const dh = 360 / nh;
const dv = 100 / nv;
_.each(_.range(0, 360, dh), h => {
_.each(_.range(-5, 100, dv), v => {
// Fill each tile
const dvh = (h / dh) % 2;
const dvv = ((dv + v) / dv) % 2;
const tileValue = 52 + (dvh ^ dvv) * 4;
ctx.fillStyle = d3.hcl(h, 50, tileValue);
ctx.fillRect(xScale(h), yScale(v), xScale(dh), yScale(dv));
// Horizontal gridlines
_.each(_.range(0, dv, dv/4), t => {
ctx.strokeStyle = d3.hcl(0, 0, tileValue+10);
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(xScale(h), yScale(v + t));
ctx.lineTo(xScale(h + dh), yScale(v + t));
ctx.stroke();
});
// Vertical gridlines
_.each(_.range(0, dh, dh/3), t => {
ctx.strokeStyle = d3.hcl(0, 0, tileValue+10);
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(xScale(h + t), yScale(v));
ctx.lineTo(xScale(h + t), yScale(v + dv));
ctx.stroke();
});
});
// Hue scale (Alphabetic)
ctx.fillStyle = props.textColor;
ctx.fillText(String.fromCharCode(65 + (h / dh)), xScale(h + dh / 2), yScale(dv / 4));
ctx.fillText(String.fromCharCode(65 + (h / dh)), xScale(h + dh / 2), yScale(100 - dv / 4));
});
// Value scale (Numeric)
_.each(_.range(10, 100, dv), v => {
ctx.fillStyle = props.textColor;
ctx.fillText(String.fromCharCode(58 - (v / dv)), xScale(dh / 2), yScale(v));
ctx.fillText(String.fromCharCode(58 - (v / dv)), xScale(360 - dh / 2), yScale(v));
});
// Vertical 90' Gridlines
_.each(_.range(0, 380, 360/4), t => {
ctx.strokeStyle = d3.hcl(0, 0, 70);
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(xScale(t), yScale(0));
ctx.lineTo(xScale(t), yScale(100));
ctx.stroke();
});
// Vertical 90' Hue Angle Labels
// _.each(_.range(0, 380, 360/4), t => {
// ctx.font = `${props.fontSize*3/4}px ${props.fontFace}`;
// ctx.fillStyle = props.textColor;
// ctx.save();
// ctx.translate(xScale(t), yScale(dv / 4));
// ctx.rotate(-Math.PI/2);
// ctx.fillText(t, 0, 0);
// ctx.restore();
// });
return props;
}
export function createBackplaneMaterials(options) {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = 1024;
canvas.height = 1024;
drawBackplane(context, options);
const front = new THREE.CanvasTexture(canvas);
const top = new THREE.CanvasTexture(canvas);
top.repeat = new THREE.Vector2(1, 0.05);
const left = new THREE.CanvasTexture(canvas);
left.repeat = new THREE.Vector2(15 / 360, 1);
const right = new THREE.CanvasTexture(canvas);
right.offset = new THREE.Vector2(345 / 360, 0);
right.repeat = new THREE.Vector2(15 / 360, 1);
const materials = [
new THREE.MeshStandardMaterial({ map: right }),
new THREE.MeshStandardMaterial({ map: left }),
new THREE.MeshStandardMaterial({ map: top }),
new THREE.MeshStandardMaterial({ map: top }),
new THREE.MeshStandardMaterial({ map: front }),
new THREE.MeshStandardMaterial({ map: front }),
];
return new THREE.MultiMaterial(materials);
}
|
JavaScript
| 0 |
@@ -169,16 +169,71 @@
-color';
+%0Aimport %7B ciecam02 %7D from '/imports/color/ciecam02.js';
%0A%0Aconst
@@ -1037,22 +1037,25 @@
e =
-d3.hcl(h, 50,
+ciecam02.jch2rgb(
tile
@@ -1059,16 +1059,23 @@
ileValue
+, 50, h
);%0A%09%09%09ct
@@ -1217,37 +1217,41 @@
rokeStyle =
-d3.hcl(0, 0,
+ciecam02.jch2rgb(
tileValue+10
@@ -1242,34 +1242,39 @@
rgb(tileValue+10
+, 0, 0
)
-;
%0A%09%09%09%09ctx.lineWid
@@ -1503,29 +1503,33 @@
Style =
-d3.hcl(0, 0,
+ciecam02.jch2rgb(
tileValu
@@ -1532,18 +1532,23 @@
Value+10
+, 0, 0
)
-;
%0A%09%09%09%09ctx
|
3f7befd512be3892de3602a7a3714139dfb238b7
|
Fix Elastic smooth effect don't work correctly
|
Animable.js
|
Animable.js
|
/**
* Animable.js
*
* https://github.com/JWhile/Animable.js
*
* version 1.5.2
*
* Animable.js
*/
var anime,stopAnime,smooth;
(function(){ // namespace
// class Animation
function Animation(id, from, to, time, update, smooth)
{
this.id = id; // :int
this.from = from; // :float
this.diff = to - from; // :float
this.start = Date.now(); // :long
this.time = time; // :int
this.update = update; // :function
this.smooth = smooth; // :function
}
// function next(long now):boolean
Animation.prototype.next = function(now)
{
var progression = (now - this.start) / this.time;
if(progression >= 1)
{
this.update(this.diff + this.from);
return true;
}
this.update(this.diff * this.smooth(progression) + this.from);
return false;
};
var lastAnimId = 0; // :int
var animations = []; // :Array<Animation>
var loop = false; // :boolean
// function next():void
var next = function()
{
loop = (animations.length > 0);
if(loop)
{
newFrame(next);
var now = Date.now();
for(var i = 0; i < animations.length; ++i)
{
if(animations[i].next(now))
{
animations.splice(i, 1);
--i;
}
}
}
};
// var smooth:Map<String, function>
smooth = {
// function(float progression):float
'Line': function(progression)
{
return progression;
},
// function(float progression):float
'In': function(progression)
{
return progression * progression;
},
// function(float progression):float
'Out': function(progression)
{
return (progression - 2) * -progression;
},
// function(float progression):float
'InOut': function(progression)
{
return ((progression *= 2) < 1)? 0.5 * progression * progression : -0.5 * (--progression * (progression - 2) - 1);
},
// function(float progression):float
'Elastic': function(progression)
{
return Math.pow(2, -10 * progression) * Math.sin((progression * 0.075) * (Math.PI * 2) / 0.3) + 1;
},
// function(float progression):float
'Bounce': function(progression)
{
progression = 1 - progression;
for(var a = 0, b = 1; true; a += b, b /= 2)
{
if(progression >= ((7 - (4 * a)) / 11))
{
return 1 - (b * b - Math.pow((11 - (6 * a) - (11 * progression)) / 4, 2));
}
}
}
};
// function anime(function update, float from, float to, int time, function userSmooth = null):int
anime = function(update, from, to, time, userSmooth)
{
animations.push(new Animation(++lastAnimId, from, to, time, update, (typeof userSmooth === 'function')? userSmooth : smooth.Line));
if(!loop)
{
newFrame(next);
}
return lastAnimId;
};
// function stopAnime(int id):void
stopAnime = function(id)
{
for(var i = 0; i < animations.length; ++i)
{
if(animations[i].id === id)
{
animations.splice(i, 1);
--i;
}
}
};
if(typeof Builder === 'function')
{
// function anime(String property, int to, int time, function callback = null, function userSmooth = null):@Chainable
Builder.prototype.anime = function(property, to, time, callback, userSmooth)
{
this.stopAnime(''+ property);
var self = this;
var style = Builder.getStyle(this.node, property);
var unit = (style.match(/em$|px$|%$/i) || [''])[0];
this._animations[property] = anime(function(value)
{
if(value === to)
{
delete self._animations[property];
if(callback != null)
{
callback();
}
}
self.node.style[property] = value + unit;
}, parseInt(style), to, time, userSmooth);
return this;
};
// function stopAnime(String property = null):void
Builder.prototype.stopAnime = function(property)
{
this._animations = this._animations || {}; // Map<String, int>
if(typeof property === 'string')
{
if(this._animations[property])
{
stopAnime(this._animations[property]);
delete this._animations[property];
}
}
else
{
for(var key in this._animations)
{
if(this._animations.hasOwnProperty(key))
{
stopAnime(this._animations[key]);
}
}
this._animations = {};
}
};
}
})();
|
JavaScript
| 0.000001 |
@@ -2076,17 +2076,17 @@
ression
-*
+-
0.075)
|
b2b4d7e27c33ef9d2ddf402c2935384a91faf097
|
combine positive filters on the same field before searching
|
scripts/search/search.js
|
scripts/search/search.js
|
'use strict';
/* @flow */
type map = { [key: string]: any };
var Q = require('q');
var _ = require('lodash');
var searchCache = require('./searchInterfaceCache');
var searchInterface = require('gramene-search-client').client;
function checkRequestedResultTypesArePresent(data: map): map {
_.forIn(data.metadata.searchQuery.resultTypes,
function (params, key) {
if (!data[key]) {
console.error(key + ' not found in search results');
}
});
return data;
}
module.exports = {
debounced: function(stateObj: map, searchComplete: Function, searchError: Function, time: number): Function {
var func = function() {
this.search(stateObj, searchComplete, searchError);
}.bind(this);
return _.debounce(func, time);
},
// Note that this function should probably be used via debounced.
// It might be called many times in succession when a user is
// interacting with the page, and then only the last one will fire.
search: function (search: map, searchComplete: Function, searchError: Function): void {
// make a copy of the query state when we make the async call...
var queryCopy = _.cloneDeep(search.query);
console.log('performing search', queryCopy);
// find cached results and move them from
// query.resultTypes to query.cachedResultTypes
searchCache.findCachedResults(queryCopy);
// if we have any uncached result types, we need to
// ask the server for some data, otherwise we will
// just use what we have
var promise;
if(_.size(queryCopy.resultTypes) || !queryCopy.count) {
promise = this.searchPromise(queryCopy)
// when we get data from the server, put it in the
// cache
.then(searchCache.addResultsToCache(queryCopy))
// and also add the query for the actual search
// to the results metadata.
.then(function addQueryToResults(data) {
data.metadata.searchQuery = queryCopy;
return data;
});
}
else {
promise = this.nullSearchPromise(queryCopy);
}
promise
// add any cached data
.then(searchCache.getResultsFromCache)
// console.log for anything we asked for but didn't get
// TODO should we error out here?
.then(checkRequestedResultTypesArePresent)
// tell interested parties about what has happened
.then(searchComplete)
.catch(searchError);
},
searchPromise: function(query: map): Promise {
console.log('asking search interface for', query);
return searchInterface.geneSearch(query);
},
nullSearchPromise: function(query: map): map {
return Q.fcall(function refactorQueryToHaveShapeOfResponse() {
console.log('remote query not required');
var metadata = {searchQuery: query, count: query.count};
return {metadata: metadata};
});
}
};
|
JavaScript
| 0 |
@@ -484,16 +484,610 @@
ata;%0A%7D%0A%0A
+function prepFilters(filters: map): void %7B%0A var newFilters = %7B%7D;%0A var fieldValues = %7B%7D;%0A for (var fq in filters) %7B%0A if (fq.substr(0,1) === '-') %7B%0A newFilters%5Bfq%5D = %7B%7D;%0A %7D%0A else %7B%0A var fv = fq.split(':');%0A var field = fv%5B0%5D;%0A var value = fv%5B1%5D;%0A if (!fieldValues.hasOwnProperty(field)) %7B%0A fieldValues%5Bfield%5D = %5B%5D;%0A %7D%0A fieldValues%5Bfield%5D.push(value);%0A %7D%0A %7D%0A for (var field in fieldValues) %7B%0A newFilters%5Bfield+':'+'('+fieldValues%5Bfield%5D.join(' ')+')'%5D = %7B%7D;%0A %7D%0A console.log('prepFilters',filters,newFilters);%0A return newFilters;%0A%7D%0A%0A
module.e
@@ -1759,24 +1759,118 @@
ch.query);%0A%0A
+ if (queryCopy.filters) %7B%0A queryCopy.filters = prepFilters(queryCopy.filters);%0A %7D%0A%0A
console.
|
9c174bd2fbf86a01f805061083ffe1f4928eb9b5
|
Clean up
|
intents/polling_places.js
|
intents/polling_places.js
|
var utilities = require('../utilities/utilities');
var config = require('../config/config');
exports.respond = function(bot, message, response) {
if(!response.entities.location) {
bot.reply(message, 'You need to specify an address, like this: ```123 some street```');
}
else {
var payload = { address: response.entities.location[0].value };
var url = config.apis.polling_location_url;
utilities.postJson(bot, message, url, settings, payload, buildResonse);
}
}
// Settings for use in rendering user response.
var settings = {};
// Build the response to the user.
function buildResonse(bot, message, settings, error, response, body) {
if(!error && response.statusCode == 200) {
var place = body.features[0].attributes;
bot.reply(message, 'Location: ' + place.location);
bot.reply(message, 'Address: ' + place.display_address);
bot.reply(message, 'Parking: ' + utilities.parkingCodeLookup(place.parking));
bot.reply(message, 'Accessibility: ' + utilities.buildingCodeLookup(place.building));
bot.reply(message, 'Map: https://www.google.com/maps/place/' + encodeURIComponent(place.display_address + ', Philadelphia, PA'));
}
else {
bot.reply(message, 'Sorry, I could not look up polling location for that address.');
}
}
// Look up the description for a building accessibility code.
exports.buildingCodeLookup = function(code) {
return building[code];
}
// Look up the description for a parking code.
exports.parkingCodeLookup = function(code) {
return parking[code];
}
var building = [];
building['F'] = 'Building Fully Accessible';
building['B'] = 'Building Substantially Accessible';
building['M'] = 'Building Accessibilty Modified';
building['A'] = 'Alternate Entrance';
building['R'] = 'Building Accessible With Ramp';
building['N'] = 'Building Not Accessible';
var parking = [];
parking['N'] = 'No Parking';
parking['G'] = 'General Parking';
parking['L'] = 'Loading Zone';
parking['H'] = 'Handicap Parking';
|
JavaScript
| 0.000002 |
@@ -876,26 +876,16 @@
ng: ' +
-utilities.
parkingC
@@ -952,26 +952,16 @@
ty: ' +
-utilities.
building
@@ -1288,24 +1288,16 @@
y code.%0A
-exports.
building
@@ -1401,24 +1401,16 @@
g code.%0A
-exports.
parkingC
|
9e30e7c2f9400018cd3d3e1466d4c09bf18289a7
|
Format code.
|
website/app/application/core/login/login-controller.js
|
website/app/application/core/login/login-controller.js
|
(function(module) {
module.controller('LoginController', LoginController);
LoginController.$inject = ["$state", "User", "toastr",
"mcapi", "pubsub", "model.projects",
"projectFiles", "$anchorScroll", "$location"];
/* @ngInject */
function LoginController($state, User, toastr, mcapi, pubsub, projects, projectFiles, $anchorScroll, $location) {
var ctrl = this;
ctrl.cancel = cancel;
ctrl.gotoID = gotoID;
ctrl.login = login;
////////////////////
function login () {
mcapi('/user/%/apikey', ctrl.email, ctrl.password)
.success(function (u) {
User.setAuthenticated(true, u);
pubsub.send("tags.change");
projects.clear();
projectFiles.clear();
projects.getList().then(function (projects) {
if (projects.length === 0) {
$state.go("projects.create");
} else {
$state.go('projects.project.home', {id: projects[0].id});
}
});
})
.error(function (reason) {
ctrl.message = "Incorrect Password/Username!";
toastr.error(reason.error, 'Error', {
closeButton: true
});
}).put({password: ctrl.password});
}
function cancel() {
$state.transitionTo('home');
}
function gotoID(id) {
// set the location.hash to the id of
// the element you wish to scroll to.
$location.hash(id);
// call $anchorScroll()
$anchorScroll();
}
}
}(angular.module('materialscommons')));
|
JavaScript
| 0.000001 |
@@ -2,16 +2,17 @@
function
+
(module)
@@ -141,20 +141,16 @@
-
%22mcapi%22,
@@ -178,20 +178,16 @@
jects%22,%0A
-
@@ -539,17 +539,16 @@
on login
-
() %7B%0A
|
e42d95d27b06494e2c051ad854075b52d9a7ea6f
|
Add tests for second item selection
|
test/Autocomplete.spec.js
|
test/Autocomplete.spec.js
|
import React from 'react';
import { shallow } from 'enzyme';
import Autocomplete from '../src/Autocomplete';
const data = {
Apple: null,
Microsoft: null,
Google: 'http://placehold.it/250x250',
'Apple Inc': null
};
const componentId = 'testAutocompleteId';
const wrapper = shallow(
<Autocomplete title="Test Title" data={data} id={componentId} />
);
describe('<Autocomplete />', () => {
const typedKey = 'A';
test('renders', () => {
expect(wrapper).toMatchSnapshot();
});
test('generates correct ID for input and label', () => {
expect(wrapper.find('.autocomplete').props()).toHaveProperty(
'id',
componentId
);
expect(wrapper.find('label').props()).toHaveProperty(
'htmlFor',
componentId
);
});
describe('on input change', () => {
beforeAll(() => {
wrapper
.find('.autocomplete')
.simulate('change', { target: { value: typedKey } });
});
test('renders a dropdown', () => {
expect(wrapper.find('.autocomplete-content')).toHaveLength(1);
});
test("highlight's results", () => {
expect(wrapper.find('.highlight').length).toEqual(2);
expect(
wrapper
.find('.highlight')
.first()
.text()
).toEqual(typedKey);
});
});
describe('on dropdown select', () => {
const expectedValue = 'Apple';
beforeAll(() => {
wrapper
.find('.autocomplete')
.simulate('change', { target: { value: typedKey } });
wrapper
.find('ul li')
.first()
.simulate('click');
});
test('updates the state with the new value', () => {
expect(wrapper.state('value')).toEqual(expectedValue);
});
test('adds clicked value to input', () => {
expect(wrapper.find('.autocomplete').prop('value')).toEqual(
expectedValue
);
});
test('hides other matches', () => {
expect(wrapper.find('.highlight').length).toEqual(0);
});
});
describe('on controlled input', () => {
const expectedValue = 'Apple';
const props = {
onChange: jest.fn(),
onAutocomplete: jest.fn()
};
const wrapper2 = shallow(
<Autocomplete title="Test Title" data={data} value="" {...props} />
);
beforeAll(() => {
wrapper2
.find('.autocomplete')
.simulate('change', { target: { value: typedKey } });
});
test('updates the state with the new value', () => {
expect(wrapper2.state('value')).toEqual(typedKey);
});
test('calls only onChange callback', () => {
expect(props.onChange).toHaveBeenCalled();
expect(props.onChange.mock.calls[0][1]).toEqual(typedKey);
});
test('works after value change', () => {
wrapper2.setProps({
...props,
value: typedKey
});
expect(wrapper2.state('value')).toEqual(typedKey);
expect(props.onChange).toHaveBeenCalled();
});
test('adds clicked value to input', () => {
wrapper2
.find('ul li')
.first()
.simulate('click');
expect(wrapper2.find('.autocomplete').prop('value')).toEqual(
expectedValue
);
});
test('calls callbacks after autocomplete', () => {
expect(props.onChange).toHaveBeenCalledTimes(2);
expect(props.onChange.mock.calls[1][1]).toEqual(expectedValue);
expect(props.onAutocomplete).toHaveBeenCalledWith(expectedValue);
});
test('clears input', () => {
wrapper2.setProps({
...props,
value: ''
});
expect(wrapper2.state('value')).toEqual('');
expect(props.onChange).toHaveBeenCalledTimes(2);
expect(props.onAutocomplete).toHaveBeenCalled();
});
});
});
|
JavaScript
| 0 |
@@ -1314,16 +1314,27 @@
ropdown
+first item
select',
@@ -1987,32 +1987,741 @@
%0A %7D);%0A %7D);%0A%0A
+ describe('on dropdown second item select', () =%3E %7B%0A const expectedValue = 'Apple Inc';%0A%0A beforeAll(() =%3E %7B%0A wrapper%0A .find('.autocomplete')%0A .simulate('change', %7B target: %7B value: typedKey %7D %7D);%0A wrapper%0A .find('ul li')%0A .last()%0A .simulate('click');%0A %7D);%0A%0A test('updates the state with the new value', () =%3E %7B%0A expect(wrapper.state('value')).toEqual(expectedValue);%0A %7D);%0A%0A test('adds clicked value to input', () =%3E %7B%0A expect(wrapper.find('.autocomplete').prop('value')).toEqual(%0A expectedValue%0A );%0A %7D);%0A%0A test('hides other matches', () =%3E %7B%0A expect(wrapper.find('.highlight').length).toEqual(0);%0A %7D);%0A %7D);%0A%0A
describe('on c
|
38f6999e1305cff96b9edae0d826d5f37ed4501a
|
Add newcontact controller
|
client/js/controllers.js
|
client/js/controllers.js
|
var curemControllers = angular.module('curemControllers', ['ngResource', 'ngRoute']);
curemControllers.factory('contactFactory', ['$resource', function($resource) {
return $resource(
'http://localhost:3000/contacts/:slug',
{slug: '@slug'},
{
'update': { method:'PATCH' }
}
);
}]);
curemControllers.controller('contactsController', ['$scope', 'contactFactory', function ($scope, contactFactory) {
$scope.contacts = contactFactory.query();
$scope.orderProp = '-updatedAt';
console.log($scope.contacts)
}]);
curemControllers.controller('contactDetailController', ['$scope','$routeParams','contactFactory', function ($scope, $routeParams, contactFactory) {
$scope.slug = $routeParams.slug;
contactFactory.get({slug:$routeParams.slug})
.$promise.then(function(contact) {
$scope.contact = contact
});
}]);
/*
Stub for newContactController
*/
curemControllers.controller('newContactController',['$scope', function($scope) {
}]);
curemControllers.factory('leadFactory', ['$resource', function($resource) {
return $resource(
'http://localhost:3000/leads/:id',
{id: '@id'},
{
'update': {method: 'PATCH'}
}
);
}]);
curemControllers.controller('leadsController', ['$scope', 'leadFactory', function ($scope, leadFactory) {
$scope.leads = leadFactory.query();
console.log($scope.leads)
}]);
|
JavaScript
| 0 |
@@ -866,46 +866,8 @@
);%0A%0A
-/*%0A Stub for newContactController%0A*/%0A
cure
@@ -927,27 +927,193 @@
pe',
- function($scope) %7B
+'$location','contactFactory', function($scope, $location, contactFactory) %7B%0A $scope.createNewContact = function() %7B%0A%09contactFactory.save($scope.contact);%0A%09$location.path('/');%0A %7D;
%0A%7D%5D)
|
11d3bc72cfe3350045e88960fd53a57140d338fa
|
move and zoom map according to locations of results
|
src/components/map-container/MapContainer.js
|
src/components/map-container/MapContainer.js
|
import React, { Component } from 'react';
import axios from 'axios'
import GoogleMapReact from 'google-map-react';
import './MapContainer.css'
class MapContainer extends Component {
constructor(props) {
super(props)
this.state = {
lat: -37.9722342,
lon: 144.7729551,
results: null
}
this.getUserLocation = this.getUserLocation.bind(this)
this.getResults = this.getResults.bind(this)
this.makeSearchRequest = this.makeSearchRequest.bind(this)
// this.getUserLocation()
}
getUserLocation() {
global.getUserLocation((data) => {
const lat = data.latitude
const lon = data.longitude
this.setState({
lat: lat,
lon: lon
})
})
}
getResults(e) {
if (e.key === 'Enter') {
const postcode = e.target.value
console.log(`${postcode} entered`)
this.makeSearchRequest(postcode)
}
}
makeSearchRequest(postcode) {
var baseUrl = 'https://api.serviceseeker.com.au'
var endpoint = '/api/v3/search'
var url = baseUrl + endpoint
var config = {
url: url,
method: 'get',
params: {
q: 'GP',
area: postcode
},
auth: {
username: 'FXFDVZVGZOWUEEPJWBOGACIZRYGPGBII',
password: 'WIJOQPFWUOTPBRIPJYTYUFOBRWLUSZQY'
}
}
axios(config)
.then(res => {
console.log(res.data)
this.setState({
results: res.data.objects
})
})
}
render() {
var lat = this.state.lat
var lon = this.state.lon
var results = this.state.results
return (
<div className="sf-map-container">
<div className="sf-map-sidebar">
<div className="sf-map-filters">
<input id="sf-map-input-postcode" type="text" placeholder="Postcode" onKeyPress={this.getResults}/>
</div>
<div className="sf-map-results">
{results && <div>Result</div>}
</div>
</div>
<div className="sf-map-view">
<GoogleMapReact
defaultCenter={{lat: lat, lng: lon}}
defaultZoom={9}>
{results && results.map(result => {
return (
<div className="sf-map-marker"
lat={result.location.point.lat}
lng={result.location.point.lon}
text={result.site.name}
/>
)
})}
</GoogleMapReact>
</div>
</div>
)
}
}
export default MapContainer
|
JavaScript
| 0 |
@@ -221,21 +221,29 @@
%0A%09%09this.
-sta
+defaultCen
te
+r
= %7B%0A%09%09%09
@@ -264,18 +264,18 @@
42,%0A%09%09%09l
-o
n
+g
: 144.77
@@ -283,24 +283,105 @@
9551,%0A%09%09
-%09results
+%7D%0A%09%09this.defaultZoom = 9%0A%09%09this.state = %7B%0A%09%09%09coords: null,%0A%09%09%09results: null,%0A%09%09%09zoomLevel
: null%0A%09
@@ -712,24 +712,39 @@
.setState(%7B%0A
+%09%09%09%09coords: %7B%0A%09
%09%09%09%09lat: lat
@@ -753,17 +753,24 @@
%09%09%09%09
-lon
+%09lng
: lon%0A
+%09%09%09%09%7D%0A
%09%09%09%7D
@@ -1416,22 +1416,195 @@
.objects
-%0A%09%09%09%09%7D
+,%0A%09%09%09%09%09coords: %7B%0A%09%09%09%09%09%09lat: res.data.objects%5B0%5D.location.point.lat,%0A%09%09%09%09%09%09lng: res.data.objects%5B0%5D.location.point.lon,%0A%09%09%09%09%09%7D,%0A%09%09%09%09%09zoomLevel: 15%0A%09%09%09%09%7D)%0A%09%09%09%09console.log(this.state
)%0A%09%09%09%7D)%0A
@@ -1625,19 +1625,22 @@
%7B%0A%09%09var
-lat
+coords
= this.
@@ -1649,21 +1649,30 @@
ate.
-lat
+coords
%0A%09%09var
-lon
+zoomLevel
= t
@@ -1681,19 +1681,25 @@
s.state.
-lon
+zoomLevel
%0A%09%09var r
@@ -2131,43 +2131,86 @@
%09%09%09%09
-defaultCenter=%7B%7Blat: lat, lng: lon%7D
+center=%7Bcoords%7D%0A%09%09%09%09%09%09zoom=%7BzoomLevel%7D%0A%09%09%09%09%09%09defaultCenter=%7Bthis.defaultCenter
%7D%0A%09%09
@@ -2226,17 +2226,32 @@
ltZoom=%7B
-9
+this.defaultZoom
%7D%3E%0A%09%09%09%09%09
|
570fb72355c401703e0ddc21f9d571716a150744
|
remove unused variable and increase carousel width to 6
|
website/static/js/home-page/institutionsPanelPlugin.js
|
website/static/js/home-page/institutionsPanelPlugin.js
|
/**
* Display a horizontal listing of clickable OSF4I logos (links to institution landing pages).
*/
'use strict';
var $ = require('jquery');
var m = require('mithril');
var utils = require('js/components/utils');
var required = utils.required;
var lodashChunk = require('lodash.chunk');
var institutionComps = require('js/components/institution');
var carouselComps = require('js/components/carousel');
var Institution = institutionComps.InstitutionImg;
var Carousel = carouselComps.Carousel;
var CarouselRow = carouselComps.CarouselRow;
var CAROUSEL_WIDTH = 5;
var REDUCED_CAROUSEL_WIDTH = CAROUSEL_WIDTH - 1;
var COLUMN_WIDTH = Math.floor(12 / CAROUSEL_WIDTH);
var LOGO_WIDTH = '120px';
var InstitutionsPanel = {
controller: function() {
// Helper method to render logo link
this.renderLogo = function(inst, opts) {
var href = '/institutions/' + inst.id + '/';
var columnWidth = COLUMN_WIDTH.toString();
return m('.col-sm-' + columnWidth, {style: {'display':'inline-block', 'float':'none'}}, [
m('a', {href: href, className: 'thumbnail', style: {'background': 'inherit', 'border': 'none'}},
[m.component(Institution,
{
className: 'img-responsive',
style: {'background-color': 'white'},
name: inst.name,
logoPath: inst.logoPath,
muted: opts.muted,
})])
]);
};
},
view: function(ctrl, opts) {
var affiliated = required(opts, 'affiliatedInstitutions');
var allInstitutions = required(opts, 'allInstitutions');
var affiliatedIds = affiliated.map(function(inst) { return inst.id; });
var unaffiliated = allInstitutions.filter(function(inst) {
return $.inArray(inst.id, affiliatedIds) === -1;
});
var institutions = affiliated.concat(unaffiliated);
var controls = institutions.length > CAROUSEL_WIDTH;
if (controls && (12 % CAROUSEL_WIDTH) === 0 && CAROUSEL_WIDTH > REDUCED_CAROUSEL_WIDTH) {
CAROUSEL_WIDTH = REDUCED_CAROUSEL_WIDTH;
}
var groupedInstitutions = lodashChunk(institutions, CAROUSEL_WIDTH);
return m.component(Carousel, {controls: controls},
groupedInstitutions.map(function(instGroup, idx) {
var active = idx === 0;
return m.component(CarouselRow, {active: active}, instGroup.map(function(inst) {return ctrl.renderLogo(inst, {}); }));
})
);
}
};
module.exports = InstitutionsPanel;
|
JavaScript
| 0 |
@@ -564,9 +564,9 @@
H =
-5
+6
;%0Ava
@@ -667,34 +667,8 @@
TH);
-%0Avar LOGO_WIDTH = '120px';
%0A%0Ava
|
f3d9f6098f638dc2183ad7cb2e9e94161b869a8a
|
add missing config.SECRET
|
features/website-release.js
|
features/website-release.js
|
'use strict';
var extend = require('extend'),
fs = require('fs-extra'),
cmd = require('child_process'),
glob = require('glob'),
WORK_PATH = 'work';
function _cleanWorkspace() {
if(fs.existsSync(WORK_PATH)) {
console.log('remove path ' + WORK_PATH);
fs.removeSync(WORK_PATH);
}
}
function _error(error, callback) {
console.error('\n\nERROR!\n');
console.error(error);
console.error('\n\n');
_cleanWorkspace();
if(callback) {
callback(false);
}
return false;
}
function _success(callback) {
_cleanWorkspace();
console.log('\n\nALL IS DONE!\n\n');
if(callback) {
callback(true);
}
return true;
}
module.exports = function websiteRelease(config, callback) {
config = extend(true, {
USER_AGENT: '',
USER_AGENT_EMAIL: '',
SECRET: '',
MEMORYOVERFLOW_REPO: '',
MEMORYOVERFLOW_PATH: '',
WEBSITE_REPO: '',
WEBSITE_PATH: '',
THEMACHINE_PATH: '',
COMMIT_LABEL: '',
commitID: '',
commitUrl: ''
}, config);
_cleanWorkspace();
config.MEMORYOVERFLOW_PATH = WORK_PATH + '/' + config.MEMORYOVERFLOW_PATH;
config.WEBSITE_PATH = WORK_PATH + '/' + config.WEBSITE_PATH;
config.THEMACHINE_PATH = config.MEMORYOVERFLOW_PATH + '/' + config.THEMACHINE_PATH;
console.log('\ngit clone --depth 1 ' + config.MEMORYOVERFLOW_REPO + ' ' + config.MEMORYOVERFLOW_PATH + '...');
cmd.exec('git clone --depth 1 ' + config.MEMORYOVERFLOW_REPO + ' ' + config.MEMORYOVERFLOW_PATH, function(error) {
if(error) {
return _error(error, callback);
}
console.log('\ninstall The Machine...');
cmd.exec('npm install', {
cwd: config.THEMACHINE_PATH
}, function(error) {
if(error) {
return _error(error, callback);
}
console.log('\nexecute The Machine...');
cmd.exec('npm run-script generate', {
cwd: config.THEMACHINE_PATH
}, function(error) {
if(error) {
return _error(error, callback);
}
console.log('\ngit clone ' + config.WEBSITE_REPO + ' ' + config.WEBSITE_PATH + '...');
cmd.exec('git clone ' + config.WEBSITE_REPO + ' ' + config.WEBSITE_PATH, function(error) {
if(error) {
return _error(error, callback);
}
console.log('\ncopy ' + config.MEMORYOVERFLOW_PATH + '/website' + ' ' + config.WEBSITE_PATH + '...');
fs.copySync(config.WEBSITE_PATH + '/README.md', config.WEBSITE_PATH + '/README.tmp');
fs.copySync(config.MEMORYOVERFLOW_PATH + '/website', config.WEBSITE_PATH);
fs.move(config.WEBSITE_PATH + '/README.tmp', config.WEBSITE_PATH + '/README.md', {
clobber: true
}, function(error) {
if(error) {
return _error(error, callback);
}
console.log('\nremove EJS files...');
var ejsFiles = glob.sync(config.WEBSITE_PATH + '/**/*.ejs' , {});
console.log(ejsFiles);
for(var i = 0, len = ejsFiles.length; i < len; i++) {
fs.removeSync(ejsFiles[i]);
}
console.log('\ngit config user.name "' + config.USER_AGENT + '"');
cmd.exec('git config user.name "' + config.USER_AGENT + '"', {
cwd: config.WEBSITE_PATH
}, function(error) {
if(error) {
return _error(error, callback);
}
console.log('\ngit config user.email "' + config.USER_AGENT_EMAIL + '"');
cmd.exec('git config user.email "' + config.USER_AGENT_EMAIL + '"', {
cwd: config.WEBSITE_PATH
}, function(error) {
if(error) {
return _error(error, callback);
}
console.log('\ngit add -A');
cmd.exec('git add -A', {
cwd: config.WEBSITE_PATH
}, function(error, stdout) {
if(error) {
return _error(error, callback);
}
cmd.exec('git status', {
cwd: config.WEBSITE_PATH
}, function(error, stdout) {
if(error) {
return _error(error, callback);
}
var status = stdout.split('\n');
if(status.length && status[1].trim() == 'nothing to commit, working directory clean') {
console.log('NOTHING TO COMMIT');
return _success(callback);
}
var commitAuthor = ' --author="' + config.USER_AGENT + ' <' + config.USER_AGENT_EMAIL + '>"',
commitLabel = config.COMMIT_LABEL
.replace('{commitID}', config.commitID)
.replace('{commitUrl}', config.commitUrl)
.split('\n')
.map(function(line) {
return ' -m "' + line + '"';
})
.join('');
console.log('\ngit commit' + commitAuthor + commitLabel);
cmd.exec('git commit' + commitAuthor + commitLabel, {
cwd: config.WEBSITE_PATH
}, function(error) {
if(error) {
return _error(error, callback);
}
var pushRepo = config.WEBSITE_REPO.replace('https://', 'https://' + config.USER_AGENT + ':' + config.SECRET + '@');
console.log('\ngit push ' + pushRepo.replace(SECRET, 'SECRET') + ' gh-pages');
cmd.exec('git push ' + pushRepo + ' gh-pages', {
cwd: config.WEBSITE_PATH
}, function(error) {
if(error) {
return _error(error, callback);
}
return _success(callback);
});
});
});
});
});
});
});
});
});
});
});
};
|
JavaScript
| 0.000007 |
@@ -5624,16 +5624,23 @@
replace(
+config.
SECRET,
|
98c7b7ea0032ab86a8bcb2b0ca118b0ed8a1c721
|
Rename Client to Envoy.
|
rendezvous/envoy.js
|
rendezvous/envoy.js
|
var cadence = require('cadence')
var Interlocutor = require('interlocutor')
var protocols = { http: require('http'), https: require('https') }
var Conduit = require('nascent.upgrader/socket')
var Header = require('nascent.jacket')
var url = require('url')
var Cache = require('magazine')
function Client (middleware, request, socket, head) {
this._interlocutor = new Interlocutor(middleware)
this._socket = socket
this._magazine = new Cache().createMagazine()
this._header = new Header
this._consume(head, 0, head.length)
this._socket.on('data', this._data.bind(this))
}
Client.prototype._data = function (buffer) {
var count = 0
for (var start = 0; start != buffer.length;) {
if (++count == 5) throw new Error
start = this._consume(buffer, start, buffer.length)
}
}
Client.prototype._consume = function (buffer, start, end) {
if (this._header.object != null) {
var length = Math.min(buffer.length, this._header.object.length)
var cartridge = this._magazine.hold(cookie, null)
cartridge.value.response.write(buffer.slice(start, start + length))
start += length
cartridge.release()
this._header = new Header
}
start = this._header.parse(buffer, start, end)
if (this._header.object != null) {
switch (this._header.object.type) {
case 'header':
var headers = this._header.object.headers
headers['sec-conduit-rendezvous-actual-path'] = this._header.object.actualPath
this._header.object.rawHeaders.push('sec-conduit-rendezvous-actual-path', this._header.object.actualPath)
var request = this._interlocutor.request({
httpVersion: this._header.object.httpVersion,
method: this._header.object.method,
url: this._header.object.url,
headers: headers,
rawHeaders: this._header.object.rawHeaders
})
var socket = this._socket, cookie = this._header.object.cookie
request.on('response', function (response) {
socket.write(new Buffer(JSON.stringify({
type: 'header',
cookie: cookie,
statusCode: response.statusCode,
statusMessage: response.statusMessage,
headers: response.headers
}) + '\n'))
response.on('data', function (buffer) {
socket.write(new Buffer(JSON.stringify({
type: 'chunk',
cookie: cookie,
length: buffer.length
}) + '\n'))
socket.write(buffer)
})
response.on('end', function () {
socket.write(new Buffer(JSON.stringify({ type: 'trailer', cookie: cookie }) + '\n'))
})
// response.on('error', function (error) {})
})
this._magazine.hold(this._header.object.cookie, request).release()
this._header = new Header
break
case 'chunk':
break
case 'trailer':
var cartridge = this._magazine.hold(this._header.object.cookie, null)
cartridge.value.end()
cartridge.remove()
this._header = new Header
break
}
}
return start
}
Client.prototype.close = cadence(function (async) {
this._socket.end(async())
this._socket.destroy()
})
exports.connect = cadence(function (async, location, middleware) {
var parsed = url.parse(location)
async(function () {
Conduit.connect({
secure: parsed.protocol == 'https:',
host: parsed.hostname,
port: parsed.port,
auth: parsed.auth,
headers: {
'sec-conduit-rendezvous-path': parsed.path
}
}, async())
}, function (request, socket, head) {
return new Client(middleware, request, socket, head)
})
})
|
JavaScript
| 0 |
@@ -291,22 +291,21 @@
unction
-Client
+Envoy
(middle
@@ -585,30 +585,29 @@
d(this))%0A%7D%0A%0A
-Client
+Envoy
.prototype._
@@ -810,30 +810,29 @@
h)%0A %7D%0A%7D%0A%0A
-Client
+Envoy
.prototype._
@@ -3422,22 +3422,21 @@
tart%0A%7D%0A%0A
-Client
+Envoy
.prototy
@@ -4015,14 +4015,13 @@
new
-Client
+Envoy
(mid
|
d43163373a5f2ced30ecbff252f0f840202e54b0
|
add some examples for strings
|
example/transforms.js
|
example/transforms.js
|
'use strict';
const transd = require('../'),
{ transform } = transd;
const xform = transd.compose(
transform.square,
transform.log
),
iterable = {
alpha: 1,
beta: 2,
gamma: 5,
delta: 5
};
const array = transd.into(xform, [], iterable),
object = transd.into(xform, {}, iterable),
map = transd.into(xform, new Map(), iterable),
set = transd.into(xform, new Set(), iterable);
console.log('Array: ', array); // [ 2, 6, 6 ]
console.log('Object: ', object); // { alpha: 2, gamma: 6, delta: 6 }
console.log('Map: ', map); // Map { 'alpha' => 2, 'gamma' => 6, 'delta' => 6 }
console.log('Set: ', set); // Set { 2, 6 }
|
JavaScript
| 0.000019 |
@@ -447,16 +447,65 @@
w Set(),
+ iterable),%0A string = transd.into(xform, '',
iterabl
@@ -756,12 +756,61 @@
et %7B 2, 6 %7D%0A
+console.log('String: ', string); // Set %7B 2, 6 %7D%0A
|
7292a498e333470d53d7972731756fd71c606d42
|
Fix bug with empty translations showing up
|
scripts/TranslationSystem.js
|
scripts/TranslationSystem.js
|
var TranslationSystem = {
TRANSLATABLE_ATTRIBUTES: [
'title',
'alt',
'placeholder'
],
translations: undefined,
init: function() {
var settings = new Settings();
TranslationSystem.changeLanguage(settings.language);
$('#translations').click(function() {
$(this).arrowPopup("#translationsPopup");
});
},
get: function(original) {
if (TranslationSystem.translations.hasOwnProperty(original)) {
return TranslationSystem.translations[original];
}
return original;
},
updateMarkup: function(data) {
TranslationSystem.translations = data; // global
$('.translatable').each(function(i, elem) {
elem = $(elem);
var translationKeys = elem.data('translationKeys') || {},
key;
if (translationKeys.hasOwnProperty('text')) {
key = translationKeys.text;
} else {
key = elem.text();
translationKeys.text = key;
}
if (TranslationSystem.translations.hasOwnProperty(key)) {
elem.text(TranslationSystem.translations[key]);
}
$.each(TranslationSystem.TRANSLATABLE_ATTRIBUTES, function(j, attr) {
if (elem.attr(attr) !== undefined) {
if (translationKeys.hasOwnProperty(attr)) {
key = translationKeys[attr];
} else {
key = elem.attr(attr);
translationKeys[attr] = key;
}
if (TranslationSystem.translations.hasOwnProperty(key)) {
elem.attr(attr, TranslationSystem.translations[key]);
}
}
});
elem.data('translationKeys', translationKeys);
});
},
changeLanguage: function(code) {
$('#settings .language option[value=' + code + ']').attr('selected', 'selected');
if (autoDetectedLanguageByServer === code) {
TranslationSystem.updateMarkup(autoDetectedTranslations);
} else {
$.getJSON('/api/translations/' + code, function(data, textStatus) {
TranslationSystem.updateMarkup(data);
});
}
}
};
|
JavaScript
| 0 |
@@ -482,16 +482,67 @@
riginal)
+ && TranslationSystem.translations%5Boriginal%5D.length
) %7B%0A
@@ -1238,33 +1238,24 @@
nSystem.
-translations%5Bkey%5D
+get(key)
);%0A
@@ -1807,25 +1807,16 @@
tem.
-translations%5Bkey%5D
+get(key)
);%0A
|
b0b1cfe3740451e994992c5a6b9990ab11123a76
|
Clean up
|
web/public/js/controllers/manage-dojo-controller.js
|
web/public/js/controllers/manage-dojo-controller.js
|
'use strict';
function manageDojosCtrl($scope, alertService, auth, tableUtils, cdDojoService, $location, cdCountriesService) {
$scope.filter = {};
$scope.filter.verified = 1;
$scope.itemsPerPage = 10;
$scope.pageChanged = function () {
$scope.loadPage($scope.filter, false);
};
var verificationStates = [
{label: 'Unverified', value: 0},
{label: 'Verified', value: 1},
{label: 'Previous', value: 2}
];
var changedDojos = [];
$scope.getVerificationStates = function (agreements) {
var states = verificationStates.slice();
// TODO: single origin point for current agreement version
var currentAgreementVersion = 2;
if (!_.any(agreements, function (agreement) {
return agreement.agreementVersion === currentAgreementVersion;
})) {
//
states = _.reject(states, function (state) { return state.value === 1 });
}
return states;
};
$scope.setStyle = function(agreements){
// TODO: single origin point for current agreement version
var currentAgreementVersion = 2;
var isSigned = _.any(agreements, function(agreement) {
return agreement.agreementVersion === currentAgreementVersion;
});
return !isSigned ? {color:'red'} : {color: 'black'};
};
$scope.editDojo = function (dojo) {
cdDojoService.setDojo(dojo, function (response) {
$location.path('/dashboard/edit-dojo');
}, function (err) {
if (err) {
alertService.showError(
'An error has occurred while editing dojo: <br /> ' +
(err.error || JSON.stringify(err))
);
}
});
};
$scope.resetFilter = function () {
$scope.filter = {};
$scope.filter.verified = 1;
$scope.loadPage($scope.filter, true);
};
$scope.loadPage = function (filter, resetFlag, cb) {
cb = cb || function () {};
var filteredQuery = {};
filteredQuery.query = {};
filteredQuery.query.filtered = {};
if(!_.isNull(filter.email) && filter.email !== '' && !_.isUndefined(filter.email)){
filteredQuery.query.filtered.query = {
"regexp" : {
"email" : {
"value": ".*" + filter.email + ".*"
}
}
};
}
var query = _.omit({
verified: filter.verified,
stage: filter.stage,
alpha2: filter.country && filter.country.alpha2
}, function (value) { return value === '' || _.isNull(value) || _.isUndefined(value) });
var loadPageData = tableUtils.loadPage(resetFlag, $scope.itemsPerPage, $scope.pageNo, query);
$scope.pageNo = loadPageData.pageNo;
$scope.dojos = [];
var meta = {
sort: [{
created: 'desc'
}],
from: loadPageData.skip,
size: $scope.itemsPerPage
};
filteredQuery = _.extend(filteredQuery, meta);
if (!_.isEmpty(query)) {
filteredQuery.query.filtered.filter = {
and: _.map(query, function (value, key) {
var term = {};
term[key] = value.toLowerCase ? value.toLowerCase() : value;
return {term: term};
})
};
}
cdDojoService.search(filteredQuery).then(function (result) {
$scope.dojos = _.map(result.records, function (dojo) {
dojo.verified = _.findWhere(verificationStates, {value: dojo.verified});
return dojo;
});
$scope.totalItems = result.total;
return cb();
}, function (err) {
alertService.showError('An error has occurred while loading Dojos: <br>' +
(err.error || JSON.stringify(err))
);
return cb(err);
});
};
$scope.filterDojos = function () {
$scope.loadPage($scope.filter, true);
changedDojos = [];
};
$scope.processDojos = function (event) {
changedDojos = _.map(changedDojos, function (dojo) {
if (dojo.creatorEmail) {
delete dojo.creatorEmail;
}
if (dojo.agreements) {
delete dojo.agreements;
}
return dojo;
});
$scope.dojosToBeDeleted = _.filter(changedDojos, function (changedDojo) {
return changedDojo.toBeDeleted;
});
$scope.dojosToBeUpdated = _.filter(changedDojos, function (changedDojo) {
return !changedDojo.toBeDeleted;
});
function updateDojos(cb) {
if (_.isEmpty($scope.dojosToBeUpdated)) {
return cb();
}
var dojosToBeUpdated = _.map($scope.dojosToBeUpdated, function (dojo) {
return {
id: dojo.id,
verified: dojo.verified.value
}
});
cdDojoService.bulkUpdate(dojosToBeUpdated).then(function (response) {
// TODO: review, should notify user on successfull update?
return cb();
}, function (err) {
alertService.showError('An error has occurred while updating Dojos: <br>' +
(err.error || JSON.stringify(err)));
cb(err);
});
}
function deleteDojos(cb) {
if (_.isEmpty($scope.dojosToBeDeleted)) {
return cb();
}
var dojos = _.map($scope.dojosToBeDeleted, function (dojo) {
return {id: dojo.id, creator: dojo.creator};
});
cdDojoService.bulkDelete(dojos).then(function (response) {
// TODO: review, should notify user on successfull delete?
return cb();
}, function (err) {
alertService.showError('An error has occurred while deleting Dojos: <br>' +
(err.error || JSON.stringify(err)));
cb(err);
});
}
async.series([updateDojos, deleteDojos], function (err) {
delete $scope.dojosToBeDeleted;
delete $scope.dojosToBeUpdated;
changedDojos = [];
if (err) {
alertService.showError('An error has occurred while updating Dojos: <br>' +
(err.error || JSON.stringify(err)));
}
$scope.loadPage($scope.filter, false);
});
};
cdCountriesService.listCountries(function (countries) {
$scope.countries = _.map(countries, function (country) {
return _.omit(country, 'entity$');
});
});
$scope.pushChangedDojo = function (dojo) {
var filterVerified, exists = !!(_.find(changedDojos, function (changedDojo) {
return dojo.id === changedDojo.id;
}));
filterVerified = $scope.filter && $scope.filter.verified;
if ((dojo.verified.value !== filterVerified) || (dojo.toBeDeleted)) {
if (!exists) {
changedDojos.push(dojo);
}
} else if (dojo.verified.value === filterVerified && !dojo.toBeDeleted) {
changedDojos = _.filter(changedDojos, function (filteredDojo) {
return dojo.id !== filteredDojo.id;
});
}
};
auth.get_loggedin_user(function () {
$scope.loadPage($scope.filter, true);
});
}
angular.module('cpZenPlatform')
.controller('manage-dojo-controller',
['$scope', 'alertService', 'auth', 'tableUtils', 'cdDojoService', '$location', 'cdCountriesService', manageDojosCtrl]);
|
JavaScript
| 0.000002 |
@@ -797,18 +797,16 @@
%7B%0A
-//
%0A s
@@ -1864,78 +1864,32 @@
= %7B
-%7D;%0A filteredQuery.query = %7B%7D;%0A filteredQuery.query.filtered =
+ query: %7B filtered:
%7B%7D
+%7D%7D
;%0A%0A
@@ -1898,18 +1898,8 @@
if(
-!_.isNull(
filt
@@ -1911,64 +1911,8 @@
ail)
- && filter.email !== '' && !_.isUndefined(filter.email))
%7B%0A
@@ -1993,26 +1993,24 @@
%22email%22 : %7B%0A
-
|
962e35782e674489b2e246ede3da542a1d53a634
|
Reformat protractor config
|
protractor.conf.js
|
protractor.conf.js
|
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
// Waiting for the following issues to fix e2e tests using firebase
// - https://github.com/angular/protractor/issues/4300
// - https://github.com/angular/angularfire2/issues/19
// - https://github.com/angular/angularfire2/issues/779
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./e2e/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: () => undefined
},
onPrepare() {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};
|
JavaScript
| 0.000001 |
@@ -477,21 +477,16 @@
specs: %5B
-%0A
'./e2e/*
@@ -501,19 +501,16 @@
spec.ts'
-%0A
%5D,%0A cap
@@ -526,17 +526,16 @@
: %7B%0A
-'
browserN
@@ -537,17 +537,16 @@
wserName
-'
: 'chrom
@@ -736,17 +736,10 @@
=%3E
-undefined
+%7B%7D
%0A %7D
|
7729a7409494b5a893af296d6ba7fc2b7a68435c
|
Rename module home.controller -> home.module. Refactoring. Added component
|
angular-lazyload-webpack/src/pages/home/controllers/home.controller.js
|
angular-lazyload-webpack/src/pages/home/controllers/home.controller.js
|
"use strict";
class HomeController {
constructor() {}
}
const HOME_CTRL = angular
.module("home.controller", [])
.controller("HomeController", HomeController);
export { HOME_CTRL };
|
JavaScript
| 0 |
@@ -59,25 +59,127 @@
%0A%0Aconst
-HOME_CTRL
+homeComponent = %7B%0A template: require(%22../views/home.html%22),%0A controller: HomeController%0A%7D;%0A%0Aconst HOME_MODULE
= angul
@@ -197,26 +197,22 @@
e(%22home.
-control
+modu
le
-r
%22, %5B%5D)%0A
@@ -219,49 +219,46 @@
.co
-ntroller(%22H
+mponent(%22h
omeCo
-ntroller%22, H
+mponent%22, h
omeCo
-ntroller
+mponent
);%0A%0A
@@ -275,12 +275,14 @@
OME_
-CTRL
+MODULE
%7D;%0A
|
bd99b9b82bac8e9035e1848d55a79e99104f90e5
|
Disable E2E tests temporarily
|
protractor.conf.js
|
protractor.conf.js
|
exports.config = {
baseUrl: 'http://localhost:8000/',
framework: 'jasmine',
specs: 'e2e/**/*.test.js',
capabilities: {
browserName: 'phantomjs',
shardTestFiles: true,
maxInstances: 4,
'phantomjs.binary.path': './node_modules/phantomjs-prebuilt/bin/phantomjs'
},
seleniumServerJar: 'node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.4.0.jar',
chromeDriver: './node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.29',
onPrepare: function () {
browser.driver.manage().window().setSize(1024, 768);
global.dp = require('./e2e/helpers/datapunt');
// dp.navigate requires that other helpers are already loaded, just making sure the others are initialized first
global.dp.navigate = require('./e2e/helpers/navigate');
}
};
|
JavaScript
| 0 |
@@ -102,12 +102,16 @@
*/*.
-test
+disabled
.js'
|
c619b79276be80db73442cee0b4dfd4b975bfed9
|
Fix placeholder text when empty alias input after generating alias (#4032)
|
src/Umbraco.Web.UI.Client/src/common/directives/components/umbGenerateAlias.directive.js
|
src/Umbraco.Web.UI.Client/src/common/directives/components/umbGenerateAlias.directive.js
|
/**
@ngdoc directive
@name umbraco.directives.directive:umbGenerateAlias
@restrict E
@scope
@description
Use this directive to generate a camelCased umbraco alias.
When the aliasFrom value is changed the directive will get a formatted alias from the server and update the alias model. If "enableLock" is set to <code>true</code>
the directive will use {@link umbraco.directives.directive:umbLockedField umbLockedField} to lock and unlock the alias.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<input type="text" ng-model="vm.name" />
<umb-generate-alias
enable-lock="true"
alias-from="vm.name"
alias="vm.alias">
</umb-generate-alias>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.name = "";
vm.alias = "";
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {string} alias (<code>binding</code>): The model where the alias is bound.
@param {string} aliasFrom (<code>binding</code>): The model to generate the alias from.
@param {boolean=} enableLock (<code>binding</code>): Set to <code>true</code> to add a lock next to the alias from where it can be unlocked and changed.
**/
angular.module("umbraco.directives")
.directive('umbGenerateAlias', function ($timeout, entityResource, localizationService) {
return {
restrict: 'E',
templateUrl: 'views/components/umb-generate-alias.html',
replace: true,
scope: {
alias: '=',
aliasFrom: '=',
enableLock: '=?',
serverValidationField: '@'
},
link: function (scope, element, attrs, ctrl) {
var eventBindings = [];
var bindWatcher = true;
var generateAliasTimeout = "";
var updateAlias = false;
scope.locked = true;
scope.labels = {
idle: "Enter alias...",
busy: "Generating alias..."
};
scope.placeholderText = scope.labels.idle;
localizationService.localize('placeholders_enterAlias').then(function (value) {
scope.labels.idle = scope.placeholderText = value;
});
localizationService.localize('placeholders_generatingAlias').then(function (value) {
scope.labels.busy = value;
});
function generateAlias(value) {
if (generateAliasTimeout) {
$timeout.cancel(generateAliasTimeout);
}
if( value !== undefined && value !== "" && value !== null) {
scope.alias = "";
scope.placeholderText = scope.labels.busy;
generateAliasTimeout = $timeout(function () {
updateAlias = true;
entityResource.getSafeAlias(value, true).then(function (safeAlias) {
if (updateAlias) {
scope.alias = safeAlias.alias;
}
});
}, 500);
} else {
updateAlias = true;
scope.alias = "";
scope.placeholderText = scope.labels.idle;
}
}
// if alias gets unlocked - stop watching alias
eventBindings.push(scope.$watch('locked', function(newValue, oldValue){
if(newValue === false) {
bindWatcher = false;
}
}));
// validate custom entered alias
eventBindings.push(scope.$watch('alias', function(newValue, oldValue){
if(scope.alias === "" && bindWatcher === true || scope.alias === null && bindWatcher === true) {
// add watcher
eventBindings.push(scope.$watch('aliasFrom', function(newValue, oldValue) {
if(bindWatcher) {
generateAlias(newValue);
}
}));
}
}));
// clean up
scope.$on('$destroy', function(){
// unbind watchers
for(var e in eventBindings) {
eventBindings[e]();
}
});
}
};
});
|
JavaScript
| 0 |
@@ -2786,16 +2786,17 @@
+
$timeout
@@ -2871,10 +2871,10 @@
if
-(
+(
valu
@@ -2923,26 +2923,24 @@
== null) %7B%0A%0A
-
@@ -3300,32 +3300,34 @@
+
scope.alias = sa
@@ -3360,33 +3360,105 @@
-%7D
+ %7D%0A scope.placeholderText = scope.labels.idle;
%0A
@@ -3678,33 +3678,32 @@
%7D%0A
-%0A
@@ -4096,32 +4096,33 @@
alias', function
+
(newValue, oldVa
@@ -4125,19 +4125,21 @@
ldValue)
+
%7B%0A
-%0A
+
@@ -4150,16 +4150,17 @@
if
+
(scope.a
@@ -4171,39 +4171,39 @@
=== %22%22
-&& bindWatcher
+%7C%7C scope.alias
===
-true
+null
%7C%7C scop
@@ -4218,16 +4218,49 @@
===
-null &&
+undefined) %7B%0A if (
bind
@@ -4299,16 +4299,24 @@
+
+
// add w
@@ -4322,16 +4322,24 @@
watcher%0A
+
@@ -4395,32 +4395,33 @@
sFrom', function
+
(newValue, oldVa
@@ -4450,18 +4450,28 @@
+
+
if
+
(bindWat
@@ -4474,24 +4474,34 @@
dWatcher) %7B%0A
+
@@ -4554,34 +4554,51 @@
+
-%7D%0A
+ %7D%0A
@@ -4616,34 +4616,61 @@
+ %7D%0A
%7D
-%0A
%0A
|
827c5adc6c9ce1c5ba7fded7b1336cc0a2fe90bf
|
add id to add link; add id to remove link
|
lib/js/advance_search/advance_search.js
|
lib/js/advance_search/advance_search.js
|
var AdminData = AdminData || {};
AdminData.advanceSearch = {
buildFirstRow: function() {
var img = $('<img />', {
src: 'https://github.com/neerajdotname/admin_data/raw/rails3_gem/public/images/add.png'
});
$('#advance_search_table').append(this.buildRow()).find('tr td:last a').removeClass('remove_row').addClass('add_row_link').html('').append(img);
},
buildCol1: function() {
var i, col = $('<select />', {
className: 'col1'
}).append($('<option />')),
tableStructure = $('#advance_search_table').data('table_structure');
for (i in tableStructure) {
$('<option />', {
text: i,
value: i
}).appendTo(col);
}
return $('<td />').append(col);
},
buildCol2: function() {
var select = $('<select />', {
className: 'col2'
});
return $('<td />').append(select);
},
buildCol3: function() {
return $('<td />').append($('<input />', {
className: 'col3'
}));
},
buildCol4: function() {
var img = $('<img />', {
src: 'https://github.com/neerajdotname/admin_data/raw/rails3_gem/public/images/no.png'
});
return $('<td />').append($('<a />', {
text: '',
href: '#',
className: 'remove_row'
}).append(img));
},
buildRow: function() {
var $tr = $('<tr />'),
currentRowNumber = $(document).data('currentRowNumber'),
that = this,
build_array = ['buildCol1', 'buildCol2', 'buildCol3', 'buildCol4'];
if (currentRowNumber === undefined) {
currentRowNumber = 1;
$(document).data('currentRowNumber', currentRowNumber)
} else {
currentRowNumber = parseInt(currentRowNumber) + 1;
$(document).data('currentRowNumber', currentRowNumber)
}
$.each(build_array, function(index, value) {
$tr.append(that[value]());
});
$tr.find('select.col1').attr({
name: 'adv_search[' + currentRowNumber + '_row][col1]'
});
$tr.find('select.col2').attr({
name: 'adv_search[' + currentRowNumber + '_row][col2]'
});
$tr.find('input.col3').attr({
name: 'adv_search[' + currentRowNumber + '_row][col3]'
});
return $tr;
}
};
|
JavaScript
| 0.000001 |
@@ -285,16 +285,44 @@
ast a').
+attr('id','add_row_link_1').
removeCl
@@ -2024,32 +2024,105 @@
%5D%5Bcol3%5D'%0A%09%09%7D);%0A%0A
+ $tr.find('.remove_row').attr('id', 'remove_row_'+currentRowNumber);%0A%0A
%09%09return $tr;%0A%09%7D
|
6af3c9a8ac801d41c89e61d2ddbdd9d849a77e32
|
Remove onRequest function usages
|
components/org.wso2.carbon.uuf.common.foundation.ui/src/main/fragments/uuf-client/uuf-client.js
|
components/org.wso2.carbon.uuf.common.foundation.ui/src/main/fragments/uuf-client/uuf-client.js
|
/**
* @license
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.
*/
function onRequest(env) {
sendToClient("contextPath", env.contextPath);
}
|
JavaScript
| 0 |
@@ -693,14 +693,10 @@
n on
-Reques
+Ge
t(en
|
ef457ca69b9fcb89b2760e10c5ba3817185d3f89
|
Disable crossdomainrpc_test
|
protractor_spec.js
|
protractor_spec.js
|
// TODO(joeltine): Remove promise module when stable node version supports it
// natively.
var Promise = require('promise');
var allTests = require('./alltests');
// Timeout for individual test package to complete.
var TEST_TIMEOUT = 45 * 1000;
var TEST_SERVER = 'http://localhost:8080';
var IGNORED_TESTS = [
// Test hangs in IE8.
'closure/goog/ui/plaintextspellchecker_test.html',
// TODO(joeltine): Re-enable once fixed for external testing.
'closure/goog/testing/multitestrunner_test.html',
// These Promise-based tests all timeout for unknown reasons.
// Disable for now.
'closure/goog/testing/fs/integration_test.html',
'closure/goog/debug/fpsdisplay_test.html',
'closure/goog/net/jsloader_test.html',
'closure/goog/net/filedownloader_test.html',
'closure/goog/promise/promise_test.html',
'closure/goog/editor/plugins/abstractdialogplugin_test.html'
];
describe('Run all Closure unit tests', function() {
var removeIgnoredTests = function(tests) {
for (var i = 0; i < IGNORED_TESTS.length; i++) {
var index = tests.indexOf(IGNORED_TESTS[i]);
if (index != -1) {
tests.splice(index, 1);
}
}
return tests;
};
beforeAll(function() { allTests = removeIgnoredTests(allTests); });
beforeEach(function() {
// Ignores synchronization with angular loading. Since we don't use angular,
// enable it.
browser.ignoreSynchronization = true;
});
// Polls currently loaded test page for test completion. Returns Promise that
// will resolve when test is finished.
var waitForTestSuiteCompletion = function(testPath) {
var testStartTime = +new Date();
var waitForTest = function(resolve, reject) {
// executeScript runs the passed method in the "window" context of
// the current test. JSUnit exposes hooks into the test's status through
// the "G_testRunner" global object.
browser.executeScript(function() {
if (window['G_testRunner'] &&
window['G_testRunner']['isFinished']()) {
var status = {};
status['isFinished'] = true;
status['isSuccess'] = window['G_testRunner']['isSuccess']();
status['report'] = window['G_testRunner']['getReport']();
return status;
} else {
return {'isFinished': false};
}
})
.then(
function(status) {
if (status && status.isFinished) {
resolve(status);
} else {
var currTime = +new Date();
if (currTime - testStartTime > TEST_TIMEOUT) {
status.isSuccess = false;
status.report = testPath + ' timed out after ' +
(TEST_TIMEOUT / 1000) + 's!';
// resolve so tests continue running.
resolve(status);
} else {
// Check every 300ms for completion.
setTimeout(
waitForTest.bind(undefined, resolve, reject), 300);
}
}
},
function(err) { reject(err); });
};
return new Promise(function(resolve, reject) {
waitForTest(resolve, reject);
});
};
it('should run all tests with 0 failures', function(done) {
var failureReports = [];
// Navigates to testPath to invoke tests. Upon completion inspects returned
// test status and keeps track of the total number failed tests.
var runNextTest = function(testPath) {
return browser.navigate()
.to(TEST_SERVER + '/' + testPath)
.then(function() { return waitForTestSuiteCompletion(testPath); })
.then(function(status) {
if (!status.isSuccess) {
failureReports.push(status.report);
}
return status;
});
};
// Chains the next test to the completion of the previous through its
// promise.
var chainNextTest = function(promise, test) {
return promise.then(function() { runNextTest(test); });
};
var testPromise = null;
for (var i = 0; i < allTests.length; i++) {
if (testPromise != null) {
testPromise = chainNextTest(testPromise, allTests[i]);
} else {
testPromise = runNextTest(allTests[i]);
}
}
testPromise.then(function() {
var totalFailures = failureReports.length;
if (totalFailures > 0) {
console.error('There was ' + totalFailures + ' test failure(s)!');
for (var i = 0; i < failureReports.length; i++) {
console.error(failureReports[i]);
}
}
expect(failureReports.length).toBe(0);
done();
});
});
});
|
JavaScript
| 0 |
@@ -873,16 +873,63 @@
st.html'
+,%0A 'closure/goog/net/crossdomainrpc_test.html'
%0A%5D;%0A%0Ades
|
67cf0a1fc7942dbdf177dee32ad4774322163f08
|
make sure that option.token is a string
|
lib/lambdacloud/lambdacloud-uploader.js
|
lib/lambdacloud/lambdacloud-uploader.js
|
'use strict';
var Writable = require('stream').Writable;
var _ = require('lodash');
var log = require('debug');
var request = require('request');
var retry = require('retry');
var util = require('util');
var moment = require('moment');
var SHA256 = require("crypto-js/sha256");
// Enable debugging
log.enable('lambdacloud-uploader:info');
var info = log('lambdacloud-uploader:info');
var debug = log('lambdacloud-uploader:debug');
var defaultOption = {
retries: 10,
host: 'api.lambdacloud.com'
};
function LambdacloudUploader(option)
{
if (!option.token) {
throw new Error('The token must be set in option');
}
this.option = _.defaults(option, defaultOption);
Writable.call(this, { objectMode: true });
this.stats = {
total: 0,
success: 0,
timeout: 0,
retries: 0,
lastTimestamp: '',
lastMessage: '',
error: {}
};
var self = this;
var startTimestamp = moment();
this.statusBarTimer = setInterval(function() {
process.stdout.write('\r uploading... ' +
' total: ' + self.stats.total +
' success: ' + self.stats.success +
' timeout: ' + self.stats.timeout +
' retries: ' + self.stats.retries +
' duration: ' + moment().from(startTimestamp)
);
}, 500);
this.queue = 0;
this.queueSize = 128;
this.on('finish', function() {
clearTimeout(self.statusBarTimer);
self.dumpStats();
});
}
util.inherits(LambdacloudUploader, Writable);
LambdacloudUploader.prototype._write = function writeLambdacloud(chunk, encoding, callback) {
var self = this;
if (!chunk) {
callback();
return;
}
var body = {
message: chunk
};
var frontendHost = 'http://' + this.option.host + '/log/v2';
var httpOptions = {
url: frontendHost,
headers: {
'Token': this.option.token,
'Content-type': 'application/json;charset=UTF-8',
'User-Agent': 'LambdacloudUploader.js v0.2'
},
json: true,
body: body
};
if (this.option.proxy) {
httpOptions.proxy = this.option.proxy;
}
debug('http request option: ' + JSON.stringify(httpOptions));
var op = retry.operation({
retries: this.option.retries
});
self.stats.total += chunk.length;
self.stats.lastTimestamp = moment();
self.stats.lastMessage = body.message.toString().substring(0, 16) + '...';
self.queue++;
//retry use http post method
// attempt in retry is a synchronized function
op.attempt(function(currentAttempt) {
var req = request
.put(httpOptions, function(err, res) {
if (op.retry(err)) {
debug('Retry posting message ' + chunk + ' ' + currentAttempt + ' times');
if (currentAttempt === 1) {
self.stats.retries ++;
}
return;
}
//remove req.pendingCB, just use once callback()
if (self.queue >= self.queueSize) {
callback();
}
self.queue--;
if (err && op.mainError) {
self.stats.timeout ++;
console.error('Request timeout, stats: ' + JSON.stringify(self.stats));
return;
}
if (res.statusCode >= 200 && res.statusCode < 300) {
self.stats.success += chunk.length;
} else {
self.stats.error[res.statusCode] = (self.stats.error[res.statusCode]) ?
(self.stats.error[res.statusCode] + chunk.length) : chunk.length;
console.error('Request error code ' + res.statusCode + ', stats: ' + JSON.stringify(self.stats));
}
});
});
if (self.queue < self.queueSize) {
callback();
}
};
LambdacloudUploader.prototype.dumpStats = function() {
console.log('\nLambdaCloud uploading stats: ' + JSON.stringify(this.stats));
};
module.exports = LambdacloudUploader;
|
JavaScript
| 0.999928 |
@@ -1604,16 +1604,170 @@
n;%0A %7D%0A%0A
+ if (!_.isString(this.option.token)) %7B%0A console.error(%22bad request,token is not a string, you can check '--token'%22);%0A callback();%0A return;%0A %7D%0A%0A
var bo
|
12cf0f39a2d3eec2a396359178616f9bf8f92962
|
Add confirm prompts for self-service cancel buttons
|
scripts/selfservice.js
|
scripts/selfservice.js
|
var remoteUrl = "https://api.carpoolvote.com/live";
// Create a data object containing all URL query string data:
var data = tinyQuery.getAll();
if (data.uuid_driver) {
data.uuid = data.uuid || data.uuid_driver;
data.type = data.type || 'driver';
}
if (data.uuid_rider) {
data.uuid = data.uuid || data.uuid_rider;
data.type = data.type || 'rider';
}
// Cache jQuery selectors:
var $login = $('#login'),
$manage = $('#manage'),
$info = $manage.find('#info');
if (data.uuid) {
$login.find('#enter-uuid').remove();
}
if (data.type) {
$login.find('#enter-type').remove();
}
$login.validator().on('submit', function(e) {
if (e.isDefaultPrevented()) {
return;
}
data.uuid = data.uuid || $(this).find('#inputUUID').val();
data.type = data.type || $(this).find('#enter-type').find('input:checked').val();
data.phone = $(this).find('#inputPhoneNumber').val();
$(this).slideUp(300).attr('aria-hidden','true');
$manage.slideDown(300).attr('aria-hidden','false');
updateUI();
e.preventDefault();
});
function updateUI(uuid, type, phone) {
$manage.find('#btnCancelDriveOffer').toggle(data.type === 'driver');
$manage.find('#btnCancelDriverMatch').toggle(data.type === 'driver' && data.score !== 'undefined');
$manage.find('#btnPauseDriverMatch').toggle(data.type === 'driver' && data.score !== 'undefined');
$manage.find('#btnCancelRideRequest').toggle(data.type === 'rider');
$manage.find('#btnCancelRiderMatch').toggle(data.type === 'rider' && data.score !== 'undefined');
$manage.find('#btnAcceptDriverMatch').toggle(data.type === 'driver' && data.score !== 'undefined');
}
$manage
.on('click', '#btnCancelRideRequest', cancelRideRequest)
.on('click', '#btnCancelRiderMatch', cancelRiderMatch)
.on('click', '#btnCancelDriveOffer', cancelDriveOffer)
.on('click', '#btnCancelDriverMatch', cancelDriverMatch)
.on('click', '#btnPauseDriverMatch', pauseDriverMatch)
.on('click', '#btnAcceptDriverMatch', acceptDriverMatch)
.on('click', '#logout', logout);
function cancelRideRequest() {
sendAjaxRequest(
{
uuid: data.uuid,
RiderPhone: data.phone
},
'/cancel-ride-request'
);
}
function cancelRiderMatch() {
sendAjaxRequest(
{
UUID_driver: data.uuid_driver,
UUID_rider: data.uuid,
Score: data.score,
RiderPhone: data.phone
},
'/cancel-rider-match'
);
}
function cancelDriveOffer() {
sendAjaxRequest(
{
uuid: data.uuid,
DriverPhone: data.phone
},
'/cancel-drive-offer'
);
}
function cancelDriverMatch() {
sendAjaxRequest(
{
UUID_driver: data.uuid_driver,
UUID_rider: data.uuid,
Score: data.score,
RiderPhone: data.phone
},
'/cancel-driver-match'
);
}
function acceptDriverMatch() {
sendAjaxRequest(
{
UUID_driver: data.uuid,
UUID_rider: data.uuid_rider,
Score: data.score,
DriverPhone: data.phone
},
'/accept-driver-match'
);
}
function pauseDriverMatch() {
sendAjaxRequest(
{
uuid: data.uuid,
DriverPhone: data.phone
},
'/pause-driver-match'
);
}
function logout() {
window.location.search = tinyQuery.remove(['type','uuid','uuid_driver','uuid_rider']);
}
function sendAjaxRequest(ajaxData, ajaxPath) {
var url = tinyQuery.set(ajaxData, remoteUrl + ajaxPath);
$info.html('⏳ Loading…');
$.getJSON(url, function(dbInfo) {
var keys = Object.keys(dbInfo);
if (keys) {
info = dbInfo[keys[0]].toString();
$info.text('ℹ️ ' + info);
}
})
.fail(function(err) {
$info.text('⚠️ ' + err.statusText);
});
}
|
JavaScript
| 0 |
@@ -2041,24 +2041,138 @@
Request() %7B%0A
+ if (!window.confirm('This will cancel your ride request. Are you sure you want to proceed?')) %7B%0A return;%0A %7D%0A
sendAjaxRe
@@ -2170,32 +2170,32 @@
endAjaxRequest(%0A
-
%7B%0A uuid
@@ -2300,32 +2300,144 @@
lRiderMatch() %7B%0A
+ if (!window.confirm('This will cancel your ride match. Are you sure you want to proceed?')) %7B%0A return;%0A %7D%0A
sendAjaxReques
@@ -2632,24 +2632,136 @@
veOffer() %7B%0A
+ if (!window.confirm('This will cancel your ride offer. Are you sure you want to proceed?')) %7B%0A return;%0A %7D%0A
sendAjaxRe
@@ -2859,32 +2859,32 @@
-offer'%0A );%0A%7D%0A%0A
-
function cancelD
@@ -2890,32 +2890,144 @@
DriverMatch() %7B%0A
+ if (!window.confirm('This will cancel your ride match. Are you sure you want to proceed?')) %7B%0A return;%0A %7D%0A
sendAjaxReques
|
bfb0983f1155ae89f23da3bbf3ca78129c824cc5
|
add usage instructions
|
native/blockstackProxy.js
|
native/blockstackProxy.js
|
var http = require("http"),
path = require("path"),
url = require("url"),
fs = require("fs"),
port = process.argv[2] || 8888;
basePath = process.argv[3] || "./browser";
/*
Our own quick mime lookup because nexe fails to
include the npm package mime's list of mime types
*/
var mimeLookup = function(filename) {
var tokens = filename.split('.');
if(tokens.length == 0) // default to html
return "text/html";
var extension = tokens[tokens.length - 1];
if(extension == "html")
return "text/html";
if(extension == "png")
return "image/png";
if(extension == "svg")
return "image/svg+xml";
if(extension == "jpg")
return "image/jpeg";
if(extension == "css")
return "text/css";
return "text/html";
}
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(basePath, uri);
fs.exists(filename, function(exists) {
/* Always load the single page app index.html
unless another file exists or this is a directory */
if(!exists || fs.statSync(filename).isDirectory()) {
filename = basePath + "/index.html"
}
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200, {"Content-Type": mimeLookup(filename)});
response.write(file, "binary");
response.end();
});
});
}).listen(parseInt(port, 10));
console.log("Blockstack Browser proxy server running at: http://localhost:" + port);
console.log("Browser path: " + basePath);
console.log("Press Control + C to shutdown");
|
JavaScript
| 0.011399 |
@@ -1,12 +1,139 @@
+/*%0A Quick and dirty server for serving single page apps on localhost. %0A%0A Usage:%0A node blockstackProxy.js %3Cport%3E %3CbasePath%3E%0A*/%0A%0A
var http = r
|
8c269883fd4353414ea5b6cf77c80bfa54a4ae2f
|
remove a duplicate file in angularFiles.js
|
angularFiles.js
|
angularFiles.js
|
angularFiles = {
'angularSrc': [
'src/Angular.js',
'src/loader.js',
'src/AngularPublic.js',
'src/jqLite.js',
'src/apis.js',
'src/auto/injector.js',
'src/ng/anchorScroll.js',
'src/ng/browser.js',
'src/ng/cacheFactory.js',
'src/ng/compile.js',
'src/ng/controller.js',
'src/ng/document.js',
'src/ng/exceptionHandler.js',
'src/ng/interpolate.js',
'src/ng/location.js',
'src/ng/log.js',
'src/ng/parse.js',
'src/ng/q.js',
'src/ng/route.js',
'src/ng/routeParams.js',
'src/ng/rootScope.js',
'src/ng/sniffer.js',
'src/ng/window.js',
'src/ng/http.js',
'src/ng/httpBackend.js',
'src/ng/locale.js',
'src/ng/timeout.js',
'src/ng/filter.js',
'src/ng/filter/filter.js',
'src/ng/filter/filters.js',
'src/ng/filter/limitTo.js',
'src/ng/filter/orderBy.js',
'src/ng/directive/directives.js',
'src/ng/directive/a.js',
'src/ng/directive/booleanAttrs.js',
'src/ng/directive/form.js',
'src/ng/directive/input.js',
'src/ng/directive/ngBind.js',
'src/ng/directive/ngClass.js',
'src/ng/directive/ngCloak.js',
'src/ng/directive/ngController.js',
'src/ng/directive/ngCsp.js',
'src/ng/directive/ngEventDirs.js',
'src/ng/directive/ngInclude.js',
'src/ng/directive/ngInit.js',
'src/ng/directive/ngNonBindable.js',
'src/ng/directive/ngPluralize.js',
'src/ng/directive/ngRepeat.js',
'src/ng/directive/ngShowHide.js',
'src/ng/directive/ngStyle.js',
'src/ng/directive/ngSwitch.js',
'src/ng/directive/ngTransclude.js',
'src/ng/directive/ngView.js',
'src/ng/directive/script.js',
'src/ng/directive/select.js',
'src/ng/directive/style.js'
],
'angularSrcModules': [
'src/ngCookies/cookies.js',
'src/ngResource/resource.js',
'src/ngSanitize/sanitize.js',
'src/ngSanitize/directive/ngBindHtml.js',
'src/ngSanitize/filter/linky.js',
'src/ngMock/angular-mocks.js',
'src/bootstrap/bootstrap.js'
],
'angularScenario': [
'src/ngScenario/Scenario.js',
'src/ngScenario/Application.js',
'src/ngScenario/Describe.js',
'src/ngScenario/Future.js',
'src/ngScenario/ObjectModel.js',
'src/ngScenario/Describe.js',
'src/ngScenario/Runner.js',
'src/ngScenario/SpecRunner.js',
'src/ngScenario/dsl.js',
'src/ngScenario/matchers.js',
'src/ngScenario/output/Html.js',
'src/ngScenario/output/Json.js',
'src/ngScenario/output/Xml.js',
'src/ngScenario/output/Object.js'
],
'angularTest': [
'test/testabilityPatch.js',
'test/matchers.js',
'test/ngScenario/*.js',
'test/ngScenario/output/*.js',
'test/ngScenario/jstd-scenario-adapter/*.js',
'test/*.js',
'test/auto/*.js',
'test/bootstrap/*.js',
'test/ng/*.js',
'test/ng/directive/*.js',
'test/ng/filter/*.js',
'test/ngCookies/*.js',
'test/ngResource/*.js',
'test/ngSanitize/*.js',
'test/ngSanitize/directive/*.js',
'test/ngSanitize/filter/*.js',
'test/ngMock/*.js'
],
'jstd': [
'lib/jasmine/jasmine.js',
'lib/jasmine-jstd-adapter/JasmineAdapter.js',
'lib/jquery/jquery.js',
'test/jquery_remove.js',
'@angularSrc',
'src/publishExternalApis.js',
'@angularSrcModules',
'@angularScenario',
'src/ngScenario/jstd-scenario-adapter/Adapter.js',
'@angularTest',
'example/personalLog/*.js',
'example/personalLog/test/*.js'
],
'jstdExclude': [
'test/jquery_alias.js',
'src/angular-bootstrap.js',
'src/ngScenario/angular-bootstrap.js'
],
'jstdScenario': [
'build/angular-scenario.js',
'build/jstd-scenario-adapter-config.js',
'build/jstd-scenario-adapter.js',
'build/docs/docs-scenario.js'
],
"jstdModules": [
'lib/jasmine/jasmine.js',
'lib/jasmine-jstd-adapter/JasmineAdapter.js',
'build/angular.js',
'src/ngMock/angular-mocks.js',
'src/ngCookies/cookies.js',
'src/ngResource/resource.js',
'src/ngSanitize/sanitize.js',
'src/ngSanitize/directive/ngBindHtml.js',
'src/ngSanitize/filter/linky.js',
'test/matchers.js',
'test/ngMock/*.js',
'test/ngCookies/*.js',
'test/ngResource/*.js',
'test/ngSanitize/*.js',
'test/ngSanitize/directive/*.js',
'test/ngSanitize/filter/*.js'
],
'jstdPerf': [
'lib/jasmine/jasmine.js',
'lib/jasmine-jstd-adapter/JasmineAdapter.js',
'@angularSrc',
'@angularSrcModules',
'src/ngMock/angular-mocks.js',
'perf/data/*.js',
'perf/testUtils.js',
'perf/*.js'
],
'jstdPerfExclude': [
'src/ng/angular-bootstrap.js',
'src/ngScenario/angular-bootstrap.js'
],
'jstdJquery': [
'lib/jasmine/jasmine.js',
'lib/jasmine-jstd-adapter/JasmineAdapter.js',
'lib/jquery/jquery.js',
'test/jquery_alias.js',
'@angularSrc',
'src/publishExternalApis.js',
'@angularSrcModules',
'@angularScenario',
'src/ngScenario/jstd-scenario-adapter/Adapter.js',
'@angularTest',
'example/personalLog/*.js',
'example/personalLog/test/*.js'
],
'jstdJqueryExclude': [
'src/angular-bootstrap.js',
'src/ngScenario/angular-bootstrap.js',
'test/jquery_remove.js'
]
};
if (exports) {
exports.files = angularFiles
exports.mergeFiles = function mergeFiles() {
var files = [];
[].splice.call(arguments, 0).forEach(function(file) {
if (file.match(/testacular/)) {
files.push(file);
} else {
angularFiles[file].forEach(function(f) {
// replace @ref
var match = f.match(/^\@(.*)/);
if (match) {
var deps = angularFiles[match[1]];
files = files.concat(deps);
} else {
if (!/jstd|jasmine/.test(f)) { //TODO(i): remove once we don't have jstd/jasmine in repo
files.push(f);
}
}
});
}
});
return files;
}
}
|
JavaScript
| 0.000001 |
@@ -2215,42 +2215,8 @@
s',%0A
- 'src/ngScenario/Describe.js',%0A
|
084b9135df549c3f3127d5a656d25e7a3edb86fd
|
Add ability to add properties at the end.
|
arguable.js
|
arguable.js
|
var stream = require('stream')
var events = require('events')
var exit = require('./exit')
var Program = require('./program')
var slice = [].slice
// Use given stream or create pseudo-stream.
function createStream (s) { return s || new stream.PassThrough }
module.exports = function () {
// Variadic arguments.
var vargs = slice.call(arguments)
// First argument is always the module.
var module = vargs.shift()
// Usage source can be specified explicitly, or else it is sought in the
// comments of the main module.
var usage = typeof vargs[0] == 'string'
? vargs.shift()
: module.filename
// Check for default values for named parameters when argument parser is
// invoked as a main module.
var defaults = typeof vargs[0] == 'object' ? vargs.shift() : {}
// Ensure we have defaults.
defaults.argv || (defaults.argv = [])
defaults.properties || (defaults.properties = [])
// Main body of argument parser or program is final argument.
var main = vargs.shift()
var invoke = module.exports = function (argv, options, callback) {
var vargs = slice.call(arguments, arguments.length >= 3 ? 2 : 1)
var parameters = []
if (Array.isArray(argv)) {
argv = [ argv ]
} else {
var object = {}
for (var key in argv) {
object[key] = argv[key]
}
argv = [ object ]
if (Array.isArray(object.argv)) {
argv.push(object.argv)
delete object.argv
}
}
if (typeof options == 'function') {
callback = options
options = {}
}
argv.unshift(defaults.argv)
argv = argv.slice()
while (argv.length != 0) {
var argument = argv.shift()
switch (typeof argument) {
case 'object':
if (Array.isArray(argument)) {
argv.unshift.apply(argv, argument)
} else {
if (('name' in argument) &&
('value' in argument) &&
Object.keys(argument).length == 2
) {
parameters.push(argument)
} else {
for (var name in argument) {
parameters.push({ name: name, value: argument[name] })
}
}
}
break
default:
parameters.push(argument)
break
}
}
// What we're shooting for here is this:
//
// Create a signature that would be a reasonable signature for a
// generic function that is not an Arguable argument parser.
//
// Or put another way, tell the user to create an argument parser that
// accepts an arguments array and a pseudo-process, the program, and a
// callback, so that you can tell them to either use Arguable, or else
// implement an argument parser that accepts reasonable arguments as
// opposed to accepting convoluted named parameters.
//
// If options is really an `EventEmitter`, then our argument parser is
// being called as a universal submodule. This is an interface that
// allows a library module author to document that a submodule accepts
// an arguments array and a signal handler. The library module author
// can document as many `Program` features as they would like, or they
// could simply say that it is only for events, or they can say that it
// is mean to be ignored by the submodule author.
//
// Now the submodule author can use Arguable for their argument parser
// and program will be correctly configured, or they can create a
// function that takes the argument array and use the argument parser
// module of their choice. Additional properties are arguments to the
// argument parser, not properties on this mystery event emitter.
// Note that all the other options are debugging options.
if (options instanceof events.EventEmitter) {
options = { events: options }
options.stdin = options.events.stdin
options.stdout = options.events.stdout
options.stderr = options.events.stderr
}
// TODO Okay, now we have space for additional arguments that follow the
// event emitter or the options. These can be passed in as variadic
// arguments to be interpreted by the caller. This can be experimental.
//
var send = options.send || options.events && options.events.send && function () {
options.events.send.apply(options.events, slice.call(arguments))
}
var ee = options.events
if (ee == null) {
ee = new events.EventEmitter
ee.mainModule = process.mainModule
ee.connected = ('connected' in options) ? options.connected : true
ee.disconnect = function () { this.connected = false }
}
var isMainModule = ('isMainModule' in options)
? options.isMainModule
: process.mainModule === module
var program = new Program(usage, parameters, {
module: module,
stdout: createStream(options.stdout),
stdin: createStream(options.stdin),
stderr: createStream(options.stderr),
isMainModule: isMainModule,
events: ee,
properties: [ defaults.properties, options.properties || {} ],
send: send || null,
env: options.env || {}
})
main.apply(null, [ program ].concat(vargs))
return program
}
if (module === process.mainModule) {
invoke(process.argv.slice(2), {
// No. Stop! There is no `process.stdio`. Do not add one! (Again.)
env: process.env,
stdout: process.stdout,
stdin: process.stdin,
stderr: process.stderr,
events: process
}, exit(process))
}
}
|
JavaScript
| 0 |
@@ -1047,24 +1047,66 @@
gs.shift()%0A%0A
+ var properties = vargs.shift() %7C%7C %7B%7D%0A%0A
var invo
@@ -5758,16 +5758,28 @@
perties,
+ properties,
options
|
eecf3fd49ea355ba32e8faaff0e64571a472d52f
|
Send user email if logged in
|
controllers/home_controller.js
|
controllers/home_controller.js
|
module.exports = {
index: function(req, res, next){
res.render('index');
}
};
|
JavaScript
| 0 |
@@ -70,16 +70,58 @@
('index'
+, %7Buser: req.user ? req.user.email : null%7D
);%0A %7D%0A%0A
|
fc9a25f7a1e6c790ff4e276d0f7058e81c8240de
|
Include missing next param.
|
controllers/new_transaction.js
|
controllers/new_transaction.js
|
var async = require('async');
var _ = require('underscore');
var graph = require('fbgraph');
/**
* GET /new_transaction
* Contact form page.
*/
exports.getNewTransaction = function(req, res) {
var token = _.findWhere(req.user.tokens, { kind: 'facebook' });
graph.setAccessToken(token.accessToken);
async.parallel({
getMyFriends: function(done) {
graph.get(req.user.facebook + '/friends', function(err, friends) {
done(err, friends.data);
});
}
},
function(err, results) {
if (err) return next(err);
var friends = results.getMyFriends;
var friendsLength = Object.keys(friends).length;
var friendsJson = [];
for (var i = 0; i < friendsLength; i++) {
friendsJson.push("{name:'"+friends[i].name+"'}");
}
res.render('new_transaction', {
title: 'New Transaction',
friends: "["+friendsJson+"]"
});
});
};
/**
* POST /new_transaction
* Send a contact form via Nodemailer.
* @param name
* @param amount
* @param comment
*/
exports.postNewTransaction = function(req, res) {
req.assert('name', 'Name cannot be blank').notEmpty();
req.assert('comment', 'Comment cannot be blank').notEmpty();
var errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/new_transaction');
}
};
|
JavaScript
| 0 |
@@ -183,24 +183,30 @@
ion(req, res
+, next
) %7B%0A var to
|
4cf6b384d5bbda0f5d37ebfe7dd5c5215b170897
|
Rearrange exports
|
lib/node_modules/@stdlib/utils/index.js
|
lib/node_modules/@stdlib/utils/index.js
|
'use strict';
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
// UTILS //
var utils = {};
setReadOnly( utils, 'fs', {} );
// General:
setReadOnly( utils, 'setReadOnly', setReadOnly );
setReadOnly( utils, 'isLittleEndian', require( '@stdlib/utils/is-little-endian' ) );
setReadOnly( utils, 'moveProperty', require( '@stdlib/utils/move-property' ) );
setReadOnly( utils, 'noop', require( '@stdlib/utils/noop' ) );
setReadOnly( utils, 'evil', require( '@stdlib/utils/eval' ) );
setReadOnly( utils, 'tryFunction', require( '@stdlib/utils/try-function' ) );
setReadOnly( utils, 'repeatString', require( '@stdlib/utils/repeat-string' ) );
setReadOnly( utils, 'leftPadString', require( '@stdlib/utils/left-pad-string' ) );
setReadOnly( utils, 'rightPadString', require( '@stdlib/utils/right-pad-string' ) );
setReadOnly( utils, 'constructorName', require( '@stdlib/utils/constructor-name' ) );
setReadOnly( utils, 'functionName', require( '@stdlib/utils/function-name' ) );
// Feature detection:
setReadOnly( utils, 'hasClassSupport', require( '@stdlib/utils/detect-class-support' )() );
setReadOnly( utils, 'hasFunctionNameSupport', require( '@stdlib/utils/detect-function-name-support' )() );
setReadOnly( utils, 'hasGeneratorSupport', require( '@stdlib/utils/detect-generator-support' )() );
setReadOnly( utils, 'hasSymbolSupport', require( '@stdlib/utils/detect-symbol-support' )() );
setReadOnly( utils, 'hasToStringTagSupport', require( '@stdlib/utils/detect-tostringtag-support' )() );
// Type checking:
setReadOnly( utils, 'nativeClass', require( '@stdlib/utils/native-class' ) );
setReadOnly( utils, 'typeOf', require( '@stdlib/utils/type-of' ) );
setReadOnly( utils, 'isObjectLike', require( '@stdlib/utils/is-object-like' ) );
setReadOnly( utils, 'isBuffer', require( '@stdlib/utils/is-buffer' ) );
setReadOnly( utils, 'isString', require( '@stdlib/utils/is-string' ) );
setReadOnly( utils, 'isBoolean', require( '@stdlib/utils/is-boolean' ) );
setReadOnly( utils, 'isNumber', require( '@stdlib/utils/is-number' ) );
setReadOnly( utils, 'isInteger', require( '@stdlib/utils/is-integer' ) );
setReadOnly( utils, 'isNonNegativeInteger', require( '@stdlib/utils/is-nonnegative-integer' ) );
setReadOnly( utils, 'isBinaryString', require( '@stdlib/utils/is-binary-string' ) );
setReadOnly( utils, 'isPrimitive', require( '@stdlib/utils/is-primitive' ) );
setReadOnly( utils, 'isNaN', require( '@stdlib/utils/is-nan' ) );
setReadOnly( utils, 'isNull', require( '@stdlib/utils/is-null' ) );
setReadOnly( utils, 'isArray', require( '@stdlib/utils/is-array' ) );
setReadOnly( utils, 'isArrayLike', require( '@stdlib/utils/is-array-like' ) );
setReadOnly( utils, 'isTypedArray', require( '@stdlib/utils/is-typed-array' ) );
setReadOnly( utils, 'isFunction', require( '@stdlib/utils/is-function' ) );
// setReadOnly( utils, 'isObject', require( '@stdlib/utils/is-object' ) );
setReadOnly( utils, 'isObjectLike', require( '@stdlib/utils/is-object-like' ) );
setReadOnly( utils, 'isRegexp', require( '@stdlib/utils/is-regexp' ) );
setReadOnly( utils, 'isJSON', require( '@stdlib/utils/is-json' ) );
// Filesystem:
setReadOnly( utils.fs, 'exists', require( '@stdlib/utils/fs/exists' ) );
// EXPORTS //
module.exports = utils;
|
JavaScript
| 0.000036 |
@@ -2057,32 +2057,98 @@
s-number' ) );%0A%0A
+setReadOnly( utils, 'isNaN', require( '@stdlib/utils/is-nan' ) );%0A
setReadOnly( uti
@@ -2471,74 +2471,8 @@
);%0A
-setReadOnly( utils, 'isNaN', require( '@stdlib/utils/is-nan' ) );%0A
setR
|
f80d57203e65e5078731e415c5395def92b7e16a
|
create empty stats for missing content types
|
lib/plugins/coach/pagexrayAggregator.js
|
lib/plugins/coach/pagexrayAggregator.js
|
'use strict';
const statsHelpers = require('../../support/statsHelpers'),
forEach = require('lodash.foreach');
const METRIC_NAMES = ['transferSize', 'contentSize', 'requests'];
const CONTENT_TYPES = ['html', 'javascript', 'css', 'image', 'font'];
module.exports = {
stats: {},
addToAggregate(pageSummary) {
let stats = this.stats;
pageSummary.forEach(function(summary) {
// stats for the whole page
METRIC_NAMES.forEach(function(metric) {
statsHelpers.pushStats(stats, metric, summary[metric]);
})
// stats for each content type
CONTENT_TYPES.forEach(function(contentType) {
if (summary.contentTypes[contentType]) {
METRIC_NAMES.forEach(function(metric) {
statsHelpers.pushStats(stats, contentType + '.' + metric, summary.contentTypes[contentType][metric]);
});
}
});
})
},
summarize() {
return Object.keys(this.stats).reduce((summary, name) => {
if (METRIC_NAMES.indexOf(name) > -1) {
statsHelpers.setStatsSummary(summary, name, this.stats[name])
} else {
const data = {};
forEach(this.stats[name], (stats, metric) => {
statsHelpers.setStatsSummary(data, metric, stats)
});
summary[name] = data;
}
return summary;
}, {});
}
};
|
JavaScript
| 0.000001 |
@@ -841,32 +841,187 @@
;%0A %7D);%0A
+ %7D else %7B%0A METRIC_NAMES.forEach(function(metric) %7B%0A statsHelpers.pushStats(stats, contentType + '.' + metric, 0);%0A %7D);%0A
%7D%0A
|
ed9473377b74303afdafeb8d09f28fd2a5db5241
|
Fix confirm message in external links edit link view
|
entry_types/scrolled/package/src/contentElements/externalLinkList/editor/SidebarEditLinkView.js
|
entry_types/scrolled/package/src/contentElements/externalLinkList/editor/SidebarEditLinkView.js
|
import {ConfigurationEditorView, TextInputView, CheckBoxInputView, TextAreaInputView} from 'pageflow/ui';
import {editor, FileInputView} from 'pageflow/editor';
import Marionette from 'backbone.marionette';
import I18n from 'i18n-js';
export const SidebarEditLinkView = Marionette.Layout.extend({
template: (data) => `
<a class="back">${I18n.t('pageflow_scrolled.editor.content_elements.externalLinkList.back')}</a>
<a class="destroy">${I18n.t('pageflow_scrolled.editor.content_elements.externalLinkList.destroy')}</a>
<div class='form_container'></div>
`,
className: 'edit_external_link',
regions: {
formContainer: '.form_container',
},
events: {
'click a.back': 'goBack',
'click a.destroy': 'destroyLink'
},
initialize: function(options) {},
onRender: function () {
var configurationEditor = new ConfigurationEditorView({
model: this.model,
attributeTranslationKeyPrefixes: ['pageflow_scrolled.editor.content_elements.externalLinkList.attributes'],
tabTranslationKeyPrefix: 'pageflow_scrolled.editor.content_elements.externalLinkList.tabs'
});
var self = this;
configurationEditor.tab('edit_link', function () {
this.input('url', TextInputView, {
required: true
});
this.input('open_in_new_tab', CheckBoxInputView);
this.input('thumbnail', FileInputView, {
collection: 'image_files',
fileSelectionHandler: 'contentElement.externalLinks.link',
fileSelectionHandlerOptions: {
contentElementId: self.options.contentElement.get('id')
},
positioning: false
});
this.input('title', TextInputView, {
required: true
});
this.input('description', TextAreaInputView, {
size: 'short',
disableLinks: true
});
});
this.formContainer.show(configurationEditor);
},
goBack: function() {
editor.navigate(`/scrolled/content_elements/${this.options.contentElement.get('id')}`, {trigger: true});
},
destroyLink: function () {
if (confirm('pageflow_scrolled.editor.content_elements.externalLinkList.confirm_delete_link')) {
this.options.collection.remove(this.model);
this.goBack();
}
},
});
|
JavaScript
| 0 |
@@ -2043,23 +2043,37 @@
if (
-confirm
+window.confirm(I18n.t
('pagefl
@@ -2147,16 +2147,17 @@
_link'))
+)
%7B%0A
|
ebec266f0a5eabe24f275086d89dc65be8ff1113
|
Update expected .grn dump
|
test/api-configuration.js
|
test/api-configuration.js
|
var utils = require('./test-utils');
var assert = require('chai').assert;
var fs = require('fs');
var nroonga = require('nroonga');
var temporaryDatabase;
suiteSetup(function() {
temporaryDatabase = utils.createTemporaryDatabase();
});
suiteTeardown(function() {
temporaryDatabase.teardown();
temporaryDatabase = undefined;
});
suite('Configuration API', function() {
var database;
var server;
setup(function() {
database = temporaryDatabase.get();
server = utils.setupServer(database);
});
teardown(function() {
server.close();
temporaryDatabase.clear();
});
test('Get, Action=CreateDomain', function(done) {
var path = '/?DomainName=companies&Action=CreateDomain';
utils.get(path)
.next(function(response) {
var expected = {
statusCode: 200,
body: ''
};
// assert.deepEqual(response, expected);
var dump = database.commandSync('dump', {
tables: 'companies'
});
var expected = 'table_create companies_BigramTerms TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram\n' +
'table_create companies TABLE_HASH_KEY ShortText'
assert.equal(dump, expected);
done();
})
.error(function(error) {
done(error);
});
});
});
|
JavaScript
| 0 |
@@ -1053,168 +1053,229 @@
nies
-_BigramTerms TABLE_PAT_KEY%7CKEY_NORMALIZE ShortText --default_tokenizer TokenBigram%5Cn' +%0A 'table_create companies TABLE_HASH_KEY ShortText'
+ TABLE_HASH_KEY ShortText%5Cn' +%0A 'table_create companies_BigramTerms ' +%0A 'TABLE_PAT_KEY%7CKEY_NORMALIZE ShortText ' +%0A '--default_tokenizer TokenBigram';
%0A
|
d5be79d7efe530a42d21d1d0da9329d34b2c10a7
|
Add missing containers prop in ContainerSelect tests.
|
assets/js/modules/tagmanager/components/common/ContainerSelect.test.js
|
assets/js/modules/tagmanager/components/common/ContainerSelect.test.js
|
/**
* Container Select component tests.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import ContainerSelect from './ContainerSelect';
import { render, act } from '../../../../../../tests/js/test-utils';
import { STORE_NAME, ACCOUNT_CREATE } from '../../datastore/constants';
import { createTestRegistry } from '../../../../../../tests/js/utils';
import * as factories from '../../datastore/__factories__';
describe( 'ContainerSelect', () => {
let registry;
beforeEach( () => {
registry = createTestRegistry();
// Set settings to prevent fetch in resolver.
registry.dispatch( STORE_NAME ).setSettings( {} );
// Set set no existing tag.
registry.dispatch( STORE_NAME ).receiveGetExistingTag( null );
} );
it( 'should be disabled if there is an existing tag', async () => {
const account = factories.accountBuilder();
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( STORE_NAME ).setAccountID( account.accountId );
registry.dispatch( STORE_NAME ).receiveGetContainers( [], { accountID: account.accountId } );
const { container } = render( <ContainerSelect />, { registry } );
const select = container.querySelector( '.mdc-select' );
expect( select ).not.toHaveClass( 'mdc-select--disabled' );
await act( () => registry.dispatch( STORE_NAME ).receiveGetExistingTag( 'GTM-G000GL3' ) );
expect( select ).toHaveClass( 'mdc-select--disabled' );
} );
it( 'should be disabled if the selected account is not a valid account', async () => {
const account = factories.accountBuilder();
registry.dispatch( STORE_NAME ).receiveGetAccounts( [ account ] );
registry.dispatch( STORE_NAME ).setAccountID( account.accountId );
registry.dispatch( STORE_NAME ).receiveGetContainers( [], { accountID: account.accountId } );
const { container } = render( <ContainerSelect />, { registry } );
const select = container.querySelector( '.mdc-select' );
expect( select ).not.toHaveClass( 'mdc-select--disabled' );
// The account option to "set up a new account" is technically an invalid accountID.
await act( () => registry.dispatch( STORE_NAME ).setAccountID( ACCOUNT_CREATE ) );
expect( select ).toHaveClass( 'mdc-select--disabled' );
} );
} );
|
JavaScript
| 0 |
@@ -1706,32 +1706,50 @@
%3CContainerSelect
+ containers=%7B %5B%5D %7D
/%3E, %7B registry
@@ -2452,16 +2452,34 @@
erSelect
+ containers=%7B %5B%5D %7D
/%3E, %7B r
|
c9ab977d736c64c43e1580283ae219759bcf833a
|
Fix unit tests
|
test/app-tests/joining.js
|
test/app-tests/joining.js
|
/*
Copyright 2016 OpenMarket Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* joining.js: tests for the various paths when joining a room */
require('skin-sdk');
var jssdk = require('matrix-js-sdk');
var sdk = require('matrix-react-sdk');
var peg = require('matrix-react-sdk/lib/MatrixClientPeg');
var dis = require('matrix-react-sdk/lib/dispatcher');
var MatrixChat = sdk.getComponent('structures.MatrixChat');
var RoomDirectory = sdk.getComponent('structures.RoomDirectory');
var RoomPreviewBar = sdk.getComponent('rooms.RoomPreviewBar');
var RoomView = sdk.getComponent('structures.RoomView');
var React = require('react');
var ReactDOM = require('react-dom');
var ReactTestUtils = require('react-addons-test-utils');
var expect = require('expect');
var q = require('q');
var test_utils = require('../test-utils');
var MockHttpBackend = require('../mock-request');
var HS_URL='http://localhost';
var IS_URL='http://localhost';
var USER_ID='@me:localhost';
var ACCESS_TOKEN='access_token';
describe('joining a room', function () {
describe('over federation', function () {
var parentDiv;
var httpBackend;
var matrixChat;
beforeEach(function() {
test_utils.beforeEach(this);
httpBackend = new MockHttpBackend();
jssdk.request(httpBackend.requestFn);
parentDiv = document.createElement('div');
// uncomment this to actually add the div to the UI, to help with
// debugging (but slow things down)
// document.body.appendChild(parentDiv);
});
afterEach(function() {
if (parentDiv) {
ReactDOM.unmountComponentAtNode(parentDiv);
parentDiv.remove();
parentDiv = null;
}
});
it('should not get stuck at a spinner', function(done) {
var ROOM_ALIAS = '#alias:localhost';
var ROOM_ID = '!id:localhost';
httpBackend.when('PUT', '/presence/'+encodeURIComponent(USER_ID)+'/status')
.respond(200, {});
httpBackend.when('GET', '/pushrules').respond(200, {});
httpBackend.when('POST', '/filter').respond(200, { filter_id: 'fid' });
httpBackend.when('GET', '/sync').respond(200, {});
httpBackend.when('GET', '/publicRooms').respond(200, {chunk: []});
httpBackend.when('GET', '/directory/room/'+encodeURIComponent(ROOM_ALIAS)).respond(200, { room_id: ROOM_ID });
// start with a logged-in client
peg.replaceUsingAccessToken(HS_URL, IS_URL, USER_ID, ACCESS_TOKEN);
var mc = <MatrixChat config={{}}/>;
matrixChat = ReactDOM.render(mc, parentDiv);
// switch to the Directory
dis.dispatch({
action: 'view_room_directory',
});
var roomView;
httpBackend.flush().then(() => {
var roomDir = ReactTestUtils.findRenderedComponentWithType(
matrixChat, RoomDirectory);
// enter an alias in the input, and simulate enter
var input = ReactTestUtils.findRenderedDOMComponentWithTag(
roomDir, 'input');
input.value = ROOM_ALIAS;
ReactTestUtils.Simulate.keyUp(input, {key: 'Enter'});
// that should create a roomview which will start a peek; wait
// for the peek.
httpBackend.when('GET', '/rooms/'+encodeURIComponent(ROOM_ID)+"/initialSync")
.respond(401, {errcode: 'M_GUEST_ACCESS_FORBIDDEN'});
return httpBackend.flush();
}).then(() => {
httpBackend.verifyNoOutstandingExpectation();
// we should now have a roomview, with a preview bar
roomView = ReactTestUtils.findRenderedComponentWithType(
matrixChat, RoomView);
var previewBar = ReactTestUtils.findRenderedComponentWithType(
roomView, RoomPreviewBar);
var joinLink = ReactTestUtils.findRenderedDOMComponentWithTag(
previewBar, 'a');
ReactTestUtils.Simulate.click(joinLink);
// that will fire off a request to check our displayname, followed by a
// join request
httpBackend.when('GET', '/profile/'+encodeURIComponent(USER_ID))
.respond(200, {displayname: 'boris'});
httpBackend.when('POST', '/join/'+encodeURIComponent(ROOM_ALIAS))
.respond(200, {room_id: ROOM_ID});
return httpBackend.flush();
}).then(() => {
httpBackend.verifyNoOutstandingExpectation();
// the roomview should now be loading
expect(roomView.state.room).toBe(null);
expect(roomView.state.joining).toBe(true);
// there should be a spinner
ReactTestUtils.findRenderedDOMComponentWithClass(
roomView, "mx_Spinner");
// now send the room down the /sync pipe
httpBackend.when('GET', '/sync').
respond(200, {
rooms: {
join: {
[ROOM_ID]: {
state: {},
timeline: {
events: [],
limited: true,
},
},
},
},
});
return httpBackend.flush();
}).then(() => {
// now the room should have loaded
expect(roomView.state.room).toExist();
expect(roomView.state.joining).toBe(false);
}).done(done, done);
});
});
});
|
JavaScript
| 0.000003 |
@@ -3080,57 +3080,217 @@
sing
-AccessToken(HS_URL, IS_URL, USER_ID, ACCESS_TOKEN
+Creds(%7B%0A homeserverUrl: HS_URL,%0A identityServerUrl: IS_URL,%0A userId: USER_ID,%0A accessToken: ACCESS_TOKEN,%0A guest: false,%0A %7D
);%0A
|
161978ab05c5541d405acce7cd7ea23d3d4d8b71
|
Fix tests
|
test/app-tests/joining.js
|
test/app-tests/joining.js
|
/*
Copyright 2016 OpenMarket Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* joining.js: tests for the various paths when joining a room */
require('skin-sdk');
var jssdk = require('matrix-js-sdk');
var sdk = require('matrix-react-sdk');
var peg = require('matrix-react-sdk/lib/MatrixClientPeg');
var dis = require('matrix-react-sdk/lib/dispatcher');
var MatrixChat = sdk.getComponent('structures.MatrixChat');
var RoomDirectory = sdk.getComponent('structures.RoomDirectory');
var RoomPreviewBar = sdk.getComponent('rooms.RoomPreviewBar');
var RoomView = sdk.getComponent('structures.RoomView');
var React = require('react');
var ReactDOM = require('react-dom');
var ReactTestUtils = require('react-addons-test-utils');
var expect = require('expect');
var q = require('q');
var test_utils = require('../test-utils');
var MockHttpBackend = require('../mock-request');
var HS_URL='http://localhost';
var IS_URL='http://localhost';
var USER_ID='@me:localhost';
var ACCESS_TOKEN='access_token';
describe('joining a room', function () {
describe('over federation', function () {
var parentDiv;
var httpBackend;
var matrixChat;
beforeEach(function() {
test_utils.beforeEach(this);
httpBackend = new MockHttpBackend();
jssdk.request(httpBackend.requestFn);
parentDiv = document.createElement('div');
// uncomment this to actually add the div to the UI, to help with
// debugging (but slow things down)
// document.body.appendChild(parentDiv);
});
afterEach(function() {
if (parentDiv) {
ReactDOM.unmountComponentAtNode(parentDiv);
parentDiv.remove();
parentDiv = null;
}
});
it('should not get stuck at a spinner', function(done) {
var ROOM_ALIAS = '#alias:localhost';
var ROOM_ID = '!id:localhost';
httpBackend.when('PUT', '/presence/'+encodeURIComponent(USER_ID)+'/status')
.respond(200, {});
httpBackend.when('GET', '/pushrules').respond(200, {});
httpBackend.when('POST', '/filter').respond(200, { filter_id: 'fid' });
httpBackend.when('GET', '/sync').respond(200, {});
httpBackend.when('POST', '/publicRooms').respond(200, {chunk: []});
httpBackend.when('GET', '/directory/room/'+encodeURIComponent(ROOM_ALIAS)).respond(200, { room_id: ROOM_ID });
// start with a logged-in client
localStorage.setItem("mx_hs_url", HS_URL );
localStorage.setItem("mx_is_url", IS_URL );
localStorage.setItem("mx_access_token", ACCESS_TOKEN );
localStorage.setItem("mx_user_id", USER_ID);
var mc = <MatrixChat config={{}}/>;
matrixChat = ReactDOM.render(mc, parentDiv);
// switch to the Directory
dis.dispatch({
action: 'view_room_directory',
});
var roomView;
httpBackend.flush().then(() => {
var roomDir = ReactTestUtils.findRenderedComponentWithType(
matrixChat, RoomDirectory);
// enter an alias in the input, and simulate enter
var input = ReactTestUtils.findRenderedDOMComponentWithTag(
roomDir, 'input');
input.value = ROOM_ALIAS;
ReactTestUtils.Simulate.change(input);
ReactTestUtils.Simulate.keyUp(input, {key: 'Enter'});
// that should create a roomview which will start a peek; wait
// for the peek.
httpBackend.when('GET', '/rooms/'+encodeURIComponent(ROOM_ID)+"/initialSync")
.respond(401, {errcode: 'M_GUEST_ACCESS_FORBIDDEN'});
return httpBackend.flush();
}).then(() => {
httpBackend.verifyNoOutstandingExpectation();
// we should now have a roomview, with a preview bar
roomView = ReactTestUtils.findRenderedComponentWithType(
matrixChat, RoomView);
var previewBar = ReactTestUtils.findRenderedComponentWithType(
roomView, RoomPreviewBar);
var joinLink = ReactTestUtils.findRenderedDOMComponentWithTag(
previewBar, 'a');
ReactTestUtils.Simulate.click(joinLink);
// that will fire off a request to check our displayname, followed by a
// join request
httpBackend.when('GET', '/profile/'+encodeURIComponent(USER_ID))
.respond(200, {displayname: 'boris'});
httpBackend.when('POST', '/join/'+encodeURIComponent(ROOM_ALIAS))
.respond(200, {room_id: ROOM_ID});
return httpBackend.flush();
}).then(() => {
httpBackend.verifyNoOutstandingExpectation();
// the roomview should now be loading
expect(roomView.state.room).toBe(null);
expect(roomView.state.joining).toBe(true);
// there should be a spinner
ReactTestUtils.findRenderedDOMComponentWithClass(
roomView, "mx_Spinner");
// now send the room down the /sync pipe
httpBackend.when('GET', '/sync').
respond(200, {
rooms: {
join: {
[ROOM_ID]: {
state: {},
timeline: {
events: [],
limited: true,
},
},
},
},
});
return httpBackend.flush();
}).then(() => {
// now the room should have loaded
expect(roomView.state.room).toExist();
expect(roomView.state.joining).toBe(false);
}).done(done, done);
});
});
});
|
JavaScript
| 0.000003 |
@@ -2848,24 +2848,103 @@
hunk: %5B%5D%7D);%0A
+ httpBackend.when('GET', '/thirdparty/protocols').respond(200, %7B%7D);%0A
@@ -5485,32 +5485,259 @@
%7D).then(() =%3E %7B%0A
+ // wait for the join request to be made%0A return q.delay(1);%0A %7D).then(() =%3E %7B%0A // flush it through%0A return httpBackend.flush();%0A %7D).then(() =%3E %7B%0A
|
42b44e51f2c5366a23d57ebbbc5963d2c048b9bd
|
test order of layers
|
test/base/feed-forward.js
|
test/base/feed-forward.js
|
'use strict';
import assert from 'assert';
import FeedForward from '../../src/feed-forward';
import { input, output, convolution, relu, pool, softMax } from '../../src/layer';
describe('FeedForward Neural Network', () => {
describe('instantiation', () => {
describe('flat hiddenLayer option', () => {
it('can setup and traverse entire network as needed', () => {
const net = new FeedForward({
inputLayer: () => input(),
hiddenLayers: [
(input) => convolution({ filterCount: 8, filterWidth: 5, filterHeight: 5, padding: 2, stride: 1 }, input),
(input) => relu(input),
(input) => pool({ padding: 2, stride: 2 }, input),
(input) => convolution({ padding: 2, stride: 1, filterCount: 16, filterWidth: 5, filterHeight: 5 }, input),
(input) => relu(input),
(input) => pool({ width: 3, stride: 3 }, input),
(input) => softMax({ width: 10 }, input)
],
outputLayer: () => output({ width: 10 })
});
assert.equal(net.layers.length, 9);
});
});
describe('functional hiddenLayer option', () => {
const net = new FeedForward({
inputLayer: () => input(),
hiddenLayers: [
(input) => softMax({ width: 10 },
pool({ width: 3, stride: 3 },
relu(
convolution({ padding: 2, stride: 1, filterCount: 16, filterWidth: 5, filterHeight: 5 },
pool({ padding: 2, stride: 2 },
relu(
convolution({ filterCount: 8, filterWidth: 5, filterHeight: 5, padding: 2, stride: 1 }, input)
)
)
)
)
)
)
],
outputLayer: () => output({ width: 10 })
});
assert.equal(net.layers.length, 9);
});
});
});
|
JavaScript
| 0.000002 |
@@ -105,16 +105,23 @@
put,
+ Input,
output,
con
@@ -116,16 +116,24 @@
output,
+ Output,
convolu
@@ -142,21 +142,55 @@
on,
-relu, pool, s
+Convolution, relu, Relu, pool, Pool, softMax, S
oftM
@@ -1124,24 +1124,270 @@
length, 9);%0A
+ assert.deepEqual(net.layers.map(layer =%3E layer.constructor), %5B%0A Input,%0A Convolution,%0A Relu,%0A Pool,%0A Convolution,%0A Relu,%0A Pool,%0A SoftMax,%0A Output%0A %5D);%0A
%7D);%0A
@@ -2113,24 +2113,24 @@
)%0A %7D);%0A
-
assert
@@ -2155,24 +2155,248 @@
length, 9);%0A
+ assert.deepEqual(net.layers.map(layer =%3E layer.constructor), %5B%0A Input,%0A Convolution,%0A Relu,%0A Pool,%0A Convolution,%0A Relu,%0A Pool,%0A SoftMax,%0A Output%0A %5D);%0A
%7D);%0A %7D)
|
0c2c52e590be5fa4a22f1a4c9fb78d5061652d5d
|
fix nanoModal reference
|
lib/settings-forum/delete-modal-view.js
|
lib/settings-forum/delete-modal-view.js
|
import modal from 'nanomodal';
import FormView from '../form-view/form-view';
import template from './delete-modal.jade';
import forumStore from '../forum-store/forum-store';
export default class DeleteForumModal extends FormView {
/**
* Creates a profile edit view
*/
constructor (forum) {
super(template, { forum: forum });
this.forum = forum;
this.input = this.find('input.forum-name');
this.button = this.find('button.ok');
this.fire();
}
switchOn () {
this.bind('input', '.forum-name', this.bound('onchange'));
this.bind('click', '.close', this.bound('hide'));
this.on('error', this.bound('error'));
this.on('valid', this.bound('doDestroy'));
}
switchOff () {
this.unbind();
this.off('error');
}
fire () {
this.modal = modal('', { buttons: [] });
this.modal.modal.add(this.el[0]);
this.show();
}
onchange () {
if (this.input.val() == this.forum.name) {
this.button.attr('disabled', null);
} else {
this.button.attr('disabled', true);
}
}
error () {
this.find('.form-messages').removeClass('hide');
}
show () {
this.modal.show();
}
hide () {
this.modal.hide();
}
doDestroy () {
this.loading();
forumStore.destroy(this.forum.name)
.then(() => {
this.hide();
this.unloading();
})
.catch(() => {
this.unloading();
});
}
}
|
JavaScript
| 0 |
@@ -1,16 +1,20 @@
import
-m
+nanoM
odal fro
@@ -797,17 +797,21 @@
modal =
-m
+nanoM
odal('',
|
a92582a477c53f6bea8c222de4611cdae574e3d0
|
add placeholders for clisk on mocked request
|
lib/ui/components/new/MockedRequests.js
|
lib/ui/components/new/MockedRequests.js
|
import React from 'react';
import styled from 'styled-components';
const List = styled.div`
`;
const Mock = styled.div`
display: flex;
align-items: center;
padding: 4px;
background-color: ${(props) => props.isSelected ? '#cbddf5' : 'white'};
&:hover {
cursor: ${(props) => props.isSelected ? 'default' : 'pointer'};
background-color: #cbddf5;
}
`;
const Method = styled.div`
font-size: 12px;
min-width: 40px;
`;
const URL = styled.div`
font-size: 12px;
flex-grow: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
`;
const Checkbox = styled.input`
`;
const MockedRequests = (props) => (
<List>
{
props.API.mockedRequests.map((mock) => (
<Mock onClick={ () => props.selectMock(mock) } isSelected={ mock === props.selectedMock }>
<Method>{ mock.method }</Method>
<URL>{ mock.url }</URL>
<Checkbox type="checkbox" checked={ mock.active }/>
</Mock>
))
}
</List>
);
export default MockedRequests;
|
JavaScript
| 0 |
@@ -756,16 +756,30 @@
(mock) %7D
+%0A
isSelec
@@ -813,16 +813,147 @@
edMock %7D
+%0A onDoubleClick=%7B () =%3E console.log('RENAME MOCK') %7D%0A onContextMenu=%7B () =%3E console.log('CONTEXT MENU') %7D
%3E%0A
|
9ae7aaecbf423392b6879da458c83a53a6023026
|
add filename key to output
|
server/core/compile.js
|
server/core/compile.js
|
'use babel';
/* @flow */
/**
* Compile Data With Template
*
* The MIT License (MIT)
* Copyright (c) 2014 Equan Pr.
*/
'use strict';
var TEMPLATE_INDEX = 'template/index.hbs';
var STATIC_FOLDER = 'static';
var fs = require('fs');
var handlebars = require('handlebars');
var mkdirp = require('mkdirp');
var root = require('../util').path();
var static_folder = `${root}/${STATIC_FOLDER}/`;
var { genFilename } = require('./helper');
import type { Post, PostCreated, PostDocument } from './types.js';
function compile(docData:Post): Promise {
return new Promise((resolve, reject) => {
var { title, postCreated } = docData;
fs.readFile(`${root}/${TEMPLATE_INDEX}`, 'utf-8', (err, data) => {
var pageBuilder = handlebars.compile(data);
var dateCreated:PostCreated = {
year: postCreated.getFullYear(),
month: postCreated.getMonth(),
date: postCreated.getDate()
};
var docContent:PostDocument = {
filename: `${genFilename(title)}.html`,
compiledContent: pageBuilder(docData),
postCreated: dateCreated,
post: docData
};
saveCompiled(docContent).then((status) => {
resolve(status);
}, (err) => {
reject(err);
})
});
});
}
function saveCompiled(data: PostDocument): Promise {
var { filename, postCreated: { year: y, month: m, date: d}, compiledContent, post:{title:postTitle, status: postStatus, postCreated: pCreated}} = data;
var postDir = `${static_folder}/${y}/${m}/${d}`;
var filepath = `${postDir}/${filename}`;
return new Promise((resolve, reject) => {
mkdirp(postDir, (err) => {
if(!err) {
fs.writeFile(filepath, compiledContent, (err) => {
if(err) {
reject(err);
} else {
resolve({
title: postTitle,
status: postStatus,
created: pCreated
});
}
});
} else {
console.log(err);
return null;
}
});
});
}
module.exports = { compile, saveCompiled };
|
JavaScript
| 0.000003 |
@@ -401,16 +401,31 @@
Filename
+, cleanHtmlTags
%7D = req
@@ -2074,16 +2074,30 @@
title:
+cleanHtmlTags(
postTitl
@@ -2097,16 +2097,17 @@
ostTitle
+)
,%0A
@@ -2193,16 +2193,64 @@
pCreated
+,%0A filename: filename
%0A
|
6742625afe6ed1f36d6c1eeea050ad8f013f0b6a
|
Fix typo
|
server/downloadUrls.js
|
server/downloadUrls.js
|
var urlJoin = Npm.require('url-join');
// Global for tests.
parseMacDownloadUrl = function(electronSettings) {
if (!electronSettings || !electronSettings.downloadUrls || !electronSettings.downloadUrls.darwin) return;
return electronSettings.downloadUrls.darwin.replace('{{version}}', electronSettings.version);
};
// Global for tests.
parseWindowsDownloadUrls = function(electronSettings) {
if (!electronSettings || !electronSettings.downloadUrls || !electronSettings.downloadUrls.win32) return;
// The default value here is what `createBinaries` writes into the app's package.json, which is
// what is read by `grunt-electron-installer` to name the installer.
var appName = electronSettings.name || 'electron';
var releasesUrl, installerUrl;
var installerUrlIsVersioned = false;
if (_.isString(electronSettings.downloadUrls.win32)) {
if (electronSettings.downloadUrls.win32.indexOf('{{version}}') > -1) {
console.error('Only the Windows installer URL may be versioned. Specify `downloadUrls.win32.installer`.');
return;
}
releasesUrl = electronSettings.downloadUrls.win32;
// 'AppSetup.exe' refers to the output of `grunt-electron-installer`.
installerUrl = urlJoin(electronSettings.downloadUrls.win32, appName + 'Setup.exe');
} else {
releasesUrl = electronSettings.downloadUrls.win32.releases;
if (releasesUrl.indexOf('{{version}}') > -1) {
console.error('Only the Windows installer URL may be versioned.');
return;
}
installerUrl = electronSettings.downloadUrls.win32.installer;
if (installerUrl.indexOf('{{version}}') > -1) {
installerUrl = installerUrl.replace('{{version}}', electronSettings.version);
installerUrlIsVersioned = true;
}
}
// Cachebust the installer URL if it's not versioned.
// (The releases URL will also be cachebusted, but by `serveDownloadUrl` since we've got to append
// the particular paths requested by the client).
if (!installerUrlIsVersioned) {
installerUrl = cachebustedUrl(installerUrl);
}
return {
releases: releasesUrl,
installer: installerUrl
};
};
function cachebustedUrl(url) {
var querySeparator = (url.indexOf('?') > -1) ? '&' : '?';
return url + querySeparator + 'cb=' + Date.now();
}
DOWNLOAD_URLS = {
darwin: parseMacDownloadUrl(Meteor.settings.electron),
win32: parseWindowsDownloadUrls(Meteor.settings.electron)
};
|
JavaScript
| 0.999999 |
@@ -1865,27 +1865,26 @@
y %60serve
-DownloadUrl
+UpdateFeed
%60 since
|
70547272efd7a1bc27fd23f3fd6af53ccda55dd3
|
Making consistent
|
test/attachments/test.js
|
test/attachments/test.js
|
/*global require:true */
require(['backbone', 'jquery'], function (Backbone, jquery) {
$('#versions').append('<li>Backbone: ' + Backbone.VERSION + '</li>');
var DumbView = Backbone.View.extend({
tagName: "li",
render: function(){
var view = this;
var list = $("<ul></ul>");
list.append('<li>Length: ' + this.collection.length + '</li>');
list.append('<li>Total Length: ' + this.collection.totalLength + '</li>');
list.append('<li>Query options: ' + JSON.stringify(this.collection.cloudant_options) + '</li>');
// Print 10 rows out to the screen
_.each(this.collection.first(5), function(doc){
list.append('<li><pre><code>' + JSON.stringify(doc) + '</code></pre></li>');
});
$(view.id).html(list);
},
initialize: function(args){
this.collection = args.collection;
this.collection.on("reset", this.render, this);
this.collection.on("add", this.render, this);
}
});
// Bit of a hack to load out non- require module code
require(['backbone.cloudant'], function () {
$('#versions').append('<li>Backbone.Cloudant: ' + Backbone.Cloudant.VERSION + '</li>');
Backbone.Cloudant.database = "/backbone-cloudant-demo/";
// start the change handler
Backbone.Cloudant.changeHandler();
var all_docs = new Backbone.Cloudant.Docs.Collection();
var all_docs_view = new DumbView({collection: all_docs, id: '#all_docs'});
all_docs.fetch().fail(function(){console.log('Could not load all_docs collection');});
var view = new Backbone.Cloudant.Index();
view.design = 'app';
view.view = 'test';
view.cloudant_options = {"reduce": false, "limit": 10};
var view_view = new DumbView({collection: view, id: '#view'});
view.fetch().fail(function(){console.log('Could not load view collection');});
var reducedview = new Backbone.Cloudant.Index({"watch": true});
reducedview.design = 'app';
reducedview.view = 'test';
reducedview.cloudant_options = {"reduce": true, "group": true};
var reduced_view_view = new DumbView({collection: reducedview, id: '#reduced_view'});
reducedview.fetch().fail(function(){console.log('Could not load reduced view collection');});
var watchedview = new Backbone.Cloudant.Index({"watch": true});
watchedview.design = 'app';
watchedview.view = 'test';
watchedview.cloudant_options = {"reduce": false, "limit": 10, "descending": true};
var watchedview_view = new DumbView({collection: watchedview, id: '#watchedview'});
watchedview.fetch().fail(function(){console.log('Could not load watched view collection');});
var search = new Backbone.Cloudant.Search();
search.design = 'app';
search.index = 'mysearch';
search.cloudant_options = {"q": "a:1", "limit": 2};
var search_view = new DumbView({collection: search, id: '#search'});
search.fetch().fail(function(){console.log('Could not load search collection');});
var limited_all_docs = new Backbone.Cloudant.Docs.Collection();
limited_all_docs.cloudant_options = {"limit": 2, "skip": 5};
console.log(limited_all_docs);
var limited_all_docs_view = new DumbView({collection: limited_all_docs, id: '#limited_all_docs'});
limited_all_docs.fetch().fail(function(){console.log('Could not load all_docs collection');});
function testFetchMore(){
limited_all_docs.fetchMore();
search.fetchMore();
}
setTimeout(testFetchMore, 3000);
function addDocs(did){
var doc = new Backbone.Cloudant.Model();
doc.set("a", Math.floor(Math.random()*11));
doc.save();
if (did){
var deleteMe = new Backbone.Cloudant.Model({_id:did});
deleteMe.fetch({success: function(){
deleteMe.destroy();
}});
}
function loop(){
addDocs(doc.id);
}
setTimeout(loop, 10000);
}
addDocs();
});
});
|
JavaScript
| 0.999774 |
@@ -561,18 +561,17 @@
/ Print
-10
+5
rows ou
@@ -1675,18 +1675,17 @@
limit%22:
-10
+5
%7D;%0A%0A
@@ -2415,18 +2415,17 @@
limit%22:
-10
+5
, %22desce
|
0e3af43d15d4981834738427c6ec102f67e73488
|
Add last-step casper test
|
test/casper/last-step.js
|
test/casper/last-step.js
|
module.exports = function(conjure) {
'use strict';
conjure.test('r1', function() {
this.describe('click', function() {
this.it('should tag last step in native-click mode' , function() {
this.conjure.click('body', true);
});
this.it('should tag last step in jQuery-click mode' , function() {
this.conjure.click('body');
});
});
this.describe('then', function() {
this.it('should tag last step' , function() {
this.conjure.then(function() {
this.test.assertEquals(1, 1);
});
});
});
this.describe('thenOpen', function() {
this.it('should tag last step' , function() {
this.conjure.thenOpen('/', function() {
});
});
});
this.describe('assertSelText', function() {
this.it('should tag last step' , function() {
this.conjure.assertSelText('body', /.?/);
});
});
this.describe('next test', function() {
this.it('should trigger error' , function() { var a; a.b = 'foo'; });
});
});
};
function conjureLastStepTestNoOp() {}
|
JavaScript
| 0 |
@@ -910,32 +910,1209 @@
%7D);%0A %7D);%0A%0A
+ this.describe('each', function() %7B%0A this.it('should tag last step' , function() %7B%0A this.conjure.each(%5B1%5D, function() %7B%0A this.test.assertEquals(1, 1);%0A %7D);%0A %7D);%0A %7D);%0A%0A this.describe('openHash', function() %7B%0A this.it('should tag last step when not waiting for selector' , function() %7B%0A this.conjure.openHash('#foo');%0A %7D);%0A this.it('should tag last step when waiting for selector' , function() %7B%0A this.conjure.openHash('#foo', 'body');%0A %7D);%0A %7D);%0A%0A this.describe('openInitUrl', function() %7B%0A this.it('should tag last step' , function() %7B%0A this.conjure.openInitUrl();%0A %7D);%0A %7D);%0A%0A this.describe('selectorExists', function() %7B%0A this.it('should tag last step' , function() %7B%0A this.conjure.selectorExists('body');%0A %7D);%0A %7D);%0A%0A this.describe('selectorMissing', function() %7B%0A this.it('should tag last step' , function() %7B%0A this.conjure.selectorMissing('.not-present');%0A %7D);%0A %7D);%0A%0A this.describe('sendKeys', function() %7B%0A this.it('should tag last step' , function() %7B%0A this.conjure.sendKeys('body', 'foo');%0A %7D);%0A %7D);%0A%0A
this.describ
|
fc2aa864246976e0f833f0363a823f07cdb8f5be
|
set socketio transports websocket as default
|
sensor/GuardianSensor.js
|
sensor/GuardianSensor.js
|
/* Copyright 2016 Firewalla LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
const log = require('../net2/logger.js')(__filename)
const Sensor = require('./Sensor.js').Sensor
const Promise = require('bluebird')
const extensionManager = require('./ExtensionManager.js')
const configServerKey = "ext.guardian.socketio.server";
const configRegionKey = "ext.guardian.socketio.region";
const configBizModeKey = "ext.guardian.business";
const configAdminStatusKey = "ext.guardian.socketio.adminStatus";
const rclient = require('../util/redis_manager.js').getRedisClient();
const io = require('socket.io-client');
const EncipherTool = require('../net2/EncipherTool.js');
const et = new EncipherTool();
const CloudWrapper = require('../api/lib/CloudWrapper.js');
const cw = new CloudWrapper();
const receicveMessageAsync = Promise.promisify(cw.getCloud().receiveMessage).bind(cw.getCloud());
const encryptMessageAsync = Promise.promisify(cw.getCloud().encryptMessage).bind(cw.getCloud());
const zlib = require('zlib');
const deflateAsync = Promise.promisify(zlib.deflate);
class GuardianSensor extends Sensor {
constructor() {
super();
}
async apiRun() {
extensionManager.onGet("guardianSocketioServer", (msg) => {
return this.getServer();
});
extensionManager.onSet("guardianSocketioServer", (msg, data) => {
return this.setServer(data.server, data.region);
});
extensionManager.onGet("guardian.business", async (msg) => {
const data = await rclient.getAsync(configBizModeKey);
if(!data) {
return null;
}
try {
return JSON.parse(data);
} catch(err) {
log.error(`Failed to parse data, err: ${err}`);
return null;
}
});
extensionManager.onSet("guardian.business", async (msg, data) => {
await rclient.setAsync(configBizModeKey, JSON.stringify(data));
});
extensionManager.onGet("guardianSocketioRegion", (msg) => {
return this.getRegion();
});
extensionManager.onCmd("startGuardianSocketioServer", (msg, data) => {
return this.start();
});
extensionManager.onCmd("stopGuardianSocketioServer", (msg, data) => {
return this.stop();
});
extensionManager.onCmd("setAndStartGuardianService", async (msg, data) => {
const socketioServer = data.server;
if(!socketioServer) {
throw new Error("invalid guardian relay server");
}
await this.setServer(socketioServer, data.region);
await this.start();
});
const adminStatusOn = await this.isAdminStatusOn();
if(adminStatusOn) {
await this.start();
}
}
async setServer(server, region) {
if(server) {
if(region) {
await rclient.setAsync(configRegionKey, region);
} else {
await rclient.delAsync(configRegionKey);
}
return rclient.setAsync(configServerKey, server);
} else {
throw new Error("invalid server");
}
}
async getServer() {
const value = await rclient.getAsync(configServerKey);
return value || "";
}
async getRegion() {
return rclient.getAsync(configRegionKey);
}
async isAdminStatusOn() {
const status = await rclient.getAsync(configAdminStatusKey);
return status === '1';
}
async adminStatusOn() {
return rclient.setAsync(configAdminStatusKey, '1');
}
async adminStatusOff() {
return rclient.setAsync(configAdminStatusKey, '0');
}
async start() {
const server = await this.getServer();
if(!server) {
throw new Error("socketio server not set");
}
await this._stop();
await this.adminStatusOn();
const gid = await et.getGID();
const eid = await et.getEID();
const region = await this.getRegion();
if(region) {
this.socket = io(server, {path: `/${region}/socket.io`});
} else {
this.socket = io.connect(server);
}
if(!this.socket) {
throw new Error("failed to init socket io");
}
this.socket.on('connect', () => {
log.info(`Socket IO connection to ${server}, ${region} is connected.`);
this.socket.emit("box_registration", {
gid: gid,
eid: eid
});
});
this.socket.on('disconnect', () => {
log.info(`Socket IO connection to ${server}, ${region} is disconnected.`);
});
const key = `send_to_box_${gid}`;
this.socket.on(key, (message) => {
if(message.gid === gid) {
this.onMessage(gid, message);
}
})
}
async _stop() {
if(this.socket) {
this.socket.disconnect();
this.socket = null;
}
}
async stop() {
await this.adminStatusOff();
return this._stop();
}
async onMessage(gid, message) {
const controller = await cw.getNetBotController(gid);
if(controller && this.socket) {
const encryptedMessage = message.message;
const decryptedMessage = await receicveMessageAsync(gid, encryptedMessage);
decryptedMessage.mtype = decryptedMessage.message.mtype;
const response = await controller.msgHandlerAsync(gid, decryptedMessage);
const input = new Buffer(JSON.stringify(response), 'utf8');
const output = await deflateAsync(input);
const compressedResponse = JSON.stringify({
compressed: 1,
compressMode: 1,
data: output.toString('base64')
});
const encryptedResponse = await encryptMessageAsync(gid, compressedResponse);
this.socket.emit("send_from_box", {
message: encryptedResponse,
gid: gid
});
}
}
}
module.exports = GuardianSensor;
|
JavaScript
| 0.000001 |
@@ -4418,16 +4418,25 @@
erver, %7B
+%0A
path: %60/
@@ -4459,62 +4459,141 @@
.io%60
-%7D);%0A %7D else %7B%0A this.socket = io.connect(server
+,%0A transports: %5B'websocket'%5D%0A %7D);%0A %7D else %7B%0A this.socket = io(server, %7B%0A transports: %5B'websocket'%5D%0A %7D
);%0A
|
d35ad332e37a78f3cc2ff89d549c36123dbbcfcc
|
fix youtube url check
|
sentigator/sentigator.js
|
sentigator/sentigator.js
|
// Include The 'http' Module
var http = require("http");
// Include The 'url' Module
var url = require("url");
// Include The 'request' Module
var request = require("request");
// Include The 'async' Module
var async = require("async");
// Include The 'JSONStream' Module
var jsonStream = require("JSONStream");
// Include The 'event-stream' Module
var eventStream = require("event-stream");
// Include The 'parser' Module
var Parser = require("./lib/parser");
// Create the HTTP Server
var server = http.createServer(function(req, res) {
// Handle HTTP Request
// Parse the request querystring
var parsedUrl = url.parse(req.url, true);
var qs = parsedUrl.query;
// Validating existence of query param
if (qs.term) {
async.auto({
twitxy: function (callback) {
var parser = new Parser();
request("http://twitxy.itkoren.com/?lang=en&count=5&term=" + encodeURIComponent(qs.term))
.pipe(jsonStream.parse("statuses.*"))
.pipe(eventStream.mapSync(function (data) {
parser.parse({
src: "Twitter",
text: data.text,
score: 0
});
})).on("end", function(){
console.log("End Of Twitter Search Stream");
callback(null, { items: parser.getItems() });
});
},
google: function (callback) {
var parser = new Parser();
var hasUTube = false;
request("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&language=en&resultSize=5&q=" + encodeURIComponent(qs.term))
.pipe(jsonStream.parse("responseData.results.*"))
.pipe(eventStream.mapSync(function (data) {
parser.parse({
src: "Google",
text: data.title,
score: 0
});
// Check if in utube
if (!hasUTube && -1 !== data.unescapedUrl.indexOf("utube.com")) {
hasUTube = true;
}
})).on("end", function() {
console.log("End Of Google Search Stream");
callback(null, { items: parser.getItems(), hasUTube: hasUTube });
});
},
utube: ["google", function (callback, results) {
var parser = new Parser();
if (results.google.hasUTube) {
callback(null, parser.getItems());
}
else {
request("https://gdata.youtube.com/feeds/api/videos?max-results=5&alt=json&orderby=published&v=2&q=" + encodeURIComponent(qs.term))
.pipe(jsonStream.parse("feed.entry.*"))
.pipe(eventStream.mapSync(function (data) {
parser.parse({
src: "UTube",
text: data.title.$t,
score: 0
});
})).on("end", function() {
console.log("End Of Utube Search Stream");
callback(null, { items: parser.getItems() });
});
}
}]
},
// optional callback
function (err, results) {
// the results array will equal ['one','two'] even though
// the second function had a shorter timeout.
if (err) {
// Deal with errors
console.log("Got error: " + err.message);
res.writeHead(500);
res.end("** Only Bear Here :) **");
}
else {
var items = results.twitxy.items.concat(results.google.items, results.utube.items);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(items));
}
});
}
else {
// No search term supplied, just return
console.log("Search failed!");
console.log("Query parameters are missing");
res.writeHead(500);
res.end("** Only Bear Here :) **");
}
}).listen(process.env.PORT || 8000, process.env.HOST || "0.0.0.0", function() {
console.log("HTTP Server Started. Listening on " + server.address().address + " : Port " + server.address().port);
});
|
JavaScript
| 0 |
@@ -2207,16 +2207,18 @@
ndexOf(%22
+yo
utube.co
|
dd19327e2383f9cd8fe238b19b182fa236667f04
|
Update Just-Eat rating
|
extension/chrome/js/content.js
|
extension/chrome/js/content.js
|
init();
urls = [chrome.extension.getURL("images/fhrs_0_en-gb.jpg"),
chrome.extension.getURL("images/fhrs_1_en-gb.jpg"),
chrome.extension.getURL("images/fhrs_2_en-gb.jpg"),
chrome.extension.getURL("images/fhrs_3_en-gb.jpg"),
chrome.extension.getURL("images/fhrs_4_en-gb.jpg"),
chrome.extension.getURL("images/fhrs_5_en-gb.jpg"),
chrome.extension.getURL("images/fhrs_awaitinginspection_en-gb.jpg")];
function init() {
takeaways = []
$( "div" ).filter(function( index ) {
return $( this ).attr( "class" ) == "o-tile c-restaurant";
}).each(function( index ) {
var postcode = $( this ).find(
"[data-ft='restaurantDetailsAddress']"
).html();
postcode = postcode.split(", ");
postcode = postcode[postcode.length - 1];
var rating = 0;
takeaways.push(
[
postcode,
$( this ).find(
"[data-ft='restaurantDetailsName']"
).html()
,
rating
]
);
});
for (var res in takeaways) {
var rating = getTakeawayRatingMP(takeaways[res], res);
console.log(takeaways[res]);
}
}
function getTakeawayRatingMP(takeaway, index) {
var takeawayPostcode = takeaway[0];
var takeawayName = takeaway[1];
/*
var ratingUrl = FSA_HOST + takeawayName + "/" + takeawayPostcode + "/" + FSA_HOST_SUFFIX;*/
var ratingJson = "";
//console.log(ratingUrl);
/*var ratingJson = $.ajax({
url: ratingUrl,
success: function(data) {
console.log(data);
},
error: function () {
console.log("Error!");
}
});chrom*/
chrome.runtime.sendMessage({"postcode": takeawayPostcode, "name": takeawayName}, function(response) {
jsonResponse = JSON.parse(response.rating);
/**
* Call a function here to insert the RATING IMAGE.
* Index: index
* Data: jsonResponse.FHRSEstablishment.EstablishmentCollection.EstablishmentDetail
* eg --> somefunction(index, jsonResponse.FHRSEstablishment.EstablishmentCollection.EstablishmentDetail.ratingValue)
*/
if (jsonResponse.FHRSEstablishment.EstablishmentCollection) {
insertRatingImage(index, '<img src="' + urls[jsonResponse.FHRSEstablishment.EstablishmentCollection.EstablishmentDetail.RatingValue] + '" />');
} else {
insertRatingImage(index, '<img src="' + urls[6] + '" />');}
});
}
jQuery.fn.insertAt = function(index, element) {
var lastIndex = this.children().size();
if (index < 0) {
index = Math.max(0, lastIndex + 1 + index)
}
this.append(element);
if (index < lastIndex) {
this.children().eq(index).before(this.children().last())
}
return this;
};
function insertRatingImage(index, rating) {
//Quite possibly the most disgusting javascript selector I've ever written.
var $detailsDiv = $("div").filter(function( index ) {
return $( this ).attr( "class" ) == "o-tile c-restaurant";
}).eq(index).eq(0).children().eq(0).children().eq(2).children().eq(1);
$( "<p style='margin-top: 10px;float: right;margin-top: -30px;margin-right: 20px;'>" + rating + "</p>" ).insertAfter($detailsDiv)
}
insertRatingImage(1, "");
|
JavaScript
| 0 |
@@ -3176,25 +3176,8 @@
le='
-margin-top: 10px;
floa
@@ -3198,17 +3198,17 @@
n-top: -
-3
+4
0px;marg
@@ -3216,16 +3216,34 @@
n-right:
+ 10px;padding-top:
20px;'%3E
|
2b76d1c99a53b9469904254db90dd39a8e6bd55c
|
add test for video xss challenge
|
test/e2e/complainSpec.js
|
test/e2e/complainSpec.js
|
const config = require('config')
const path = require('path')
const utils = require('../../lib/utils')
describe('/#/complain', () => {
let file, complaintMessage, submitButton
protractor.beforeEach.login({ email: 'admin@' + config.get('application.domain'), password: 'admin123' })
beforeEach(() => {
browser.get('/#/complain')
file = element(by.id('file'))
complaintMessage = element(by.id('complaintMessage'))
submitButton = element(by.id('submitButton'))
})
describe('challenge "uploadSize"', () => {
it('should be possible to upload files greater 100 KB directly through backend', () => {
browser.waitForAngularEnabled(false)
browser.executeScript(() => {
const over100KB = Array.apply(null, new Array(11000)).map(String.prototype.valueOf, '1234567890')
const blob = new Blob(over100KB, { type: 'application/pdf' })
const data = new FormData()
data.append('file', blob, 'invalidSizeForClient.pdf')
const request = new XMLHttpRequest()
request.open('POST', '/file-upload')
request.send(data)
})
browser.driver.sleep(1000)
browser.waitForAngularEnabled(true)
})
protractor.expect.challengeSolved({ challenge: 'Upload Size' })
})
describe('challenge "uploadType"', () => {
it('should be possible to upload files with other extension than .pdf directly through backend', () => {
browser.waitForAngularEnabled(false)
browser.executeScript(() => {
const data = new FormData()
const blob = new Blob([ 'test' ], { type: 'application/x-msdownload' })
data.append('file', blob, 'invalidTypeForClient.exe')
const request = new XMLHttpRequest()
request.open('POST', '/file-upload')
request.send(data)
})
browser.driver.sleep(1000)
browser.waitForAngularEnabled(true)
})
protractor.expect.challengeSolved({ challenge: 'Upload Type' })
})
describe('challenge "xxeFileDisclosure"', () => {
it('should be possible to retrieve file from Windows server via .xml upload with XXE attack', () => {
complaintMessage.sendKeys('XXE File Exfiltration Windows!')
file.sendKeys(path.resolve('test/files/xxeForWindows.xml'))
submitButton.click()
})
protractor.expect.challengeSolved({ challenge: 'Deprecated Interface' })
})
if (!utils.disableOnContainerEnv()) {
describe('challenge "xxeFileDisclosure"', () => {
it('should be possible to retrieve file from Windows server via .xml upload with XXE attack', () => {
complaintMessage.sendKeys('XXE File Exfiltration Windows!')
file.sendKeys(path.resolve('test/files/xxeForWindows.xml'))
submitButton.click()
})
it('should be possible to retrieve file from Linux server via .xml upload with XXE attack', () => {
complaintMessage.sendKeys('XXE File Exfiltration Linux!')
file.sendKeys(path.resolve('test/files/xxeForLinux.xml'))
submitButton.click()
})
afterAll(() => {
protractor.expect.challengeSolved({ challenge: 'XXE Tier 1' })
})
})
describe('challenge "xxeDos"', () => {
it('should be possible to trigger request timeout via .xml upload with Quadratic Blowup attack', () => {
complaintMessage.sendKeys('XXE Quadratic Blowup!')
file.sendKeys(path.resolve('test/files/xxeQuadraticBlowup.xml'))
submitButton.click()
})
it('should be possible to trigger request timeout via .xml upload with dev/random attack', () => {
complaintMessage.sendKeys('XXE Quadratic Blowup!')
file.sendKeys(path.resolve('test/files/xxeDevRandom.xml'))
submitButton.click()
})
afterAll(() => {
protractor.expect.challengeSolved({ challenge: 'XXE Tier 2' })
})
})
}
describe('challenge "arbitraryFileWrite"', () => {
it('should be possible to upload zip file with filenames having path traversal', () => {
complaintMessage.sendKeys('Zip Slip!')
file.sendKeys(path.resolve('test/files/arbitraryFileWrite.zip'))
submitButton.click()
})
protractor.expect.challengeSolved({ challenge: 'Arbitrary File Write' })
})
})
|
JavaScript
| 0 |
@@ -4210,12 +4210,788 @@
%7D)%0A %7D)
+%0A%0A describe('challenge %22videoXssChallenge%22', () =%3E %7B%0A it('should be possible to inject js in subtitles by uploading zip file with filenames having path traversal', () =%3E %7B%0A const EC = protractor.ExpectedConditions%0A complaintMessage.sendKeys('Here we go!')%0A file.sendKeys(path.resolve('test/files/videoExploit.zip'))%0A submitButton.click()%0A browser.get('/promotion')%0A browser.wait(EC.alertIsPresent(), 5000, %22'xss' alert is not present%22)%0A browser.switchTo().alert().then(alert =%3E %7B%0A expect(alert.getText()).toEqual('xss')%0A alert.accept()%0A %7D)%0A browser.get('/')%0A browser.driver.sleep(5000)%0A browser.waitForAngularEnabled(true)%0A %7D)%0A protractor.expect.challengeSolved(%7B challenge: 'XSS Tier 3.5' %7D)%0A %7D)
%0A%7D)%0A
|
9f42b8b41fa481816083ce0b17fc9586440ec368
|
fix variable name for tests
|
test/engine.io-client.js
|
test/engine.io-client.js
|
var expect = require('expect.js');
var eio = require('../');
describe('engine.io-client', function () {
it('should expose protocol number', function () {
expect(eio.protocol).to.be.a('number');
});
it('should properly parse http uri without port', function(done) {
var server = eio('http://localhost');
server.on('close', function() {
done();
});
expect(server.port).to.be('80');
server.close();
});
it('should properly parse https uri without port', function(done) {
var server = eio('https://localhost');
server.on('close', function() {
done();
});
expect(server.port).to.be('443');
server.close();
});
it('should properly parse wss uri without port', function(done) {
var server = eio('wss://localhost');
server.on('close', function() {
done();
});
expect(server.port).to.be('443');
server.close();
});
it('should properly parse wss uri with port', function(done) {
var server = eio('wss://localhost:2020');
server.on('close', function() {
done();
});
expect(server.port).to.be('2020');
server.close();
});
});
|
JavaScript
| 0.000039 |
@@ -272,38 +272,38 @@
done) %7B%0A var
-server
+client
= eio('http://l
@@ -310,38 +310,38 @@
ocalhost');%0A
-server
+client
.on('close', fun
@@ -375,38 +375,38 @@
%7D);%0A expect(
-server
+client
.port).to.be('80
@@ -405,38 +405,38 @@
o.be('80');%0A
-server
+client
.close();%0A %7D);%0A
@@ -506,38 +506,38 @@
done) %7B%0A var
-server
+client
= eio('https://
@@ -545,38 +545,38 @@
ocalhost');%0A
-server
+client
.on('close', fun
@@ -610,38 +610,38 @@
%7D);%0A expect(
-server
+client
.port).to.be('44
@@ -641,38 +641,38 @@
.be('443');%0A
-server
+client
.close();%0A %7D);%0A
@@ -740,38 +740,38 @@
done) %7B%0A var
-server
+client
= eio('wss://lo
@@ -777,38 +777,38 @@
ocalhost');%0A
-server
+client
.on('close', fun
@@ -842,38 +842,38 @@
%7D);%0A expect(
-server
+client
.port).to.be('44
@@ -873,38 +873,38 @@
.be('443');%0A
-server
+client
.close();%0A %7D);%0A
@@ -977,22 +977,22 @@
var
-server
+client
= eio('
@@ -1019,22 +1019,22 @@
');%0A
-server
+client
.on('clo
@@ -1084,22 +1084,22 @@
expect(
-server
+client
.port).t
@@ -1120,14 +1120,14 @@
-server
+client
.clo
|
7aad716216bbb00f805963a4d6f63447ccf9d59e
|
add the “error” action
|
test/fixtures/actions.js
|
test/fixtures/actions.js
|
module.exports = {
toUpper({args: {message}}) {
return message.toUpperCase();
},
customEvent({emit}) {
emit({fooEvent: 'foobar'});
}
};
|
JavaScript
| 0.000008 |
@@ -159,11 +159,84 @@
);%0A %7D
+,%0A%0A error() %7B%0A throw new Error('something went wrong!');%0A %7D,
%0A%7D;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.