commit
stringlengths 40
40
| old_file
stringlengths 4
236
| new_file
stringlengths 4
236
| old_contents
stringlengths 1
3.26k
| new_contents
stringlengths 16
4.43k
| subject
stringlengths 16
624
| message
stringlengths 17
3.29k
| lang
stringclasses 5
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
|---|---|---|---|---|---|---|---|---|---|
3c21402775b39586d62cc137f4832c3397192aac
|
public/javascripts/documents.js
|
public/javascripts/documents.js
|
$(document).ready(function(){
var i=0;
var $td;
var state;
function checkDocumentsStatuses(){
$.getJSON("/api/documents_states", function(data){
var $bars = $(".bar");
for(i=0;i<$bars.length;i++){
$($bars[i]).css("width", data[i] + "%");
}
});
setTimeout(checkDocumentsStatuses, 15000 );
}
$(".link a").popover();
$(".link a").click(function(event){
event.preventDefault();
var $this = $(this);
$.get($this.attr("href"),
null,
function(data){
$this.parent().siblings(".content").html(data.p);
},
'json');
});
$("#stillProcessing").alert().css("display", "block");
setTimeout(checkDocumentsStatuses, 15000 );
if($(".tablesorter").length !== 0) {
$(".tablesorter").tablesorter();
}
$(".documents tbody tr").click(function() {
$(this).siblings().removeClass("selected");
$(this).addClass("selected");
var url = "/api/" + $(this).data("id") + "/context";
var template = $("#documentContext").html();
$("#document").html("").spin();
$.getJSON(url, null, function(data) {
$("#document").html(Mustache.render(template, data));
}).error(function() {
$("#document").html(Mustache.render($("#documentContextError").html()));
});
return false;
});
});
|
$(document).ready(function(){
var i=0;
var $td;
var state;
function checkDocumentsStatuses(){
$.getJSON("/api/documents_states", function(data){
var $bars = $(".bar");
for(i=0;i<$bars.length;i++){
$($bars[i]).css("width", data[i] + "%");
}
});
setTimeout(checkDocumentsStatuses, 15000 );
}
$(".link a").popover();
$(".link a").click(function(event){
event.preventDefault();
var $this = $(this);
$.get($this.attr("href"),
null,
function(data){
$this.parent().siblings(".content").html(data.p);
},
'json');
});
$("#stillProcessing").alert().css("display", "block");
setTimeout(checkDocumentsStatuses, 15000 );
if($(".tablesorter").length !== 0) {
$(".tablesorter").tablesorter();
}
$(".documents tbody tr").click(function(e) {
$(this).siblings().removeClass("selected");
$(this).addClass("selected");
var url = "/api/" + $(this).data("id") + "/context";
var template = $("#documentContext").html();
$("#document").html("").spin();
$.getJSON(url, null, function(data) {
$("#document").html(Mustache.render(template, data));
}).error(function() {
$("#document").html(Mustache.render($("#documentContextError").html()));
});
});
$(".documents .tools a").click(function(e) {
e.stopPropagation();
});
});
|
Stop event bubbling when clicking on document toolbar
|
Stop event bubbling when clicking on document toolbar
|
JavaScript
|
mit
|
analiceme/chaos
|
b6988ddfadcc5636fcdfff772715cd5199954f04
|
tasks/lib/sigint-hook.js
|
tasks/lib/sigint-hook.js
|
var sigintHooked = false;
module.exports = function sigintHook( fn ) {
if ( sigintHooked ) {
return;
}
sigintHooked = true;
// ctrl+c should stop this task and quit grunt gracefully
// (process.on("SIGINT", fn) doesn't behave correctly on Windows):
var rl = require( "readline" ).createInterface( {
input: process.stdin,
output: process.stdout
} );
rl.on( "SIGINT", function() {
fn();
rl.close();
} );
};
|
var sigintHooked = false;
module.exports = function sigintHook( fn ) {
if ( sigintHooked ) {
return;
}
sigintHooked = true;
// ctrl+c should stop this task and quit grunt gracefully
// (process.on("SIGINT", fn) doesn't behave correctly on Windows):
var rl = require( "readline" ).createInterface( {
input: process.stdin,
output: process.stdout
} );
rl.on( "SIGINT", function() {
fn();
rl.close();
sigintHooked = false;
} );
};
|
Reset sigint hook when readline closes.
|
Reset sigint hook when readline closes.
|
JavaScript
|
mit
|
peol/grunt-surveil
|
bd77652a50eb0feab274d65ed45a127ddf2402c7
|
src/components/chat/AddChatMessage.js
|
src/components/chat/AddChatMessage.js
|
import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
}
handleKeyPress = (e) => {
if (e.key === 'Enter'){
e.preventDefault()
this.onSendCick()
return false
}
}
render() {
return (
<div>
<textarea onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick}>Send</button>
</div>
)
}
}
AddChatMessage.propTypes = {
onClick: PropTypes.func
}
|
import React from 'react'
import PropTypes from 'prop-types'
/* Component with a state */
export default class AddChatMessage extends React.Component {
constructor(props) {
super(props)
this.state = {message: ''}
}
onChangeMessage = (e) => {
this.setState({message: e.target.value})
}
onSendCick = () => {
this.props.onClick({message: this.state.message})
this.setState({message:''})
this.textInput.focus()
}
handleKeyPress = (e) => {
if (e.key === 'Enter'){
e.preventDefault()
this.onSendCick()
return false
}
}
render() {
return (
<div>
<textarea ref={(e) => { this.textInput = e }} onChange={this.onChangeMessage} onKeyPress={this.handleKeyPress} value={this.state.message}/>
<button onClick={this.onSendCick}>Send</button>
</div>
)
}
}
AddChatMessage.propTypes = {
onClick: PropTypes.func
}
|
Set focus back to textarea after button was pressed
|
Set focus back to textarea after button was pressed
|
JavaScript
|
mit
|
axax/lunuc,axax/lunuc,axax/lunuc
|
594ece2b5001d39a2cd255c2a25829a1291cb75f
|
test/compare-versions.js
|
test/compare-versions.js
|
import test from 'ava';
import fn from '../source/libs/compare-versions';
test('Compare versions', t => {
t.is(-1, fn('1', '2'));
t.is(-1, fn('v1', '2'));
t.is(-1, fn('1.1', '1.2'));
t.is(-1, fn('1', '1.1'));
t.is(-1, fn('1', '1.0.1'));
t.is(-1, fn('2.0', '10.0'));
t.is(-1, fn('1.2.3', '1.22.3'));
t.is(-1, fn('1.1.1.1.1', '1.1.1.1.2'));
t.is(-1, fn('r1', 'r2'));
t.is(-1, fn('1.0-beta', '1.0'));
t.is(-1, fn('v0.11-M4', 'v0.20'));
});
|
import test from 'ava';
import fn from '../source/libs/compare-versions';
test('Compare versions', t => {
t.is(-1, fn('1', '2'));
t.is(-1, fn('v1', '2'));
t.is(-1, fn('1.1', '1.2'));
t.is(-1, fn('1', '1.1'));
t.is(-1, fn('1', '1.0.1'));
t.is(-1, fn('2.0', '10.0'));
t.is(-1, fn('1.2.3', '1.22.3'));
t.is(-1, fn('1.1.1.1.1', '1.1.1.1.2'));
t.is(-1, fn('r1', 'r2'));
});
test.failing('Support beta versions', t => {
t.is(-1, fn('1.0-beta', '1.0'));
t.is(-1, fn('v2.0-RC4', 'v2.0'));
});
|
Add failing beta version test
|
Add failing beta version test
|
JavaScript
|
mit
|
busches/refined-github,busches/refined-github,sindresorhus/refined-github,sindresorhus/refined-github
|
67b66b5568f264a9ed4b0940de406ed26797fd4e
|
test/specificity.test.js
|
test/specificity.test.js
|
var path = require('path'),
assert = require('assert'),
fs = require('fs');
var carto = require('../lib/carto');
var tree = require('../lib/carto').tree;
var helper = require('./support/helper');
function cleanupItem(key, value) {
if (key === 'rules') return;
else if (key === 'ruleIndex') return;
else if (key === 'elements') return value.map(function(item) { return item.value; });
else if (key === 'filters') {
var arr = [];
for (var id in value.filters) arr.push(id + value.filters[id].val);
if (arr.length) return arr;
}
else if (key === 'attachment' && value === '__default__') return;
else if (key === 'zoom') {
if (value != tree.Zoom.all) return tree.Zoom.toString(value);
}
else return value;
}
describe('Specificity', function() {
helper.files('specificity', 'mss', function(file) {
it('should handle spec correctly in ' + file, function(done) {
helper.file(file, function(content) {
var tree = (new carto.Parser({
paths: [ path.dirname(file) ],
filename: file
})).parse(content);
var mss = tree.toList({});
mss = helper.makePlain(mss, cleanupItem);
helper.compareToFile(mss, file, helper.resultFile(file));
done();
});
});
});
});
|
var path = require('path'),
assert = require('assert'),
fs = require('fs');
var carto = require('../lib/carto');
var tree = require('../lib/carto').tree;
var helper = require('./support/helper');
function cleanupItem(key, value) {
if (key === 'rules') return;
else if (key === 'ruleIndex') return;
else if (key === 'elements') return value.map(function(item) { return item.value; });
else if (key === 'filters') {
var arr = [];
for (var id in value.filters) arr.push(id + value.filters[id].val);
if (arr.length) return arr;
}
else if (key === 'attachment' && value === '__default__') return;
else if (key === 'zoom') {
if (value != tree.Zoom.all) return (new tree.Zoom()).setZoom(value).toString();
}
else return value;
}
describe('Specificity', function() {
helper.files('specificity', 'mss', function(file) {
it('should handle spec correctly in ' + file, function(done) {
helper.file(file, function(content) {
var tree = (new carto.Parser({
paths: [ path.dirname(file) ],
filename: file
})).parse(content);
var mss = tree.toList({});
mss = helper.makePlain(mss, cleanupItem);
helper.compareToFile(mss, file, helper.resultFile(file));
done();
});
});
});
});
|
Fix zoom interpretation in helper
|
Fix zoom interpretation in helper
|
JavaScript
|
apache-2.0
|
pnorman/carto,clhenrick/carto,CartoDB/carto,CartoDB/carto,gravitystorm/carto,stefanklug/carto,tomhughes/carto,whitelynx/carto,mapbox/carto,midnightcomm/carto,madeinqc/carto,1ec5/carto
|
e65b54770e47356e2aba9afc46b1551fa7ece6b0
|
build/tasks/dev.js
|
build/tasks/dev.js
|
import gulp from 'gulp'
import path from 'path'
import BrowserSync from 'browser-sync'
import { compiler, handleWebpackResults } from '../webpack/compiler'
const browserSync = BrowserSync.create()
const args = global.__args
const themeDir = path.resolve(__pkg._themepath)
const themeRelPath = themeDir.replace(process.cwd()+'/', '')
gulp.task('dev', ['build'], ()=> {
compiler.watch({}, handleWebpackResults(true))
gulp.watch(`${themeRelPath}/scss/**/*.scss`, ['styles'])
gulp.watch(`${themeRelPath}/images/**/*`, ['images'])
gulp.watch(`${themeRelPath}/fonts/**/*`, ['static'])
if (args.sync) {
browserSync.init({
proxy: __pkg._criticalUrl,
files: [
`${themeRelPath}/assets/js/*.js`,
`${themeRelPath}/**/*.php`
]
})
}
})
|
import gulp from 'gulp'
import path from 'path'
import BrowserSync from 'browser-sync'
import { compiler, handleWebpackResults } from '../webpack/compiler'
const browserSync = BrowserSync.create()
const args = global.__args
const themeDir = path.resolve(__pkg._themepath)
const themeRelPath = themeDir.replace(process.cwd()+'/', '')
gulp.task('dev', ['build'], ()=> {
compiler.watch({}, handleWebpackResults(true))
gulp.watch(`${themeRelPath}/scss/**/*.scss`, ['styles'])
gulp.watch(`${themeRelPath}/images/**/*`, ['images'])
gulp.watch(`${themeRelPath}/fonts/**/*`, ['static'])
if (args.sync) {
browserSync.init({
proxy: __pkg._criticalUrl,
files: [
`${themeRelPath}/assets/js/*.js`,
`${themeRelPath}/assets/css/*.css`,
`${themeRelPath}/**/*.php`
]
})
}
})
|
Make sure CSS files are watched
|
Make sure CSS files are watched
|
JavaScript
|
mit
|
3five/Rudiments-Stack,3five/Rudiments-Stack,3five/Rudiments-Stack,3five/Rudiments-Stack,3five/Rudiments-Stack
|
03217724b92da3636e1e8b81acd35d652a21bc57
|
packages/expo/bin/commands/add-hook.js
|
packages/expo/bin/commands/add-hook.js
|
const prompts = require('prompts')
const addHook = require('../lib/add-hook')
const { onCancel } = require('../lib/utils')
const { blue, yellow } = require('kleur')
module.exports = async (argv, globalOpts) => {
const res = await prompts({
type: 'confirm',
name: 'addHook',
message: `This will modify your app.json. Is that ok?`,
initial: true
}, { onCancel })
if (res.addHook) {
console.log(blue(`> Inserting hook config into app.json`))
const msg = await addHook(globalOpts['project-root'])
if (msg) console.log(yellow(` ${msg}`))
}
}
|
const prompts = require('prompts')
const addHook = require('../lib/add-hook')
const { onCancel } = require('../lib/utils')
const { blue, yellow } = require('kleur')
module.exports = async (argv, globalOpts) => {
const res = await prompts({
type: 'confirm',
name: 'addHook',
message,
initial: true
}, { onCancel })
if (res.addHook) {
console.log(blue(`> Inserting hook config into app.json`))
const msg = await addHook(globalOpts['project-root'])
if (msg) console.log(yellow(` ${msg}`))
}
}
const message = `Do you want to automatically upload source maps to Bugsnag? (this will modify your app.json)`
|
Add API hook command should say what it's going to do
|
fix(expo-cli): Add API hook command should say what it's going to do
|
JavaScript
|
mit
|
bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js,bugsnag/bugsnag-js
|
67098dc24693d31a34ac2fd78d9b145b4e8aee9a
|
bin/avails.js
|
bin/avails.js
|
#!/usr/bin/env node
var packageJson = require('../package.json');
var program = require('commander');
program
.version(packageJson.version)
.description(packageJson.description)
.command('convert', 'convert Avails between various formats', {
isDefault: true
})
.parse(process.argv);
|
#!/usr/bin/env node
var packageJson = require('../package.json');
var program = require('commander');
program
.version(packageJson.version)
.description(packageJson.description)
.command('convert', 'convert Avails between various formats')
.command('merge', 'merge historical Avails into one')
.parse(process.argv);
|
Remove default setting for Avails command
|
Remove default setting for Avails command
|
JavaScript
|
mit
|
pivotshare/avails
|
225f12f2527e9d8d7d6d4b65da642375d31ffbcc
|
src/javascript/binary/static_pages/video_facility.js
|
src/javascript/binary/static_pages/video_facility.js
|
const BinaryPjax = require('../base/binary_pjax');
const Client = require('../base/client');
const defaultRedirectUrl = require('../base/url').defaultRedirectUrl;
const getLoginToken = require('../common_functions/common_functions').getLoginToken;
const DeskWidget = require('../common_functions/attach_dom/desk_widget');
const BinarySocket = require('../websocket_pages/socket');
const VideoFacility = (() => {
const onLoad = () => {
BinarySocket.send({ get_account_status: 1 }).then((response) => {
if (response.error) {
$('#error_message').setVisibility(1).text(response.error.message);
} else {
const status = response.get_account_status.status;
if (/authenticated/.test(status)) {
BinaryPjax.load(defaultRedirectUrl());
} else {
DeskWidget.showDeskLink('', '#facility_content');
if (!Client.isFinancial()) {
$('#not_authenticated').setVisibility(1);
}
$('.msg_authenticate').setVisibility(1);
$('#generated_token').text(getLoginToken().slice(-4));
}
}
});
};
return {
onLoad: onLoad,
};
})();
module.exports = VideoFacility;
|
const BinaryPjax = require('../base/binary_pjax');
const Client = require('../base/client');
const localize = require('../base/localize').localize;
const defaultRedirectUrl = require('../base/url').defaultRedirectUrl;
const getLoginToken = require('../common_functions/common_functions').getLoginToken;
const DeskWidget = require('../common_functions/attach_dom/desk_widget');
const BinarySocket = require('../websocket_pages/socket');
const VideoFacility = (() => {
const onLoad = () => {
if (Client.get('loginid_array').find(obj => obj.id === Client.get('loginid')).non_financial) {
$('#loading').replaceWith($('<p/>', { class: 'notice-msg center-text', text: localize('Sorry, this feature is not available in your jurisdiction.') }));
return;
}
BinarySocket.send({ get_account_status: 1 }).then((response) => {
if (response.error) {
$('#error_message').setVisibility(1).text(response.error.message);
} else {
const status = response.get_account_status.status;
if (/authenticated/.test(status)) {
BinaryPjax.load(defaultRedirectUrl());
} else {
DeskWidget.showDeskLink('', '#facility_content');
if (!Client.isFinancial()) {
$('#not_authenticated').setVisibility(1);
}
$('.msg_authenticate').setVisibility(1);
$('#generated_token').text(getLoginToken().slice(-4));
}
}
});
};
return {
onLoad: onLoad,
};
})();
module.exports = VideoFacility;
|
Hide video facility contents from non-financial clients
|
Hide video facility contents from non-financial clients
|
JavaScript
|
apache-2.0
|
negar-binary/binary-static,binary-static-deployed/binary-static,ashkanx/binary-static,4p00rv/binary-static,ashkanx/binary-static,binary-com/binary-static,raunakkathuria/binary-static,binary-static-deployed/binary-static,kellybinary/binary-static,kellybinary/binary-static,4p00rv/binary-static,binary-com/binary-static,binary-static-deployed/binary-static,raunakkathuria/binary-static,raunakkathuria/binary-static,negar-binary/binary-static,ashkanx/binary-static,4p00rv/binary-static,binary-com/binary-static,negar-binary/binary-static,kellybinary/binary-static
|
2e4976b3515f7afda8275fe89b2ac16b3e2c4f2c
|
sections/faqs/when-to-use-attrs.js
|
sections/faqs/when-to-use-attrs.js
|
import md from 'components/md'
const WhenToUseAttrs = () => md`
## When to use attrs?
You can pass in attributes to styled components using \`attrs\`, but
it is not always sensible to do so.
The rule of thumb is to use \`attrs\` when you want every instance of a styled
component to have that prop, and pass props directly when every instance needs a
different one:
\`\`\`js
const PasswordInput = styled.input.attrs({
// Every <PasswordInput /> should be type="password"
type: 'password'
})\`\`
// This specific one is hidden, so let's set aria-hidden
<PasswordInput aria-hidden="true" />
\`\`\`
`
export default WhenToUseAttrs
|
import md from 'components/md'
const WhenToUseAttrs = () => md`
## When to use attrs?
You can pass in attributes to styled components using [attrs](/docs/basics#attaching-additional-props), but
it is not always sensible to do so.
The rule of thumb is to use \`attrs\` when you want every instance of a styled
component to have that prop, and pass props directly when every instance needs a
different one:
\`\`\`js
const PasswordInput = styled.input.attrs({
// Every <PasswordInput /> should be type="password"
type: 'password'
})\`\`
// This specific one is hidden, so let's set aria-hidden
<PasswordInput aria-hidden="true" />
\`\`\`
`
export default WhenToUseAttrs
|
Add a link to attrs in the docs
|
Add a link to attrs in the docs
|
JavaScript
|
mit
|
styled-components/styled-components-website,styled-components/styled-components-website
|
cb68c4e32710ae8963df5f1b60d0b3bda6a61404
|
server/controllers/eventPreview.js
|
server/controllers/eventPreview.js
|
import {
DEFAULT_LIMIT,
DEFAULT_OFFSET,
} from './base'
import {
EventBelongsToManyImage,
EventBelongsToPlace,
EventHasManySlots,
} from '../database/associations'
import Event from '../models/event'
export default {
findAll: (req, res, next) => {
const {
limit = DEFAULT_LIMIT,
offset = DEFAULT_OFFSET,
} = req.query
return Event.findAndCountAll({
include: [
EventBelongsToManyImage,
EventHasManySlots, {
association: EventBelongsToPlace,
required: true,
where: {
isPublic: true,
},
},
],
limit,
offset,
where: {
isPublic: true,
},
order: [
[
EventHasManySlots,
'from',
'ASC',
],
],
})
.then(result => {
res.json({
data: result.rows,
limit: parseInt(limit, 10),
offset: parseInt(offset, 10),
total: result.count,
})
})
.catch(err => next(err))
},
}
|
import {
DEFAULT_LIMIT,
DEFAULT_OFFSET,
} from './base'
import {
EventBelongsToManyImage,
EventBelongsToPlace,
EventHasManySlots,
} from '../database/associations'
import Event from '../models/event'
export default {
findAll: (req, res, next) => {
const {
limit = DEFAULT_LIMIT,
offset = DEFAULT_OFFSET,
} = req.query
return Event.findAndCountAll({
distinct: true,
include: [
EventBelongsToManyImage,
EventHasManySlots, {
association: EventBelongsToPlace,
required: true,
where: {
isPublic: true,
},
},
],
limit,
offset,
where: {
isPublic: true,
},
order: [
[
EventHasManySlots,
'from',
'ASC',
],
],
})
.then(result => {
res.json({
data: result.rows,
limit: parseInt(limit, 10),
offset: parseInt(offset, 10),
total: result.count,
})
})
.catch(err => next(err))
},
}
|
Enable distinct results for calendar preview
|
Enable distinct results for calendar preview
|
JavaScript
|
agpl-3.0
|
adzialocha/hoffnung3000,adzialocha/hoffnung3000
|
69f93bb91f57900f337b6ba7c5d0602e6846cdd8
|
lib/addMethod/validateRESTInput.js
|
lib/addMethod/validateRESTInput.js
|
var _ = require('lodash');
module.exports = function (methodName, config) {
// Ensure the minimum parameters have been passed
if (!methodName || !_.isString(methodName)) {
throw new Error('The first parameter passed to `addMethod` should be a string.');
}
// If a function is inputted as the `config`, then just return - there's
// really not much to validate.
if (_.isFunction(config)) {
return;
}
if (!config || !_.isObject(config)) {
throw new Error('The `config` object should be an object.');
}
// Check to see if the method has already been declared
if (!_.isUndefined(this[methodName])) {
throw new Error('Method `'+methodName+'` has already been declared.');
}
// Ensure the config parameters have been specified correctly
if (!config.url) {
throw new Error('The `url` config parameter should be declared.');
}
if (!config.method || !_.isString(config.method)) {
throw new Error('The `method` config parameter should be declared as string.');
}
var method = config.method.toLowerCase();
var allowedMethods = [ 'get', 'put', 'post', 'delete', 'head', 'patch' ];
if (allowedMethods.indexOf(method) === -1) {
throw new Error('The `method` "'+method+'" is not a valid method. Allowed methods are: '+allowedMethods.join(', '));
}
};
|
var _ = require('lodash');
module.exports = function (methodName, config) {
// Ensure the minimum parameters have been passed
if (!methodName || !_.isString(methodName)) {
throw new Error('The first parameter passed to `addMethod` should be a string.');
}
// If a function is inputted as the `config`, then just return - there's
// really not much to validate.
if (_.isFunction(config)) {
return;
}
if (!config || !_.isObject(config)) {
throw new Error('The `config` object should be an object.');
}
// Check to see if the method has already been declared
if (!_.isUndefined(this[methodName])) {
throw new Error('Method `'+methodName+'` has already been declared.');
}
// Ensure the config parameters have been specified correctly
if (!config.url && config.url !== '') {
throw new Error('The `url` config parameter should be declared.');
}
if (!config.method || !_.isString(config.method)) {
throw new Error('The `method` config parameter should be declared as string.');
}
var method = config.method.toLowerCase();
var allowedMethods = [ 'get', 'put', 'post', 'delete', 'head', 'patch' ];
if (allowedMethods.indexOf(method) === -1) {
throw new Error('The `method` "'+method+'" is not a valid method. Allowed methods are: '+allowedMethods.join(', '));
}
};
|
Allow method URL to be an empty string
|
Allow method URL to be an empty string
|
JavaScript
|
mit
|
trayio/threadneedle
|
be394881923665df48a9d9b82c290e2c8a03a41a
|
server/entities/team/team.model.js
|
server/entities/team/team.model.js
|
'use strict';
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let teamSchema = new Schema({
name : {
type: String,
required: true,
unique: true
},
email : {
type: String,
required: true,
unique: true
},
description : {
type: String
},
logisticsRequirements : {
type: String
},
openForApplications : {
type: Boolean,
default: true
},
members : {
leader : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
list : [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
},
cremiRoom : {
type: String
},
data : mongoose.Schema.Types.Mixed
});
require('./team.controller')(teamSchema);
module.exports = mongoose.model('Team', teamSchema);
|
'use strict';
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let teamSchema = new Schema({
name : {
type: String,
required: true,
unique: true
},
email : {
type: String,
required: true
},
description : {
type: String
},
logisticsRequirements : {
type: String
},
openForApplications : {
type: Boolean,
default: true
},
members : {
leader : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
list : [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}]
},
cremiRoom : {
type: String
},
data : mongoose.Schema.Types.Mixed
});
require('./team.controller')(teamSchema);
module.exports = mongoose.model('Team', teamSchema);
|
Remove unique emails for teams
|
fix(server): Remove unique emails for teams
|
JavaScript
|
apache-2.0
|
asso-labeli/nuitinfo,asso-labeli/nuitinfo,asso-labeli/nuitinfo
|
16fa91c15f27843b8d947ca47fac4e50bd765d2f
|
lib/controllers/list_controller.js
|
lib/controllers/list_controller.js
|
ListController = RouteController.extend({
layoutTemplate: 'Layout',
subscriptions: function () {
this.subscribe('hosts');
},
action: function () {
this.render('HostList');
}
});
|
ListController = RouteController.extend({
layoutTemplate: 'Layout',
subscriptions: function () {
this.subscribe('hosts', {
sort: {sort: 1}
});
},
action: function () {
this.render('HostList');
}
});
|
Add sort for host list subscription.
|
Add sort for host list subscription.
|
JavaScript
|
mit
|
steyep/syrinx,hb5co/syrinx,mikebarkas/syrinx,bfodeke/syrinx,bfodeke/syrinx,hb5co/syrinx,steyep/syrinx,shrop/syrinx,shrop/syrinx,mikebarkas/syrinx
|
0889452062f149dbba5ce8acf005908fd7355b34
|
app/assets/javascripts/_analytics.js
|
app/assets/javascripts/_analytics.js
|
(function() {
"use strict";
GOVUK.Tracker.load();
var cookieDomain = (document.domain === 'www.beta.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain;
GOVUK.analytics = new GOVUK.Tracker({
universalId: 'UA-49258698-3',
cookieDomain: cookieDomain
});
GOVUK.analytics.trackPageview();
})();
|
(function() {
"use strict";
GOVUK.Tracker.load();
var cookieDomain = (document.domain === 'www.beta.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain;
var property = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? 'UA-49258698-1' : 'UA-49258698-3';
GOVUK.analytics = new GOVUK.Tracker({
universalId: property,
cookieDomain: cookieDomain
});
GOVUK.analytics.trackPageview();
})();
|
Use correct analytics properties for live/other
|
Use correct analytics properties for live/other
This commit makes the app select different Google analytics properties to track
against depending on which domain the user is browsing.
This will ensure continuity of analytics when we switch the DNS.
|
JavaScript
|
mit
|
alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend
|
ea87c51a6de416f083d9015166db9008b800da61
|
assets/js/components/Chip.stories.js
|
assets/js/components/Chip.stories.js
|
/**
* Chip Component Stories.
*
* Site Kit by Google, Copyright 2022 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 Chip from './Chip';
const Template = ( args ) => <Chip { ...args } />;
export const DefaultButton = Template.bind( {} );
DefaultButton.storyName = 'Default Chip';
DefaultButton.args = {
id: 'default',
label: 'Default Chip',
};
export default {
title: 'Components/Chip',
component: Chip,
};
|
/**
* Chip Component Stories.
*
* Site Kit by Google, Copyright 2022 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 Chip from './Chip';
const Template = ( args ) => <Chip { ...args } />;
export const DefaultChip = Template.bind( {} );
DefaultChip.storyName = 'Default Chip';
DefaultChip.args = {
id: 'default',
label: 'Default Chip',
};
export const SelectedChip = Template.bind( {} );
SelectedChip.storyName = 'Selected Chip';
SelectedChip.args = {
id: 'selected',
label: 'Selected Chip',
selected: true,
};
export default {
title: 'Components/Chip',
component: Chip,
};
|
Add story for a selected chip.
|
Add story for a selected chip.
|
JavaScript
|
apache-2.0
|
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
|
cacebb76a7554c5713d4f88a8060969c0eea7d7c
|
app/scripts/filters/previewfilter.js
|
app/scripts/filters/previewfilter.js
|
'use strict';
/**
* @ngdoc filter
* @name dockstore.ui.filter:PreviewFilter
* @function
* @description
* # PreviewFilter
* Filter in the dockstore.ui.
*/
angular.module('dockstore.ui')
.filter('PreviewFilter', [function () {
return function (containers, contLimit) {
if (!contLimit) return containers;
var sortedByBuildTime = containers.sort(function(a, b) {
if (!a.lastBuild) a.lastBuild.lastBuild = Number.MAX_VALUE;
if (!b.lastBuild) b.lastBuild = Number.MAX_VALUE;
return a.lastBuild - b.lastBuild;
});
return sortedByBuildTime.slice(0, contLimit - 1);
};
}]);
|
'use strict';
/**
* @ngdoc filter
* @name dockstore.ui.filter:PreviewFilter
* @function
* @description
* # PreviewFilter
* Filter in the dockstore.ui.
*/
angular.module('dockstore.ui')
.filter('PreviewFilter', [function () {
return function (containers, contLimit) {
if (!contLimit) return containers;
var sortedByBuildTime = containers.sort(function(a, b) {
if (!a.lastBuild) a.lastBuild = Number.MAX_VALUE;
if (!b.lastBuild) b.lastBuild = Number.MAX_VALUE;
return a.lastBuild - b.lastBuild;
});
return sortedByBuildTime.slice(0, contLimit - 1);
};
}]);
|
Update PreviewFilter for invalid/non-returned timestamps (v3).
|
Update PreviewFilter for invalid/non-returned timestamps (v3).
|
JavaScript
|
apache-2.0
|
ga4gh/dockstore-ui,ga4gh/dockstore-ui,ga4gh/dockstore-ui
|
a55921bc5ee2fa74ce11f8936121ec914240ee56
|
createTest.js
|
createTest.js
|
var ACCEPTANCE_TESTS_ENDPOINT = 'http://paie.sgmap.fr/tests/api/acceptance-tests',
ACCEPTANCE_TESTS_GUI_URL = 'http://paie.sgmap.fr/tests/';
function createTest() {
var formattedResults = Object.keys(window.lastResult).map(function(key) {
return {
code: key,
expectedValue: window.lastResult[key]
}
});
var form = document.getElementsByTagName('form')[0];
var data = {
expectedResults: formattedResults,
scenario: form.action + '?' + serialize(form)
}
var request = new XMLHttpRequest();
request.withCredentials = true;
request.open('POST', ACCEPTANCE_TESTS_ENDPOINT);
request.onload = function() {
if (request.status >= 300)
throw request;
var data = JSON.parse(request.responseText);
document.location = [ ACCEPTANCE_TESTS_GUI_URL, data._id, 'edit' ].join('/');
};
request.onerror = function() {
throw request;
}
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));
}
|
var ACCEPTANCE_TESTS_ENDPOINT = 'http://paie.sgmap.fr/tests/api/public/acceptance-tests',
ACCEPTANCE_TESTS_GUI_URL = 'http://paie.sgmap.fr/tests/';
function createTest() {
var formattedResults = Object.keys(window.lastResult).map(function(key) {
return {
code: key,
expectedValue: window.lastResult[key]
}
});
var form = document.getElementsByTagName('form')[0];
var data = {
expectedResults: formattedResults,
scenario: form.action + '?' + serialize(form)
}
var request = new XMLHttpRequest();
request.open('POST', ACCEPTANCE_TESTS_ENDPOINT);
request.onload = function() {
if (request.status >= 300)
throw request;
var data = JSON.parse(request.responseText);
document.location = [ ACCEPTANCE_TESTS_GUI_URL, data._id, 'edit' ].join('/');
};
request.onerror = function() {
throw request;
}
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));
}
|
Use public API route to add tests
|
Use public API route to add tests
Avoid sending credentials
|
JavaScript
|
agpl-3.0
|
sgmap/cout-embauche,sandcha/cout-embauche,sandcha/cout-embauche,sgmap/cout-embauche
|
b7648a75e3fa793aedcbf902b11c64133b34a893
|
auto-updater.js
|
auto-updater.js
|
const autoUpdater = require('electron').autoUpdater
const Menu = require('electron').Menu
var state = 'checking'
exports.initialize = function () {
autoUpdater.on('checking-for-update', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-available', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-downloaded', function () {
state = 'installed'
exports.updateMenu()
})
autoUpdater.on('update-not-available', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.on('error', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.setFeedURL('https://electron-api-demos.githubapp.com/updates')
autoUpdater.checkForUpdates()
}
exports.updateMenu = function () {
var menu = Menu.getApplicationMenu()
if (!menu) return
menu.items.forEach(function (item) {
if (item.submenu) {
item.submenu.items.forEach(function (item) {
switch (item.key) {
case 'checkForUpdate':
item.visible = state === 'no-update'
break
case 'checkingForUpdate':
item.visible = state === 'checking'
break
case 'restartToUpdate':
item.visible = state === 'installed'
break
}
})
}
})
}
|
const app = require('electron').app
const autoUpdater = require('electron').autoUpdater
const Menu = require('electron').Menu
var state = 'checking'
exports.initialize = function () {
autoUpdater.on('checking-for-update', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-available', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-downloaded', function () {
state = 'installed'
exports.updateMenu()
})
autoUpdater.on('update-not-available', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.on('error', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.setFeedURL(`https://electron-api-demos.githubapp.com/updates?version=${app.getVersion()}`)
autoUpdater.checkForUpdates()
}
exports.updateMenu = function () {
var menu = Menu.getApplicationMenu()
if (!menu) return
menu.items.forEach(function (item) {
if (item.submenu) {
item.submenu.items.forEach(function (item) {
switch (item.key) {
case 'checkForUpdate':
item.visible = state === 'no-update'
break
case 'checkingForUpdate':
item.visible = state === 'checking'
break
case 'restartToUpdate':
item.visible = state === 'installed'
break
}
})
}
})
}
|
Add version to update url
|
Add version to update url
|
JavaScript
|
mit
|
blep/electron-api-demos,blep/electron-api-demos,PanCheng111/XDF_Personal_Analysis,blep/electron-api-demos,PanCheng111/XDF_Personal_Analysis,electron/electron-api-demos,blep/electron-api-demos,PanCheng111/XDF_Personal_Analysis,electron/electron-api-demos,electron/electron-api-demos
|
854644f46cdc10387ef27399bbde7a61f835e9bf
|
scripts/grunt/default_task.js
|
scripts/grunt/default_task.js
|
// Lint and build CSS
module.exports = function (grunt) {
'use strict';
grunt.registerTask('default', [
'clean:build',
'phantomjs',
'webpack:dev',
]);
grunt.registerTask('test', [
'sasslint',
'tslint',
'typecheck',
"exec:jest",
'no-only-tests'
]);
grunt.registerTask('tslint', [
'newer:exec:tslintPackages',
'newer:exec:tslintRoot',
]);
grunt.registerTask('typecheck', [
'newer:exec:typecheckPackages',
'newer:exec:typecheckRoot',
]);
grunt.registerTask('precommit', [
'newer:sasslint',
'typecheck',
'tslint',
'no-only-tests'
]);
grunt.registerTask('no-only-tests', function () {
var files = grunt.file.expand('public/**/*_specs\.ts', 'public/**/*_specs\.js');
files.forEach(function (spec) {
var rows = grunt.file.read(spec).split('\n');
rows.forEach(function (row) {
if (row.indexOf('.only(') > 0) {
grunt.log.errorlns(row);
grunt.fail.warn('found only statement in test: ' + spec)
}
});
});
});
};
|
// Lint and build CSS
module.exports = function (grunt) {
'use strict';
grunt.registerTask('default', [
'clean:build',
'phantomjs',
'webpack:dev',
]);
grunt.registerTask('test', [
'sasslint',
'tslint',
'typecheck',
"exec:jest",
'no-only-tests'
]);
grunt.registerTask('tslint', [
'newer:exec:tslintPackages',
'newer:exec:tslintRoot',
]);
grunt.registerTask('typecheck', [
'newer:exec:typecheckPackages',
'newer:exec:typecheckRoot',
]);
grunt.registerTask('precommit', [
'newer:sasslint',
'typecheck',
'tslint',
'no-only-tests'
]);
grunt.registerTask('no-only-tests', function () {
var files = grunt.file.expand(
'public/**/*@(_specs|\.test)\.@(ts|js|tsx|jsx)',
'packages/grafana-ui/**/*@(_specs|\.test)\.@(ts|js|tsx|jsx)'
);
files.forEach(function (spec) {
var rows = grunt.file.read(spec).split('\n');
rows.forEach(function (row) {
if (row.indexOf('.only(') > 0) {
grunt.log.errorlns(row);
grunt.fail.warn('found only statement in test: ' + spec);
}
});
});
});
};
|
Add more patterns to no-only-test task
|
Add more patterns to no-only-test task
|
JavaScript
|
agpl-3.0
|
grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana,grafana/grafana
|
b79deb524fe24ae0e82bb1cf377b497657bba459
|
public/scripts/run/visibilityEvents.js
|
public/scripts/run/visibilityEvents.js
|
"use strict";
angular
.module('app')
.run([
'$document',
'$rootScope',
function($document, $rootScope) {
function visibilitychanged() {
var d = $document[0],
isHidden = d.hidden || d.webkitHidden || d.mozHidden || d.msHidden;
$rootScope.$emit('visibility:change', isHidden);
}
$document.on('visibilitychange',visibilitychanged);
$document.on('webkitvisibilitychange', visibilitychanged);
$document.on('msvisibilitychange', visibilitychanged);
}
]);
|
"use strict";
angular
.module('app')
.run([
'$document',
'$rootScope',
function($document, $rootScope) {
var last;
function visibilitychanged() {
var d = $document[0],
isHidden = d.hidden || d.webkitHidden || d.mozHidden || d.msHidden;
if (isHidden !== last) {
$rootScope.$emit('visibility:change', isHidden);
last = isHidden;
}
}
$document.on('visibilitychange',visibilitychanged);
$document.on('webkitvisibilitychange', visibilitychanged);
$document.on('msvisibilitychange', visibilitychanged);
}
]);
|
Fix doubled event of visibility change
|
Fix doubled event of visibility change
|
JavaScript
|
mit
|
xemle/spop-web,Schnouki/spop-web,Schnouki/spop-web,xemle/spop-web
|
892a30519995cbbbb05beb80c405fae2c1ccf155
|
webpack.config.js
|
webpack.config.js
|
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
app: './app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
context: path.resolve(__dirname, 'src'),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [['env', {modules: false}], 'stage-3'],
plugins: ['transform-runtime', 'check-es2015-constants']
}
}
},
{
test: /\.sass$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'file-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app.pug',
filename: 'app.html'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css',
})
],
devServer: {
publicPath: '/',
contentBase: path.join(__dirname, 'dist')
}
}
|
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
app: './app.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
context: path.resolve(__dirname, 'src'),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [['env', {modules: false}], 'stage-3'],
plugins: ['transform-runtime', 'check-es2015-constants']
}
}
},
{
test: /\.sass$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.pug$/,
use: ['html-loader', 'pug-html-loader']
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'file-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'app.pug',
filename: 'app.html'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css',
})
],
devServer: {
publicPath: '/',
contentBase: path.join(__dirname, 'dist')
},
devtool: "source-map"
}
|
Add source maps to get better debugging in the browser
|
Add source maps to get better debugging in the browser
|
JavaScript
|
mit
|
javierportillo/webpack-starter,javierportillo/webpack-starter
|
96d65ebacf80370c36ac80407ae38c3823294a0e
|
webpack.config.js
|
webpack.config.js
|
var webpack = require('webpack');
var fs = require('fs');
var config = {
entry: {
'app': './app/index.js'
},
devtool: 'source-map',
output: {
path: __dirname + '/dist',
filename: `[name].[hash].js`,
publicPath: __dirname + '/dist'
},
module: {
loaders: [
{
test: /(\.js)$/,
loader: 'babel',
exclude: /(node_modules)/,
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
function() {
this.plugin("done", function(stats) {
const hash = stats.toJson().hash;
fs.readFile('./index.html', 'utf8', function (err,data) {
if (err) {
return console.log('ERR', err);
}
var result = data.replace(/dist\/app.*.js/g, `dist/app.${hash}.js`);
fs.writeFile('./index.html', result, 'utf8', function (err) {
if (err) return console.log('ERR', err);
});
});
});
}
]
};
module.exports = config;
|
var webpack = require('webpack');
var fs = require('fs');
var config = {
entry: {
'app': './app/index.js'
},
devtool: 'source-map',
output: {
path: __dirname + '/dist',
filename: `[name].[hash].js`,
publicPath: __dirname + '/dist'
},
module: {
loaders: [
{
test: /(\.js)$/,
loader: 'babel',
exclude: /(node_modules)/,
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
function() {
this.plugin("compile", function() {
require( 'child_process' ).exec('rm -rf ./dist');
});
this.plugin("done", function(stats) {
const hash = stats.toJson().hash;
fs.readFile('./index.html', 'utf8', function (err,data) {
if (err) {
return console.log('ERR', err);
}
var result = data.replace(/dist\/app.*.js/g, `dist/app.${hash}.js`);
fs.writeFile('./index.html', result, 'utf8', function (err) {
if (err) return console.log('ERR', err);
});
});
});
}
]
};
module.exports = config;
|
Clear dist on every build
|
Clear dist on every build
|
JavaScript
|
mit
|
bsingr/mastermind,bsingr/mastermind
|
d0758e87e20d9a8996a648fa197c10aec62480ca
|
lib/server-factory-https.js
|
lib/server-factory-https.js
|
module.exports = ServerFactory => class HttpsServerFactory extends ServerFactory {
create (options) {
const fs = require('fs')
const https = require('https')
const t = require('typical')
const serverOptions = {}
if (options.pfx) {
serverOptions.pfx = fs.readFileSync(options.pfx)
} else {
if (!(options.key && options.cert)) {
serverOptions.key = this.getDefaultKeyPath()
serverOptions.cert = this.getDefaultCertPath()
}
serverOptions.key = fs.readFileSync(serverOptions.key, 'utf8')
serverOptions.cert = fs.readFileSync(serverOptions.cert, 'utf8')
}
if (t.isDefined(options.maxConnections)) serverOptions.maxConnections = options.maxConnections
if (t.isDefined(options.keepAliveTimeout)) serverOptions.keepAliveTimeout = options.keepAliveTimeout
this.emit('verbose', 'server.config', serverOptions)
return https.createServer(serverOptions)
}
}
|
module.exports = ServerFactory => class HttpsServerFactory extends ServerFactory {
create (options) {
const fs = require('fs')
const https = require('https')
const t = require('typical')
const serverOptions = {}
if (options.pfx) {
serverOptions.pfx = fs.readFileSync(options.pfx)
} else {
if (!(options.key && options.cert)) {
serverOptions.key = this.getDefaultKeyPath()
serverOptions.cert = this.getDefaultCertPath()
} else {
serverOptions.key = fs.readFileSync(options.key, 'utf8')
serverOptions.cert = fs.readFileSync(options.cert, 'utf8')
}
}
if (t.isDefined(options.maxConnections)) serverOptions.maxConnections = options.maxConnections
if (t.isDefined(options.keepAliveTimeout)) serverOptions.keepAliveTimeout = options.keepAliveTimeout
this.emit('verbose', 'server.config', serverOptions)
return https.createServer(serverOptions)
}
}
|
Fix key and cert file params when using personal version
|
Fix key and cert file params when using personal version
|
JavaScript
|
mit
|
lwsjs/lws
|
112aec851eb4c6f85ee4c365f663adc2bc80cb0b
|
dangerfile.js
|
dangerfile.js
|
import { message, danger } from "danger"
message(":tada:, this worked @" + danger.github.pr.user.login)
|
import { message, danger } from "danger";
import prettier from 'prettier';
const srcDir = `${__dirname}/src/**/*.js`;
const options = {
singleQuote: true,
printWidth: 100
};
if (prettier.check(srcDir, options)) {
message(':tada: Your code is formatted correctly');
} else {
warn('You haven\'t formated the code using prettier. Please run `npm run format` before merging the PR');
}
|
Check if src dir has been formatted
|
Check if src dir has been formatted
|
JavaScript
|
mit
|
ldabiralai/simulado
|
876827176d608677adce254c9cc3c957abbcb5f2
|
bin/sass-lint.js
|
bin/sass-lint.js
|
#!/usr/bin/env node
'use strict';
var program = require('commander'),
meta = require('../package.json'),
lint = require('../index');
var detects;
program
.version(meta.version)
.usage('[options] \'<file or glob>\'')
.option('-q, --no-exit', 'do not exit on errors')
.parse(process.argv);
detects = lint.lintFiles(program.args[0]);
detects = lint.format(detects);
lint.outputResults(detects);
if (program.exit) {
lint.failOnError(detects);
}
|
#!/usr/bin/env node
'use strict';
var program = require('commander'),
meta = require('../package.json'),
lint = require('../index');
var detects,
formatted;
program
.version(meta.version)
.usage('[options] \'<file or glob>\'')
.option('-q, --no-exit', 'do not exit on errors')
.parse(process.argv);
detects = lint.lintFiles(program.args[0]);
formatted = lint.format(detects);
lint.outputResults(formatted);
if (program.exit) {
lint.failOnError(detects);
}
|
Fix fail on error for CLI
|
:bug: Fix fail on error for CLI
|
JavaScript
|
mit
|
skovhus/sass-lint,benthemonkey/sass-lint,zallek/sass-lint,sasstools/sass-lint,MethodGrab/sass-lint,donabrams/sass-lint,zaplab/sass-lint,joshuacc/sass-lint,srowhani/sass-lint,sktt/sass-lint,carsonmcdonald/sass-lint,Snugug/sass-lint,bgriffith/sass-lint,DanPurdy/sass-lint,srowhani/sass-lint,sasstools/sass-lint,alansouzati/sass-lint,ngryman/sass-lint,flacerdk/sass-lint,Dru89/sass-lint
|
dfb21cd44ae2c0d1dd70b4a2253839c98daa1683
|
src/clusterpost-auth/index.js
|
src/clusterpost-auth/index.js
|
var Boom = require('boom');
exports.register = function (server, conf, next) {
const validate = function(req, decodedToken, callback){
var exs = server.methods.executionserver.getExecutionServer(decodedToken.executionserver);
if(exs){
exs.scope = ['executionserver'];
callback(undefined, true, exs);
}else{
callback(Boom.unauthorized(exs));
}
}
conf.validate = validate;
return require('hapi-jwt-couch').register(server, conf, next);
};
exports.register.attributes = {
pkg: require('./package.json')
};
|
var Boom = require('boom');
exports.register = function (server, conf, next) {
const validate = function(req, decodedToken, callback){
var exs = server.methods.executionserver.getExecutionServer(decodedToken.executionserver);
if(exs){
exs.scope = ['executionserver'];
callback(undefined, true, exs);
}else{
callback(Boom.unauthorized(exs));
}
}
conf.validate = validate;
server.register({
register: require('hapi-jwt-couch'),
options: conf
}, function(err){
if(err){
throw err;
}
server.method({
name: 'clusterpostauth.verify',
method: server.methods.jwtauth.verify,
options: {}
});
});
return next();
};
exports.register.attributes = {
pkg: require('./package.json')
};
|
Use the register function from server when discovering the hapi-jwt-couch plugin
|
STYLE: Use the register function from server when discovering the hapi-jwt-couch plugin
|
JavaScript
|
apache-2.0
|
juanprietob/clusterpost,juanprietob/clusterpost,juanprietob/clusterpost
|
0719710c9d5c34be3a236028848db437269baf03
|
server/plugins/bookmarks/validators.js
|
server/plugins/bookmarks/validators.js
|
// Validation for bookmark payloads.
'use strict';
var Hoek = require('hoek');
var Joi = require('joi');
var validators = {};
validators.bookmarkID = Joi.string().guid();
// Bookmark without ID. Used for the update and save payloads.
validators.bookmarkWithoutID = {
id: validators.bookmarkID.allow(null),
url: Joi.string()
.required()
.max(200, 'utf-8'),
title: Joi.string()
.max(200, 'utf-8')
.allow(null),
description: Joi.string().allow(null),
added_at: Joi.string().allow(null),
created_at: Joi.string().allow(null),
updated_at: Joi.string().allow(null),
};
// The full bookmark payload, requiring the ID.
validators.bookmark = Hoek.clone(validators.bookmarkWithoutID);
validators.bookmark.id = validators.bookmarkID.required();
module.exports = validators;
|
// Validation for bookmark payloads.
'use strict';
var Hoek = require('hoek');
var Joi = require('joi');
var validators = {};
validators.bookmarkID = Joi.string().guid();
// Bookmark without ID. Used for the update and save payloads.
validators.bookmarkWithoutID = {
id: validators.bookmarkID.allow(null),
url: Joi.string()
.required()
.max(200, 'utf-8'),
title: Joi.string()
.max(200, 'utf-8')
.allow(null),
description: Joi.string().allow(null),
added_at: Joi.date().iso().allow(null),
created_at: Joi.date().iso().allow(null),
updated_at: Joi.date().iso().allow(null),
};
// The full bookmark payload, requiring the ID.
validators.bookmark = Hoek.clone(validators.bookmarkWithoutID);
validators.bookmark.id = validators.bookmarkID.required();
module.exports = validators;
|
Validate date fields as ISO-format dates.
|
Validate date fields as ISO-format dates.
|
JavaScript
|
isc
|
mikl/bookmeister,mikl/bookmeister
|
8382d5c2147188eea4c1a78971a91abbfce32ef9
|
src/app/auth/auth.controller.js
|
src/app/auth/auth.controller.js
|
(function() {
'use strict';
angular
.module('app.auth')
.controller('AuthController', AuthController);
AuthController.$inject = ['$location', 'authService'];
function AuthController($location, authService) {
var vm = this;
vm.user = {
email: '',
password: ''
};
vm.register = register;
vm.login = login;
function register(user) {
return authService.register(user)
.then(function() {
return vm.login(user);
})
.then(function() {
return authService.sendWelcomeEmail(user.email);
})
.catch(function(error) {
console.log(error);
});
}
function login(user) {
return authService.login(user)
.then(function(loggedInUser) {
console.log(loggedInUser);
$location.path('/waitlist');
})
.catch(function(error) {
console.log(error);
});
}
}
})();
|
(function() {
'use strict';
angular
.module('app.auth')
.controller('AuthController', AuthController);
AuthController.$inject = ['$location', 'authService'];
function AuthController($location, authService) {
var vm = this;
vm.user = {
email: '',
password: ''
};
vm.error = null;
vm.register = register;
vm.login = login;
function register(user) {
return authService.register(user)
.then(function() {
return vm.login(user);
})
.then(function() {
return authService.sendWelcomeEmail(user.email);
})
.catch(function(error) {
vm.error = error;
});
}
function login(user) {
return authService.login(user)
.then(function() {
$location.path('/waitlist');
})
.catch(function(error) {
vm.error = error;
});
}
}
})();
|
Set vm.error in register and login on AuthController.
|
Set vm.error in register and login on AuthController.
|
JavaScript
|
mit
|
anthonybrown/angular-course-demo-app-v2,anthonybrown/angular-course-demo-app-v2
|
b71557376bb31512ba96a81621b5051166b01f60
|
public/js/channel.js
|
public/js/channel.js
|
$(function() {
var $loadMore = $('#load-more');
if ($loadMore.length) {
var $spinner = $('#spinner');
function init() {
$spinner.hide();
$.ajaxPrefilter(function(options, _, xhr) {
if (!xhr.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', securityToken);
}
});
}
function updateUI() {
$(this).hide();
$spinner.show();
}
$loadMore.on('click', function() {
updateUI.call(this);
// $.ajax({
// url: '/api/videos',
// type: 'POST',
// dataType: 'json',
// complete: function() {
// $('#spinner').hide();
// }
// });
});
init();
}
});
|
$(function() {
var $loadMore = $('#load-more');
if ($loadMore.length) {
var $spinner = $('#spinner');
var init = function() {
$spinner.hide();
$.ajaxPrefilter(function(options, _, xhr) {
if (!xhr.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', securityToken);
}
});
};
var updateUI = function() {
$(this).hide();
$spinner.show();
};
$loadMore.on('click', function() {
updateUI.call(this);
// $.ajax({
// url: '/api/videos',
// type: 'POST',
// dataType: 'json',
// complete: function() {
// $('#spinner').hide();
// }
// });
});
init();
}
});
|
Change function declaration to function expression
|
Change function declaration to function expression
|
JavaScript
|
mit
|
CreaturePhil/Usub,CreaturePhil/Usub
|
d5855f3e4fc63f120af56a94f0842fae2ffd4871
|
src/components/posts_index.js
|
src/components/posts_index.js
|
import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, post => {
return (
<li className="list-group-item">
{post.title}
</li>
);
});
}
render() {
return (
<div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
|
import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
import { Link } from 'react-router-dom';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, post => {
return (
<li className="list-group-item">
{post.title}
</li>
);
});
}
render() {
return (
<div>
<div className="text-xs-right">
<Link className="btn btn-primary" to="/posts/new">
Add a Post
</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
|
Add button to new post page
|
Add button to new post page
|
JavaScript
|
mit
|
heatherpark/blog,heatherpark/blog
|
de48510fa5b038cbdda7d2386bba0419af1b8542
|
src/client/reducers/BoardReducer.js
|
src/client/reducers/BoardReducer.js
|
import initialState from './initialState';
import {
BOARD_REQUESTED,
BOARD_LOADED,
BOARD_DESTROYED,
BOARD_SCROLLED_BOTTOM
} from '../constants'
export default function (state = initialState.board, action) {
switch (action.type) {
case BOARD_REQUESTED:
return Object.assign({}, state, {
isFetching: true,
requestType: action.type // for logging error to user...?
})
case BOARD_LOADED:
return Object.assign({}, state, {
posts: action.payload,
isFetching: false
})
case BOARD_DESTROYED:
return Object.assign({}, state, {
posts: []
})
case BOARD_SCROLLED_BOTTOM:
return Object.assign({}, state, {
limit: action.payload
})
default:
return state
}
}
|
import initialState from './initialState';
import {
BOARD_REQUESTED,
BOARD_LOADED,
BOARD_DESTROYED,
BOARD_SCROLLED_BOTTOM,
BOARD_FILTER
} from '../constants'
export default function (state = initialState.board, action) {
switch (action.type) {
case BOARD_REQUESTED:
return Object.assign({}, state, {
isFetching: true,
requestType: action.type // for logging error to user...?
})
case BOARD_LOADED:
return Object.assign({}, state, {
posts: action.payload,
isFetching: false
})
case BOARD_DESTROYED:
return Object.assign({}, state, {
posts: []
})
case BOARD_SCROLLED_BOTTOM:
return Object.assign({}, state, {
limit: action.payload
})
case BOARD_FILTER:
return Object.assign({}, state, {
filterWord: action.payload || null
})
default:
return state
}
}
|
Add board reducer case for filtering
|
Add board reducer case for filtering
|
JavaScript
|
mit
|
AdamSalma/Lurka,AdamSalma/Lurka
|
9a9c348c05850beb1f3ad7a73bde54eb2d45bab1
|
service/load-schemas.js
|
service/load-schemas.js
|
// This module loads and exposes an object of all available schemas, using
// the schema key as the object key.
//
// The schemas are loaded from the extension plugin directory. We therefore need
// to have a checkout of the extension alongside the web service in order to use
// this module.
'use strict';
let jsonfile = require('jsonfile');
let fs = require('fs');
let path = require('path');
let pluginDir = '../extension/src/plugins';
let dirs = getDirectories(pluginDir);
let schemas = {};
for (let dir of dirs) {
try {
let schema = jsonfile.readFileSync(`${pluginDir}/${dir}/schema.json`);
if (schema.hasOwnProperty('schema') && schema.schema.hasOwnProperty('key')) {
schemas[schema.schema.key] = schema;
} else {
console.log(`schema.json for plugin "${dir}" does not have a valid schema header. Skipping.`);
}
} catch (e) {
console.log(`Problem reading schema.json for plugin "${dir}". Skipping.`);
}
}
function getDirectories(srcpath) {
return fs.readdirSync(srcpath).filter(function(file) {
return fs.statSync(path.join(srcpath, file)).isDirectory();
});
}
module.exports = schemas;
|
// This module loads and exposes an object of all available schemas, using
// the schema key as the object key. It adds the site metadata to the schema
// header for convenient access.
//
// The schemas and site metadata are loaded from the extension plugin directory.
// We therefore need to have a checkout of the extension alongside the web
// service in order to use this module.
'use strict';
let jsonfile = require('jsonfile');
let sitesDir = '../extension';
let pluginDir = '../extension/src/plugins';
let sites = jsonfile.readFileSync(`${sitesDir}/sites.json`);
let schemas = {};
for (let site of sites) {
try {
let schema = jsonfile.readFileSync(`${pluginDir}/${site.plugin}/schema.json`);
if (schema.hasOwnProperty('schema') && schema.schema.hasOwnProperty('key')) {
schemas[schema.schema.key] = schema;
schema.schema.site = site;
} else {
console.log(`schema.json for plugin "${site.plugin}" does not have a valid schema header. Skipping.`);
}
} catch (e) {
console.log(`Problem reading schema.json for plugin "${site.plugin}". Skipping. Error was: ${e}`);
}
}
module.exports = schemas;
|
Use site metadata to find registered plugins/schemas.
|
Use site metadata to find registered plugins/schemas.
This simplifies loading schemas, and eliminates some dependencies.
We also stash site metadata in the schema object, since it's useful
for tests.
|
JavaScript
|
cc0-1.0
|
eloquence/freeyourstuff.cc,eloquence/freeyourstuff.cc
|
69b467a039b0b8e9ae21d1d06025a793f6f7f865
|
src/components/editor/EmbedBlock.js
|
src/components/editor/EmbedBlock.js
|
/* eslint-disable react/no-danger */
import React, { Component, PropTypes } from 'react'
import Block from './Block'
export function reloadPlayers() {
if (typeof window !== 'undefined' && window.embetter) {
window.embetter.reloadPlayers()
}
}
class EmbedBlock extends Component {
static propTypes = {
data: PropTypes.object,
}
static defaultProps = {
data: {},
}
componentDidMount() {
reloadPlayers()
}
componentDidUpdate() {
reloadPlayers()
}
render() {
const { data: { service, url, thumbnailLargeUrl, id } } = this.props
const children = typeof window !== 'undefined' ?
window.embetter.utils.playerHTML(
window.embetter.services[service],
url,
thumbnailLargeUrl,
id,
) :
null
return (
<Block {...this.props}>
<div
className="editable embed"
dangerouslySetInnerHTML={{ __html: children }}
/>
</Block>
)
}
}
export default EmbedBlock
|
/* eslint-disable react/no-danger */
import React, { Component, PropTypes } from 'react'
import Block from './Block'
export function reloadPlayers() {
if (typeof window !== 'undefined' && window.embetter) {
window.embetter.reloadPlayers()
}
}
class EmbedBlock extends Component {
static propTypes = {
data: PropTypes.object,
}
static defaultProps = {
data: {},
}
componentDidMount() {
reloadPlayers()
}
componentDidUpdate() {
reloadPlayers()
}
render() {
const dataJS = this.props.data.toJS()
const { service, url, thumbnailLargeUrl, id } = dataJS
const children = typeof window !== 'undefined' ?
window.embetter.utils.playerHTML(
window.embetter.services[service],
url,
thumbnailLargeUrl,
id,
) :
null
return (
<Block {...this.props}>
<div
className="editable embed"
dangerouslySetInnerHTML={{ __html: children }}
/>
</Block>
)
}
}
export default EmbedBlock
|
Fix an issue with embed previews.
|
Fix an issue with embed previews.
[Fixes #137488987](https://www.pivotaltracker.com/story/show/137488987)
[Fixes #137491203](https://www.pivotaltracker.com/story/show/137491203)
|
JavaScript
|
mit
|
ello/webapp,ello/webapp,ello/webapp
|
1dcacbc8a960279db61610185b7155719f5046d5
|
find-core/src/main/public/static/js/find/app/pages.js
|
find-core/src/main/public/static/js/find/app/pages.js
|
/*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'find/app/find-pages',
'find/app/page/find-search',
'find/app/page/find-settings-page',
'i18n!find/nls/bundle'
], function(FindPages, FindSearch, SettingsPage) {
return FindPages.extend({
initializePages: function() {
this.pages = [
{
constructor: SettingsPage
, pageName: 'settings'
, classes: 'hide-from-non-useradmin'
}
];
}
});
});
|
/*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'find/app/find-pages',
'find/app/page/find-settings-page',
'i18n!find/nls/bundle'
], function(FindPages, SettingsPage) {
return FindPages.extend({
initializePages: function() {
this.pages = [
{
constructor: SettingsPage
, pageName: 'settings'
, classes: 'hide-from-non-useradmin'
}
];
}
});
});
|
Remove unnecessary import [rev: minor]
|
Remove unnecessary import [rev: minor]
|
JavaScript
|
mit
|
hpautonomy/find,hpautonomy/find,LinkPowerHK/find,hpe-idol/find,hpe-idol/find,LinkPowerHK/find,hpe-idol/find,hpautonomy/find,LinkPowerHK/find,LinkPowerHK/find,hpe-idol/find,hpautonomy/find,hpe-idol/java-powerpoint-report,hpe-idol/java-powerpoint-report,LinkPowerHK/find,hpautonomy/find,hpe-idol/find
|
2e4fa079ee4b0a870ce3e1a530ffcfccecac7dfd
|
src/js/tael_sizing.js
|
src/js/tael_sizing.js
|
function resizeTaelContainer() {
$('.tael-container').css('bottom', 16);
}
$(document).ready(function () {
var header_bbox = $('.header')[0].getBoundingClientRect();
$('.tael-container').css('top', header_bbox.bottom + 8);
resizeTaelContainer();
$(window).resize(resizeTaelContainer);
});
|
function resizeTaelContainer() {
var
header_bbox = $('.header')[0].getBoundingClientRect(),
tael_container = $('.tael-container');
tael_container.css('top', header_bbox.bottom);
tael_container.css('bottom', 16);
}
$(document).ready(function () {
resizeTaelContainer();
$(window).resize(resizeTaelContainer);
});
|
Fix Tael container top resizing
|
Fix Tael container top resizing
|
JavaScript
|
mit
|
hinsley-it/maestro,hinsley-it/maestro
|
c9ecf996edac66be9997fccd353419a8e7f07235
|
app/services/me.js
|
app/services/me.js
|
import Service from '@ember/service';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
export default Service.extend({
session: service(),
init() {
let routeName = window.location.href.split('/').pop();
if (routeName == 'logout') {
if (this.get('session.isAuthenticated')) {
return this.get('session').invalidate();
}
}
this.set('data', computed('session.session.content.authenticated', function() {
// console.log('session', this.get('session.session.content.authenticated'));
return this.get('session.session.content.authenticated');
}));
}
});
|
import Service from '@ember/service';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import ENV from '../config/environment';
import RSVP from 'rsvp';
export default Service.extend({
session: service(),
ajax: service(),
endpoint: `${ENV.APP.apiHost}/account/login`,
details: computed('data', function() {
let options = {
headers: {
'Authorization': this.get('data').access_token
},
method: 'GET'
};
let self = this;
return new RSVP.Promise((resolve, reject) => {
fetch(this.get('endpoint'), options).then((response) => {
return self.set('user', response);
}).catch(reject);
});
}),
init() {
let routeName = window.location.href.split('/').pop();
if (routeName == 'logout') {
if (this.get('session.isAuthenticated')) {
return this.get('session').invalidate();
}
}
this.set('data', computed('session.session.content.authenticated', function() {
// console.log('session', this.get('session.session.content.authenticated'));
let data = this.get('session.session.content.authenticated');
return data;
}));
}
});
|
Add logged in user details
|
Add logged in user details
|
JavaScript
|
agpl-3.0
|
tenders-exposed/elvis-ember,tenders-exposed/elvis-ember
|
8e0c34795e11dc229a87277379de9b8da4afa9f4
|
src-server/socket.io-wrapper/server.js
|
src-server/socket.io-wrapper/server.js
|
import SocketIONamespace from "./namespace";
export default class SocketIOServer {
constructor(io) {
this._io = io;
this._sockets = this.of("/");
this._nsps = Object.create(null);
}
get rawServer() {
return this._io;
}
//
// Delegation methods
//
of(name, fn) {
var nsp = this._nsps[name];
if (! nsp) {
nsp = new SocketIONamespace(this._io.of(name, fn));
this._nsps[name] = nsp;
}
return nsp;
}
}
// pass through methods
[
"serveClient", "set", "path", "adapter", "origins",
"listen", "attach", "bind", "onconnection",
/* "of", */ "close"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
this._io[methodName](...args);
return this;
};
});
[
/* "on" */, "to", "in", "use", "emit", "send",
"write", "clients", "compress",
// mayajs-socketio-wrapper methods
"on", "off", "receive", "offReceive"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
return this._sockets[methodName](...args);
}
});
|
import SocketIONamespace from "./namespace";
export default class SocketIOServer {
constructor(io) {
this._io = io;
this._nsps = Object.create(null);
this._sockets = this.of("/");
}
get rawServer() {
return this._io;
}
//
// Delegation methods
//
of(name, fn) {
var nsp = this._nsps[name];
if (! nsp) {
nsp = new SocketIONamespace(this._io.of(name, fn));
this._nsps[name] = nsp;
}
return nsp;
}
}
// pass through methods
[
"serveClient", "set", "path", "adapter", "origins",
"listen", "attach", "bind", "onconnection",
/* "of", */ "close"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
this._io[methodName](...args);
return this;
};
});
[
/* "on" */, "to", "in", "use", "emit", "send",
"write", "clients", "compress",
// mayajs-socketio-wrapper methods
"on", "off", "receive", "offReceive"
].forEach(methodName => {
SocketIOServer.prototype[methodName] = function (...args) {
return this._sockets[methodName](...args);
}
});
|
Fix annot read property '/' of undefined
|
Fix annot read property '/' of undefined
|
JavaScript
|
mit
|
Ragg-/rektia,Ragg-/maya.js,Ragg-/rektia,Ragg-/rektia,Ragg-/maya.js
|
12be4f8e9b60a9577246ed0fce6b5c47f28f01d3
|
src/redux-dialog.js
|
src/redux-dialog.js
|
import React, { Component } from 'react';
import { connect } from 'react-redux'
import Modal from 'react-modal'
import { closeDialog } from './actions';
const reduxDialog = (dialogProps) => {
const {
name,
onAfterOpen = () => {},
onRequestClose = () => {}
} = dialogProps;
return((WrappedComponent) => {
class ReduxDialog extends Component {
render () {
return (
<Modal {...dialogProps} {...this.props}>
<WrappedComponent {...this.props} />
</Modal>
);
}
}
const mapStateToProps = (state) => ({
isOpen: (state.dialogs.dialogs
&& state.dialogs.dialogs[name]
&& state.dialogs.dialogs[name].isOpen) || false
})
const mapDispatchToProps = (dispatch) => ({
onAfterOpen: () => {
onAfterOpen();
},
onRequestClose: () => {
onRequestClose();
dispatch(closeDialog(name))
}
})
return connect(mapStateToProps, mapDispatchToProps)(ReduxDialog);
});
}
export default reduxDialog;
|
import React, { Component } from 'react';
import { connect } from 'react-redux'
import Modal from 'react-modal'
import { closeDialog } from './actions';
const reduxDialog = (defaults) => {
const {
name,
onAfterOpen = () => {},
onRequestClose = () => {}
} = defaults;
return((WrappedComponent) => {
class ReduxDialog extends Component {
render () {
return (
<Modal {...defaults} {...this.props}>
<WrappedComponent {...this.props} />
</Modal>
);
}
}
const mapStateToProps = (state) => {
let isOpen = defaults.isOpen;
const {
dialogReducer: { dialogs }
} = state;
if (dialogs && dialogs[name].isOpen !== undefined)
isOpen = dialogs[name].isOpen;
return { isOpen };
};
const mapDispatchToProps = (dispatch) => ({
onAfterOpen: () => {
onAfterOpen();
},
onRequestClose: () => {
onRequestClose();
dispatch(closeDialog(name))
}
})
return connect(mapStateToProps, mapDispatchToProps)(ReduxDialog);
});
}
export default reduxDialog;
|
Allow an initial isOpen property to be set
|
Allow an initial isOpen property to be set
|
JavaScript
|
mit
|
JakeDluhy/redux-dialog,JakeDluhy/redux-dialog
|
e5f246b56bb3efe9567c587739dbb0c65032a57a
|
index.js
|
index.js
|
// Karme Edge Launcher
// =================
// Dependencies
// ------------
var urlparse = require('url').parse
var urlformat = require('url').format
var exec = require('child_process').exec
// Constants
// ---------
var PROCESS_NAME = 'spartan.exe'
var EDGE_COMMAND = [
'powershell',
'start',
'shell:AppsFolder\\Microsoft.Windows.Spartan_cw5n1h2txyewy!Microsoft.Spartan.Spartan'
]
// Constructor
function EdgeBrowser (baseBrowserDecorator, logger) {
baseBrowserDecorator(this)
var log = logger.create('launcher')
this._getOptions = function (url) {
var urlObj = urlparse(url, true)
// url.format does not want search attribute
delete urlObj.search
url = urlformat(urlObj)
return EDGE_COMMAND.splice(1).concat(url)
}
}
EdgeBrowser.prototype = {
name: 'Edge',
DEFAULT_CMD: {
win32: EDGE_COMMAND[0]
},
ENV_CMD: 'EDGE_BIN'
}
EdgeBrowser.$inject = ['baseBrowserDecorator', 'logger']
// Publish di module
// -----------------
module.exports = {
'launcher:Edge': ['type', EdgeBrowser]
}
|
// Karme Edge Launcher
// =================
// Dependencies
// ------------
var urlparse = require('url').parse
var urlformat = require('url').format
// Constants
// ---------
var EDGE_COMMAND = [
'powershell',
'start',
'shell:AppsFolder\\Microsoft.Windows.Spartan_cw5n1h2txyewy!Microsoft.Spartan.Spartan'
]
// Constructor
function EdgeBrowser (baseBrowserDecorator) {
baseBrowserDecorator(this)
this._getOptions = function (url) {
var urlObj = urlparse(url, true)
// url.format does not want search attribute
delete urlObj.search
url = urlformat(urlObj)
return EDGE_COMMAND.splice(1).concat(url)
}
}
EdgeBrowser.prototype = {
name: 'Edge',
DEFAULT_CMD: {
win32: EDGE_COMMAND[0]
},
ENV_CMD: 'EDGE_BIN'
}
EdgeBrowser.$inject = ['baseBrowserDecorator']
// Publish di module
// -----------------
module.exports = {
'launcher:Edge': ['type', EdgeBrowser]
}
|
Remove variables that are defined but never used
|
Remove variables that are defined but never used
|
JavaScript
|
mit
|
nicolasmccurdy/karma-edge-launcher,karma-runner/karma-edge-launcher
|
0bc5a286de1afefc26b32599bfec8ff550a73cf8
|
index.js
|
index.js
|
function renderCat(catGifId) {
var container = document.getElementById('cat');
container.innerHTML =
"<img " +
"src='http://iconka.com/wp-content/uploads/edd/2015/10/" + catGifId +".gif' " +
"style='width:90%'>";
}
Dashboard.registerWidget(function (dashboardAPI, registerWidgetAPI) {
dashboardAPI.setTitle('Keep calm and purrrrr...');
renderCat("purr");
registerWidgetAPI({
onConfigure: function() {
renderCat("meal");
},
onRefresh: function() {
renderCat("knead");
}
});
});
|
var listOfCatIds = ["purr", "meal", "knead"];
function renderCat(catGifId) {
var container = document.getElementById('cat');
container.innerHTML =
"<img " +
"src='http://iconka.com/wp-content/uploads/edd/2015/10/" + catGifId +".gif' " +
"style='width:90%'>";
}
function renderSelector(dashboardAPI) {
var container = document.getElementById('cat');
container.innerHTML =
"<select>" +
"<option value='random'>Random Cat</option>" +
"<option value='purr'>Purr</option>" +
"<option value='meal'>Meal</option>" +
"<option value='knead'>Knead</option>" +
"</select>" +
"<input type='button' value='Save' id='save'>";
var button = document.getElementById('save');
button.onclick = function() {
dashboardAPI.storeConfig({
cat: 'random'
});
dashboardAPI.exitConfigMode();
}
}
function drawCatFromConfig(dashboardAPI) {
dashboardAPI.readConfig().then(function(config) {
var catId = config.cat || 'purr';
if (catId === 'random') {
catId = listOfCatIds[Math.floor(Math.random() * listOfCatIds.length)];
}
renderCat(catId);
});
}
Dashboard.registerWidget(function (dashboardAPI, registerWidgetAPI) {
dashboardAPI.setTitle('Keep calm and purrrrr...');
drawCatFromConfig(dashboardAPI);
registerWidgetAPI({
onConfigure: function() {
renderSelector(dashboardAPI);
},
onRefresh: function() {
drawCatFromConfig(dashboardAPI);
}
});
});
|
Save random; load random cat on 'random' option
|
Save random; load random cat on 'random' option
|
JavaScript
|
apache-2.0
|
mariyadavydova/youtrack-cats-widget,mariyadavydova/youtrack-cats-widget
|
f65c93b109e2005bea1daaac1494a93f6fc5205b
|
index.js
|
index.js
|
#!/usr/bin/env iojs
var program = require('commander'),
fs = require('fs'),
sequoria = require('sequoria'),
createBot = require('./lib').createBot;
function main() {
program
.version(require('./package').version)
.usage('[configFile]')
.action(function(configFile){
// this module is being directly run.
var configFile = configFile || 'config.json';
if (!configFile.startsWith('/')) {
// hack: should use proper path joining package
configFile = [
process.cwd(),
configFile
].join('/');
}
var config = JSON.parse(fs.readFileSync(configFile));
var bot = createBot(config);
bot.start();
})
.parse(process.argv);
}
if (require.main === module) {
main();
}
module.exports = createBot;
|
#!/usr/bin/env iojs
var path = require('path'),
program = require('commander'),
fs = require('fs'),
sequoria = require('sequoria'),
createBot = require('./lib').createBot;
function main() {
program
.version(require('./package').version)
.usage('[configFile]')
.action(function(configFile){
// this module is being directly run.
var configFile = path.resolve(configFile || 'config.json');
var config = JSON.parse(fs.readFileSync(configFile));
var bot = createBot(config);
bot.start();
})
.parse(process.argv);
}
if (require.main === module) {
main();
}
module.exports = createBot;
|
Use path.resolve to resolve path
|
Use path.resolve to resolve path
|
JavaScript
|
mit
|
elvinyung/botstrap,lvn/botstrap
|
89aa3813432083bc4bc192a27167f7a48d3a482f
|
index.js
|
index.js
|
module.exports = reviewersEditionCompare
var ordinal = require('number-to-words').toWordsOrdinal
var parse = require('reviewers-edition-parse')
var numbers = require('reviewers-edition-parse/numbers')
function reviewersEditionCompare (edition) {
var parsed = parse(edition)
if (parsed) {
return (
(parsed.draft ? (ordinal(parsed.draft) + ' draft of ') : '') +
numbers
.filter(function (number) {
return number !== 'draft'
})
.reduce(function (components, number) {
return parsed.hasOwnProperty(number)
? components.concat(ordinal(parsed[number]) + ' ' + number)
: components
}, [])
.join(', ')
)
} else {
return false
}
}
|
var ordinal = require('number-to-words').toWordsOrdinal
var parse = require('reviewers-edition-parse')
var numbers = require('reviewers-edition-parse/numbers')
module.exports = function reviewersEditionCompare (edition) {
var parsed = parse(edition)
if (parsed) {
return (
(parsed.draft ? (ordinal(parsed.draft) + ' draft of ') : '') +
numbers
.filter(function (number) {
return number !== 'draft'
})
.reduce(function (components, number) {
return parsed.hasOwnProperty(number)
? components.concat(ordinal(parsed[number]) + ' ' + number)
: components
}, [])
.join(', ')
)
} else {
return false
}
}
|
Put module.exports and function on same line
|
Put module.exports and function on same line
|
JavaScript
|
mit
|
kemitchell/reviewers-edition-spell.js
|
9310026c8cbc4af5f4326a27cfc27121e5636323
|
index.js
|
index.js
|
var es = require('event-stream'),
clone = require('clone'),
path = require('path');
module.exports = function(opt){
// clone options
opt = opt ? clone(opt) : {};
if (!opt.splitter && opt.splitter !== "") opt.splitter = '\r\n';
if (!opt.fileName) throw new Error("Missing fileName option for gulp-concat");
var buffer = [];
function bufferContents(file){
// clone the file so we arent mutating stuff
buffer.push(clone(file));
}
function endStream(){
if (buffer.length === 0) return this.emit('end');
var joinedContents = buffer.map(function(file){
return file.contents;
}).join(opt.splitter);
var joinedPath = path.join(path.dirname(buffer[0].path), opt.fileName);
var joinedFile = {
shortened: opt.fileName,
path: joinedPath,
contents: joinedContents
};
this.emit('data', joinedFile);
this.emit('end');
}
return es.through(bufferContents, endStream);
};
|
var es = require('event-stream'),
clone = require('clone'),
path = require('path');
module.exports = function(opt){
// clone options
opt = opt ? clone(opt) : {};
if (typeof opt.splitter === 'undefined') opt.splitter = '\r\n';
if (!opt.fileName) throw new Error("Missing fileName option for gulp-concat");
var buffer = [];
function bufferContents(file){
// clone the file so we arent mutating stuff
buffer.push(clone(file));
}
function endStream(){
if (buffer.length === 0) return this.emit('end');
var joinedContents = buffer.map(function(file){
return file.contents;
}).join(opt.splitter);
var joinedPath = path.join(path.dirname(buffer[0].path), opt.fileName);
var joinedFile = {
shortened: opt.fileName,
path: joinedPath,
contents: joinedContents
};
this.emit('data', joinedFile);
this.emit('end');
}
return es.through(bufferContents, endStream);
};
|
Adjust opt.splitter to compare against undefined for the default value.
|
Adjust opt.splitter to compare against undefined for the default value.
|
JavaScript
|
mit
|
wearefractal/gulp-concat,queckezz/gulp-concat,KenanY/gulp-concat,BinaryMuse/gulp-concat,contra/gulp-concat,colynb/gulp-concat,stevelacy/gulp-concat,callumacrae/gulp-concat,abdurrachman-habibi/gulp-concat
|
4021d99786f51646633cf9d15fead8c3a58bef7c
|
index.js
|
index.js
|
var rimraf = require('rimraf')
var path = require('path');
var join = path.join;
function Plugin(paths) {
// determine webpack root
this.context = path.dirname(module.parent.filename);
// allows for a single string entry
if (typeof paths == 'string' || paths instanceof String){
paths = [paths];
}
// store paths
this.paths = paths;
}
Plugin.prototype.apply = function(compiler) {
var self = this;
// preform an rm -rf on each path
self.paths.forEach(function(path){
var path = join(self.context, path);
rimraf.sync(path);
});
}
module.exports = Plugin;
|
var rimraf = require('rimraf')
var path = require('path');
var join = path.join;
function Plugin(paths, context) {
// determine webpack root
this.context = context || path.dirname(module.parent.filename);
// allows for a single string entry
if (typeof paths == 'string' || paths instanceof String){
paths = [paths];
}
// store paths
this.paths = paths;
}
Plugin.prototype.apply = function(compiler) {
var self = this;
// preform an rm -rf on each path
self.paths.forEach(function(path){
var path = join(self.context, path);
rimraf.sync(path);
});
}
module.exports = Plugin;
|
Add opportunity pass webpack root (context)
|
Add opportunity pass webpack root (context)
|
JavaScript
|
mit
|
chrisblossom/clean-webpack-plugin,mhuggins/clean-webpack-plugin,johnagan/clean-webpack-plugin,chrisblossom/clean-webpack-plugin,johnagan/clean-webpack-plugin
|
f4d7e0d0917f7af388c75b4b4816591c4f7410b5
|
src/utils/config.js
|
src/utils/config.js
|
import _ from 'lodash'
import defaultConfig from '../config/defaults'
let globalConfig = _.assign({}, _.cloneDeep(defaultConfig))
export default class Config {
static load(cfg) {
globalConfig = _.cloneDeep(cfg)
}
static get(item, defaultValue) {
if(item === '*') {
return _.cloneDeep(globalConfig)
}
return _.get(globalConfig, item, defaultValue)
}
static set(path, item) {
_.set(globalConfig, path, item)
}
}
|
import _ from 'lodash'
import defaultConfig from '../config/defaults'
let globalConfig = _.assign({}, _.cloneDeep(defaultConfig))
export default class Config {
static load(cfg) {
globalConfig = _.merge(globalConfig, _.cloneDeep(cfg))
}
static overwrite(cfg) {
globalConfig = _.cloneDeep(cfg)
}
static get(item, defaultValue) {
if(item === '*') {
return _.cloneDeep(globalConfig)
}
return _.get(globalConfig, item, defaultValue)
}
static set(path, item) {
_.set(globalConfig, path, item)
}
}
|
Add loading/merging methods to Config utility
|
Add loading/merging methods to Config utility
|
JavaScript
|
mit
|
thinktopography/reframe,thinktopography/reframe
|
628a1e56241fd82104d69ac7e8e4b751ff85e34b
|
index.js
|
index.js
|
var addElevation = require('geojson-elevation').addElevation,
TileSet = require('node-hgt').TileSet,
express = require('express'),
bodyParser = require('body-parser'),
app = express(),
tiles = new TileSet('./data');
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.contentType('application/json');
next();
});
app.post('/geojson', function(req, res) {
var geojson = req.body;
if (!geojson || Object.keys(geojson).length === 0) {
res.status(400).send('Error: invalid geojson.');
return;
}
addElevation(geojson, tiles, function(err) {
if (err) {
res.status(500).send(err);
} else {
res.send(JSON.stringify(geojson));
}
});
});
var server = app.listen(5001, function() {
var host = server.address().address;
var port = server.address().port;
console.log('elevation-server listening at http://%s:%s', host, port);
});
|
var addElevation = require('geojson-elevation').addElevation,
TileSet = require('node-hgt').TileSet,
ImagicoElevationDownloader = require('node-hgt').ImagicoElevationDownloader,
express = require('express'),
bodyParser = require('body-parser'),
app = express(),
tiles,
tileDownloader,
tileDirectory = process.env.TILE_DIRECTORY;
if(!tileDirectory) {
tileDirectory = "./data";
}
if(process.env.TILE_DOWNLOADER) {
if(process.env.TILE_DOWNLOADER == "imagico") {
tileDownloader = new ImagicoElevationDownloader();
}
}
tiles = new TileSet(tileDirectory, {downloader:tileDownloader});
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.contentType('application/json');
next();
});
app.post('/geojson', function(req, res) {
var geojson = req.body;
if (!geojson || Object.keys(geojson).length === 0) {
res.status(400).send('Error: invalid geojson.');
return;
}
addElevation(geojson, tiles, function(err) {
if (err) {
res.status(500).send(err);
} else {
res.send(JSON.stringify(geojson));
}
});
});
var server = app.listen(5001, function() {
var host = server.address().address;
var port = server.address().port;
console.log('elevation-server listening at http://%s:%s', host, port);
});
|
Read environment variables for data directory and tile downloader
|
Read environment variables for data directory and tile downloader
|
JavaScript
|
isc
|
perliedman/elevation-service,JesseCrocker/elevation-service
|
43204c269a394d1805d9ddc208ea6a524729c7cf
|
index.js
|
index.js
|
/*!
* tweensy - Copyright (c) 2017 Jacob Buck
* https://github.com/jacobbuck/tweensy
* Licensed under the terms of the MIT license.
*/
'use strict';
var assign = require('lodash/assign');
var now = require('performance-now');
var rafq = require('rafq')();
var defaultOptions = {
duration: 0,
easing: function linear(t) { return t; },
from: 0,
loop: 1,
onComplete: function() {},
onProgress: function() {},
to: 1
};
module.exports = function tween(instanceOptions) {
var options = assign({}, defaultOptions, instanceOptions);
var isFinished = false;
var iteration = 1;
var startTime = null;
function tick() {
var time = now();
if (!startTime) {
startTime = time;
}
var progress = isFinished ?
1 :
(time - (startTime * iteration)) / options.duration;
options.onProgress(
options.easing(progress) *
(options.to - options.from) +
options.from
);
if (progress === 1) {
if (iteration < options.loop) {
iteration += 1;
} else {
isFinished = true;
}
}
if (isFinished) {
options.onComplete();
} else {
rafq.add(tick);
}
}
function stop(finish) {
isFinished = true;
if (!finish) {
rafq.remove(tick);
}
}
tick();
return stop;
};
|
/*!
* tweensy - Copyright (c) 2017 Jacob Buck
* https://github.com/jacobbuck/tweensy
* Licensed under the terms of the MIT license.
*/
'use strict';
var assign = require('lodash/assign');
var now = require('performance-now');
var rafq = require('rafq')();
var defaultOptions = {
duration: 0,
easing: function linear(t) { return t; },
from: 0,
onComplete: function() {},
onProgress: function() {},
to: 1
};
module.exports = function tween(instanceOptions) {
var options = assign({}, defaultOptions, instanceOptions);
var isFinished = false;
var fromToMultiplier = (options.to - options.from) + options.from;
var startTime = null;
function tick() {
var time = now();
if (!startTime) {
startTime = time;
}
var progress = isFinished ? 1 : (time - startTime) / options.duration;
options.onProgress(options.easing(progress) * fromToMultiplier);
if (progress === 1) {
isFinished = true;
}
if (isFinished) {
options.onComplete(time);
} else {
rafq.add(tick);
}
}
function stop(finish) {
isFinished = true;
if (!finish) {
rafq.remove(tick);
}
}
tick();
return stop;
};
|
Remove loop to keep scope small. Simplify some code, and pre calculate some things for perf
|
Remove loop to keep scope small. Simplify some code, and pre calculate some things for perf
|
JavaScript
|
mit
|
jacobbuck/tweensy,jacobbuck/tweenie
|
7c953aa414ea16fd831a11b3be4d74f5c52b5653
|
src/database/utilities/constants.js
|
src/database/utilities/constants.js
|
/* eslint-disable import/prefer-default-export */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
const HOURS_PER_DAY = 24;
const MINUTES_PER_HOUR = 60;
const SECONDS_PER_MINUTE = 60;
const MILLISECONDS_PER_SECOND = 1000;
export const MILLISECONDS_PER_MINUTE = MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE;
export const MILLISECONDS_PER_HOUR = MILLISECONDS_PER_MINUTE * MINUTES_PER_HOUR;
export const MILLISECONDS_PER_DAY = MILLISECONDS_PER_HOUR * HOURS_PER_DAY;
export const NUMBER_SEQUENCE_KEYS = {
CUSTOMER_INVOICE_NUMBER: 'customer_invoice_serial_number',
INVENTORY_ADJUSTMENT_SERIAL_NUMBER: 'inventory_adjustment_serial_number',
REQUISITION_SERIAL_NUMBER: 'requisition_serial_number',
REQUISITION_REQUESTER_REFERENCE: 'requisition_requester_reference',
STOCKTAKE_SERIAL_NUMBER: 'stocktake_serial_number',
SUPPLIER_INVOICE_NUMBER: 'supplier_invoice_serial_number',
};
|
/* eslint-disable import/prefer-default-export */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
const HOURS_PER_DAY = 24;
const MINUTES_PER_HOUR = 60;
const SECONDS_PER_MINUTE = 60;
const MILLISECONDS_PER_SECOND = 1000;
export const MILLISECONDS_PER_MINUTE = MILLISECONDS_PER_SECOND * SECONDS_PER_MINUTE;
export const MILLISECONDS_PER_HOUR = MILLISECONDS_PER_MINUTE * MINUTES_PER_HOUR;
export const MILLISECONDS_PER_DAY = MILLISECONDS_PER_HOUR * HOURS_PER_DAY;
export const NUMBER_SEQUENCE_KEYS = {
CUSTOMER_INVOICE_NUMBER: 'customer_invoice_serial_number',
INVENTORY_ADJUSTMENT_SERIAL_NUMBER: 'inventory_adjustment_serial_number',
REQUISITION_SERIAL_NUMBER: 'requisition_serial_number',
REQUISITION_REQUESTER_REFERENCE: 'requisition_requester_reference',
STOCKTAKE_SERIAL_NUMBER: 'stocktake_serial_number',
SUPPLIER_INVOICE_NUMBER: 'supplier_invoice_serial_number',
PATIENT_CODE: 'patient_code',
};
|
Add patient code number sequence
|
Add patient code number sequence
|
JavaScript
|
mit
|
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
|
a4acc1c3dbd3d77104f39c957051f2f38884224c
|
server/app.js
|
server/app.js
|
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var router = express.Router();
var Sequelize = require('sequelize');
var sequelize = new Sequelize(process.env.DATABASE_URL);
var matchmaker = require('./controllers/Matchmaker');
var playController = require('./controllers/Play');
var turnController = require('./controllers/Turn');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
router.route('/play')
.post(matchmaker.startGame);
router.route('/fire')
.post(playController.fire);
router.route('/cancel/:username')
.post(matchmaker.cancel);
router.route('/turn/:username')
.get(turnController.nextPlayer);
app.use('/api', router);
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
|
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var router = express.Router();
var Sequelize = require('sequelize');
var sequelize = new Sequelize(process.env.DATABASE_URL);
var matchmaker = require('./controllers/Matchmaker');
var playController = require('./controllers/Play');
var turnController = require('./controllers/Turn');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
router.route('/play')
.post(matchmaker.startGame);
router.route('/fire')
.post(playController.fire);
router.route('/cancel')
.post(matchmaker.cancel);
router.route('/turn/:username')
.get(turnController.nextPlayer);
app.use('/api', router);
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
|
Edit server route url to match client request
|
Edit server route url to match client request
|
JavaScript
|
mit
|
andereld/progark,andereld/progark
|
7af80538c9232f5bf0d929d4164076a44cb2b704
|
render-mustache.js
|
render-mustache.js
|
/**
* render-mustache
*
* This module implements support for rendering [Mustache](http://mustache.github.com/)
* templates using [mustache.js](https://github.com/janl/mustache.js).
*/
define(['mustache'],
function(Mustache) {
/**
* Setup Mustache template engine.
*
* When rendering, this engine returns a compiled template function which can
* be cached for performance optimization.
*
* Examples:
*
* render.engine('text/template', mustache());
*
* @return {Function}
* @api public
*/
return function() {
return function(str) {
return Mustache.compile(str);
}
}
});
|
/**
* render-mustache
*
* This module implements support for rendering [Mustache](http://mustache.github.com/)
* templates using [mustache.js](https://github.com/janl/mustache.js).
*/
define(['mustache'],
function(Mustache) {
/**
* Setup Mustache template engine.
*
* When rendering, this engine returns a compiled template function which can
* be cached for performance optimization.
*
* Examples:
*
* render.engine('text/x-mustache-template', mustache());
*
* A Note on MIME Types:
*
* It has become common convention to include templates within HTML by
* enclosing them within script tags:
*
* <script type=“text/template”>...</script>
*
* Recommended practice for Sail.js applications is to be more specific when
* indicating the MIME type, both as a way to communicate explicitly with
* other developers and as a means to use multiple template engines within an
* application.
*
* While no standard exists, the following list of MIME types are used to
* indicate Mustache templates in practice:
*
* * text/x-mustache-template
* [Announcing Handlebars.js](http://yehudakatz.com/2010/09/09/announcing-handlebars-js/)
*
* @return {Function}
* @api public
*/
return function() {
return function(str) {
return Mustache.compile(str);
}
}
});
|
Add documentation regarding MIME types.
|
Add documentation regarding MIME types.
|
JavaScript
|
mit
|
sailjs/render-mustache
|
91e5e219929c894cb48391261cc38780c728b0d9
|
src/cmd/main/music/handlers/YouTubeHandler.js
|
src/cmd/main/music/handlers/YouTubeHandler.js
|
/**
* @file Music handler for YouTube videos. Does not support livestreams.
* @author Ovyerus
*/
const ytdl = require('ytdl-core');
const got = require('got');
const ITAG = '251'; // Preferred iTag quality to get. Default: 251.
class YouTubeHandler {
constructor() {}
async getInfo(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
let res = {
url,
title: info.title,
uploader: info.author.name,
thumbnail: info.thumbnail_url.replace('default.jpg', 'hqdefault.jpg'),
length: Number(info.length_seconds),
type: 'YouTubeVideo'
};
return res;
}
async getStream(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
return got.stream(info.formats.find(f => f.itag === ITAG).url);
}
}
module.exports = YouTubeHandler;
|
/**
* @file Music handler for YouTube videos. Does not support livestreams.
* @author Ovyerus
*/
const ytdl = require('ytdl-core');
const got = require('got');
// List of all itag qualities can be found here: https://en.wikipedia.org/w/index.php?title=YouTube&oldid=800910021#Quality_and_formats.
const ITAG = '140'; // Preferred itag quality to get. Default: 140.
const ITAG_FALLBACK = '22'; // In the event that the previous itag could not be found, try finding this one. Should probably be a lower value.
class YouTubeHandler {
constructor() {}
async getInfo(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
let res = {
url,
title: info.title,
uploader: info.author.name,
thumbnail: info.thumbnail_url.replace('default.jpg', 'hqdefault.jpg'),
length: Number(info.length_seconds),
type: 'YouTubeVideo'
};
return res;
}
async getStream(url) {
if (typeof url !== 'string') throw new TypeError('url is not a string.');
let info = await ytdl.getInfo(url);
let format = info.formats.find(f => f.itag === ITAG) || info.formats.find(f => f.itag === ITAG_FALLBACK);
format = format ? format.url : info.url; // Fallback to default URL if the wanted itags could not be found;
return got.stream(format);
}
}
module.exports = YouTubeHandler;
|
Change requested itag for YouTube music to a M4A+AAC stream, instead of a WebM+Opus stream in an attempt to fix issues
|
Change requested itag for YouTube music to a M4A+AAC stream, instead of a WebM+Opus stream in an attempt to fix issues
|
JavaScript
|
unknown
|
awau/owo-whats-this,sr229/owo-whats-this,ClarityMoe/Clara,awau/Clara,owo-dev-team/owo-whats-this
|
3f96581aa2df3892d673a3ef175bf8e76f321075
|
renderer/middleware/index.js
|
renderer/middleware/index.js
|
// @flow
import type {Store, Dispatch, Action} from 'redux';
export const save = (store: Store) => (next: Dispatch) => (action: Action) => {
setImmediate(() => {
localStorage.setItem('store', JSON.stringify(store.getState()));
});
next(action);
};
|
// @flow
import type {Store, Dispatch, Action} from 'redux';
export const save = (store: Store) => (next: Dispatch) => (action: Action) => {
if (action.id) {
setImmediate(() => {
localStorage.setItem('store', JSON.stringify(store.getState()));
});
}
next(action);
};
|
Update store at Only import change
|
Update store at Only import change
|
JavaScript
|
mit
|
akameco/PixivDeck,akameco/PixivDeck
|
6288e418a248e997f1e6830d8bfa4e09d33a3717
|
src/modules/getPrice/index.js
|
src/modules/getPrice/index.js
|
import module from '../../module'
import command from '../../components/command'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const esiURL = 'https://esi.tech.ccp.is/latest/';
const {data: itemData} = await axios.get(
`${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const {data: priceData} = await axios.get(
`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`
);
const sellFivePercent = humanize(priceData[0].sell.fivePercent);
const buyFivePercent = humanize(priceData[0].buy.fivePercent);
message.channel.sendMessage(
`__Price of **${args}** (or nearest match) in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
)
|
import module from '../../module'
import command from '../../components/command'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const esiURL = 'https://esi.tech.ccp.is/latest/';
const {data: itemData} = await axios.get(
`${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const [{data: [priceData]}, {data: {name: itemName}}] = await Promise.all([
axios.get(`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`),
axios.get(`${esiURL}universe/types/${itemid}/?datasource=tranquility&language=en-us`)
]);
const sellFivePercent = humanize(priceData.sell.fivePercent);
const buyFivePercent = humanize(priceData.buy.fivePercent);
message.channel.sendMessage(
`__Price of **${itemName}** in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
)
|
Modify getPrice to report name of item actually queried
|
Modify getPrice to report name of item actually queried
|
JavaScript
|
mit
|
emensch/thonk9k
|
56e76553bb5a4f6e44a4739fb4f9eb46dfbfa463
|
src/plugins/FileVersioningPlugin.js
|
src/plugins/FileVersioningPlugin.js
|
let chokidar = require('chokidar');
let glob = require('glob');
/**
* Create a new plugin instance.
*
* @param {Array} files
*/
function FileVersioningPlugin(files = []) {
this.files = files;
}
/**
* Apply the plugin.
*/
FileVersioningPlugin.prototype.apply = function () {
if (this.files && Mix.isWatching()) {
this.watch(this.files);
}
Mix.listen('files-concatenated', file => {
file = new File(file);
// Find and delete all matching versioned files in the directory.
glob(path.join(file.base(), '**'), (err, files) => {
files.filter(file => {
return /\.(\w{20}|\w{32})(\..+)/.test(file);
}).forEach(file => new File(file).delete());
});
// Then create a fresh versioned file.
this.reversion(file.path());
});
};
/**
* Watch all relevant files for changes.
*
* @param {Object} files
* @param {Object} destination
*/
FileVersioningPlugin.prototype.watch = function (files, destination) {
chokidar.watch(files, { persistent: true })
.on('change', this.reversion);
};
/**
* Re-version the updated file.
*
* @param {string} updatedFile
*/
FileVersioningPlugin.prototype.reversion = function (updatedFile) {
let name = new File(updatedFile).version(false).pathFromPublic();
try { File.find(Mix.manifest.get(updatedFile)).delete(); }
catch (e) {}
Mix.manifest.add(name).refresh();
};
module.exports = FileVersioningPlugin;
|
let chokidar = require('chokidar');
let glob = require('glob');
/**
* Create a new plugin instance.
*
* @param {Array} files
*/
function FileVersioningPlugin(files = []) {
this.files = files;
}
/**
* Apply the plugin.
*/
FileVersioningPlugin.prototype.apply = function () {
if (this.files && Mix.isWatching()) {
this.watch(this.files);
}
Mix.listen('files-concatenated', this.reversion);
};
/**
* Watch all relevant files for changes.
*
* @param {Object} files
* @param {Object} destination
*/
FileVersioningPlugin.prototype.watch = function (files, destination) {
chokidar.watch(files, { persistent: true })
.on('change', this.reversion);
};
/**
* Re-version the updated file.
*
* @param {string} updatedFile
*/
FileVersioningPlugin.prototype.reversion = function (updatedFile) {
updatedFile = new File(updatedFile);
try { File.find(Mix.manifest.get(updatedFile.pathFromPublic())).delete(); }
catch (e) {}
let name = updatedFile.version(false).pathFromPublic();
Mix.manifest.add(name).refresh();
};
module.exports = FileVersioningPlugin;
|
Clean up file versioning handler
|
Clean up file versioning handler
|
JavaScript
|
mit
|
JeffreyWay/laravel-mix
|
6e95c2af465fc296984e86b73192eca1c32c8f9d
|
lib/rules/load-average.js
|
lib/rules/load-average.js
|
var util = require('util');
var Duplex = require('stream').Duplex;
var LoadAverage = module.exports = function LoadAverage(options) {
this.warn = options.warn;
this.critical = options.critical;
Duplex.call(this, { objectMode: true });
};
util.inherits(LoadAverage, Duplex);
LoadAverage.prototype._write = function(chunk, _, cb) {
var split = chunk.name.split('.');
if (split[0] !== 'load-average') return cb();
var period = parseInt(split[1], 10);
if (!this.warn[period] || !this.critical[period]) return cb();
var nprocs = chunk.meta.nprocs;
var value = chunk.value.toFixed(2) + '/' + nprocs + ' CPUs';
var message = period + ' minute load average (' + value + ') on host ' + chunk.host;
if (chunk.value > this.critical[period] * nprocs)
{
this.push(
{
name: 'load-average',
host: chunk.host,
message: message,
status: 'critical',
value: value
});
}
else if (chunk.value > this.warn[period] * nprocs)
{
this.push(
{
name: 'load-average',
host: chunk.host,
message: message,
status: 'warning',
value: value
});
}
cb();
};
LoadAverage.prototype._read = function(){};
|
var util = require('util');
var Duplex = require('stream').Duplex;
var LoadAverage = module.exports = function LoadAverage(options) {
this.warn = options.warn;
this.critical = options.critical;
Duplex.call(this, { objectMode: true });
};
util.inherits(LoadAverage, Duplex);
LoadAverage.prototype._write = function(chunk, _, cb) {
var split = chunk.name.split('.');
if (split[0] !== 'load-average') return cb();
var period = parseInt(split[1], 10);
if (!this.warn[period] || !this.critical[period]) return cb();
var nprocs = chunk.meta.nprocs;
var value = chunk.value.toFixed(2) + '/' + nprocs + ' CPUs';
var message = period + ' minute load average (' + value + ') on host ' + chunk.host;
if (chunk.value > this.critical[period] * nprocs)
{
this.push(
{
name: chunk.name,
host: chunk.host,
message: message,
status: 'critical',
value: value
});
}
else if (chunk.value > this.warn[period] * nprocs)
{
this.push(
{
name: chunk.name,
host: chunk.host,
message: message,
status: 'warning',
value: value
});
}
cb();
};
LoadAverage.prototype._read = function(){};
|
Use event name for incident name
|
Use event name for incident name
|
JavaScript
|
isc
|
numbat-metrics/numbat-analyzer,ceejbot/numbat-analyzer
|
dc9a45d38a5857472b7d9a72f7c2363276cc4efc
|
tdd/server/palindrome/test/palindrome-test.js
|
tdd/server/palindrome/test/palindrome-test.js
|
var expect = require('chai').expect;
var isPalindrome = require('../src/palindrome');
describe('palindrome-test', function() {
it('should pass the canary test', function() {
expect(true).to.be.true;
});
it('should return true when passed "mom"', function() {
expect(isPalindrome('mom')).to.be.true;
});
});
|
/*
* Test ideas
*
* 'dad' is a palindrome
* 'dude' is not a palindrome
* 'mom mom' is a palindrome
* 'dad dae' is a palindrome'
*/
var expect = require('chai').expect;
var isPalindrome = require('../src/palindrome');
describe('palindrome-test', function() {
it('should pass the canary test', function() {
expect(true).to.be.true;
});
it('should return true when passed "mom"', function() {
expect(isPalindrome('mom')).to.be.true;
});
it('should return true when passed "dad"', function() {
expect(isPalindrome('dad')).to.be.true;
});
});
|
Add test: 'dad' is a palindrome
|
Add test: 'dad' is a palindrome
|
JavaScript
|
apache-2.0
|
mrwizard82d1/tdjsa
|
aa9717b62f1a0c0e41f06e9f54393d8cd55769f9
|
templates/demo/config/namesystem.js
|
templates/demo/config/namesystem.js
|
module.exports = {
default: {
available_providers: ["ens", "ipns"],
provider: "ens",
register: {
rootDomain: "embark.eth",
subdomains: {
'status': '0x1a2f3b98e434c02363f3dac3174af93c1d690914'
}
}
}
};
|
module.exports = {
default: {
available_providers: ["ens", "ipns"],
provider: "ens"
},
development: {
register: {
rootDomain: "embark.eth",
subdomains: {
'status': '0x1a2f3b98e434c02363f3dac3174af93c1d690914'
}
}
}
};
|
Move name config to development
|
[CHORES] Move name config to development
|
JavaScript
|
mit
|
iurimatias/embark-framework,iurimatias/embark-framework
|
2d14e852c9c833eeec7b63a76102ce4dc29bd2cb
|
angular/app-foundation.module.js
|
angular/app-foundation.module.js
|
/**
* Created by anonymous on 13/12/15 11:09.
*/
(function() {
'use strict';
angular
.module('appFoundation', [
/* Angularjs */
'ngMaterial',
'ngMessages',
'ngResource',
/* 3rd-party */
'ui.router',
'satellizer',
'restangular',
'ngStorage',
'angular-loading-bar',
'ngMdIcons',
'toastr',
'vAccordion',
'md.data.table',
/* Intra-services */
'inServices.exception',
'inServices.logger',
'inServices.routes'
]);
angular.module('widgets', []);
angular.module('inServices.exception', []);
angular.module('inServices.logger', []);
angular.module('inServices.routes', []);
})();
|
/**
* Created by anonymous on 13/12/15 11:09.
*/
(function() {
'use strict';
angular
.module('appFoundation', [
/* Angularjs */
'ngMaterial',
'ngMessages',
'ngResource',
/* 3rd-party */
'ui.router',
'satellizer',
'restangular',
'ngStorage',
'angular-loading-bar',
'ngMdIcons',
'toastr',
'vAccordion',
/* Intra-services */
'inServices.exception',
'inServices.logger',
'inServices.routes'
]);
angular.module('widgets', []);
angular.module('inServices.exception', []);
angular.module('inServices.logger', []);
angular.module('inServices.routes', []);
})();
|
Update bower @ Uninstall angular-material-data-table
|
Update bower @ Uninstall angular-material-data-table
|
JavaScript
|
mit
|
onderdelen/app-foundation,componeint/app-foundation,onderdelen/app-foundation,onderdelen/app-foundation,componeint/app-foundation,componeint/app-foundation,consigliere/app-foundation,consigliere/app-foundation,consigliere/app-foundation
|
0492af81a8140b89347ea721f46fcc71088466d8
|
test/lib/api-util/api-util-test.js
|
test/lib/api-util/api-util-test.js
|
'use strict';
const preq = require('preq');
const assert = require('../../utils/assert');
const mwapi = require('../../../lib/mwapi');
const logger = require('bunyan').createLogger({
name: 'test-logger',
level: 'warn'
});
logger.log = function(a, b) {};
describe('lib:apiUtil', function() {
this.timeout(20000); // eslint-disable-line no-invalid-this
it('checkForQueryPagesInResponse should return 504 when query.pages are absent', () => {
return preq.post({
uri: 'https://commons.wikimedia.org/w/api.php',
body: {
action: 'query',
format: 'json',
formatversion: 2,
generator: 'images',
prop: 'imageinfo|revisions',
iiextmetadatafilter: 'ImageDescription',
iiextmetadatamultilang: true,
iiprop: 'url|extmetadata|dimensions',
iiurlwidth: 1024,
rawcontinue: '',
titles: `Template:Potd/1980-07-06`
}
}).then((response) => {
assert.throws(() => {
mwapi.checkForQueryPagesInResponse({ logger }, response);
}, /api_error/);
});
});
});
|
'use strict';
const assert = require('../../utils/assert');
const mwapi = require('../../../lib/mwapi');
const logger = require('bunyan').createLogger({
name: 'test-logger',
level: 'warn'
});
logger.log = function(a, b) {};
describe('lib:apiUtil', () => {
it('checkForQueryPagesInResponse should return 504 when query.pages are absent', () => {
return new Promise((resolve) => {
return resolve({});
}).then((response) => {
assert.throws(() => {
mwapi.checkForQueryPagesInResponse({ logger }, response);
}, /api_error/);
});
});
});
|
Remove unnecessary API call in unit test
|
Remove unnecessary API call in unit test
We do not need to hit the API in this test. It's unnecessary and makes
the test harder to comprehend.
Instead of testing this way, simulate a promise that resolves without
pages.
(npm run test:unit should work without an internet connection)
Change-Id: Iee834114890a64c96ccf255601503a25efd884bc
|
JavaScript
|
apache-2.0
|
wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps,wikimedia/mediawiki-services-mobileapps
|
9eaa53c31ddb5170a9cd3d81e4fc4846a370b6ba
|
addon/change-gate.js
|
addon/change-gate.js
|
import Em from 'ember';
var get = Em.get;
var defaultFilter = function(value) { return value; };
export default function(dependentKey, filter) {
filter = filter || defaultFilter;
var computed = Em.computed(function handler(key) {
var meta = computed.meta();
meta.hasObserver = false;
meta.lastValue = null;
var isFirstRun = !meta.hasObserver;
if(isFirstRun) { //setup an observer which is responsible for notifying property changes
var value = filter(get(this, dependentKey));
meta.hasObserver = true;
meta.lastValue = value;
this.addObserver(dependentKey, function() {
var newValue = filter(get(this, dependentKey));
var lastValue = meta.lastValue;
if(newValue !== lastValue) {
meta.lastValue = value;
this.notifyPropertyChange(key);
}
});
return value;
} else {
return meta.lastValue;
}
});
return computed;
}
|
import Em from 'ember';
var get = Em.get,
getMeta = Em.getMeta,
setMeta = Em.setMeta;
var defaultFilter = function(value) { return value; };
export default function(dependentKey, filter) {
filter = filter || defaultFilter;
return Em.computed(function(key) {
var hasObserverKey = '_changeGate:%@:hasObserver'.fmt(key);
var lastValueKey = '_changeGate:%@:lastValue'.fmt(key);
var isFirstRun = !getMeta(this, hasObserverKey);
if(isFirstRun) { //setup an observer which is responsible for notifying property changes
var value = filter(get(this, dependentKey));
setMeta(this, hasObserverKey, true);
setMeta(this, lastValueKey, value);
this.addObserver(dependentKey, function() {
var newValue = filter(get(this, dependentKey));
var lastValue = getMeta(this, lastValueKey);
if(newValue !== lastValue) {
setMeta(this, lastValueKey, newValue);
this.notifyPropertyChange(key);
}
});
return value;
} else {
return getMeta(this, lastValueKey);
}
});
}
|
Revert "Refactored macro to use ComputedProperty meta instead of object's meta"
|
Revert "Refactored macro to use ComputedProperty meta instead of object's meta"
|
JavaScript
|
mit
|
givanse/ember-computed-change-gate,GavinJoyce/ember-computed-change-gate,givanse/ember-computed-change-gate,GavinJoyce/ember-computed-change-gate
|
daf08f7840abf24d076c604fb58ca0771c79a25c
|
snippets/device.js
|
snippets/device.js
|
const {TextView, device, ui} = require('tabris');
// Display available device information
['platform', 'version', 'model', 'language', 'orientation'].forEach((property) => {
new TextView({
id: property,
left: 10, right: 10, top: 'prev() 10',
text: property + ': ' + device[property]
}).appendTo(ui.contentView);
});
device.on('orientationChanged', ({value: orientation}) => {
ui.contentView.find('#orientation').set('text', 'orientation: ' + orientation);
});
|
const {TextView, device, ui} = require('tabris');
// Display available device information
['platform', 'version', 'model', 'vendor', 'language', 'orientation'].forEach((property) => {
new TextView({
id: property,
left: 10, right: 10, top: 'prev() 10',
text: property + ': ' + device[property]
}).appendTo(ui.contentView);
});
device.on('orientationChanged', ({value: orientation}) => {
ui.contentView.find('#orientation').set('text', 'orientation: ' + orientation);
});
|
Add "vendor" to list of printed properties
|
Add "vendor" to list of printed properties
|
JavaScript
|
bsd-3-clause
|
eclipsesource/tabris-js,eclipsesource/tabris-js,eclipsesource/tabris-js
|
9ad30d7fb666403f0a74e5905ef928be13547a7b
|
gulpfile.js
|
gulpfile.js
|
'use strict';
const path = require('path');
const gulp = require('gulp');
const eslint = require('gulp-eslint');
const spawn = require('cross-spawn');
const excludeGitignore = require('gulp-exclude-gitignore');
const nsp = require('gulp-nsp');
gulp.task('nsp', nodeSecurityProtocol);
gulp.task('watch', watch);
gulp.task('static', eslintCheck);
gulp.task('test', gulp.series([avaTest, nycReport]));
gulp.task('prepublish', gulp.series('nsp'));
gulp.task('default', gulp.series('static', 'test'));
function nodeSecurityProtocol(cb) {
nsp({package: path.resolve('package.json')}, cb);
}
function eslintCheck() {
return gulp.src(['**/*.js', '!**/templates/**'])
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
}
function avaTest() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava'], {stdio: 'inherit'});
}
function nycReport() {
return spawn('./node_modules/.bin/nyc', ['report', '--colors'], {stdio: 'inherit'});
}
function watch() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava', '--watch'], {stdio: 'inherit'});
}
|
'use strict';
const path = require('path');
const gulp = require('gulp');
const eslint = require('gulp-eslint');
const spawn = require('cross-spawn');
const excludeGitignore = require('gulp-exclude-gitignore');
const nsp = require('gulp-nsp');
gulp.task('nsp', nodeSecurityProtocol);
gulp.task('watch', watch);
gulp.task('static', eslintCheck);
gulp.task('test', gulp.series([avaTest, nycReport]));
gulp.task('prepublish', gulp.series('nsp'));
gulp.task('default', gulp.series('static', 'test'));
function nodeSecurityProtocol(cb) {
nsp({package: path.resolve('package.json')}, cb);
}
function eslintCheck() {
return gulp.src(['**/*.js', '!**/templates/**', '!test/assets/**'])
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
}
function avaTest() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava'], {stdio: 'inherit'});
}
function nycReport() {
return spawn('./node_modules/.bin/nyc', ['report', '--colors'], {stdio: 'inherit'});
}
function watch() {
return spawn('./node_modules/.bin/nyc', ['--all', '--reporter=lcov', './node_modules/.bin/ava', '--watch'], {stdio: 'inherit'});
}
|
Disable lint for test assets
|
Disable lint for test assets
|
JavaScript
|
mit
|
FountainJS/generator-fountain-systemjs,FountainJS/generator-fountain-systemjs
|
c62191bfcb066f9f544f3df019db32da48dbbeee
|
test/examples/Counter-test.js
|
test/examples/Counter-test.js
|
/** @jsx createElement */
const {createElement, createEventHandler, render} = Yolk
function Counter () {
const handlePlus = createEventHandler(1, 0)
const handleMinus = createEventHandler(-1, 0)
const count = handlePlus.merge(handleMinus).scan((x, y) => x+y, 0)
return (
<div>
<button id="plus" onClick={handlePlus}>+</button>
<button id="minus" onClick={handleMinus}>-</button>
<span>{count}</span>
</div>
)
}
describe(`A simple counter`, () => {
it(`increments and decrements a number`, () => {
const component = <Counter />
const node = document.createElement(`div`)
render(component, node)
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>0</span></div>`)
const plus = node.querySelector(`#plus`)
const minus = node.querySelector(`#minus`)
plus.click()
plus.click()
plus.click()
minus.click()
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>2</span></div>`)
})
})
|
/** @jsx createElement */
const {createElement, createEventHandler, render} = Yolk
function Counter () {
const handlePlus = createEventHandler(1)
const handleMinus = createEventHandler(-1)
const count = handlePlus.merge(handleMinus).scan((x, y) => x+y, 0).startWith(0)
return (
<div>
<button id="plus" onClick={handlePlus}>+</button>
<button id="minus" onClick={handleMinus}>-</button>
<span>{count}</span>
</div>
)
}
describe(`A simple counter`, () => {
it(`increments and decrements a number`, () => {
const component = <Counter />
const node = document.createElement(`div`)
render(component, node)
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>0</span></div>`)
const plus = node.querySelector(`#plus`)
const minus = node.querySelector(`#minus`)
plus.click()
plus.click()
plus.click()
minus.click()
assert.equal(node.innerHTML, `<div><button id="plus">+</button><button id="minus">-</button><span>2</span></div>`)
})
})
|
Update Counter test to no relying on initial values for event handlers
|
Update Counter test to no relying on initial values for event handlers
|
JavaScript
|
mit
|
StateFarmIns/yolk,garbles/yolk,KenPowers/yolk,yolkjs/yolk,jadbox/yolk,brandonpayton/yolk,kamilogorek/yolk,BrewhouseTeam/yolk,knpwrs/yolk
|
1ed8856f1a4861213c73b857582a18e6c836a7ef
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src(docsSrcDir)
.pipe(
jsdoc(docsDestDir,
{
path: './node_modules/jaguarjs-jsdoc',
applicationName: 'Dough JavaScript',
cleverLinks: true,
copyright: 'Copyright Money Advice Service ©',
linenums: true,
collapseSymbols: false
},
{
plugins: ['plugins/markdown'],
}
)
);
};
gulp.task('default', ['jsdoc']);
gulp.task('jsdoc', jsDocTask);
gulp.task('watch', function() {
jsDocTask();
gulp.watch(docsSrcDir, ['jsdoc']);
});
|
var gulp = require('gulp'),
jsdoc = require('gulp-jsdoc'),
ghPages = require('gulp-gh-pages'),
docsSrcDir = './assets/js/**/*.js',
docsDestDir = './docs/js',
jsDocTask;
jsDocTask = function() {
return gulp.src(docsSrcDir)
.pipe(
jsdoc(docsDestDir,
{
path: './node_modules/jaguarjs-jsdoc',
applicationName: 'Dough JavaScript',
cleverLinks: true,
copyright: 'Copyright Money Advice Service ©',
linenums: true,
collapseSymbols: false
},
{
plugins: ['plugins/markdown'],
}
)
);
};
gulp.task('deploy', function() {
return gulp.src(docsDestDir + '/**/*')
.pipe(ghPages());
});
gulp.task('default', ['jsdoc']);
gulp.task('build', ['jsdoc', 'deploy']);
gulp.task('jsdoc', jsDocTask);
gulp.task('watch', function() {
jsDocTask();
gulp.watch(docsSrcDir, ['jsdoc']);
});
|
Add gulp task to deploy jsDocs
|
Add gulp task to deploy jsDocs
|
JavaScript
|
mit
|
moneyadviceservice/dough,moneyadviceservice/dough,moneyadviceservice/dough,moneyadviceservice/dough
|
af37455fed835172c2e533a60f2e65f3833058a9
|
gulpfile.js
|
gulpfile.js
|
var gulp = require("gulp");
var sass = require("gulp-sass");
var postcss = require("gulp-postcss");
var autoprefixer = require("autoprefixer");
var cssnano = require("cssnano");
var uglify = require("gulp-uglify");
var rename = require("gulp-rename");
var browserSync = require("browser-sync");
gulp.task("serve", ["css", "js"], function () {
browserSync.init({
server: "./"
});
gulp.watch("css/main.scss", ["css"]);
gulp.watch("index.html").on("change", browserSync.reload);
gulp.watch("js/main.js", ["js"]);
gulp.watch("js/main.min.js").on("change", browserSync.reload);
});
gulp.task("css", function () {
gulp.src("css/main.scss")
.pipe(sass().on("error", sass.logError))
.pipe(postcss([
autoprefixer(),
cssnano()
]))
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest("css"))
.pipe(browserSync.stream());
});
gulp.task("js", function () {
gulp.src("js/main.js")
.pipe(uglify())
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest("js"));
});
gulp.task("default", ["serve"]);
|
const gulp = require('gulp');
const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const browserSync = require('browser-sync');
gulp.task('serve', ['css', 'js'], () => {
browserSync.init({
server: './'
});
gulp.watch('css/main.scss', ['css']);
gulp.watch('index.html').on('change', browserSync.reload);
gulp.watch('js/main.js', ['js']);
gulp.watch('js/main.min.js').on('change', browserSync.reload);
});
gulp.task('css', () => {
gulp
.src('css/main.scss')
.pipe(sass().on('error', sass.logError))
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(
rename({
suffix: '.min'
})
)
.pipe(gulp.dest('css'))
.pipe(browserSync.stream());
});
gulp.task('js', () => {
gulp
.src('js/main.js')
.pipe(uglify())
.pipe(
rename({
suffix: '.min'
})
)
.pipe(gulp.dest('js'));
});
gulp.task('default', ['serve']);
|
Update Gulp file to use es6 syntax.
|
Update Gulp file to use es6 syntax.
|
JavaScript
|
mit
|
mohouyizme/minimado,mohouyizme/minimado
|
ac04ecd69e559d018f7d9e24d7f6de617aac3a26
|
src/apis/Dimensions/index.js
|
src/apis/Dimensions/index.js
|
/**
* Copyright (c) 2015-present, Nicolas Gallagher.
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @flow
*/
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'
import invariant from 'fbjs/lib/invariant'
const win = ExecutionEnvironment.canUseDOM ? window : { screen: {} }
const dimensions = {
screen: {
fontScale: 1,
get height() { return win.screen.height },
scale: win.devicePixelRatio || 1,
get width() { return win.screen.width }
},
window: {
fontScale: 1,
get height() { return win.innerHeight },
scale: win.devicePixelRatio || 1,
get width() { return win.innerWidth }
}
}
class Dimensions {
static get(dimension: string): Object {
invariant(dimensions[dimension], 'No dimension set for key ' + dimension)
return dimensions[dimension]
}
}
module.exports = Dimensions
|
/**
* Copyright (c) 2015-present, Nicolas Gallagher.
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @flow
*/
import debounce from 'lodash.debounce'
import ExecutionEnvironment from 'fbjs/lib/ExecutionEnvironment'
import invariant from 'fbjs/lib/invariant'
const win = ExecutionEnvironment.canUseDOM ? window : { screen: {} }
const dimensions = {}
class Dimensions {
static get(dimension: string): Object {
invariant(dimensions[dimension], 'No dimension set for key ' + dimension)
return dimensions[dimension]
}
static set(): void {
dimensions.window = {
fontScale: 1,
height: win.innerHeight,
scale: win.devicePixelRatio || 1,
width: win.innerWidth
}
dimensions.screen = {
fontScale: 1,
height: win.screen.height,
scale: win.devicePixelRatio || 1,
width: win.screen.width
}
}
}
Dimensions.set();
ExecutionEnvironment.canUseDOM && window.addEventListener('resize', debounce(Dimensions.set, 50))
module.exports = Dimensions
|
Update Dimensions when window resizes
|
Update Dimensions when window resizes
|
JavaScript
|
mit
|
necolas/react-native-web,necolas/react-native-web,necolas/react-native-web
|
e5fb18d4a59e707f075d76310af2ec919ca5716c
|
src/modules/getPrice/index.js
|
src/modules/getPrice/index.js
|
import module from '../../module'
import command from '../../components/command'
import loader from '../../components/loader'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
loader(() => {
console.log('test')
}),
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const {data: itemData} = await axios.get(
`https://esi.tech.ccp.is/latest/search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const {data: priceData} = await axios.get(
`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`
);
const sellFivePercent = humanize(priceData[0].sell.fivePercent);
const buyFivePercent = humanize(priceData[0].buy.fivePercent);
message.channel.sendMessage(
`__Price of **${args}** (or nearest match) in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
)
|
import module from '../../module'
import command from '../../components/command'
import loader from '../../components/loader'
import axios from 'axios'
import humanize from '../../utils/humanize'
export default module(
loader(() => {
console.log('test')
}),
command('getprice', 'Gets the Jita price of a given item.', async (state, message, args) => {
try {
const esiURL = 'https://esi.tech.ccp.is/latest/';
const {data: itemData} = await axios.get(
`${esiURL}search/?categories=inventorytype&datasource=tranquility&language=en-us&search=${args}`
);
const itemid = itemData.inventorytype[0];
const {data: priceData} = await axios.get(
`http://api.eve-central.com/api/marketstat/json?typeid=${itemid}&usesystem=30000142`
);
const sellFivePercent = humanize(priceData[0].sell.fivePercent);
const buyFivePercent = humanize(priceData[0].buy.fivePercent);
message.channel.sendMessage(
`__Price of **${args}** (or nearest match) in Jita__:\n` +
`**Sell**: ${sellFivePercent} ISK\n` +
`**Buy**: ${buyFivePercent} ISK`
)
} catch(e) {
console.error(e);
throw e
}
})
)
|
Move ESI url prefix to variable
|
Move ESI url prefix to variable
|
JavaScript
|
mit
|
emensch/thonk9k
|
6801d288ec728671330a6881306753abd30e0a8f
|
app/student.front.js
|
app/student.front.js
|
const $answer = $('.answer')
const {makeRichText} = require('./rich-text-editor')
const save = ($elem, async = true) => $.post({
url: '/save',
data: {text: $elem.html(), answerId: $elem.attr('id')},
async
})
function saveScreenshot(questionId) {
return ({data, type}) => {
return $.post({
type: 'POST',
url: `/saveImg?answerId=${questionId}`,
data: data,
processData: false,
contentType: type
}).then(res => {
return res.url
})
}
}
const richTextOptions = id => ({
screenshot: {
saver: data => saveScreenshot(id)(data),
limit: 10
}
})
$answer.each((i, answer) => {
makeRichText(answer, richTextOptions(answer.id))
$.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html))
}).on('keypress', e => {
if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') {
e.preventDefault()
save($(e.target))
}
})
$('#answer1').focus()
|
const $answer = $('.answer')
const {makeRichText} = require('./rich-text-editor')
const save = ($elem, async = true) => $.post({
url: '/save',
data: {text: $elem.html(), answerId: $elem.attr('id')},
async
})
function saveScreenshot(questionId) {
return ({data, type}) => {
return $.post({
type: 'POST',
url: `/saveImg?answerId=${questionId}`,
data: data,
processData: false,
contentType: type
}).then(res => {
return res.url
})
}
}
const richTextOptions = id => ({
screenshot: {
saver: data => saveScreenshot(id)(data),
limit: 10
}
})
$answer.each((i, answer) => {
$.get(`/load?answerId=${answer.id}`, data => {
data && $(answer).html(data.html)
makeRichText(answer, richTextOptions(answer.id), onValueChange)
})
}).on('keypress', e => {
if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') {
e.preventDefault()
save($(e.target))
}
})
$('#answer1').focus()
function onValueChange() {
}
|
Update answer content before initializing rich text
|
Update answer content before initializing rich text
|
JavaScript
|
mit
|
digabi/math-editor,digabi/rich-text-editor,digabi/rich-text-editor,digabi/rich-text-editor,digabi/math-editor
|
d02ef235fb382ff749a41561518c18c7ebd81f2f
|
src/JokeMeUpBoy.js
|
src/JokeMeUpBoy.js
|
/**
* Prints a random programmer joke.
* @author Vitor Cortez <vitoracortez+github@gmail.com>
*/
var jokeMeUpBoy = function() {
const jokes = getListOfJokes();
let rand = Math.floor(Math.random() * jokes.length);
console.log(jokes[rand]);
};
/**
* Holds a list of classic programmer jokes.
* Feel free to add a new joke each day.
* @private
*/
function getListOfJokes() {
var arr = [];
arr.push('Q: How do you tell an introverted computer scientist from an extroverted computer scientist?\nA: An extroverted computer scientist looks at your shoes when he talks to you.');
return arr;
}
anything.prototype.JokeMeUpBoy = jokeMeUpBoy;
|
/**
* Prints a random programmer joke.
* @author Vitor Cortez <vitoracortez+github@gmail.com>
*/
var jokeMeUpBoy = function() {
const jokes = getListOfJokes();
let rand = Math.floor(Math.random() * jokes.length);
console.log(jokes[rand]);
};
/**
* Holds a list of classic programmer jokes.
* Feel free to add a new joke each day.
* @private
*/
function getListOfJokes() {
var arr = [];
arr.push('Q: How do you tell an introverted computer scientist from an extroverted computer scientist?\nA: An extroverted computer scientist looks at your shoes when he talks to you.');
arr.push('Q: Why do programmers always mix up Halloween and Christmas?\nA: Because Oct 31 == Dec 25!');
return arr;
}
anything.prototype.JokeMeUpBoy = jokeMeUpBoy;
|
Add a new dank joke
|
Add a new dank joke
Dem jokes
|
JavaScript
|
mit
|
Rabrennie/anything.js,Sha-Grisha/anything.js,Rabrennie/anything.js,Rabrennie/anything.js,Rabrennie/anything.js,Sha-Grisha/anything.js,Sha-Grisha/anything.js,Sha-Grisha/anything.js
|
86cef9310543200502e822cbfbc39066e3f91967
|
public/app/user-account/user-login/user-login-controller.js
|
public/app/user-account/user-login/user-login-controller.js
|
define(function() {
var LoginController = function($location, AuthenticationService) {
// reset login status
AuthenticationService.clearCredentials();
this.login = function() {
this.dataLoading = true;
var self = this
AuthenticationService.login(this.username, this.password)
.success(function(userProfile, status) {
AuthenticationService.setCredentials(self.username, self.password);
$location.path('/');
})
.error(function(error, status) {
self.error = error.message;
self.dataLoading = false;
});
};
}
LoginController.$inject = ['$location', 'UserAuthenticationService']
return LoginController
})
|
define(function() {
var LoginController = function($location, $mdDialog, AuthenticationService) {
// reset login status
AuthenticationService.clearCredentials()
this.login = function() {
this.dataLoading = true
var self = this
AuthenticationService.login(this.username, this.password)
.success(function(userProfile, status) {
AuthenticationService.setCredentials(self.username, self.password)
$location.path('/')
})
.error(function(error, status) {
self.dataLoading = false
var alert = $mdDialog.alert({
title: 'We couldn\'t sign you in!',
content: error.message,
ok: 'Try again'
})
$mdDialog.show(alert)
})
}
}
LoginController.$inject = ['$location', '$mdDialog', 'UserAuthenticationService']
return LoginController
})
|
Update login controller to display dialog on error
|
Update login controller to display dialog on error
|
JavaScript
|
mit
|
tenevdev/idiot,tenevdev/idiot
|
297c942ffefae923501d5988c36ef6930b5888b7
|
examples/http-random-user/src/main.js
|
examples/http-random-user/src/main.js
|
import Cycle from '@cycle/core';
import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom';
import {makeHTTPDriver} from '@cycle/http';
function main(sources) {
const getRandomUser$ = sources.DOM.select('.get-random').events('click')
.map(() => {
const randomNum = Math.round(Math.random() * 9) + 1;
return {
url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum),
key: 'users',
method: 'GET'
};
});
const user$ = sources.HTTP
.filter(res$ => res$.request.key === 'users')
.mergeAll()
.map(res => res.body)
.startWith(null);
const vtree$ = user$.map(user =>
div('.users', [
button('.get-random', 'Get random user'),
user === null ? null : div('.user-details', [
h1('.user-name', user.name),
h4('.user-email', user.email),
a('.user-website', {href: user.website}, user.website)
])
])
);
return {
DOM: vtree$,
HTTP: getRandomUser$
};
}
Cycle.run(main, {
DOM: makeDOMDriver('#main-container'),
HTTP: makeHTTPDriver()
});
|
import Cycle from '@cycle/core';
import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom';
import {makeHTTPDriver} from '@cycle/http';
function main(sources) {
const getRandomUser$ = sources.DOM.select('.get-random').events('click')
.map(() => {
const randomNum = Math.round(Math.random() * 9) + 1;
return {
url: 'http://jsonplaceholder.typicode.com/users/' + String(randomNum),
category: 'users',
method: 'GET'
};
});
const user$ = sources.HTTP
.filter(res$ => res$.request.category === 'users')
.mergeAll()
.map(res => res.body)
.startWith(null);
const vtree$ = user$.map(user =>
div('.users', [
button('.get-random', 'Get random user'),
user === null ? null : div('.user-details', [
h1('.user-name', user.name),
h4('.user-email', user.email),
a('.user-website', {href: user.website}, user.website)
])
])
);
return {
DOM: vtree$,
HTTP: getRandomUser$
};
}
Cycle.run(main, {
DOM: makeDOMDriver('#main-container'),
HTTP: makeHTTPDriver()
});
|
Rename http-random-user key to category
|
Rename http-random-user key to category
|
JavaScript
|
mit
|
cyclejs/cyclejs,cyclejs/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cyclejs,usm4n/cyclejs,maskinoshita/cyclejs,cyclejs/cycle-core,staltz/cycle,ntilwalli/cyclejs,ntilwalli/cyclejs,feliciousx-open-source/cyclejs,usm4n/cyclejs,usm4n/cyclejs,maskinoshita/cyclejs,maskinoshita/cyclejs,ntilwalli/cyclejs,feliciousx-open-source/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cycle-core,ntilwalli/cyclejs,staltz/cycle,usm4n/cyclejs,cyclejs/cyclejs,maskinoshita/cyclejs
|
73e99f993882ddd754fefd112f2c95ce62e5dad2
|
app/components/OverFlowMenu.js
|
app/components/OverFlowMenu.js
|
import React, { Component, PropTypes, cloneElement } from 'react';
import styles from './OverFlowMenu.module.scss';
export class OverflowItem extends Component {
onClick(e) {
this.props.onClick(e);
this.props.onClicked();
}
render() {
return (
<div className={styles.item} {...this.props} onClick={this.onClick.bind(this)}>
{ this.props.children }
</div>
);
}
}
export default class OverFlowMenu extends Component {
constructor(props) {
super(props);
this.state = {open: false};
}
toggle() {
this.setState({open: !this.state.open});
}
onItemClicked() {
this.toggle();
}
onMouseLeave() {
this.toggle();
}
render() {
const cn = [this.state.open ? styles.overflowMenuOpen : styles.overflowMenu, this.props.className].join(' ');
return (
<div className={ cn }>
<button className={styles.btn} onClick={this.toggle.bind(this)}>
<i className="fa small fa-ellipsis-v"/>
</button>
<div className="items" onMouseLeave={this.onMouseLeave.bind(this)}>
{ React.Children.map(this.props.children, (child) => {
return cloneElement(child, {
onClicked: this.onItemClicked.bind(this)
});
})}
</div>
</div>
);
}
}
|
import React, { Component, PropTypes, cloneElement } from 'react';
import styles from './OverFlowMenu.module.scss';
export class OverflowItem extends Component {
onClick(e) {
this.props.onClick(e);
this.props.onClicked();
}
render() {
return (
<div className={styles.item} {...this.props} onClick={this.onClick.bind(this)}>
{ this.props.children }
</div>
);
}
}
export default class OverFlowMenu extends Component {
constructor(props) {
super(props);
this.state = {open: false};
}
toggle() {
this.setOpen(!this.isOpen());
}
isOpen() {
return this.state.open;
}
setOpen(openOrClosed) {
this.setState({open: openOrClosed});
}
onItemClicked() {
this.toggle();
}
onMouseLeave() {
this.setOpen(false);
}
render() {
const cn = [this.state.open ? styles.overflowMenuOpen : styles.overflowMenu, this.props.className].join(' ');
return (
<div className={ cn }>
<button className={styles.btn} onClick={this.toggle.bind(this)}>
<i className="fa small fa-ellipsis-v"/>
</button>
<div className="items" onMouseLeave={this.onMouseLeave.bind(this)}>
{ React.Children.map(this.props.children, (child) => {
return cloneElement(child, {
onClicked: this.onItemClicked.bind(this)
});
})}
</div>
</div>
);
}
}
|
Fix overflow menu reopening immediately after selecting an item
|
Fix overflow menu reopening immediately after selecting an item
Was caused by mouseout toggling, instead of closing
|
JavaScript
|
mpl-2.0
|
pascalw/gettable,pascalw/gettable
|
5e850fc85216fed6848878eaf66841c8dc25fc1b
|
src/selectors/cashRegister.js
|
src/selectors/cashRegister.js
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import { createSelector } from 'reselect';
import { pageStateSelector } from './pageSelectors';
import currency from '../localization/currency';
/**
* Derives current balance from cash register transactions.
* @return {Number}
*/
export const selectTransactions = createSelector([pageStateSelector], pageState => pageState.data);
export const selectReceipts = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'receipt')
);
export const selectPayments = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'payment')
);
export const selectReceiptsTotal = createSelector([selectReceipts], receipts =>
receipts.reduce((acc, { total }) => acc + total, 0)
);
export const selectPaymentsTotal = createSelector([selectPayments], payments =>
payments.reduce((acc, { total }) => acc + total, 0)
);
export const selectBalance = createSelector(
[selectReceiptsTotal, selectPaymentsTotal],
(receiptsTotal, paymentsTotal) => currency(receiptsTotal - paymentsTotal).format(false)
);
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import { createSelector } from 'reselect';
import { pageStateSelector } from './pageSelectors';
import currency from '../localization/currency';
/**
* Derives current balance from cash register transactions.
* @return {Number}
*/
export const selectTransactions = createSelector([pageStateSelector], pageState => pageState.data);
export const selectReceipts = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'receipt')
);
export const selectPayments = createSelector([selectTransactions], transactions =>
transactions.filter(({ type }) => type === 'payment')
);
export const selectReceiptsTotal = createSelector([selectReceipts], receipts =>
receipts.reduce((acc, { total }) => acc.add(total), currency(0))
);
export const selectPaymentsTotal = createSelector([selectPayments], payments =>
payments.reduce((acc, { total }) => acc.add(total), currency(0))
);
export const selectBalance = createSelector(
[selectReceiptsTotal, selectPaymentsTotal],
(receiptsTotal, paymentsTotal) => receiptsTotal.subtract(paymentsTotal).format()
);
|
Add currency to cash register selectors
|
Add currency to cash register selectors
|
JavaScript
|
mit
|
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
|
39c4271933e1392d20483aa3e1c6e7287fb3d820
|
src/api/githubAPI.js
|
src/api/githubAPI.js
|
let Octokat = require('octokat');
let octo = new Octokat({});
class GithubApi {
constructor(){
this.octo = new Octokat({});
}
static newOctokatNoToken(){
this.octo = new Octokat({});
}
static newOctokatWithToken(token){
this.octo = new Octokat({
token: token
});
}
static testOctokat(){
return new Promise((resolve) => {
resolve(octo.repos('compumike08', 'GitHub_Status_API_GUI').fetch());
});
}
}
export default GithubApi;
|
let Octokat = require('octokat');
let octo = new Octokat({});
class GithubApi {
static testOctokat(){
return new Promise((resolve) => {
resolve(octo.repos('compumike08', 'GitHub_Status_API_GUI').fetch());
});
}
}
export default GithubApi;
|
Revert "Modify GithubApi to be able to set an OAuth token when instantiating"
|
Revert "Modify GithubApi to be able to set an OAuth token when instantiating"
This reverts commit 2197aa8a6246348070b9c26693ec08fc44f02031.
|
JavaScript
|
mit
|
compumike08/GitHub_Status_API_GUI,compumike08/GitHub_Status_API_GUI
|
60f02a26c5857e28e268cbfdd242644089c6626c
|
react.js
|
react.js
|
module.exports = {
extends: ["./index.js", "plugin:react/recommended"],
env: {
browser: true
},
plugins: [
"react"
],
parserOptions: {
sourceType: 'module',
ecmaVersion: 6,
ecmaFeatures: {
"jsx": true
}
}
};
|
module.exports = {
extends: ["./index.js", "plugin:react/recommended"],
env: {
browser: true
},
plugins: [
"react"
],
parserOptions: {
sourceType: 'module',
ecmaVersion: 6,
ecmaFeatures: {
"jsx": true
}
},
rules: {
"react/display-name": 0,
"react/no-danger": 0
}
};
|
Add common React rules to preset
|
Add common React rules to preset
|
JavaScript
|
mit
|
netconomy/eslint-config-netconomy
|
55e44ff76a4baae8214cd89c498868b661d99049
|
spawnAsync.js
|
spawnAsync.js
|
'use strict';
let spawn = require('cross-spawn');
module.exports = function spawnAsync() {
let args = Array.prototype.slice.call(arguments, 0);
let child;
let promise = new Promise((fulfill, reject) => {
child = spawn.apply(spawn, args);
let stdout = '';
let stderr = '';
if (child.stdout) {
child.stdout.on('data', data => {
stdout += data;
});
}
if (child.stderr) {
child.stderr.on('data', data => {
stderr += data;
});
}
child.on('close', (code, signal) => {
child.removeAllListeners();
let result = {
pid: child.pid,
output: [stdout, stderr],
stdout,
stderr,
status: code,
signal,
};
if (code) {
let error = new Error(`Process exited with non-zero code: ${code}`);
Object.assign(error, result);
reject(error);
} else {
fulfill(result);
}
});
child.on('error', error => {
child.removeAllListeners();
error.pid = child.pid;
error.output = [stdout, stderr];
error.stdout = stdout;
error.stderr = stderr;
error.status = null;
reject(error);
});
});
promise.child = child;
return promise;
};
|
'use strict';
let spawn = require('cross-spawn');
module.exports = function spawnAsync(...args) {
let child;
let promise = new Promise((fulfill, reject) => {
child = spawn.apply(spawn, args);
let stdout = '';
let stderr = '';
if (child.stdout) {
child.stdout.on('data', data => {
stdout += data;
});
}
if (child.stderr) {
child.stderr.on('data', data => {
stderr += data;
});
}
child.on('close', (code, signal) => {
child.removeAllListeners();
let result = {
pid: child.pid,
output: [stdout, stderr],
stdout,
stderr,
status: code,
signal,
};
if (code) {
let error = new Error(`Process exited with non-zero code: ${code}`);
Object.assign(error, result);
reject(error);
} else {
fulfill(result);
}
});
child.on('error', error => {
child.removeAllListeners();
error.pid = child.pid;
error.output = [stdout, stderr];
error.stdout = stdout;
error.stderr = stderr;
error.status = null;
reject(error);
});
});
promise.child = child;
return promise;
};
|
Use rest param instead of slice
|
Use rest param instead of slice
|
JavaScript
|
mit
|
exponentjs/spawn-async,650Industries/spawn-async
|
9017acd8ec8e0aaf9cf95d0b64385fb18fff0dcc
|
lib/config.js
|
lib/config.js
|
// Load configurations file
var config = require('../configs/config.json');
// Validate settings
if (!config.mpd || !config.mpd.host || !config.mpd.port) {
throw new Error("You must specify MPD host and port");
}
if (!config.radioStations || (typeof config.radioStations !== 'object')) {
throw new Error('"radioStations" field must be an object');
}
var isRadioStationsEmpty = true;
for(var index in config.radioStations) {
if (config.radioStations.hasOwnProperty(index)) {
isRadioStationsEmpty = false;
config.defaultRadioStation = config.defaultRadioStation || index;
}
}
if (isRadioStationsEmpty) {
throw new Error("You must specify at least one radio station");
}
module.exports = config;
|
// Load configurations file
var config = require('../configs/config.json');
// Validate settings
if (!config.mpd || !config.mpd.host || !config.mpd.port) {
throw new Error("You must specify MPD host and port");
}
if (!config.radioStations || (typeof config.radioStations !== 'object')) {
throw new Error('"radioStations" field must be an object');
}
var isRadioStationsEmpty = true;
for(var index in config.radioStations) {
if (config.radioStations.hasOwnProperty(index)) {
isRadioStationsEmpty = false;
config.defaultRadioStation = config.defaultRadioStation || index;
}
}
if (isRadioStationsEmpty) {
throw new Error("You must specify at least one radio station");
}
// Make sure the application port is set
config.server.port = config.server.port || 8000;
module.exports = config;
|
Make use server port is set
|
Make use server port is set
|
JavaScript
|
apache-2.0
|
JustBlackBird/bluethroat,JustBlackBird/bluethroat,JustBlackBird/bluethroat
|
ee5a87db22b7e527d7d0102072bba5de91ac38fb
|
lib/errors.js
|
lib/errors.js
|
/**
AuthGW Custom Errors
@author tylerFowler
**/
/**
@name InvalidRoleError
@desc Thrown when a role is given that is not in the list of roles
@param { String } invalidRole
**/
function InvalidRoleError(invalidRole) {
this.name = 'InvalidRoleError';
this.message = `${invalidRole} is not a valid role`;
this.stack = (new Error()).stack;
}
InvalidRoleError.prototype = Object.create(Error.prototype);
InvalidRoleError.prototype.constructor = InvalidRoleError;
exports.InvalidRoleError = InvalidRoleError;
|
/**
AuthGW Custom Errors
@author tylerFowler
**/
/**
@class InvalidRoleError @extends Error
@desc Thrown when a role is given that is not in the list of roles
@param { String } invalidRole
**/
class InvalidRoleError extends Error {
constructor(invalidRole) {
this.name = 'InvalidRoleError';
this.message = `${invalidRole} is not a valid role`;
}
}
exports.InvalidRoleError = InvalidRoleError;
|
Use class syntax for creating error
|
Use class syntax for creating error
|
JavaScript
|
mit
|
tylerFowler/authgw
|
48ef57b90e8567574199dddb5b6cee78b6b039b0
|
src/config.js
|
src/config.js
|
export const TZ = 'Europe/Prague'
export const SIRIUS_PROXY_PATH = process.env.SIRIUS_PROXY_PATH
|
export const TZ = 'Europe/Prague'
export const SIRIUS_PROXY_PATH = global.SIRIUS_PROXY_PATH || process.env.SIRIUS_PROXY_PATH
|
Allow SIRIUS_PROXY_PATH override by global var
|
Allow SIRIUS_PROXY_PATH override by global var
|
JavaScript
|
mit
|
cvut/fittable-widget,cvut/fittable,cvut/fittable-widget,cvut/fittable-widget,cvut/fittable,cvut/fittable
|
57789e5d40c448ab1138dad987f7d8f9595966ee
|
.storybook/config.js
|
.storybook/config.js
|
import { configure } from '@storybook/vue';
// automatically import all files ending in *.stories.js
const req = require.context('../stories', true, /\.stories\.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
|
import { configure, addParameters } from '@storybook/vue';
// Option defaults:
addParameters({
options: {
name: 'Vue Visual',
panelPosition: 'right',
}
})
// automatically import all files ending in *.stories.js
const req = require.context('../stories', true, /\.stories\.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
|
Put package name in the storybook
|
Put package name in the storybook
|
JavaScript
|
mit
|
BKWLD/vue-visual
|
2de18a5628f1acf45a5884c93bd985d4f6f367a3
|
lib/server.js
|
lib/server.js
|
var acquires = {};
var Responder = require('cote').Responder;
var autoReleaseTimeout = 30000;
var counts = {
acquires: 0,
releases: 0
};
function acquire(req, cb) {
console.log('acquire', req.id);
counts.acquires++;
cb.autoRelease = setTimeout(function() {
console.log('auto release', req.id);
release(req);
}, autoReleaseTimeout);
if (acquires[req.id])
return acquires[req.id].push(cb);
acquires[req.id] = [];
cb();
}
function release(req) {
console.log('release', req.id);
counts.releases++;
if (!(req.id in acquires)) return;
if (!acquires[req.id].length)
return delete acquires[req.id];
var cb = acquires[req.id].shift();
cb && cb();
clearTimeout(cb.autoRelease);
}
function init() {
var server = new Responder({
name: 'semaver server',
key: 'semaver',
respondsTo: ['acquire', 'release']
});
server.on('acquire', acquire);
server.on('release', release);
setInterval(function() {
console.log('counts', counts);
if (Object.keys(acquires).length)
console.log(acquires);
}, 1000);
}
module.exports = {
init: init
};
|
var acquires = {};
var Responder = require('cote').Responder;
var autoReleaseTimeout = 30000;
var counts = {
acquires: 0,
releases: 0
};
function acquire(req, cb) {
console.log('acquire', req.id);
counts.acquires++;
if (acquires[req.id]) {
cb.autoRelease = setTimeout(function() {
console.log('auto release', req.id);
release(req);
}, autoReleaseTimeout);
return acquires[req.id].push(cb);
}
acquires[req.id] = [];
cb();
}
function release(req) {
console.log('release', req.id);
counts.releases++;
if (!(req.id in acquires)) return;
if (!acquires[req.id].length)
return delete acquires[req.id];
var cb = acquires[req.id].shift();
cb && cb();
clearTimeout(cb.autoRelease);
}
function init() {
var server = new Responder({
name: 'semaver server',
key: 'semaver',
respondsTo: ['acquire', 'release']
});
server.on('acquire', acquire);
server.on('release', release);
setInterval(function() {
console.log('counts', counts);
if (Object.keys(acquires).length)
console.log(acquires);
}, 1000);
}
module.exports = {
init: init
};
|
Move auto release timeout to if check in acquire.
|
Move auto release timeout to if check in acquire.
|
JavaScript
|
apache-2.0
|
tart/semaver
|
f5774e3fb24ca403de481e446c3bf68fa78b2c47
|
spec/fixtures/api/quit-app/main.js
|
spec/fixtures/api/quit-app/main.js
|
var app = require('electron').app
app.on('ready', function () {
app.exit(123)
})
process.on('exit', function (code) {
console.log('Exit event with code: ' + code)
})
|
var app = require('electron').app
app.on('ready', function () {
// This setImmediate call gets the spec passing on Linux
setImmediate(function () {
app.exit(123)
})
})
process.on('exit', function (code) {
console.log('Exit event with code: ' + code)
})
|
Exit from a setImmediate callback
|
Exit from a setImmediate callback
|
JavaScript
|
mit
|
seanchas116/electron,felixrieseberg/electron,pombredanne/electron,bpasero/electron,wan-qy/electron,leftstick/electron,the-ress/electron,jaanus/electron,deed02392/electron,thomsonreuters/electron,brave/muon,tonyganch/electron,tinydew4/electron,thomsonreuters/electron,gerhardberger/electron,roadev/electron,simongregory/electron,the-ress/electron,rreimann/electron,shiftkey/electron,thomsonreuters/electron,kcrt/electron,preco21/electron,aichingm/electron,ankitaggarwal011/electron,Floato/electron,Gerhut/electron,voidbridge/electron,leftstick/electron,seanchas116/electron,thingsinjars/electron,aliib/electron,jhen0409/electron,MaxWhere/electron,roadev/electron,bpasero/electron,lzpfmh/electron,joaomoreno/atom-shell,lzpfmh/electron,kokdemo/electron,rajatsingla28/electron,Floato/electron,dongjoon-hyun/electron,renaesop/electron,brenca/electron,etiktin/electron,posix4e/electron,astoilkov/electron,brenca/electron,Floato/electron,ankitaggarwal011/electron,thompsonemerson/electron,lzpfmh/electron,miniak/electron,dongjoon-hyun/electron,gabriel/electron,posix4e/electron,minggo/electron,deed02392/electron,leftstick/electron,thompsonemerson/electron,shiftkey/electron,astoilkov/electron,voidbridge/electron,miniak/electron,felixrieseberg/electron,rreimann/electron,lzpfmh/electron,simongregory/electron,pombredanne/electron,stevekinney/electron,roadev/electron,stevekinney/electron,gerhardberger/electron,jaanus/electron,minggo/electron,Floato/electron,the-ress/electron,tinydew4/electron,bbondy/electron,wan-qy/electron,gabriel/electron,the-ress/electron,tinydew4/electron,aliib/electron,biblerule/UMCTelnetHub,leethomas/electron,bbondy/electron,biblerule/UMCTelnetHub,brave/muon,miniak/electron,renaesop/electron,noikiy/electron,stevekinney/electron,lzpfmh/electron,ankitaggarwal011/electron,thingsinjars/electron,thompsonemerson/electron,noikiy/electron,minggo/electron,kokdemo/electron,joaomoreno/atom-shell,etiktin/electron,thomsonreuters/electron,tonyganch/electron,stevekinney/electron,kcrt/electron,leethomas/electron,bbondy/electron,voidbridge/electron,stevekinney/electron,kcrt/electron,rajatsingla28/electron,Floato/electron,felixrieseberg/electron,Gerhut/electron,felixrieseberg/electron,voidbridge/electron,evgenyzinoviev/electron,brave/electron,electron/electron,dongjoon-hyun/electron,simongregory/electron,voidbridge/electron,gabriel/electron,rajatsingla28/electron,gabriel/electron,electron/electron,thomsonreuters/electron,kokdemo/electron,tonyganch/electron,gerhardberger/electron,aichingm/electron,twolfson/electron,electron/electron,simongregory/electron,leftstick/electron,simongregory/electron,aichingm/electron,tonyganch/electron,aliib/electron,brave/electron,leethomas/electron,seanchas116/electron,tylergibson/electron,aichingm/electron,rajatsingla28/electron,roadev/electron,tylergibson/electron,twolfson/electron,bbondy/electron,shiftkey/electron,tinydew4/electron,astoilkov/electron,dongjoon-hyun/electron,evgenyzinoviev/electron,electron/electron,aliib/electron,brave/muon,rajatsingla28/electron,thingsinjars/electron,twolfson/electron,voidbridge/electron,joaomoreno/atom-shell,kcrt/electron,evgenyzinoviev/electron,renaesop/electron,tinydew4/electron,thompsonemerson/electron,leftstick/electron,leftstick/electron,MaxWhere/electron,brave/electron,bpasero/electron,renaesop/electron,brave/electron,seanchas116/electron,shiftkey/electron,brave/muon,wan-qy/electron,minggo/electron,thingsinjars/electron,noikiy/electron,etiktin/electron,brave/muon,tonyganch/electron,kcrt/electron,rreimann/electron,deed02392/electron,astoilkov/electron,Gerhut/electron,jaanus/electron,aichingm/electron,bpasero/electron,biblerule/UMCTelnetHub,minggo/electron,pombredanne/electron,rreimann/electron,deed02392/electron,kokdemo/electron,the-ress/electron,biblerule/UMCTelnetHub,rreimann/electron,brenca/electron,wan-qy/electron,thompsonemerson/electron,thingsinjars/electron,leethomas/electron,renaesop/electron,minggo/electron,jhen0409/electron,posix4e/electron,leethomas/electron,aichingm/electron,preco21/electron,Evercoder/electron,brave/electron,preco21/electron,seanchas116/electron,shiftkey/electron,tylergibson/electron,Evercoder/electron,miniak/electron,Evercoder/electron,gerhardberger/electron,dongjoon-hyun/electron,Gerhut/electron,posix4e/electron,evgenyzinoviev/electron,tylergibson/electron,Evercoder/electron,MaxWhere/electron,brenca/electron,jhen0409/electron,electron/electron,preco21/electron,bpasero/electron,noikiy/electron,jhen0409/electron,felixrieseberg/electron,tylergibson/electron,astoilkov/electron,kokdemo/electron,seanchas116/electron,astoilkov/electron,wan-qy/electron,dongjoon-hyun/electron,jaanus/electron,preco21/electron,gerhardberger/electron,brenca/electron,simongregory/electron,leethomas/electron,roadev/electron,noikiy/electron,posix4e/electron,kcrt/electron,electron/electron,gerhardberger/electron,deed02392/electron,preco21/electron,Evercoder/electron,twolfson/electron,joaomoreno/atom-shell,felixrieseberg/electron,gabriel/electron,jaanus/electron,tonyganch/electron,evgenyzinoviev/electron,thompsonemerson/electron,brave/electron,twolfson/electron,gerhardberger/electron,ankitaggarwal011/electron,twolfson/electron,bpasero/electron,pombredanne/electron,renaesop/electron,jaanus/electron,thingsinjars/electron,etiktin/electron,shiftkey/electron,bbondy/electron,MaxWhere/electron,bpasero/electron,ankitaggarwal011/electron,MaxWhere/electron,Gerhut/electron,joaomoreno/atom-shell,pombredanne/electron,the-ress/electron,tylergibson/electron,jhen0409/electron,jhen0409/electron,brave/muon,gabriel/electron,rajatsingla28/electron,tinydew4/electron,posix4e/electron,lzpfmh/electron,joaomoreno/atom-shell,biblerule/UMCTelnetHub,electron/electron,ankitaggarwal011/electron,aliib/electron,biblerule/UMCTelnetHub,miniak/electron,wan-qy/electron,miniak/electron,bbondy/electron,Evercoder/electron,etiktin/electron,noikiy/electron,roadev/electron,kokdemo/electron,brenca/electron,pombredanne/electron,aliib/electron,MaxWhere/electron,rreimann/electron,the-ress/electron,thomsonreuters/electron,Gerhut/electron,Floato/electron,deed02392/electron,etiktin/electron,evgenyzinoviev/electron,stevekinney/electron
|
ad16587294c3186a89e84105fb2e390b36f26ca0
|
lib/switch.js
|
lib/switch.js
|
const gpio = require('raspi-gpio')
module.exports = class Switch {
constructor (pinId) {
this.nInput = new gpio.DigitalInput(pinId, gpio.PULL_UP)
}
on (changeListener) {
this.nInput.on('change', (value) => {
changeListener(value)
})
}
}
|
const gpio = require('raspi-gpio')
module.exports = class Switch {
constructor (pinId) {
this.nInput = new gpio.DigitalInput({
pin: pinId,
pullResistor: gpio.PULL_UP})
}
on (changeListener) {
this.nInput.on('change', (value) => {
changeListener(value)
})
}
}
|
Fix pin pull resistor config
|
Fix pin pull resistor config
|
JavaScript
|
mit
|
DanStough/josl
|
a6a42353b20a9282bdb83cf45c0111954b9d6888
|
ember-cli-build.js
|
ember-cli-build.js
|
/* eslint-env node */
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
// Add options here
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
return app.toTree();
};
|
/* eslint-env node */
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
'ember-cli-babel': {
includePolyfill: true
},
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
return app.toTree();
};
|
Include ember-cli-babel polyfil to fix tests
|
Include ember-cli-babel polyfil to fix tests
|
JavaScript
|
mit
|
amiel/ember-data-url-templates,amiel/ember-data-url-templates
|
1db74f03479538911f1c9336df233aea3c7cc622
|
karma.conf.js
|
karma.conf.js
|
var webpackConfig = require('./webpack.config');
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai'],
files: [
'test/**/*.ts'
],
exclude: [
],
preprocessors: {
'src/**/!(defaults)/*.js': ['coverage'],
'test/**/*.ts': ['webpack']
},
webpack: {
module: webpackConfig.module,
resolve: webpackConfig.resolve
},
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['ChromeES6'],
singleRun: true,
concurrency: Infinity,
coverageReporter: {
includeAllSources: true,
reporters: [
// generates ./coverage/lcov.info
{ type: 'lcovonly', subdir: '.' },
// generates ./coverage/coverage-final.json
{ type: 'json', subdir: '.' },
// generates HTML reports
{ type: 'html', dir: 'coverage/' }
]
},
customLaunchers: {
ChromeES6: {
base: 'Chrome',
flags: ['--javascript-harmony', '--no-sandbox']
}
}
})
}
|
var webpackConfig = require('./webpack.config');
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai'],
files: [
'test/**/*.ts'
],
mime: {
'text/x-typescript': ['ts', 'tsx']
},
exclude: [
],
preprocessors: {
'src/**/!(defaults)/*.js': ['coverage'],
'test/**/*.ts': ['webpack']
},
webpack: {
module: webpackConfig.module,
resolve: webpackConfig.resolve
},
reporters: ['progress', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['ChromeES6'],
singleRun: true,
concurrency: Infinity,
coverageReporter: {
includeAllSources: true,
reporters: [
// generates ./coverage/lcov.info
{ type: 'lcovonly', subdir: '.' },
// generates ./coverage/coverage-final.json
{ type: 'json', subdir: '.' },
// generates HTML reports
{ type: 'html', dir: 'coverage/' }
]
},
customLaunchers: {
ChromeES6: {
base: 'Chrome',
flags: ['--javascript-harmony', '--no-sandbox']
}
}
})
}
|
Add mime type option in karma file!
|
Add mime type option in karma file!
|
JavaScript
|
apache-2.0
|
proteus-h2020/proteic,proteus-h2020/proteic,proteus-h2020/proteus-charts,proteus-h2020/proteic
|
a551c502c03f0e324aa0765d36799f3c8305b2f2
|
app/utils/index.js
|
app/utils/index.js
|
const moment = require('moment');
export const dateFormat = (utcDate) => {
return moment(utcDate, 'YYYY-MM-DD hh:mm:ss z').format('LLL');
};
|
const moment = require('moment');
export const dateFormat = (utcDate) => {
return moment.utc(new Date(utcDate)).format('LLL');
};
|
Use Date function to help parse timezone.
|
Use Date function to help parse timezone.
|
JavaScript
|
mit
|
FuBoTeam/fubo-flea-market,FuBoTeam/fubo-flea-market
|
ec5401d64467628fa318a96363dcd4ae85ff1d98
|
get_languages.js
|
get_languages.js
|
var request = require('request');
var yaml = require('js-yaml');
module.exports = function (callback) {
var languagesURL = 'https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml';
request(languagesURL, function (error, response, body) {
var languages = yaml.safeLoad(body);
Object.keys(languages).forEach(function (languageName) {
languages[languageName] = languages[languageName].color;
});
if (!error && response.statusCode === 200) {
callback(languages);
} else {
callback(undefined);
}
});
};
|
var request = require('request');
var yaml = require('js-yaml');
module.exports = function (callback) {
var languagesURL = 'https://raw.githubusercontent.com/github/linguist/master/lib/linguist/languages.yml';
request(languagesURL, function (error, response, body) {
var languages = yaml.safeLoad(body);
Object.keys(languages).forEach(function (languageName) {
if (languages[languageName]) {
languages[languageName] = languages[languageName].color;
} else {
delete languages[languageName];
}
});
if (!error && response.statusCode === 200) {
callback(languages);
} else {
callback(undefined);
}
});
};
|
Remove languages that don't have colors
|
Remove languages that don't have colors
|
JavaScript
|
mit
|
nicolasmccurdy/language-colors,nicolasmccurdy/language-colors
|
e24f9da2e1b107767453a8693be90cfb97ebe76c
|
lib/index.js
|
lib/index.js
|
/**
* isUndefined
* Checks if a value is undefined or not.
*
* @name isUndefined
* @function
* @param {Anything} input The input value.
* @returns {Boolean} `true`, if the input is `undefined`, `false` otherwise.
*/
module.exports = function isUndefined(input) {
return typeof input === 'undefined';
};
|
"use strict";
/**
* isUndefined
* Checks if a value is undefined or not.
*
* @name isUndefined
* @function
* @param {Anything} input The input value.
* @returns {Boolean} `true`, if the input is `undefined`, `false` otherwise.
*/
let u = void 0;
module.exports = input => input === u;
|
Use void 0 to get the undefined value.
|
Use void 0 to get the undefined value.
|
JavaScript
|
mit
|
IonicaBizau/is-undefined
|
5aff66da9b38b94fe0e6b453ecb2678e0f743d8a
|
example/i18n/fr.js
|
example/i18n/fr.js
|
export const messages = {
post: {
name: 'Article',
all: 'Articles',
list: {
search: 'Recherche',
title: 'Titre',
published_at: 'Publié le',
commentable: 'Commentable',
views: 'Vues',
},
form: {
title: 'Titre',
published_at: 'Publié le',
teaser: 'Description',
body: 'Contenu',
average_note: 'Note moyenne',
allow_comments: 'Accepte les commentaires ?',
password: 'Mot de passe (si protégé)',
summary: 'Résumé',
miscellaneous: 'Extra',
nb_view: 'Nb de vues ?',
comments: 'Commentaires',
created_at: 'Créer le',
},
},
comment: {
name: 'Commentaire',
all: 'Commentaires',
form: {
body: 'Contenu',
created_at: 'Créer le',
author_name: 'Nom de l\'auteur',
},
},
author: {
name: 'Auteur',
list: {
name: 'Nom',
},
},
};
export default messages;
|
export const messages = {
post: {
name: 'Article',
all: 'Articles',
list: {
search: 'Recherche',
title: 'Titre',
published_at: 'Publié le',
commentable: 'Commentable',
views: 'Vues',
},
form: {
title: 'Titre',
published_at: 'Publié le',
teaser: 'Description',
body: 'Contenu',
average_note: 'Note moyenne',
allow_comments: 'Accepte les commentaires ?',
password: 'Mot de passe (si protégé)',
summary: 'Résumé',
miscellaneous: 'Extra',
nb_view: 'Nb de vues',
comments: 'Commentaires',
created_at: 'Créé le',
},
},
comment: {
name: 'Commentaire',
all: 'Commentaires',
form: {
body: 'Contenu',
created_at: 'Créé le',
author_name: 'Nom de l\'auteur',
},
},
author: {
name: 'Auteur',
list: {
name: 'Nom',
},
},
resources: {
comments: 'Commentaire |||| Commentaires'
}
};
export default messages;
|
Fix typos in French translation of the example
|
Fix typos in French translation of the example
|
JavaScript
|
mit
|
matteolc/admin-on-rest,matteolc/admin-on-rest,marmelab/admin-on-rest,marmelab/admin-on-rest
|
cbfb5044b5d16a826f98104f52c8588fffbfb6c0
|
src/deploy.spec.js
|
src/deploy.spec.js
|
import {describe, it} from 'mocha';
import {
assertThat, equalTo,
} from 'hamjest';
const toSrcDestPairs = (files, {sourcePath, destinationPath}) =>
files.map(file => ({
sourceFileName: file,
destinationFilename: file.replace(sourcePath, destinationPath)
}))
;
describe('Build src-dest pairs from file names', () => {
const sourcePath = '/src/path';
const destinationPath = '/dest/path';
const deps = {sourcePath, destinationPath};
const buildPairs = (files) =>
toSrcDestPairs(files, deps)
;
it('WHEN no file names given return empty pairs', () => {
const noFiles = [];
assertThat(buildPairs(noFiles), equalTo([]));
});
it('WHEN one file given, replace src path with dest path', () => {
const oneSrcFile = [`${sourcePath}/file.js`];
const onePair = [{
sourceFileName: `${sourcePath}/file.js`,
destinationFilename: `${destinationPath}/file.js`
}];
assertThat(buildPairs(oneSrcFile), equalTo(onePair));
});
});
|
import {describe, it} from 'mocha';
import {
assertThat, equalTo,
} from 'hamjest';
const toSrcDestPairs = (files, {sourcePath, destinationPath}) =>
files.map(file => ({
sourceFileName: file,
destinationFilename: file.replace(sourcePath, destinationPath)
}))
;
describe('Build src-dest pairs from file names', () => {
const sourcePath = '/src/path';
const destinationPath = '/dest/path';
const deps = {sourcePath, destinationPath};
const buildPairs = (files) =>
toSrcDestPairs(files, deps)
;
it('WHEN no file names given return empty pairs', () => {
const noFiles = [];
assertThat(buildPairs(noFiles), equalTo([]));
});
it('WHEN one file given, replace src path with dest path', () => {
const oneSrcFile = [`${sourcePath}/file.js`];
const onePair = [{
sourceFileName: `${sourcePath}/file.js`,
destinationFilename: `${destinationPath}/file.js`
}];
assertThat(buildPairs(oneSrcFile), equalTo(onePair));
});
it('WHEN many files given, replace src path with dest path', () => {
const manyFile = [
`${sourcePath}/file.js`,
`${sourcePath}/any/depth/file.js`,
];
const manyPairs = [
{sourceFileName: `${sourcePath}/file.js`, destinationFilename: `${destinationPath}/file.js`},
{sourceFileName: `${sourcePath}/any/depth/file.js`, destinationFilename: `${destinationPath}/any/depth/file.js`},
];
assertThat(buildPairs(manyFile), equalTo(manyPairs));
});
});
|
Write a (documenting) test that describes the "lots-case".
|
Write a (documenting) test that describes the "lots-case".
|
JavaScript
|
mit
|
tddbin/katas,tddbin/katas,tddbin/katas
|
e082e386adc50466d4c30a24dea8ce6a93b265b4
|
routes/admin/authenticated/sidebar/templates-list/page.connected.js
|
routes/admin/authenticated/sidebar/templates-list/page.connected.js
|
import { provideHooks } from 'redial'
import { connect } from 'react-redux'
import * as MobilizationActions from '~mobilizations/action-creators'
import * as MobilizationSelectors from '~mobilizations/selectors'
import * as TemplateActions from '~mobilizations/templates/action-creators'
import * as TemplateSelectors from '~mobilizations/templates/selectors'
import Page from './page'
const redial = {
fetch: ({ dispatch, getState, params }) => {
const state = getState()
const promises = []
!TemplateSelectors.isLoaded(state) && promises.push(
dispatch(TemplateActions.asyncFetch())
)
promises.push(dispatch(MobilizationActions.toggleMenu(undefined)))
return Promise.all(promises)
}
}
const mapStateToProps = state => ({
loading: TemplateSelectors.isLoading(state),
menuActiveIndex: MobilizationSelectors.getMenuActiveIndex(state),
mobilizationTemplates: TemplateSelectors.getCustomTemplates(state)
})
const mapActionCreatorsToProps = {
asyncDestroyTemplate: TemplateActions.asyncDestroyTemplate,
toggleMenu: MobilizationActions.toggleMenu
}
export default provideHooks(redial)(
connect(mapStateToProps, mapActionCreatorsToProps)(Page)
)
|
import { provideHooks } from 'redial'
import { connect } from 'react-redux'
import MobSelectors from '~client/mobrender/redux/selectors'
import { toggleMobilizationMenu } from '~client/mobrender/redux/action-creators'
import * as TemplateActions from '~mobilizations/templates/action-creators'
import * as TemplateSelectors from '~mobilizations/templates/selectors'
import Page from './page'
const redial = {
fetch: ({ dispatch, getState, params }) => {
const state = getState()
const promises = []
!TemplateSelectors.isLoaded(state) && promises.push(
dispatch(TemplateActions.asyncFetch())
)
promises.push(dispatch(toggleMobilizationMenu(undefined)))
return Promise.all(promises)
}
}
const mapStateToProps = state => ({
loading: TemplateSelectors.isLoading(state),
menuActiveIndex: MobSelectors(state).getMobilizationMenuActive(),
mobilizationTemplates: TemplateSelectors.getCustomTemplates(state)
})
const mapActionCreatorsToProps = {
asyncDestroyTemplate: TemplateActions.asyncDestroyTemplate,
toggleMenu: toggleMobilizationMenu
}
export default provideHooks(redial)(
connect(mapStateToProps, mapActionCreatorsToProps)(Page)
)
|
Fix menu in template list
|
Fix menu in template list
|
JavaScript
|
agpl-3.0
|
nossas/bonde-client,nossas/bonde-client,nossas/bonde-client
|
26325efdf4836d0eb44a4f987830c38562222cda
|
public/javascripts/app.js
|
public/javascripts/app.js
|
var app = angular.module("blogApp", []);
var posts = [];
app.config(function($routeProvider)
{
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'BlogCtrl'
})
.when('/post/:postId', {
templateUrl: 'views/post.html',
controller: 'PostCtrl'
})
.otherwise({
redirectTo: '/'
});
});
var socket = io.connect(window.location.origin);
socket.on('message', function(data)
{
switch(data.type)
{
default: break;
}
});
|
var app = angular.module("blogApp", []);
var posts = [];
app.config(function($routeProvider)
{
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'BlogCtrl'
})
.when('/post/:postId', {
templateUrl: 'views/post.html',
controller: 'PostCtrl'
})
.otherwise({
redirectTo: '/'
});
});
var host = location.origin.replace(/^http/, 'ws');
var socket = io.connect(host);
socket.on('message', function(data)
{
switch(data.type)
{
default: break;
}
});
|
Change for socket connection on Heroku
|
Change for socket connection on Heroku
|
JavaScript
|
mit
|
Somojojojo/blog
|
6621c6e7cc5fb3d62d8a5fabb08cf870b72ed5fe
|
lib/dropbox/index.js
|
lib/dropbox/index.js
|
'use strict';
var cp = require('child_process');
var child = cp.fork(__dirname + '/child.js');
var passport = require('passport');
var DropboxOAuth2Strategy = require('passport-dropbox-oauth2').Strategy;
var active = false;
module.exports = function (options) {
child.send({
options: options.dropbox
});
return {
initialize: function () {
active = true;
passport.use(new DropboxOAuth2Strategy({
clientID: options.dropbox.id,
clientSecret: options.dropbox.secret,
callbackURL: 'https://jsbin.dev/auth/dropbox/callback'
}, function (accessToken, refreshToken, profile, done) {
done(null, profile);
}
));
}
};
};
module.exports.saveBin = function (file, fileName, user) {
if (!active) {
return;
}
child.send({
file: file,
fileName: fileName,
user: user
});
};
|
'use strict';
var cp = require('child_process');
var child = cp.fork(__dirname + '/child.js');
var passport = require('passport');
var DropboxOAuth2Strategy = require('passport-dropbox-oauth2').Strategy;
var active = false;
module.exports = function (options) {
child.send({
options: options.dropbox
});
return {
initialize: function () {
active = true;
passport.use(new DropboxOAuth2Strategy({
clientID: options.dropbox.id,
clientSecret: options.dropbox.secret,
callbackURL: 'https://jsbin.dev/auth/dropbox/callback'
}, function (accessToken, refreshToken, profile, done) {
profile.access_token = accessToken;
done(null, profile);
}
));
}
};
};
module.exports.saveBin = function (file, fileName, user) {
if (!active) {
return;
}
child.send({
file: file,
fileName: fileName,
user: user
});
};
|
Add accessToken to profile before done
|
Add accessToken to profile before done
|
JavaScript
|
mit
|
svacha/jsbin,filamentgroup/jsbin,eggheadio/jsbin,late-warrior/jsbin,thsunmy/jsbin,pandoraui/jsbin,ilyes14/jsbin,digideskio/jsbin,saikota/jsbin,AverageMarcus/jsbin,fgrillo21/NPA-Exam,late-warrior/jsbin,peterblazejewicz/jsbin,juliankrispel/jsbin,francoisp/jsbin,ctide/jsbin,juliankrispel/jsbin,KenPowers/jsbin,mdo/jsbin,mingzeke/jsbin,dedalik/jsbin,jsbin/jsbin,IvanSanchez/jsbin,Freeformers/jsbin,jwdallas/jsbin,ilyes14/jsbin,vipulnsward/jsbin,arcseldon/jsbin,HeroicEric/jsbin,mingzeke/jsbin,digideskio/jsbin,jasonsanjose/jsbin-app,jamez14/jsbin,IvanSanchez/jsbin,yohanboniface/jsbin,saikota/jsbin,dennishu001/jsbin,jsbin/jsbin,ctide/jsbin,carolineartz/jsbin,arcseldon/jsbin,HeroicEric/jsbin,yize/jsbin,Hamcha/jsbin,johnmichel/jsbin,y3sh/jsbin-fork,pandoraui/jsbin,nitaku/jervis,fgrillo21/NPA-Exam,kentcdodds/jsbin,johnmichel/jsbin,peterblazejewicz/jsbin,knpwrs/jsbin,dennishu001/jsbin,filamentgroup/jsbin,vipulnsward/jsbin,kirjs/jsbin,eggheadio/jsbin,Hamcha/jsbin,KenPowers/jsbin,simonThiele/jsbin,francoisp/jsbin,mlucool/jsbin,dedalik/jsbin,roman01la/jsbin,yohanboniface/jsbin,blesh/jsbin,jwdallas/jsbin,jamez14/jsbin,kentcdodds/jsbin,jasonsanjose/jsbin-app,simonThiele/jsbin,thsunmy/jsbin,dhval/jsbin,IveWong/jsbin,mcanthony/jsbin,IveWong/jsbin,martinvd/jsbin,minwe/jsbin,yize/jsbin,fend-classroom/jsbin,dhval/jsbin,Freeformers/jsbin,roman01la/jsbin,AverageMarcus/jsbin,knpwrs/jsbin,y3sh/jsbin-fork,carolineartz/jsbin,mcanthony/jsbin,kirjs/jsbin,minwe/jsbin,KenPowers/jsbin,svacha/jsbin,martinvd/jsbin,mlucool/jsbin,knpwrs/jsbin,fend-classroom/jsbin,remotty/jsbin
|
bb9858b1edbc7f8fe7a2abd70110adb50055ff8c
|
lib/main.js
|
lib/main.js
|
import "es6-symbol";
import "weakmap";
import svgLoader from "./loader.js";
import Icon from "./components/Icon.js";
import Sprite from "./components/Sprite.js";
import Theme from "./components/Theme.js";
var callback = function callback() { };
const icons = Icon;
const initLoader = svgLoader;
// loads an external SVG file as sprite.
function load(loader, onFulfilled, onRejected) {
if (!onRejected) { onRejected = callback; }
if (typeof loader === "string") {
loader = svgLoader(loader);
} else if (!loader || !loader.request) {
onRejected(new TypeError("Invalid Request"));
}
loader.onSuccess = function(svg) {
make(svg, onFulfilled, onRejected);
};
loader.onFailure = function(e) {
onRejected(new TypeError(e));
};
loader.send();
}
function make(svg, onFulfilled, onRejected) {
var theme;
var autorun = false;
if (!onFulfilled) {
onFulfilled = callback;
autorun = true;
}
if (!onRejected) { onRejected = callback; }
try {
var sprite = new Sprite(svg);
theme = new Theme(sprite);
onFulfilled(theme);
if (autorun) {
theme.render();
}
} catch (e) {
onRejected(e);
}
}
export { icons, initLoader, load, make };
|
import "es6-symbol";
import "weakmap";
import svgLoader from "./loader.js";
import Icon from "./components/Icon.js";
import Sprite from "./components/Sprite.js";
import Theme from "./components/Theme.js";
var callback = function callback() { };
const icons = Icon;
const initLoader = svgLoader;
// loads an external SVG file as sprite.
function load(loader, onFulfilled, onRejected) {
if (!onRejected) { onRejected = callback; }
if (typeof loader === "string") {
loader = svgLoader(loader);
} else if (!loader || !loader.request) {
onRejected(new TypeError("Invalid Request"));
}
loader.onSuccess = function onSuccess(svg) {
make(svg, onFulfilled, onRejected);
};
loader.onFailure = function onFailure(e) {
onRejected(new TypeError(e));
};
loader.send();
}
function make(svg, onFulfilled, onRejected) {
var theme;
var autorun = false;
if (!onFulfilled) {
onFulfilled = callback;
autorun = true;
}
if (!onRejected) { onRejected = callback; }
try {
var sprite = new Sprite(svg);
theme = new Theme(sprite);
onFulfilled(theme);
if (autorun) {
theme.render();
}
} catch (e) {
onRejected(e);
}
}
export { icons, initLoader, load, make };
|
Update name of callback functions
|
Update name of callback functions
|
JavaScript
|
mit
|
vuzonp/uxon
|
0c44942fa439737c8adf26a2e196bbd700e18e66
|
R7.University.Employee/js/module.js
|
R7.University.Employee/js/module.js
|
$(function () {
// paint tables with dnnGrid classes
var table = ".employeeDetails #employeeDisciplines table";
$(table).addClass ("dnnGrid").css ("border-collapse", "collapse");
// use parent () to get rows with matched cell types
$(table + " tr:nth-child(even) td").parent ().addClass ("dnnGridItem");
$(table + " tr:nth-child(odd) td").parent ().addClass ("dnnGridAltItem");
// paint headers
$(table + " tr th").parent ().addClass ("dnnGridHeader").attr ("align", "left");
});
|
$(function () {
// paint tables with dnnGrid classes
var table = ".employeeDetails #employeeDisciplines table";
$(table).addClass ("dnnGrid").css ("border-collapse", "collapse");
// use parent () to get rows with matched cell types
$(table + " tr:nth-child(even) td").parent ().addClass ("dnnGridItem")
.next ().addClass ("dnnGridAltItem");
// paint headers
$(table + " tr th").parent ().addClass ("dnnGridHeader").attr ("align", "left");
});
|
Optimize & fix table painting script
|
Optimize & fix table painting script
|
JavaScript
|
agpl-3.0
|
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
|
ef259591d22d303c351b419f130b13061e28771a
|
app/native/src/types/Navigation.js
|
app/native/src/types/Navigation.js
|
// @flow
export type Navigation = {
navigate: (screen: string, parameters?: Object) => void,
state: {
params: Object,
},
};
|
// @flow
type NavigationStateParameters = Object;
/**
* @see https://reactnavigation.org/docs/navigators/navigation-prop
*/
export type Navigation = {
navigate: (routeName: string, parameters?: NavigationStateParameters) => void,
state: {
params: NavigationStateParameters,
},
setParams: (newParameters: NavigationStateParameters) => void,
goBack: () => void,
};
|
Improve Flow type of the navigation
|
Improve Flow type of the navigation
|
JavaScript
|
mit
|
mrtnzlml/native,mrtnzlml/native
|
1b6904a33c0f83eddf6c759ebe4243d54eb1f54f
|
app/services/resizeable-columns.js
|
app/services/resizeable-columns.js
|
import Ember from "ember";
const { $, inject, run } = Ember;
export default Ember.Service.extend({
fastboot: inject.service(),
init() {
this._super(...arguments);
if (!this.get('fastboot.isFastBoot')) {
this.setupMouseEventsFromIframe();
}
},
setupMouseEventsFromIframe() {
window.addEventListener('message', (m) => {
run(() => {
if(typeof m.data==='object' && 'mousemove' in m.data) {
let event = $.Event("mousemove", {
pageX: m.data.mousemove.pageX + $("#dummy-content-iframe").offset().left,
pageY: m.data.mousemove.pageY + $("#dummy-content-iframe").offset().top
});
$(window).trigger(event);
}
if(typeof m.data==='object' && 'mouseup' in m.data) {
let event = $.Event("mouseup", {
pageX: m.data.mouseup.pageX + $("#dummy-content-iframe").offset().left,
pageY: m.data.mouseup.pageY + $("#dummy-content-iframe").offset().top
});
$(window).trigger(event);
}
});
});
}
});
|
import Ember from "ember";
const { $, inject, run } = Ember;
export default Ember.Service.extend({
fastboot: inject.service(),
init() {
this._super(...arguments);
if (!this.get('fastboot.isFastBoot')) {
this.setupMouseEventsFromIframe();
}
},
handleMouseEvents(m, mouseEvent) {
const event = $.Event(mouseEvent, {
pageX: m.pageX + $("#dummy-content-iframe").offset().left,
pageY: m.pageY + $("#dummy-content-iframe").offset().top
});
$(window).trigger(event);
},
setupMouseEventsFromIframe() {
window.addEventListener('message', (m) => {
run(() => {
if(typeof m.data==='object' && 'mousemove' in m.data) {
this.handleMouseEvents(m.data.mousemove, 'mousemove');
}
if(typeof m.data==='object' && 'mouseup' in m.data) {
this.handleMouseEvents(m.data.mouseup, 'mousemove');
}
});
});
}
});
|
Refactor mouse events in resizeable columns
|
Refactor mouse events in resizeable columns
|
JavaScript
|
mit
|
ember-cli/ember-twiddle,ember-cli/ember-twiddle,Gaurav0/ember-twiddle,Gaurav0/ember-twiddle,knownasilya/ember-twiddle,knownasilya/ember-twiddle,knownasilya/ember-twiddle,ember-cli/ember-twiddle,Gaurav0/ember-twiddle
|
78874dcdad510e76c2ee6d47c6b0ac72073b3e7c
|
lib/loaders/index.js
|
lib/loaders/index.js
|
import loadersWithAuthentication from "./loaders_with_authentication"
import loadersWithoutAuthentication from "./loaders_without_authentication"
export default (accessToken, userID) => {
const loaders = loadersWithoutAuthentication()
if (accessToken) {
return Object.assign({}, loaders, loadersWithAuthentication(accessToken, userID))
}
return loaders
}
|
import loadersWithAuthentication from "./loaders_with_authentication"
import loadersWithoutAuthentication from "./loaders_without_authentication"
/**
* Creates a new set of data loaders for all routes. These should be created for each GraphQL query and passed to the
* `graphql` query execution function.
*
* Only if credentials are provided will the set include authenticated loaders, so before using an authenticated loader
* it would be wise to check if the loader is not in fact `undefined`.
*/
export default (accessToken, userID) => {
const loaders = loadersWithoutAuthentication()
if (accessToken) {
return Object.assign({}, loaders, loadersWithAuthentication(accessToken, userID))
}
return loaders
}
|
Add documentation for a bunch of functions.
|
[loaders] Add documentation for a bunch of functions.
|
JavaScript
|
mit
|
craigspaeth/metaphysics,mzikherman/metaphysics-1,artsy/metaphysics,artsy/metaphysics,craigspaeth/metaphysics,mzikherman/metaphysics-1,artsy/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1
|
9520ab1f9e7020879c8e3c2e8f6faad31fd572ef
|
Kwc/Shop/Box/Cart/Component.defer.js
|
Kwc/Shop/Box/Cart/Component.defer.js
|
var onReady = require('kwf/on-ready');
var $ = require('jQuery');
var getKwcRenderUrl = require('kwf/get-kwc-render-url');
onReady.onRender('.kwcClass',function(el) {
var url = getKwcRenderUrl();
$.each($('.kwfUp-addToCardForm .kwfUp-formContainer'), $.proxy(function(index, form) {
$(form).on('kwfUp-form-submitSuccess', $.proxy(function(event) {
$.ajax({
url: url,
data: { componentId: el.data('component-id') },
success: function(response) {
el.html(response);
onReady.callOnContentReady(el, {newRender: true});
}
});
}, el));
}, el));
}, { priority: 0 }); //call after Kwc.Form.Component
|
var onReady = require('kwf/on-ready');
var $ = require('jQuery');
var getKwcRenderUrl = require('kwf/get-kwc-render-url');
onReady.onRender('.kwcClass',function(el) {
var url = getKwcRenderUrl();
$.each($('.kwfUp-addToCardForm .kwfUp-formContainer'), $.proxy(function(index, form) {
$(form).on('kwfUp-form-submitSuccess', $.proxy(function(event) {
$.ajax({
url: url,
data: { componentId: el.data('component-id') },
success: function(response) {
$('.kwcClass').html(response);
onReady.callOnContentReady(el, {newRender: true});
}
});
}, el));
}, el));
}, { priority: 0 }); //call after Kwc.Form.Component
|
Fix wrong exchange of cartbox-domelement
|
Fix wrong exchange of cartbox-domelement
|
JavaScript
|
bsd-2-clause
|
koala-framework/koala-framework,koala-framework/koala-framework
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.