commit
stringlengths 40
40
| subject
stringlengths 1
1.49k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| new_contents
stringlengths 1
29.8k
| old_contents
stringlengths 0
9.9k
| lang
stringclasses 3
values | proba
float64 0
1
|
|---|---|---|---|---|---|---|---|
cdf2a558eec4b351d7742bf2a358f70a73ed21ad
|
Revert 334b408..8695551
|
src/app.js
|
src/app.js
|
/**
* Welcome to Pebble.js!
*
* This is where you write your app.
*/
var UI = require('ui');
// fake out configuration information for now
var exercises = [];
for (var i=0; i < 10; i++) {
var name = 'Exercise '+i;
exercises.push({
name: name,
starting: 100,
reps: 3,
increase: 5
});
}
function weightsString(exercise){
var weights = [];
for (var i=0; i<exercise.reps; i++){
weights.push(exercise.starting+i*exercise.increase);
}
return weights.join(', ');
}
// menu item for each exercise
var items = exercises.map(function(exercise){
return {
title: exercise.name,
subtitle: weightsString(exercise)
};
});
var main = new UI.Menu({
sections: [{
items: items
}]
});
main.on('select', function(e) {
var exercise = exercises[e.itemIndex];
var card = new UI.Card();
card.title(exercise.name);
card.subtitle(weightsString(exercise));
card.show();
});
main.show();
// main.on('click', 'up', function(e) {
// var menu = new UI.Menu({
// sections: [{
// items: [{
// title: 'Pebble.js',
// icon: 'images/menu_icon.png',
// subtitle: 'Can do Menus'
// }, {
// title: 'Second Item',
// subtitle: 'Subtitle Text'
// }]
// }]
// });
// menu.on('select', function(e) {
// console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
// console.log('The item is titled "' + e.item.title + '"');
// });
// menu.show();
// });
// main.on('click', 'select', function(e) {
// var wind = new UI.Window();
// var textfield = new UI.Text({
// position: new Vector2(0, 50),
// size: new Vector2(144, 30),
// font: 'gothic-24-bold',
// text: 'Text Anywhere!',
// textAlign: 'center'
// });
// wind.add(textfield);
// wind.show();
// });
// main.on('click', 'down', function(e) {
// var card = new UI.Card();
// card.title('A Card');
// card.subtitle('Is a Window');
// card.body('The simplest window type in Pebble.js.');
// card.show();
// });
|
/**
* Welcome to Pebble.js!
*
* This is where you write your app.
*/
var UI = require('ui');
// fake out configuration information for now
var exercises = [];
for (var i=0; i < 10; i++) {
var name = 'Exercise '+i;
var starting = 100;
exercises.push({
name: name,
reps: [starting, starting+5, starting+10]
});
}
// menu item for each exercise
var items = exercises.map(function(exercise){
return {
title: exercise.name,
subtitle: exercise.reps.join()
};
});
var main = new UI.Menu({
sections: [{
items: items
}]
});
main.on('select', function(e) {
var exercise = exercises[e.itemIndex];
var card = new UI.Card();
card.title(exercise.name);
card.subtitle(exercise.reps.join());
card.show();
});
main.show();
// main.on('click', 'up', function(e) {
// var menu = new UI.Menu({
// sections: [{
// items: [{
// title: 'Pebble.js',
// icon: 'images/menu_icon.png',
// subtitle: 'Can do Menus'
// }, {
// title: 'Second Item',
// subtitle: 'Subtitle Text'
// }]
// }]
// });
// menu.on('select', function(e) {
// console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
// console.log('The item is titled "' + e.item.title + '"');
// });
// menu.show();
// });
// main.on('click', 'select', function(e) {
// var wind = new UI.Window();
// var textfield = new UI.Text({
// position: new Vector2(0, 50),
// size: new Vector2(144, 30),
// font: 'gothic-24-bold',
// text: 'Text Anywhere!',
// textAlign: 'center'
// });
// wind.add(textfield);
// wind.show();
// });
// main.on('click', 'down', function(e) {
// var card = new UI.Card();
// card.title('A Card');
// card.subtitle('Is a Window');
// card.body('The simplest window type in Pebble.js.');
// card.show();
// });
|
JavaScript
| 0
|
83617243dd5d4c0156ba4cee3c43a6f03369fe7d
|
Use predefined "global" var in place of "this".
|
src/end.js
|
src/end.js
|
if ( typeof define === "function" && define.amd ) {
define(this.sn = sn);
} else if ( typeof module === "object" && module.exports ) {
module.exports = sn;
} else {
global.sn = sn;
}
}();
|
if ( typeof define === "function" && define.amd ) {
define(this.sn = sn);
} else if ( typeof module === "object" && module.exports ) {
module.exports = sn;
}
else this.sn = sn;
}();
|
JavaScript
| 0
|
d95e53c8ae63e8c32db4ab94a0db0055b913ee40
|
Update reason why micro.blog is skipped
|
test/remote.js
|
test/remote.js
|
import test from 'ava'
import Ajv from 'ajv'
import got from 'got'
import schema from '..'
const macro = (t, url) => {
return got(url, { json: true }).then(res => {
const valid = t.context.ajv.validate(schema, res.body)
t.true(valid, t.context.ajv.errorsText())
})
}
test.beforeEach(t => {
t.context.ajv = new Ajv()
})
test('shapeof.com', macro, 'http://shapeof.com/feed.json')
test('flyingmeat.com', macro, 'http://flyingmeat.com/blog/feed.json')
test('maybepizza.com', macro, 'http://maybepizza.com/feed.json')
test('daringfireball.net', macro, 'https://daringfireball.net/feeds/json')
test('hypercritical.co', macro, 'http://hypercritical.co/feeds/main.json')
test('inessential.com', macro, 'http://inessential.com/feed.json')
test('manton.org', macro, 'https://manton.org/feed/json')
// `author.url` sometimes is empty.
// See https://github.com/brentsimmons/JSONFeed/issues/35.
test.skip('micro.blog', macro, 'https://micro.blog/feeds/manton.json')
test('timetable.manton.org', macro, 'http://timetable.manton.org/feed.json')
test('therecord.co', macro, 'http://therecord.co/feed.json')
test('allenpike.com', macro, 'http://www.allenpike.com/feed.json')
|
import test from 'ava'
import Ajv from 'ajv'
import got from 'got'
import schema from '..'
const macro = (t, url) => {
return got(url, { json: true }).then(res => {
const valid = t.context.ajv.validate(schema, res.body)
t.true(valid, t.context.ajv.errorsText())
})
}
test.beforeEach(t => {
t.context.ajv = new Ajv()
})
test('shapeof.com', macro, 'http://shapeof.com/feed.json')
test('flyingmeat.com', macro, 'http://flyingmeat.com/blog/feed.json')
test('maybepizza.com', macro, 'http://maybepizza.com/feed.json')
test('daringfireball.net', macro, 'https://daringfireball.net/feeds/json')
test('hypercritical.co', macro, 'http://hypercritical.co/feeds/main.json')
test('inessential.com', macro, 'http://inessential.com/feed.json')
test('manton.org', macro, 'https://manton.org/feed/json')
// Item IDs are numbers instead of strings.
test.skip('micro.blog', macro, 'https://micro.blog/feeds/manton.json')
test('timetable.manton.org', macro, 'http://timetable.manton.org/feed.json')
test('therecord.co', macro, 'http://therecord.co/feed.json')
test('allenpike.com', macro, 'http://www.allenpike.com/feed.json')
|
JavaScript
| 0.000001
|
f46a57919e9d8ddbe48027abb497ebf9214d0aa9
|
support option '-i' and '--image' to specify rootfs image
|
bin/makerboard.js
|
bin/makerboard.js
|
#!/usr/bin/env node
/*
QEMU=`which qemu-mipsel-static`
if [ ! -x "$QEMU" ]; then
echo "No available QEMU utility can be used."
echo "Please install it with command:"
echo " sudo apt-get install qemu-user-static"
exit
fi
*/
var path = require('path');
var fs = require('fs');
var MakerBoard = require('../lib/makerboard');
var unzip = require('unzip2');
var yargs = require('yargs')
.usage('Usage: $0 <command> [options]')
.command('create', 'Create a new emulation environment')
.command('run', 'Run specific emulation')
.demand(1, 'require a valid command')
.help('help');
var argv = yargs.argv;
var command = argv._[0];
if (command === 'create') {
var argv = yargs.reset()
.usage('Usage: $0 create <path>')
.option('i', {
alias: 'image',
describe: 'specifying an image to be used',
type: 'string'
})
.nargs('i', 1)
.help('help')
.example('$0 create <path>', 'Create a new emulation environment')
.demand(2, 'require a valid path')
.argv;
var targetPath = argv._[1].toString();
function extract(fwPath, targetPath) {
console.log('Extracting ' + fwPath + '...');
// Extract filesystem
var extract = new MakerBoard.Extract();
extract.unsquashFS(fwPath, targetPath, function() {
// Initializing simulation
var container = new MakerBoard.Container();
container.initEnvironment(targetPath, function() {
console.log('Done');
});
});
}
if (fs.existsSync(argv.image)) {
extract(argv.image, targetPath);
return;
}
var firmwareUrl = 'https://s3-ap-southeast-1.amazonaws.com/mtk.linkit/openwrt-ramips-mt7688-root.squashfs';
var downloader = new MakerBoard.Downloader();
downloader.on('finished', function(fwPath) {
extract(fwPath, targetPath);
});
downloader.download(firmwareUrl, false, path.join(__dirname, '..', 'data'));
} else if (command === 'run') {
var argv = yargs.reset()
.usage('Usage: $0 run <path> [options]')
.help('help')
.example('$0 run <path>', 'Run specific emulation')
.demand(2, 'require a valid path')
.argv;
var targetPath = argv._[1].toString();
var container = new MakerBoard.Container();
container.run(targetPath, function() {
console.log('QUIT!');
});
} else {
yargs.showHelp();
}
|
#!/usr/bin/env node
/*
QEMU=`which qemu-mipsel-static`
if [ ! -x "$QEMU" ]; then
echo "No available QEMU utility can be used."
echo "Please install it with command:"
echo " sudo apt-get install qemu-user-static"
exit
fi
*/
var path = require('path');
var fs = require('fs');
var MakerBoard = require('../lib/makerboard');
var unzip = require('unzip2');
var yargs = require('yargs')
.usage('Usage: $0 <command> [options]')
.command('create', 'Create a new emulation environment')
.command('run', 'Run specific emulation')
.demand(1, 'require a valid command')
.help('help');
var argv = yargs.argv;
var command = argv._[0];
if (command === 'create') {
var argv = yargs.reset()
.usage('Usage: $0 create <path>')
.help('help')
.example('$0 create <path>', 'Create a new emulation environment')
.demand(2, 'require a valid path')
.argv;
var targetPath = argv._[1].toString();
var firmwareUrl = 'https://s3-ap-southeast-1.amazonaws.com/mtk.linkit/openwrt-ramips-mt7688-root.squashfs';
var downloader = new MakerBoard.Downloader();
downloader.on('finished', function(fwPath) {
console.log('Extracting ' + fwPath + '...');
// Extract filesystem
var extract = new MakerBoard.Extract();
extract.unsquashFS(fwPath, targetPath, function() {
// Initializing simulation
var container = new MakerBoard.Container();
container.initEnvironment(targetPath, function() {
console.log('Done');
});
});
});
downloader.download(firmwareUrl, false, path.join(__dirname, '..', 'data'));
} else if (command === 'run') {
var argv = yargs.reset()
.usage('Usage: $0 run <path>')
.help('help')
.example('$0 run <path>', 'Run specific emulation')
.demand(2, 'require a valid path')
.argv;
var targetPath = argv._[1].toString();
var container = new MakerBoard.Container();
container.run(targetPath, function() {
console.log('QUIT!');
});
} else {
yargs.showHelp();
}
|
JavaScript
| 0.000003
|
3a38e4aa5deb756f49054d85512342b2b209396f
|
Fix assertion in a bot method
|
src/bot.js
|
src/bot.js
|
'use strict';
const { expect } = require('code');
const Rx = require('rx-lite');
const Logger = require('./logger');
const logLevel = process.env.NODE_ENV === 'production' ? 'info' : 'debug';
const slackToken = process.env.SLACK_TOKEN;
class Bot {
constructor(controller) {
this._logger = new Logger(logLevel, ['slack-api']);
this._bot = controller
.spawn({ token: slackToken })
.startRTM((err, bot, payload) => {
if (err) {
throw new Error(`Error connecting to Slack: ${err}`);
}
this._logger.info('Connected to Slack');
});
}
getUsers() {
return Rx.Observable
.fromNodeCallback(this._bot.api.users.list)({})
.map(response => (response || {}).members)
.do(
users => {
this._logger.debug(`Got ${(users || []).length} users on the team`);
},
err => {
this._logger.error(`Failed to get users on the team: ${err}`);
}
);
}
getChannels() {
return Rx.Observable
.fromNodeCallback(this._bot.api.channels.list)({})
.map(response => (response || {}).channels)
.do(
channels => {
this._logger.debug(`Got ${(channels || []).length} channels on ' +
'the team`);
},
err => {
this._logger.error(`Failed to get channels on the team: ${err}`);
}
);
}
sayError(channel) {
return this.sayMessage({
channel,
text: 'Something went wrong. Please try again or contact @yenbekbay'
});
}
sayMessage(message) {
expect(message).to.be.an.object().and.to.include(['text', 'channel']);
return Rx.Observable
.fromNodeCallback(this._bot.say)(message)
.doOnError(err => this._logger
.error(`Failed to send a message to channel ${message.channel}: ${err}`)
);
}
}
module.exports = Bot;
|
'use strict';
const { expect } = require('code');
const Rx = require('rx-lite');
const Logger = require('./logger');
const logLevel = process.env.NODE_ENV === 'production' ? 'info' : 'debug';
const slackToken = process.env.SLACK_TOKEN;
class Bot {
constructor(controller) {
this._logger = new Logger(logLevel, ['slack-api']);
this._bot = controller
.spawn({ token: slackToken })
.startRTM((err, bot, payload) => {
if (err) {
throw new Error(`Error connecting to Slack: ${err}`);
}
this._logger.info('Connected to Slack');
});
}
getUsers() {
return Rx.Observable
.fromNodeCallback(this._bot.api.users.list)({})
.map(response => (response || {}).members)
.do(
users => {
this._logger.debug(`Got ${(users || []).length} users on the team`);
},
err => {
this._logger.error(`Failed to get users on the team: ${err}`);
}
);
}
getChannels() {
return Rx.Observable
.fromNodeCallback(this._bot.api.channels.list)({})
.map(response => (response || {}).channels)
.do(
channels => {
this._logger.debug(`Got ${(channels || []).length} channels on ' +
'the team`);
},
err => {
this._logger.error(`Failed to get channels on the team: ${err}`);
}
);
}
sayError(channel) {
return this.sayMessage({
channel,
text: 'Something went wrong. Please try again or contact @yenbekbay'
});
}
sayMessage(message) {
expect(message).to.be.an.object.and.to.include(['text', 'channel']);
return Rx.Observable
.fromNodeCallback(this._bot.say)(message)
.doOnError(err => this._logger
.error(`Failed to send a message to channel ${message.channel}: ${err}`)
);
}
}
module.exports = Bot;
|
JavaScript
| 0.001017
|
3edaf73ce8b9eddb926be3ca50c57097a587410e
|
Remove code for debugging Travis
|
test/shared.js
|
test/shared.js
|
import React from 'react';
import { mount } from 'enzyme';
import { createStore } from 'redux';
import Phone from '../dev-server/Phone';
import App from '../dev-server/containers/App';
import brandConfig from '../dev-server/brandConfig';
import version from '../dev-server/version';
import prefix from '../dev-server/prefix';
import state from './state.json';
const apiConfig = {
appKey: process.env.appKey,
appSecret: process.env.appSecret,
server: process.env.server,
};
export const getPhone = async () => {
const phone = new Phone({
apiConfig,
brandConfig,
prefix,
appVersion: version,
});
if (window.authData === null) {
await phone.client.service.platform().login({
username: process.env.username,
extension: process.env.extension,
password: process.env.password
});
window.authData = phone.client.service.platform().auth().data();
} else {
phone.client.service.platform().auth().setData(window.authData);
}
state.storage.status = 'module-initializing';
const store = createStore(phone.reducer, state);
phone.setStore(store);
return phone;
};
export const getWrapper = async () => {
const phone = await getPhone();
return mount(<App phone={phone} />);
};
export const getState = wrapper => wrapper.props().phone.store.getState();
export const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
|
import React from 'react';
import { mount } from 'enzyme';
import { createStore } from 'redux';
import Phone from '../dev-server/Phone';
import App from '../dev-server/containers/App';
import brandConfig from '../dev-server/brandConfig';
import version from '../dev-server/version';
import prefix from '../dev-server/prefix';
import state from './state.json';
console.info(process.env);
const apiConfig = {
appKey: process.env.appKey,
appSecret: process.env.appSecret,
server: process.env.server,
};
export const getPhone = async () => {
const phone = new Phone({
apiConfig,
brandConfig,
prefix,
appVersion: version,
});
if (window.authData === null) {
await phone.client.service.platform().login({
username: process.env.username,
extension: process.env.extension,
password: process.env.password
});
window.authData = phone.client.service.platform().auth().data();
} else {
phone.client.service.platform().auth().setData(window.authData);
}
state.storage.status = 'module-initializing';
const store = createStore(phone.reducer, state);
phone.setStore(store);
return phone;
};
export const getWrapper = async () => {
const phone = await getPhone();
return mount(<App phone={phone} />);
};
export const getState = wrapper => wrapper.props().phone.store.getState();
export const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
|
JavaScript
| 0.000038
|
95838bfb121b5a0c4ed38f7a1c8a910a0bf65285
|
Update simple.js
|
test/simple.js
|
test/simple.js
|
var assert = require('assert');
var global_variable = 'i am global';
describe('mocha runner', function () {
this.timeout(0);
var describe_variable = 'i am in describe';
before('Before all hook', function (done) {
console.info('before all');
//throw new Error('whatever');
done();
});
it('should start log', function (done) {
console.info('Hello');
done();
});
it('should throw', function () {
console.error(new Error('test#1'));
console.log('sgsdglknsldgnslkdgnlasgndl;asdgnlasdgnasldg0');
});
it('should return console log text and shows strings diff', function () {
console.info('test#string');
assert.equal('stringA', 'stringB');
});
it('should return console log text and shows date diff', function () {
console.info('test#date');
assert.equal(new Date(), new Date('01-01-2016'));
});
it('should return console log text and shows array diff', function () {
console.info('test#array');
assert.equal(['1', '2'], ['3', '2']);
});
it('should compare two objects', function () {
console.info('test#object');
var foo = {
'largestCities': [
'São Paulo',
'Buenos Aires',
'Rio de Janeiro',
'Lima',
'Bogotá'
],
'languages': [
'spanish',
'portuguese',
'english',
'dutch',
'french',
'quechua',
'guaraní',
'aimara',
'mapudungun'
]
};
var bar = {
'largestCities': [
'São Paulo',
'Buenos Aires',
'Rio de Janeiro',
'Lima',
'Bogotá'
],
'languages': [
'spanish',
'portuguese',
'inglés',
'dutch',
'french',
'quechua',
'guaraní',
'aimara',
'mapudungun'
]
};
assert.deepEqual(foo, bar);
});
it('should compare true and false', function () {
var foo = 5;
assert.equal(true, false);
});
describe('Handle console output deeper', function () {
it('should delay test and pass', function (done) {
console.info('test with delay');
assert.ok(true);
setTimeout(done, 1000);
});
});
describe('Handle console output1', function () {
it('should return console log text', function () {
console.info('test pass');
});
});
describe('Skip this', function () {
it.skip('should skip test', function () {
console.info('test skiped');
});
});
after('after this describe hook', function () {
console.info('after hook');
});
});
|
JavaScript
| 0.000001
|
|
3e20a04f3bc44dfea4a6e93fa3054c05e1f4b9d9
|
update email address
|
src/cli.js
|
src/cli.js
|
var program = require('commander');
var fs = require('fs');
var path = require('path');
var pjson = require('../package.json');
var colors = require('colors/safe');
var Runner = require('./runner');
program
.version(pjson.version)
.option('-c, --conf <config-file>', 'Path to Configuration File')
.parse(process.argv);
console.log(colors.bold('\nscreener-runner v' + pjson.version + '\n'));
if (!program.conf) {
console.error('--conf is a required argument. Type --help for more information.');
process.exit(1);
}
var configPath = path.resolve(process.cwd(), program.conf);
if (!fs.existsSync(configPath)) {
console.error('Config file path "' + program.conf + '" cannot be found.');
process.exit(1);
}
var config = require(configPath);
if (config === false) {
console.log('Config is false. Exiting...');
process.exit();
}
Runner.run(config)
.then(function(response) {
console.log(response);
process.exit();
})
.catch(function(err) {
console.error(err.message || err.toString());
if (typeof err.annotate === 'function') {
console.error('Annotated Error Details:');
console.error(err.annotate());
}
console.error('---');
console.error('Exiting Screener Runner');
console.error('Need help? Contact: [email protected]');
var exitCode = 1;
if (config && typeof config.failureExitCode === 'number' && config.failureExitCode > 0) {
exitCode = config.failureExitCode;
}
process.exit(exitCode);
});
|
var program = require('commander');
var fs = require('fs');
var path = require('path');
var pjson = require('../package.json');
var colors = require('colors/safe');
var Runner = require('./runner');
program
.version(pjson.version)
.option('-c, --conf <config-file>', 'Path to Configuration File')
.parse(process.argv);
console.log(colors.bold('\nscreener-runner v' + pjson.version + '\n'));
if (!program.conf) {
console.error('--conf is a required argument. Type --help for more information.');
process.exit(1);
}
var configPath = path.resolve(process.cwd(), program.conf);
if (!fs.existsSync(configPath)) {
console.error('Config file path "' + program.conf + '" cannot be found.');
process.exit(1);
}
var config = require(configPath);
if (config === false) {
console.log('Config is false. Exiting...');
process.exit();
}
Runner.run(config)
.then(function(response) {
console.log(response);
process.exit();
})
.catch(function(err) {
console.error(err.message || err.toString());
if (typeof err.annotate === 'function') {
console.error('Annotated Error Details:');
console.error(err.annotate());
}
console.error('---');
console.error('Exiting Screener Runner');
console.error('Need help? Contact: [email protected]');
var exitCode = 1;
if (config && typeof config.failureExitCode === 'number' && config.failureExitCode > 0) {
exitCode = config.failureExitCode;
}
process.exit(exitCode);
});
|
JavaScript
| 0.000001
|
e10198543eb2d6ee8764784b44b92187eceb4b1d
|
Update path to compare page
|
src/cli.js
|
src/cli.js
|
#!/usr/bin/env node
import 'babel-polyfill';
import commander from 'commander';
import { getPreviousSha, setPreviousSha } from './previousSha';
import constructReport from './constructReport';
import createDynamicEntryPoint from './createDynamicEntryPoint';
import createWebpackBundle from './createWebpackBundle';
import getSha from './getSha';
import loadCSSFile from './loadCSSFile';
import loadUserConfig from './loadUserConfig';
import packageJson from '../package.json';
import processSnapsInBundle from './processSnapsInBundle';
import uploadReport from './uploadReport';
commander
.version(packageJson.version)
.usage('[options] <regexForTestName>')
.parse(process.argv);
const {
apiKey,
apiSecret,
setupScript,
webpackLoaders,
stylesheets = [],
include = '**/@(*-snaps|snaps).@(js|jsx)',
targets = {},
//viewerEndpoint = 'http://localhost:4432',
viewerEndpoint = 'https://happo.now.sh',
} = loadUserConfig();
// const previewServer = new PreviewServer();
// previewServer.start();
(async function() {
const sha = await getSha();
const previousSha = getPreviousSha();
console.log('Generating entry point...');
const entryFile = await createDynamicEntryPoint({ setupScript, include });
console.log('Producing bundle...');
const bundleFile = await createWebpackBundle(entryFile, { webpackLoaders });
const cssBlocks = await Promise.all(stylesheets.map(loadCSSFile));
console.log('Executing bundle...');
const snapPayloads = await processSnapsInBundle(bundleFile, {
globalCSS: cssBlocks.join('').replace(/\n/g, ''),
});
console.log('Generating screenshots...');
const results = await Promise.all(Object.keys(targets).map(async (name) => {
const target = targets[name];
const result = await target.execute(snapPayloads);
return {
name,
result,
};
}));
const snaps = await constructReport(results);
await uploadReport({
snaps,
sha,
endpoint: viewerEndpoint,
apiKey,
apiSecret,
});
setPreviousSha(sha);
if (previousSha) {
console.log(`${viewerEndpoint}/compare?q=${previousSha}..${sha}`);
} else {
console.log('No previous report found');
}
})();
|
#!/usr/bin/env node
import 'babel-polyfill';
import commander from 'commander';
import { getPreviousSha, setPreviousSha } from './previousSha';
import constructReport from './constructReport';
import createDynamicEntryPoint from './createDynamicEntryPoint';
import createWebpackBundle from './createWebpackBundle';
import getSha from './getSha';
import loadCSSFile from './loadCSSFile';
import loadUserConfig from './loadUserConfig';
import packageJson from '../package.json';
import processSnapsInBundle from './processSnapsInBundle';
import uploadReport from './uploadReport';
commander
.version(packageJson.version)
.usage('[options] <regexForTestName>')
.parse(process.argv);
const {
apiKey,
apiSecret,
setupScript,
webpackLoaders,
stylesheets = [],
include = '**/@(*-snaps|snaps).@(js|jsx)',
targets = {},
//viewerEndpoint = 'http://localhost:4432',
viewerEndpoint = 'https://happo.now.sh',
} = loadUserConfig();
// const previewServer = new PreviewServer();
// previewServer.start();
(async function() {
const sha = await getSha();
const previousSha = getPreviousSha();
console.log('Generating entry point...');
const entryFile = await createDynamicEntryPoint({ setupScript, include });
console.log('Producing bundle...');
const bundleFile = await createWebpackBundle(entryFile, { webpackLoaders });
const cssBlocks = await Promise.all(stylesheets.map(loadCSSFile));
console.log('Executing bundle...');
const snapPayloads = await processSnapsInBundle(bundleFile, {
globalCSS: cssBlocks.join('').replace(/\n/g, ''),
});
console.log('Generating screenshots...');
const results = await Promise.all(Object.keys(targets).map(async (name) => {
const target = targets[name];
const result = await target.execute(snapPayloads);
return {
name,
result,
};
}));
const snaps = await constructReport(results);
await uploadReport({
snaps,
sha,
endpoint: viewerEndpoint,
apiKey,
apiSecret,
});
setPreviousSha(sha);
if (previousSha) {
console.log(`${viewerEndpoint}/report?q=${previousSha}..${sha}`);
} else {
console.log('No previous report found');
}
})();
|
JavaScript
| 0
|
401c01ad7684bc9451a2987d9a19269a1f9ec2ec
|
fix English grammar in CLI output when there's only 1 file
|
src/cli.js
|
src/cli.js
|
#!/usr/bin/env node
/*eslint-env node */
/*eslint no-process-exit: 0 */
'use strict';
var fs = require('fs');
var glob = require('glob');
var bootlint = require('./bootlint.js');
var totalErrCount = 0;
var totalFileCount = 0;
var disabledIds = [];
var patterns = process.argv.slice(2);
patterns.forEach(function (pattern) {
var filenames = glob.sync(pattern);
filenames.forEach(function (filename) {
var reporter = function (lint) {
console.log(filename + ":", lint.id, lint.message);
totalErrCount++;
};
var html = null;
try {
html = fs.readFileSync(filename, {encoding: 'utf8'});
}
catch (err) {
console.log(filename + ":", err);
return;
}
bootlint.lintHtml(html, reporter, disabledIds);
totalFileCount++;
});
});
console.log("" + totalErrCount + " lint error(s) found across " + totalFileCount + " file(s).");
if (totalErrCount) {
process.exit(1);
}
|
#!/usr/bin/env node
/*eslint-env node */
/*eslint no-process-exit: 0 */
'use strict';
var fs = require('fs');
var glob = require('glob');
var bootlint = require('./bootlint.js');
var totalErrCount = 0;
var totalFileCount = 0;
var disabledIds = [];
var patterns = process.argv.slice(2);
patterns.forEach(function (pattern) {
var filenames = glob.sync(pattern);
filenames.forEach(function (filename) {
var reporter = function (lint) {
console.log(filename + ":", lint.id, lint.message);
totalErrCount++;
};
var html = null;
try {
html = fs.readFileSync(filename, {encoding: 'utf8'});
}
catch (err) {
console.log(filename + ":", err);
return;
}
bootlint.lintHtml(html, reporter, disabledIds);
totalFileCount++;
});
});
console.log("" + totalErrCount + " lint error(s) found across " + totalFileCount + " files.");
if (totalErrCount) {
process.exit(1);
}
|
JavaScript
| 0.000042
|
109561225a43b1f487c09a2acf84d955892d5c37
|
add async harness to CRL
|
src/crl.js
|
src/crl.js
|
(function(){
/*
CRL (Cor Runtime Library)
*/
var
hasProp = Object.prototype.hasOwnProperty,
slice = Array.prototype.slice;
CRL = (typeof CRL === 'undefined' ? {} : CRL);
CRL.idSeed = 1;
CRL.instancers = [];
CRL.nativeTypes = {
'String' : String,
'Number' : Number,
'Boolean' : Boolean,
'RegExp' : RegExp,
'Array' : Array,
'Object' : Object,
'Function' : Function
};
CRL.copyObj = function copyObj(from, to, strict) {
var name;
if (strict) {
for (name in from) {
if (hasProp.call(from, name)) {
to[name] = from[name];
}
}
}
else {
for (name in from) {
to[name] = from[name];
}
}
return to;
};
CRL.create = function create(Class) {
var
instancerArgs,
args = slice.call(arguments, 1),
argc = args.length,
i = -1,
instancer = this.instancers[argc];
if (! instancer) {
instancerArgs = [];
while (++i < argc) {
instancerArgs.push('args[' + i + ']');
}
this.instancers[argc] = instancer = new Function('cls', 'args', 'return new cls(' + instancerArgs.join(',') + ');');
}
if (typeof Class === 'function') {
return instancer(Class, args);
}
throw Error('Runtime Error: trying to instanstiate no class');
};
CRL.extend = function extend(Cls, baseCls) {
CRL.copyObj(baseCls, Cls, true);
function Proto() {
this.constructor = Cls;
}
Proto.prototype = baseCls.prototype;
Cls.prototype = new Proto();
}
CRL.keys = function keys(obj) {
var keys, i, len;
if (obj instanceof Array) {
i = -1;
len = obj.length;
keys = [];
while (++i < len) {
keys.push(i);
}
}
else {
if (typeof Object.keys === 'function') {
keys = Object.keys(obj);
}
else {
for (i in obj) {
if (hasProp.call(obj, i)) {
keys.push(i);
}
}
}
}
return keys;
};
CRL.assertType = function assertType(obj, Class) {
var type;
// Class is a Class?
if (typeof Class === 'function') {
// object is defined?
if (typeof obj !== 'undefined') {
if (obj instanceof Class) {
return true;
}
// otherwise find the native type according to "Object.prototype.toString"
else {
type = Object.prototype.toString.call(obj);
type = type.substring(8, type.length - 1);
if(hasProp.call(this.nativeTypes, type) && this.nativeTypes[type] === Class) {
return true;
}
}
}
else {
throw 'Trying to assert undefined object';
}
}
else {
throw 'Trying to assert undefined class';
}
return false;
};
// Schedule
function schedule(fn, time) {
if (time === void 0 && typeof global.setImmediate !== 'undefined') {
setImmediate(fn);
} else {
setTimeout(fn, +time);
}
}
// Breakpoint
function Breakpoint(timeout) {
var me = this;
if (!isNaN(me.timeout)) {
schedule(function(){ me.resume() }, timeout);
}
this.resumed = false;
}
Breakpoint.prototype = {
resume: function(value, err) {
this.resumed = true;
if (this.doneListeners) {
this.doneListeners.forEach(function(listener){
listener(val, err);
});
}
},
done: function(fn) {
if (! this.doneListeners) { this.doneListeners = [] }
this.doneListeners.push(fn);
return this;
}
};
Breakpoint.resumeAll = function(array, withValue) {
while (array.length) {
array.shift().resume(withValue);
}
}
function isBreakpoint(b) {
return b instanceof Breakpoint;
}
CRL.Breakpoint = Breakpoint;
// Generator Runner
CRL.go = function go(genf, ctx) {
var state,
gen = genf.apply(ctx);
next(gen);
function next(gen, value) {
state = gen.next(value);
value = state.value;
if (isBreakpoint(value)) {
value.done(function(value) {
next(value)
})
}
if (! state.done) {
next(gen, value)
}
}
}
})();
|
(function(){
/*
CRL (Cor Runtime Library)
*/
var
hasProp = Object.prototype.hasOwnProperty,
slice = Array.prototype.slice;
CRL = (typeof CRL === 'undefined' ? {} : CRL);
CRL.idSeed = 1;
CRL.instancers = [];
CRL.nativeTypes = {
'String' : String,
'Number' : Number,
'Boolean' : Boolean,
'RegExp' : RegExp,
'Array' : Array,
'Object' : Object,
'Function' : Function
};
CRL.copyObj = function copyObj(from, to, strict) {
var name;
if (strict) {
for (name in from) {
if (hasProp.call(from, name)) {
to[name] = from[name];
}
}
}
else {
for (name in from) {
to[name] = from[name];
}
}
return to;
};
CRL.create = function create(Class) {
var
instancerArgs,
args = slice.call(arguments, 1),
argc = args.length,
i = -1,
instancer = this.instancers[argc];
if (! instancer) {
instancerArgs = [];
while (++i < argc) {
instancerArgs.push('args[' + i + ']');
}
this.instancers[argc] = instancer = new Function('cls', 'args', 'return new cls(' + instancerArgs.join(',') + ');');
}
if (typeof Class === 'function') {
return instancer(Class, args);
}
throw Error('Runtime Error: trying to instanstiate no class');
};
CRL.extend = function extend(Cls, baseCls) {
CRL.copyObj(baseCls, Cls, true);
function Proto() {
this.constructor = Cls;
}
Proto.prototype = baseCls.prototype;
Cls.prototype = new Proto();
}
CRL.keys = function keys(obj) {
var keys, i, len;
if (obj instanceof Array) {
i = -1;
len = obj.length;
keys = [];
while (++i < len) {
keys.push(i);
}
}
else {
if (typeof Object.keys === 'function') {
keys = Object.keys(obj);
}
else {
for (i in obj) {
if (hasProp.call(obj, i)) {
keys.push(i);
}
}
}
}
return keys;
};
CRL.assertType = function assertType(obj, Class) {
var type;
// Class is a Class?
if (typeof Class === 'function') {
// object is defined?
if (typeof obj !== 'undefined') {
if (obj instanceof Class) {
return true;
}
// otherwise find the native type according to "Object.prototype.toString"
else {
type = Object.prototype.toString.call(obj);
type = type.substring(8, type.length - 1);
if(hasProp.call(this.nativeTypes, type) && this.nativeTypes[type] === Class) {
return true;
}
}
}
else {
throw 'Trying to assert undefined object';
}
}
else {
throw 'Trying to assert undefined class';
}
return false;
};
CRL.go = function go(gen) {
return gen;
}
})();
|
JavaScript
| 0.000001
|
6f70f049f5e5e4a98eb38352d8f278fa8d77132f
|
Correct use of `commander` for parsing CLI options
|
bin/thoughtful.js
|
bin/thoughtful.js
|
#!/usr/bin/env node
/*!
* thoughtful-release <https://github.com/nknapp/thoughtful-release>
*
* Copyright (c) 2015 Nils Knappmeier.
* Released under the MIT license.
*/
'use strict'
var program = require('commander')
program
.version(require('../package').version)
.command('changelog <release>')
.description('update the CHANGELOG.md of the module in the current directory')
.option('<release>', 'The target release of the changelog (same as for "npm version")')
.action((release) => {
console.log('Updating changelog')
require('../index.js').updateChangelog(process.cwd(), release).done(console.log)
})
program.parse(process.argv)
if (process.argv.length === 2) {
// No args provided: Display help
program.outputHelp()
}
|
#!/usr/bin/env node
/*!
* thoughtful-release <https://github.com/nknapp/thoughtful-release>
*
* Copyright (c) 2015 Nils Knappmeier.
* Released under the MIT license.
*/
'use strict'
var program = require('commander')
program
.version(require('../package').version)
.command('changelog <release>', 'update the CHANGELOG.md of the module in the current directory')
.option('<release>', 'The target release of the changelog (same as for "npm version")')
.action((release) => {
console.log('Updating changelog')
require('../index.js').updateChangelog(process.cwd(), release).done(console.log)
})
program.parse(process.argv)
|
JavaScript
| 0
|
3f7c7299380b8aa138eaeb5d31d10636a57e37ca
|
Update basic.js
|
tests/basic.js
|
tests/basic.js
|
"use strict";
// this is a test
const assert = require('chai').assert;
describe("geek value equals 42", () => {
let geek = 42;
it("should return 42", () => {
assert.equal(geek, 32)
});
});
|
"use strict";
// this is a test
const assert = require('chai').assert;
describe("geek value equals 42", () => {
let geek = 42;
it("should return 42", () => {
assert.equal(geek, 42)
});
});
|
JavaScript
| 0.000001
|
a04ca40a1073392c35ff64b2a75bc6fe19cf88fa
|
add createTemplateElement
|
src/dom.js
|
src/dom.js
|
import {_FEATURE} from './feature';
let shadowPoly = window.ShadowDOMPolyfill || null;
/**
* Represents the core APIs of the DOM.
*/
export const _DOM = {
Element: Element,
SVGElement: SVGElement,
boundary: 'aurelia-dom-boundary',
addEventListener(eventName: string, callback: Function, capture?: boolean): void {
document.addEventListener(eventName, callback, capture);
},
removeEventListener(eventName: string, callback: Function, capture?: boolean): void {
document.removeEventListener(eventName, callback, capture);
},
adoptNode(node: Node) {
return document.adoptNode(node, true);//TODO: what is does the true mean? typo?
},
createAttribute(name: string): Attr {
return document.createAttribute(name);
},
createElement(tagName: string): Element {
return document.createElement(tagName);
},
createTextNode(text) {
return document.createTextNode(text);
},
createComment(text) {
return document.createComment(text);
},
createDocumentFragment(): DocumentFragment {
return document.createDocumentFragment();
},
createTemplateElement(): HTMLTemplateElement {
let template = document.createElement('template');
return _FEATURE.ensureHTMLTemplateElement(template);
},
createMutationObserver(callback: Function): MutationObserver {
return new (window.MutationObserver || window.WebKitMutationObserver)(callback);
},
createCustomEvent(eventType: string, options: Object): CustomEvent {
return new window.CustomEvent(eventType, options);
},
dispatchEvent(evt): void {
document.dispatchEvent(evt);
},
getComputedStyle(element: Element) {
return window.getComputedStyle(element);
},
getElementById(id: string): Element {
return document.getElementById(id);
},
querySelectorAll(query: string) {
return document.querySelectorAll(query);
},
nextElementSibling(element: Node): Element {
if (element.nextElementSibling) { return element.nextElementSibling; }
do { element = element.nextSibling; }
while (element && element.nodeType !== 1);
return element;
},
createTemplateFromMarkup(markup: string): Element {
let parser = document.createElement('div');
parser.innerHTML = markup;
let temp = parser.firstElementChild;
if (!temp || temp.nodeName !== 'TEMPLATE') {
throw new Error('Template markup must be wrapped in a <template> element e.g. <template> <!-- markup here --> </template>');
}
return _FEATURE.ensureHTMLTemplateElement(temp);
},
appendNode(newNode: Node, parentNode?: Node): void {
(parentNode || document.body).appendChild(newNode);
},
replaceNode(newNode: Node, node: Node, parentNode?: Node): void {
if (node.parentNode) {
node.parentNode.replaceChild(newNode, node);
} else if (shadowPoly !== null) { //HACK: IE template element and shadow dom polyfills not quite right...
shadowPoly.unwrap(parentNode).replaceChild(
shadowPoly.unwrap(newNode),
shadowPoly.unwrap(node)
);
} else { //HACK: same as above
parentNode.replaceChild(newNode, node);
}
},
removeNode(node: Node, parentNode?: Node): void {
if (node.parentNode) {
node.parentNode.removeChild(node);
} else if (parentNode) {
if (shadowPoly !== null) { //HACK: IE template element and shadow dom polyfills not quite right...
shadowPoly.unwrap(parentNode).removeChild(shadowPoly.unwrap(node));
} else { //HACK: same as above
parentNode.removeChild(node);
}
}
},
injectStyles(styles: string, destination?: Element, prepend?: boolean): Node {
let node = document.createElement('style');
node.innerHTML = styles;
node.type = 'text/css';
destination = destination || document.head;
if (prepend && destination.childNodes.length > 0) {
destination.insertBefore(node, destination.childNodes[0]);
} else {
destination.appendChild(node);
}
return node;
}
};
|
import {_FEATURE} from './feature';
let shadowPoly = window.ShadowDOMPolyfill || null;
/**
* Represents the core APIs of the DOM.
*/
export const _DOM = {
Element: Element,
SVGElement: SVGElement,
boundary: 'aurelia-dom-boundary',
addEventListener(eventName: string, callback: Function, capture?: boolean): void {
document.addEventListener(eventName, callback, capture);
},
removeEventListener(eventName: string, callback: Function, capture?: boolean): void {
document.removeEventListener(eventName, callback, capture);
},
adoptNode(node: Node) {
return document.adoptNode(node, true);//TODO: what is does the true mean? typo?
},
createAttribute(name: string): Attr {
return document.createAttribute(name);
},
createElement(tagName: string): Element {
return document.createElement(tagName);
},
createTextNode(text) {
return document.createTextNode(text);
},
createComment(text) {
return document.createComment(text);
},
createDocumentFragment(): DocumentFragment {
return document.createDocumentFragment();
},
createMutationObserver(callback: Function): MutationObserver {
return new (window.MutationObserver || window.WebKitMutationObserver)(callback);
},
createCustomEvent(eventType: string, options: Object): CustomEvent {
return new window.CustomEvent(eventType, options);
},
dispatchEvent(evt): void {
document.dispatchEvent(evt);
},
getComputedStyle(element: Element) {
return window.getComputedStyle(element);
},
getElementById(id: string): Element {
return document.getElementById(id);
},
querySelectorAll(query: string) {
return document.querySelectorAll(query);
},
nextElementSibling(element: Node): Element {
if (element.nextElementSibling) { return element.nextElementSibling; }
do { element = element.nextSibling; }
while (element && element.nodeType !== 1);
return element;
},
createTemplateFromMarkup(markup: string): Element {
let parser = document.createElement('div');
parser.innerHTML = markup;
let temp = parser.firstElementChild;
if (!temp || temp.nodeName !== 'TEMPLATE') {
throw new Error('Template markup must be wrapped in a <template> element e.g. <template> <!-- markup here --> </template>');
}
return _FEATURE.ensureHTMLTemplateElement(temp);
},
appendNode(newNode: Node, parentNode?: Node): void {
(parentNode || document.body).appendChild(newNode);
},
replaceNode(newNode: Node, node: Node, parentNode?: Node): void {
if (node.parentNode) {
node.parentNode.replaceChild(newNode, node);
} else if (shadowPoly !== null) { //HACK: IE template element and shadow dom polyfills not quite right...
shadowPoly.unwrap(parentNode).replaceChild(
shadowPoly.unwrap(newNode),
shadowPoly.unwrap(node)
);
} else { //HACK: same as above
parentNode.replaceChild(newNode, node);
}
},
removeNode(node: Node, parentNode?: Node): void {
if (node.parentNode) {
node.parentNode.removeChild(node);
} else if (parentNode) {
if (shadowPoly !== null) { //HACK: IE template element and shadow dom polyfills not quite right...
shadowPoly.unwrap(parentNode).removeChild(shadowPoly.unwrap(node));
} else { //HACK: same as above
parentNode.removeChild(node);
}
}
},
injectStyles(styles: string, destination?: Element, prepend?: boolean): Node {
let node = document.createElement('style');
node.innerHTML = styles;
node.type = 'text/css';
destination = destination || document.head;
if (prepend && destination.childNodes.length > 0) {
destination.insertBefore(node, destination.childNodes[0]);
} else {
destination.appendChild(node);
}
return node;
}
};
|
JavaScript
| 0.000001
|
ffc727e7806f896ff445bbe31dec25549e217722
|
add id selector
|
src/dom.js
|
src/dom.js
|
import { toArray } from "./util";
export function $(selector, el = document) {
return el.querySelector(selector);
}
export function $$(selector, el = document) {
return toArray(el.querySelectorAll(selector));
}
export function id(name, el = document) {
return el.getElementById(name);
}
export function replace(el_old, el_new) {
el_old.parentNode.replaceChild(el_new, el_old);
return el_new;
}
export function index(el) {
let idx = 0;
while(el = el.previousElementSibling) idx++;
return idx;
}
export function remove(el) {
el.parentNode && el.parentNode.removeChild(el);
return el;
}
export function addClass(el, clazz) {
el.classList.add(clazz);
return el;
}
export function toggleClass(el, clazz, force = false) {
el.classList.toggle(clazz, force);
return el;
}
export function removeClass(el, clazz) {
el.classList.remove(clazz);
return el;
}
export function getAttr(el, name, _default = undefined) {
return el && el.hasAttribute(name) ? el.getAttribute(name) : _default;
}
export function setAttr(el, name, value, append = false) {
const attrValue = append ? getAttr(el, name, "") + " " + value : value;
el.setAttribute(name, attrValue);
return el;
}
export function hasAttr(el, name) {
return el && el.hasAttribute(name);
}
export function component(name, init, opts = {}) {
function parseConfig(el) {
const confMatcher = new RegExp(`data-(?:component|${name})-([^-]+)`, "i");
const defaultConf = {};
toArray(el.attributes).forEach(attr => {
const match = confMatcher.exec(attr.name);
if(confMatcher.test(attr.name)) {
defaultConf[match[1]] = attr.value;
}
});
try {
const conf = JSON.parse(el.getAttribute("data-component-conf"));
return Object.assign(defaultConf, conf);
} catch(e) {
return defaultConf;
}
}
opts = opts instanceof HTMLElement ? { root: opts } : opts;
return $$(`[data-component~="${name}"]`, opts.root || document)
.filter(el => !el.hasAttribute("data-component-ready"))
.map((el, index) => {
const def = el.getAttribute("data-component").split(" ");
const conf = Object.assign({}, init.DEFAULTS || {}, opts.conf || {}, parseConfig(el));
const options = {
index, conf,
is_type(type) {
return def.indexOf(`${name}-${type}`) !== -1;
}
};
const component = init(el, options);
setAttr(el, "data-component-ready", name, true);
return component;
});
}
export default {
replace, index, remove,
$, $$, id, component,
addClass, toggleClass, removeClass,
getAttr, setAttr, hasAttr
}
|
import { toArray } from "./util";
export function $(selector, el = document) {
return el.querySelector(selector);
}
export function $$(selector, el = document) {
return toArray(el.querySelectorAll(selector));
}
export function replace(el_old, el_new) {
el_old.parentNode.replaceChild(el_new, el_old);
return el_new;
}
export function index(el) {
let idx = 0;
while(el = el.previousElementSibling) idx++;
return idx;
}
export function remove(el) {
el.parentNode && el.parentNode.removeChild(el);
return el;
}
export function addClass(el, clazz) {
el.classList.add(clazz);
return el;
}
export function toggleClass(el, clazz, force = false) {
el.classList.toggle(clazz, force);
return el;
}
export function removeClass(el, clazz) {
el.classList.remove(clazz);
return el;
}
export function getAttr(el, name, _default = undefined) {
return el && el.hasAttribute(name) ? el.getAttribute(name) : _default;
}
export function setAttr(el, name, value, append = false) {
const attrValue = append ? getAttr(el, name, "") + " " + value : value;
el.setAttribute(name, attrValue);
return el;
}
export function hasAttr(el, name) {
return el && el.hasAttribute(name);
}
export function component(name, init, opts = {}) {
function parseConfig(el) {
const confMatcher = new RegExp(`data-(?:component|${name})-([^-]+)`, "i");
const defaultConf = {};
toArray(el.attributes).forEach(attr => {
const match = confMatcher.exec(attr.name);
if(confMatcher.test(attr.name)) {
defaultConf[match[1]] = attr.value;
}
});
try {
const conf = JSON.parse(el.getAttribute("data-component-conf"));
return Object.assign(defaultConf, conf);
} catch(e) {
return defaultConf;
}
}
opts = opts instanceof HTMLElement ? { root: opts } : opts;
return $$(`[data-component~="${name}"]`, opts.root || document)
.filter(el => !el.hasAttribute("data-component-ready"))
.map((el, index) => {
const def = el.getAttribute("data-component").split(" ");
const conf = Object.assign({}, init.DEFAULTS || {}, opts.conf || {}, parseConfig(el));
const options = {
index, conf,
is_type(type) {
return def.indexOf(`${name}-${type}`) !== -1;
}
};
const component = init(el, options);
setAttr(el, "data-component-ready", name, true);
return component;
});
}
export default {
$, $$, component,
replace, index, remove,
addClass, toggleClass, removeClass,
getAttr, setAttr, hasAttr
}
|
JavaScript
| 0.000001
|
79551bea7d3c52a7ba7621ab4e1332ce8853f298
|
update dom
|
src/dom.js
|
src/dom.js
|
var _findInChildren = function ( element, elementToFind ) {
for ( var i = 0; i < element.children.length; ++i ) {
var childEL = element.children[i];
if ( childEL === elementToFind )
return true;
if ( childEL.children.length > 0 )
if ( _findInChildren( childEL, elementToFind ) )
return true;
}
return false;
};
//
FIRE.find = function ( elements, elementToFind ) {
if ( Array.isArray(elements) ||
elements instanceof NodeList ||
elements instanceof HTMLCollection )
{
for ( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
if ( element === elementToFind )
return true;
if ( _findInChildren ( element, elementToFind ) )
return true;
}
return false;
}
// if this is a single element
if ( elements === elementToFind )
return true;
return _findInChildren( elements, elementToFind );
};
//
FIRE.getParentTabIndex = function ( element ) {
var parent = element.parentElement;
while ( parent ) {
if ( parent.tabIndex !== null &&
parent.tabIndex !== undefined &&
parent.tabIndex !== -1 )
return parent.tabIndex;
parent = parent.parentElement;
}
return 0;
};
FIRE.getFirstFocusableChild = function ( element ) {
if ( element.tabIndex !== null &&
element.tabIndex !== undefined &&
element.tabIndex !== -1 )
{
return element;
}
var el = null;
for ( var i = 0; i < element.children.length; ++i ) {
el = FIRE.getFirstFocusableChild(element.children[i]);
if ( el !== null )
return el;
}
if ( element.shadowRoot ) {
el = FIRE.getFirstFocusableChild(element.shadowRoot);
if ( el !== null )
return el;
}
return null;
};
//
FIRE.getTrimRect = function (img, trimThreshold) {
var canvas, ctx;
if (img instanceof Image || img instanceof HTMLImageElement) {
// create temp canvas
canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
ctx = canvas.getContext('2d');
ctx.drawImage( img, 0, 0, img.width, img.height );
}
else {
canvas = img;
ctx = canvas.getContext('2d');
}
var pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
// get trim
return _doGetTrimRect(pixels, img.width, img.height, trimThreshold);
};
var _dragGhost = null;
FIRE.addDragGhost = function ( cursor ) {
// add drag-ghost
if ( _dragGhost === null ) {
_dragGhost = document.createElement('div');
_dragGhost.classList.add('drag-ghost');
_dragGhost.style.position = 'fixed';
_dragGhost.style.zIndex = '999';
_dragGhost.style.left = '0';
_dragGhost.style.top = '0';
_dragGhost.style.width = window.innerWidth + 'px';
_dragGhost.style.height = window.innerHeight + 'px';
_dragGhost.oncontextmenu = function() { return false; };
}
_dragGhost.style.cursor = cursor;
document.body.appendChild(_dragGhost);
};
FIRE.removeDragGhost = function () {
if ( _dragGhost !== null ) {
_dragGhost.style.cursor = 'auto';
if ( _dragGhost.parentNode !== null ) {
_dragGhost.parentNode.removeChild(_dragGhost);
}
}
};
|
var _findInChildren = function ( element, elementToFind ) {
for ( var i = 0; i < element.children.length; ++i ) {
var childEL = element.children[i];
if ( childEL === elementToFind )
return true;
if ( childEL.children.length > 0 )
if ( _findInChildren( childEL, elementToFind ) )
return true;
}
return false;
};
//
FIRE.find = function ( elements, elementToFind ) {
if ( Array.isArray(elements) ||
elements instanceof NodeList ||
elements instanceof HTMLCollection )
{
for ( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
if ( element === elementToFind )
return true;
if ( _findInChildren ( element, elementToFind ) )
return true;
}
return false;
}
// if this is a single element
if ( elements === elementToFind )
return true;
return _findInChildren( elements, elementToFind );
};
//
FIRE.getParentTabIndex = function ( element ) {
var parent = element.parentElement;
while ( parent ) {
if ( parent.tabIndex !== null &&
parent.tabIndex !== undefined &&
parent.tabIndex !== -1 )
return parent.tabIndex;
parent = parent.parentElement;
}
return 0;
};
FIRE.getFirstFocusableChild = function ( element ) {
if ( element.tabIndex !== null &&
element.tabIndex !== undefined &&
element.tabIndex !== -1 )
{
return element;
}
for ( var i = 0; i < element.children.length; ++i ) {
var el = FIRE.getFirstFocusableChild(element.children[i]);
if ( el !== null )
return el;
}
return null;
};
//
FIRE.getTrimRect = function (img, trimThreshold) {
var canvas, ctx;
if (img instanceof Image || img instanceof HTMLImageElement) {
// create temp canvas
canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
ctx = canvas.getContext('2d');
ctx.drawImage( img, 0, 0, img.width, img.height );
}
else {
canvas = img;
ctx = canvas.getContext('2d');
}
var pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
// get trim
return _doGetTrimRect(pixels, img.width, img.height, trimThreshold);
};
var _dragGhost = null;
FIRE.addDragGhost = function ( cursor ) {
// add drag-ghost
if ( _dragGhost === null ) {
_dragGhost = document.createElement('div');
_dragGhost.classList.add('drag-ghost');
_dragGhost.style.position = 'fixed';
_dragGhost.style.zIndex = '999';
_dragGhost.style.left = '0';
_dragGhost.style.top = '0';
_dragGhost.style.width = window.innerWidth + 'px';
_dragGhost.style.height = window.innerHeight + 'px';
_dragGhost.oncontextmenu = function() { return false; };
}
_dragGhost.style.cursor = cursor;
document.body.appendChild(_dragGhost);
};
FIRE.removeDragGhost = function () {
if ( _dragGhost !== null ) {
_dragGhost.style.cursor = 'auto';
if ( _dragGhost.parentNode !== null ) {
_dragGhost.parentNode.removeChild(_dragGhost);
}
}
};
|
JavaScript
| 0.000001
|
55aca83478807452c7e3f8fc79830e3f1c428207
|
Add missing ;
|
tests/index.js
|
tests/index.js
|
import path from 'path';
import fs from 'fs';
import FeatherPlugin from '../';
const HELPER_DIR = path.join(__dirname, 'helpers');
class MockCompiler {
constructor() {
this.options = {
context: HELPER_DIR
};
}
plugin(type, fn) {
this.fn = fn;
}
}
const compiler = new MockCompiler();
let instance;
describe('plugin initialization', () => {
it('throws an error if no options are passed', done => {
try {
new FeatherPlugin();
done('No exception was thrown');
} catch (error) {
done();
}
});
it('creates the instance', () => {
instance = new FeatherPlugin({
template: 'template.ejs',
output: 'output.ejs',
line: 1,
whitelist: ['home']
});
});
it('apply function works', () => {
instance.apply(compiler);
});
});
describe('template generation', () => {
const outputPath = path.resolve(HELPER_DIR, 'output.ejs');
it('generates file', done => {
compiler.fn(null, err => {
if (err) {
return done(err);
}
fs.exists(outputPath, exists => {
if (exists) {
done();
} else {
done(new Error(`Output file ${outputPath} doesn't exist`));
}
});
});
});
it('creates valid content', done => {
fs.readFile(outputPath, 'utf8', (err, output) => {
if (err) {
return done(err);
}
checkOutput(output, done);
});
})
})
function checkOutput(output, done) {
fs.readFile(path.resolve(HELPER_DIR, 'expected.ejs'), 'utf8', (err, expected) => {
if (err) {
return done(err);
}
if (output === expected) {
done();
} else {
done(new Error('Contents don\'t match'));
}
});
}
|
import path from 'path';
import fs from 'fs';
import FeatherPlugin from '../';
const HELPER_DIR = path.join(__dirname, 'helpers');
class MockCompiler {
constructor() {
this.options = {
context: HELPER_DIR
};
}
plugin(type, fn) {
this.fn = fn;
}
}
const compiler = new MockCompiler();
let instance;
describe('plugin initialization', () => {
it('throws an error if no options are passed', done => {
try {
new FeatherPlugin();
done('No exception was thrown');
} catch (error) {
done();
}
});
it('creates the instance', () => {
instance = new FeatherPlugin({
template: 'template.ejs',
output: 'output.ejs',
line: 1,
whitelist: ['home']
});
});
it('apply function works', () => {
instance.apply(compiler);
});
});
describe('template generation', () => {
const outputPath = path.resolve(HELPER_DIR, 'output.ejs');
it('generates file', done => {
compiler.fn(null, err => {
if (err) {
return done(err);
}
fs.exists(outputPath, exists => {
if (exists) {
done();
} else {
done(new Error(`Output file ${outputPath} doesn't exist`));
}
});
});
});
it('creates valid content', done => {
fs.readFile(outputPath, 'utf8', (err, output) => {
if (err) {
return done(err);
}
checkOutput(output, done);
});
})
})
function checkOutput(output, done) {
fs.readFile(path.resolve(HELPER_DIR, 'expected.ejs'), 'utf8', (err, expected) => {
if (err) {
return done(err);
}
if (output === expected) {
done();
} else {
done(new Error('Contents don\'t match'));
}
})
}
|
JavaScript
| 0.000015
|
a97674f2f3c0f7b5aae4571ae85e5b956686f1c0
|
Add names to Sauce environments.
|
tests/sauce.js
|
tests/sauce.js
|
define(["./intern"], function (intern) {
var config = {
proxyPort: 9000,
proxyUrl: "http://localhost:9000/",
capabilities: {
"selenium-version": "2.37.0",
"idle-timeout": 60
},
environments: [
{browserName: "internet explorer", version: "9", platform: "Windows 7", name: "liaison"},
{browserName: "internet explorer", version: "10", platform: "Windows 8", name: "liaison"},
{browserName: "internet explorer", version: "11", platform: "Windows 8.1", name: "liaison"},
{browserName: "firefox", version: "25", platform: [/*"OS X 10.6",*/ "Linux", "Windows 7"], name: "liaison"},
{browserName: "chrome", version: "", platform: [/*"OS X 10.6", */ "Linux", "Windows 7"], name: "liaison"},
{browserName: "safari", version: "6", platform: "OS X 10.8", name: "liaison"},
{browserName: "safari", version: "7", platform: "OS X 10.9", name: "liaison"},
// {browserName: "android", platform: "Linux", version: "4.1", name: "liaison"},
// {browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.1", name: "liaison"},
// {browserName: "android", platform: "Linux", version: "4.1", name: "liaison"},
// {browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.0", name: "liaison"},
// {browserName: "android", platform: "Linux", version: "4.0", name: "liaison"},
// Non-empty selenium-version causes "browser failed to start" error for unknown reason
{browserName: "iphone", platform: "OS X 10.9", version: "7", "device-orientation": "portrait", "selenium-version": "", name: "liaison"},
{browserName: "ipad", platform: "OS X 10.9", version: "7", "device-orientation": "portrait", "selenium-version": "", name: "liaison"},
{browserName: "iphone", platform: "OS X 10.8", version: "6.1", "device-orientation": "portrait", "selenium-version": "", name: "liaison"},
{browserName: "ipad", platform: "OS X 10.8", version: "6.1", "device-orientation": "portrait", "selenium-version": "", name: "liaison"},
{browserName: "iphone", platform: "OS X 10.8", version: "6.0", "device-orientation": "portrait", "selenium-version": "", name: "liaison"},
{browserName: "ipad", platform: "OS X 10.8", version: "6.0", "device-orientation": "portrait", "selenium-version": "", name: "liaison"}
],
maxConcurrency: 3,
useSauceConnect: true,
webdriver: {
host: "localhost",
port: 4444
},
suites: ["liaison/tests/all"],
functionalSuites: [
"liaison/tests/delite/sandbox",
"liaison/tests/polymer/sandbox",
"liaison/tests/polymer-platform/sandbox",
"liaison/tests/delite-polymer/sandbox"
]
};
for (var key in intern) {
if (key !== "suites") {
config[key] = intern[key];
}
}
return config;
});
|
define(["./intern"], function (intern) {
var config = {
proxyPort: 9000,
proxyUrl: "http://localhost:9000/",
capabilities: {
"selenium-version": "2.37.0",
"idle-timeout": 60
},
environments: [
{browserName: "internet explorer", version: "9", platform: "Windows 7"},
{browserName: "internet explorer", version: "10", platform: "Windows 8"},
{browserName: "internet explorer", version: "11", platform: "Windows 8.1"},
{browserName: "firefox", version: "25", platform: [/*"OS X 10.6",*/ "Linux", "Windows 7"]},
{browserName: "chrome", version: "", platform: [/*"OS X 10.6", */ "Linux", "Windows 7"]},
{browserName: "safari", version: "6", platform: "OS X 10.8"},
{browserName: "safari", version: "7", platform: "OS X 10.9"},
// {browserName: "android", platform: "Linux", version: "4.1"},
// {browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.1"},
// {browserName: "android", platform: "Linux", version: "4.1"},
// {browserName: "android", platform: "Linux", "device-type": "tablet", version: "4.0"},
// {browserName: "android", platform: "Linux", version: "4.0"},
// Non-empty selenium-version causes "browser failed to start" error for unknown reason
{browserName: "iphone", platform: "OS X 10.9", version: "7", "device-orientation": "portrait", "selenium-version": ""},
{browserName: "ipad", platform: "OS X 10.9", version: "7", "device-orientation": "portrait", "selenium-version": ""},
{browserName: "iphone", platform: "OS X 10.8", version: "6.1", "device-orientation": "portrait", "selenium-version": ""},
{browserName: "ipad", platform: "OS X 10.8", version: "6.1", "device-orientation": "portrait", "selenium-version": ""},
{browserName: "iphone", platform: "OS X 10.8", version: "6.0", "device-orientation": "portrait", "selenium-version": ""},
{browserName: "ipad", platform: "OS X 10.8", version: "6.0", "device-orientation": "portrait", "selenium-version": ""}
],
maxConcurrency: 3,
useSauceConnect: true,
webdriver: {
host: "localhost",
port: 4444
},
suites: ["liaison/tests/all"],
functionalSuites: [
"liaison/tests/delite/sandbox",
"liaison/tests/polymer/sandbox",
"liaison/tests/polymer-platform/sandbox",
"liaison/tests/delite-polymer/sandbox"
]
};
for (var key in intern) {
if (key !== "suites") {
config[key] = intern[key];
}
}
return config;
});
|
JavaScript
| 0
|
23f31e5c8f0d13984e0caa314e67fa2652ebf0d1
|
use global.environment
|
tile-server.js
|
tile-server.js
|
var Windshaft = require('windshaft');
var _ = require('underscore')._;
var fs = require('fs');
var userConfig = require('./config.json');
// Configure pluggable URLs
// =========================
// The config object must define grainstore config (generally just postgres connection details), redis config,
// a base url and a function that adds 'dbname' and 'table' variables onto the Express.js req.params object.
// In this example, the base URL is such that dbname and table will automatically be added to the req.params
// object by express.js. req2params can be extended to allow full control over the specifying of dbname and table,
// and also allows for the req.params object to be extended with other variables, such as:
//
// * sql - custom sql query to narrow results shown in map)
// * geom_type - specify the geom type (point|polygon) to get more appropriate default styles
// * cache_buster - forces the creation of a new render object, nullifying existing metatile caches
// * interactivity - specify the column to use in the UTFGrid interactivity layer (defaults to null)
// * style - specify map style in the Carto map language on a per tile basis
//
// the base url is also used for persisiting and retrieving map styles via:
//
// GET base_url + '/style' (returns a map style)
// POST base_url + '/style' (allows specifying of a style in Carto markup in the 'style' form variable).
//
// beforeTileRender and afterTileRender could be defined if you want yo implement your own tile cache policy. See
// an example below
// set environment specific variables
global.environment = require('config/settings');
//on startup, read the file synchronously
var cartoCss = fs.readFileSync(__dirname + '/carto.css','utf-8');
var cacheFolder = __dirname + '/tile_cache/';
var config = {
base_url: '/database/:dbname/table/:table',
base_url_notable: '/database/:dbname',
req2params: function(req, callback){
// no default interactivity. to enable specify the database column you'd like to interact with
req.params.interactivity = null;
// this is in case you want to test sql parameters eg ...png?sql=select * from my_table limit 10
req.params = _.extend({}, req.params);
_.extend(req.params, req.query);
// send the finished req object on
callback(null,req);
},
grainstore: {datasource: {user:userConfig.database.user,password:userConfig.database.password, host: '127.0.0.1', port: 5432},
styles: {point: cartoCss}, mapnik_version:'2.1.0'
}, //see grainstore npm for other options
redis: {host: '127.0.0.1', port: 6379},
mapnik: {
metatile: 1,
bufferSize:64
},
renderCache: {
ttl: 60000, // seconds
}
};
// Initialize tile server on port 4000
var ws = new Windshaft.Server(config);
ws.listen(4000);
console.log("map tiles are now being served out of: http://localhost:4000" + config.base_url + '/:z/:x/:y.*');
// Specify .png, .png8 or .grid.json tiles.
|
var Windshaft = require('windshaft');
var _ = require('underscore')._;
var fs = require('fs');
var userConfig = require('./config.json');
// Configure pluggable URLs
// =========================
// The config object must define grainstore config (generally just postgres connection details), redis config,
// a base url and a function that adds 'dbname' and 'table' variables onto the Express.js req.params object.
// In this example, the base URL is such that dbname and table will automatically be added to the req.params
// object by express.js. req2params can be extended to allow full control over the specifying of dbname and table,
// and also allows for the req.params object to be extended with other variables, such as:
//
// * sql - custom sql query to narrow results shown in map)
// * geom_type - specify the geom type (point|polygon) to get more appropriate default styles
// * cache_buster - forces the creation of a new render object, nullifying existing metatile caches
// * interactivity - specify the column to use in the UTFGrid interactivity layer (defaults to null)
// * style - specify map style in the Carto map language on a per tile basis
//
// the base url is also used for persisiting and retrieving map styles via:
//
// GET base_url + '/style' (returns a map style)
// POST base_url + '/style' (allows specifying of a style in Carto markup in the 'style' form variable).
//
// beforeTileRender and afterTileRender could be defined if you want yo implement your own tile cache policy. See
// an example below
// set environment specific variables
global.settings = require('config/settings');
//on startup, read the file synchronously
var cartoCss = fs.readFileSync(__dirname + '/carto.css','utf-8');
var cacheFolder = __dirname + '/tile_cache/';
var config = {
base_url: '/database/:dbname/table/:table',
base_url_notable: '/database/:dbname',
req2params: function(req, callback){
// no default interactivity. to enable specify the database column you'd like to interact with
req.params.interactivity = null;
// this is in case you want to test sql parameters eg ...png?sql=select * from my_table limit 10
req.params = _.extend({}, req.params);
_.extend(req.params, req.query);
// send the finished req object on
callback(null,req);
},
grainstore: {datasource: {user:userConfig.database.user,password:userConfig.database.password, host: '127.0.0.1', port: 5432},
styles: {point: cartoCss}, mapnik_version:'2.1.0'
}, //see grainstore npm for other options
redis: {host: '127.0.0.1', port: 6379},
mapnik: {
metatile: 1,
bufferSize:64
},
renderCache: {
ttl: 60000, // seconds
}
};
// Initialize tile server on port 4000
var ws = new Windshaft.Server(config);
ws.listen(4000);
console.log("map tiles are now being served out of: http://localhost:4000" + config.base_url + '/:z/:x/:y.*');
// Specify .png, .png8 or .grid.json tiles.
|
JavaScript
| 0.00089
|
c3afc8f7661e8edec9a64f87425b61307c2fcec3
|
Implement checkKey() function
|
storage.js
|
storage.js
|
(function(){
'use strict';
function Storage(storageAreaName)
{
var _storageArea = (storageAreaName === 'session') ? window.sessionStorage : window.localStorage;
this.isSupported = function() {
return typeof _storageArea !== 'undefined';
};
this.set = function(key, val) {
checkKey(key);
if(val === undefined)
return;
if(typeof val === 'function')
return;
else if(typeof val === 'object')
_storageArea[key] = JSON.stringify(val);
else
_storageArea[key] = val;
};
this.get = function(key) {
checkKey(key);
if(_storageArea[key] === undefined)
return null;
try {
return JSON.parse(_storageArea[key]);
}
catch(ex) {
return _storageArea[key];
}
return _storageArea[key];
};
this.exists = function(key) {
checkKey(key);
return _storageArea[key] !== undefined;
};
this.clear = function() {
if(arguments.length === 0)
_storageArea.clear();
else
{
for(var i=0; i<arguments.length; i++)
_storageArea.removeItem(arguments[i]);
}
};
this.getKeys = function() {
var list = [];
for(var i in _storageArea)
{
if(_storageArea.hasOwnProperty(i))
list.push(i);
}
return list;
};
function checkKey(key)
{
if(typeof key !== 'string' && typeof key !== 'number')
throw new TypeError('Key must be string or numeric');
return true;
}
};
window.storage = new Storage();
window.storage.local = new Storage();
window.storage.session = new Storage('session');
return;
})();
|
(function(){
'use strict';
function Storage(storageAreaName)
{
var _storageArea = (storageAreaName === 'session') ? window.sessionStorage : window.localStorage;
this.isSupported = function() {
return typeof _storageArea !== 'undefined';
};
this.set = function(key, val) {
if(val === undefined)
return;
if(typeof val === 'function')
return;
else if(typeof val === 'object')
_storageArea[key] = JSON.stringify(val);
else
_storageArea[key] = val;
};
this.get = function(key) {
if(_storageArea[key] === undefined)
return null;
try {
return JSON.parse(_storageArea[key]);
}
catch(ex) {
return _storageArea[key];
}
return _storageArea[key];
};
this.exists = function(key) {
return _storageArea[key] !== undefined;
};
this.clear = function() {
if(arguments.length === 0)
_storageArea.clear();
else
{
for(var i=0; i<arguments.length; i++)
_storageArea.removeItem(arguments[i]);
}
};
this.getKeys = function() {
var list = [];
for(var i in _storageArea)
{
if(_storageArea.hasOwnProperty(i))
list.push(i);
}
return list;
};
};
window.storage = new Storage();
window.storage.local = new Storage();
window.storage.session = new Storage('session');
return;
})();
|
JavaScript
| 0.000018
|
94552283b415871c60d491a4c7127749f080cc13
|
fix duplicated home route
|
01-Embedded-Login/src/routes.js
|
01-Embedded-Login/src/routes.js
|
import React from 'react';
import { Route, BrowserRouter } from 'react-router-dom';
import App from './App';
import Home from './Home/Home';
import Callback from './Callback/Callback';
import Auth from './Auth/Auth';
import history from './history';
const auth = new Auth();
export const makeMainRoutes = () => {
return (
<BrowserRouter history={history} component={App}>
<div>
<Route path="/" render={(props) => <App auth={auth} {...props} />} />
<Route path="/home" render={(props) => <Home auth={auth} {...props} />} />
<Route path="/callback" render={(props) => <Callback {...props} />} />
</div>
</BrowserRouter>
);
}
|
import React from 'react';
import { Route, BrowserRouter } from 'react-router-dom';
import App from './App';
import Home from './Home/Home';
import Callback from './Callback/Callback';
import Auth from './Auth/Auth';
import history from './history';
const auth = new Auth();
export const makeMainRoutes = () => {
return (
<BrowserRouter history={history} component={App}>
<div>
<Route path="/" render={(props) => <Home auth={auth} {...props} />} />
<Route path="/home" render={(props) => <Home auth={auth} {...props} />} />
<Route path="/callback" render={(props) => <Callback {...props} />} />
</div>
</BrowserRouter>
);
}
|
JavaScript
| 0.000003
|
1b6ad0ab5b95bd89d3d55ef1d5d346b9e722ef39
|
Update index.js
|
projects/acc/js/index.js
|
projects/acc/js/index.js
|
if ('Accelerometer' in window && 'Gyroscope' in window) {
//document.getElementById('moApi').innerHTML = 'Generic Sensor API';
let accelerometer = new Accelerometer();
accelerometer.addEventListener('reading', e => MaccelerationHandler(accelerometer, 'moAccel'));
accelerometer.start();
let accelerometerWithGravity = new Accelerometer({includeGravity: true});
accelerometerWithGravity.addEventListener('reading', e => MaccelerationHandler(accelerometerWithGravity, 'moAccelGrav'));
accelerometerWithGravity.start();
let gyroscope = new Gyroscope();
gyroscope.addEventListener('reading', e => rotationHandler({
alpha: gyroscope.x,
beta: gyroscope.y,
gamma: gyroscope.z
}));
gyroscope.start();
intervalHandler('Not available in Generic Sensor API');
} else if ('DeviceMotionEvent' in window) {
//document.getElementById('alert').style.display = 'none';
//document.getElementById('moApi').innerHTML = 'Device Motion API';
window.addEventListener('devicemotion', function (eventData) {
accelerationHandler(eventData.acceleration, 'moAccel');
MaccelerationHandler(eventData.accelerationIncludingGravity, 'moAccelGrav');
rotationHandler(eventData.rotationRate);
intervalHandler(eventData.interval);
}, false);
} else {
//document.getElementById('alert').style.display = 'none';
//document.getElementById('moApi').innerHTML = 'No Accelerometer & Gyroscope API available';
}
function accelerationHandler(acceleration, targetId) {
var info, xyz = "[X, Y, Z]";
info = xyz.replace("X", acceleration.x && acceleration.x.toFixed(3));
info = info.replace("Y", acceleration.y && acceleration.y.toFixed(3));
info = info.replace("Z", acceleration.z && acceleration.z.toFixed(3));
//document.getElementById(targetId).innerHTML = info;
}
function MaccelerationHandler(acceleration, targetId) {
var info, xyz = "[X, Y, Z]";
var zz = (acceleration.z && acceleration.z.toFixed(3));
if (zz>10) {
x = 1;
var timer = setInterval(function change() {
if (x === 1) {
color = "#ffffff";
x = 2;
} else {
color = "#000000";
x = 1;
}
document.body.style.background = #000000;
}, 50);
setTimeout(function() {
clearInterval(timer);
}, 1000);
}
}
function rotationHandler(rotation) {
var info, xyz = "[X, Y, Z]";
//info = xyz.replace("X", rotation.alpha && rotation.alpha.toFixed(3));
//info = info.replace("Y", rotation.beta && rotation.beta.toFixed(3));
//info = info.replace("Z", rotation.gamma && rotation.gamma.toFixed(3));
var xx = (rotation.alpha && rotation.alpha.toFixed(3));
var yy = (rotation.beta && rotation.beta.toFixed(3));
var zz = (rotation.gamma && rotation.gamma.toFixed(3));
var mean = (((xx)^2) + ((yy)^2) + ((zz)^2))*(1/2);
//document.getElementById("mean").innerHTML = mean;
//document.getElementById("moRotation").innerHTML = info;
}
function intervalHandler(interval) {
//document.getElementById("moInterval").innerHTML = interval;
}
if (location.href.indexOf('debug') !== -1) {
//document.getElementById('alert').style.display = 'none';
}
|
if ('Accelerometer' in window && 'Gyroscope' in window) {
//document.getElementById('moApi').innerHTML = 'Generic Sensor API';
let accelerometer = new Accelerometer();
accelerometer.addEventListener('reading', e => MaccelerationHandler(accelerometer, 'moAccel'));
accelerometer.start();
let accelerometerWithGravity = new Accelerometer({includeGravity: true});
accelerometerWithGravity.addEventListener('reading', e => MaccelerationHandler(accelerometerWithGravity, 'moAccelGrav'));
accelerometerWithGravity.start();
let gyroscope = new Gyroscope();
gyroscope.addEventListener('reading', e => rotationHandler({
alpha: gyroscope.x,
beta: gyroscope.y,
gamma: gyroscope.z
}));
gyroscope.start();
intervalHandler('Not available in Generic Sensor API');
} else if ('DeviceMotionEvent' in window) {
//document.getElementById('alert').style.display = 'none';
//document.getElementById('moApi').innerHTML = 'Device Motion API';
window.addEventListener('devicemotion', function (eventData) {
accelerationHandler(eventData.acceleration, 'moAccel');
MaccelerationHandler(eventData.accelerationIncludingGravity, 'moAccelGrav');
rotationHandler(eventData.rotationRate);
intervalHandler(eventData.interval);
}, false);
} else {
//document.getElementById('alert').style.display = 'none';
//document.getElementById('moApi').innerHTML = 'No Accelerometer & Gyroscope API available';
}
function accelerationHandler(acceleration, targetId) {
var info, xyz = "[X, Y, Z]";
info = xyz.replace("X", acceleration.x && acceleration.x.toFixed(3));
info = info.replace("Y", acceleration.y && acceleration.y.toFixed(3));
info = info.replace("Z", acceleration.z && acceleration.z.toFixed(3));
//document.getElementById(targetId).innerHTML = info;
}
function MaccelerationHandler(acceleration, targetId) {
var info, xyz = "[X, Y, Z]";
var zz = (acceleration.z && acceleration.z.toFixed(3));
if (zz>10) {
x = 1;
var timer = setInterval(function change() {
if (x === 1) {
color = "#ffffff";
x = 2;
} else {
color = "#000000";
x = 1;
}
document.body.style.background = color;
}, 50);
setTimeout(function() {
clearInterval(timer);
}, 1000);
}
}
function rotationHandler(rotation) {
var info, xyz = "[X, Y, Z]";
//info = xyz.replace("X", rotation.alpha && rotation.alpha.toFixed(3));
//info = info.replace("Y", rotation.beta && rotation.beta.toFixed(3));
//info = info.replace("Z", rotation.gamma && rotation.gamma.toFixed(3));
var xx = (rotation.alpha && rotation.alpha.toFixed(3));
var yy = (rotation.beta && rotation.beta.toFixed(3));
var zz = (rotation.gamma && rotation.gamma.toFixed(3));
var mean = (((xx)^2) + ((yy)^2) + ((zz)^2))*(1/2);
//document.getElementById("mean").innerHTML = mean;
//document.getElementById("moRotation").innerHTML = info;
}
function intervalHandler(interval) {
//document.getElementById("moInterval").innerHTML = interval;
}
if (location.href.indexOf('debug') !== -1) {
//document.getElementById('alert').style.display = 'none';
}
|
JavaScript
| 0.000002
|
98bd54ef5aff77d901ef5e2c118ae4027403b14c
|
fix sessions relationship in seq block model.
|
app/models/curriculum-inventory-sequence-block.js
|
app/models/curriculum-inventory-sequence-block.js
|
import Ember from 'ember';
import DS from 'ember-data';
const { computed } = Ember;
const { alias, equal } = computed;
export default DS.Model.extend({
title: DS.attr('string'),
description: DS.attr('string'),
required: DS.attr('number'),
childSequenceOrder: DS.attr('number'),
orderInSequence: DS.attr('number'),
minimum: DS.attr('number'),
maximum: DS.attr('number'),
track: DS.attr('boolean'),
startDate: DS.attr('date'),
endDate: DS.attr('date'),
duration: DS.attr('number'),
academicLevel: DS.belongsTo('curriculum-inventory-academic-level', {async: true}),
parent: DS.belongsTo('curriculum-inventory-sequence-block', {async: true, inverse: 'children'}),
children: DS.hasMany('curriculum-inventory-sequence-block', {async: true, inverse: 'parent'}),
report: DS.belongsTo('curriculum-inventory-report', {async: true}),
sessions: DS.hasMany('session', {async: true}),
course: DS.belongsTo('course', {async: true}),
isFinalized: alias('report.isFinalized'),
isRequired: equal('required', 1),
isOptional: equal('required', 2),
isRequiredInTrack: equal('required', 3),
isOrdered: equal('childSequenceOrder', 1),
isUnordered: equal('childSequenceOrder', 2),
isParallel: equal('childSequenceOrder', 3),
allParents: computed('parent', 'parent.allParents.[]', function(){
return new Promise(resolve => {
this.get('parent').then(parent => {
let parents = [];
if(!parent){
resolve(parents);
} else {
parents.pushObject(parent);
parent.get('allParents').then(allParents => {
parents.pushObjects(allParents);
resolve(parents);
});
}
});
});
}),
});
|
import Ember from 'ember';
import DS from 'ember-data';
const { computed } = Ember;
const { alias, equal } = computed;
export default DS.Model.extend({
title: DS.attr('string'),
description: DS.attr('string'),
required: DS.attr('number'),
childSequenceOrder: DS.attr('number'),
orderInSequence: DS.attr('number'),
minimum: DS.attr('number'),
maximum: DS.attr('number'),
track: DS.attr('boolean'),
startDate: DS.attr('date'),
endDate: DS.attr('date'),
duration: DS.attr('number'),
academicLevel: DS.belongsTo('curriculum-inventory-academic-level', {async: true}),
parent: DS.belongsTo('curriculum-inventory-sequence-block', {async: true, inverse: 'children'}),
children: DS.hasMany('curriculum-inventory-sequence-block', {async: true, inverse: 'parent'}),
report: DS.belongsTo('curriculum-inventory-report', {async: true}),
sessions: DS.hasMany('curriculum-inventory-sequence-block-session', {async: true}),
course: DS.belongsTo('course', {async: true}),
isFinalized: alias('report.isFinalized'),
isRequired: equal('required', 1),
isOptional: equal('required', 2),
isRequiredInTrack: equal('required', 3),
isOrdered: equal('childSequenceOrder', 1),
isUnordered: equal('childSequenceOrder', 2),
isParallel: equal('childSequenceOrder', 3),
allParents: computed('parent', 'parent.allParents.[]', function(){
return new Promise(resolve => {
this.get('parent').then(parent => {
let parents = [];
if(!parent){
resolve(parents);
} else {
parents.pushObject(parent);
parent.get('allParents').then(allParents => {
parents.pushObjects(allParents);
resolve(parents);
});
}
});
});
}),
});
|
JavaScript
| 0
|
c70d485afe776fd08fbb4a34157baa480cd9b528
|
Update common.js
|
userapp/common.js
|
userapp/common.js
|
// Init UserApp with your App Id
// https://help.userapp.io/customer/portal/articles/1322336-how-do-i-find-my-app-id-
UserApp.initialize({ appId: "57b349611262d" });
|
// Init UserApp with your App Id
// https://help.userapp.io/customer/portal/articles/1322336-how-do-i-find-my-app-id-
UserApp.initialize({ appId: "YOUR-USERAPP-APP-ID" });
|
JavaScript
| 0.000001
|
9b9d4d7c0fd1aa6d934e718dbd9d9570fc9a4ab1
|
reset XP if it isn't safe int
|
commands/server_management/giveXP.js
|
commands/server_management/giveXP.js
|
/**
* @file giveXP command
* @author Sankarsan Kampa (a.k.a k3rn31p4nic)
* @license GPL-3.0
*/
exports.exec = async (Bastion, message, args) => {
if (!args.id || !args.points) {
return Bastion.emit('commandUsage', message, this.help);
}
if (message.mentions.users.size) {
args.id = message.mentions.users.first().id;
}
let guildMemberModel = await Bastion.database.models.guildMember.findOne({
attributes: [ 'experiencePoints' ],
where: {
userID: args.id,
guildID: message.guild.id
}
});
if (!guildMemberModel) {
return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'profileNotCreated', `<@${args.id}>`), message.channel);
}
args.points = `${parseInt(guildMemberModel.dataValues.experiencePoints) + parseInt(args.points)}`;
if (!Number.isSafeInteger(args.points)) args.points = '0';
await Bastion.database.models.guildMember.update({
experiencePoints: args.points
},
{
where: {
userID: args.id,
guildID: message.guild.id
},
fields: [ 'experiencePoints' ]
});
await message.channel.send({
embed: {
color: Bastion.colors.GREEN,
description: `<@${args.id}> has been awarded with **${args.points}** experience points.`
}
}).catch(e => {
Bastion.log.error(e);
});
};
exports.config = {
aliases: [],
enabled: true,
guildOwnerOnly: true,
argsDefinitions: [
{ name: 'id', type: String, defaultOption: true },
{ name: 'points', alias: 'n', type: String }
]
};
exports.help = {
name: 'giveXP',
description: 'Give the specified amount of experience points to the specified user and increase their level.',
botPermission: '',
userTextPermission: '',
userVoicePermission: '',
usage: 'giveXP <@USER_MENTION | USER_ID> <-n POINTS>',
example: [ 'giveXP @user#0001 -n 100', 'giveXP 242621467230268813 -n 150' ]
};
|
/**
* @file giveXP command
* @author Sankarsan Kampa (a.k.a k3rn31p4nic)
* @license GPL-3.0
*/
exports.exec = async (Bastion, message, args) => {
if (!args.id || !args.points) {
return Bastion.emit('commandUsage', message, this.help);
}
if (message.mentions.users.size) {
args.id = message.mentions.users.first().id;
}
let guildMemberModel = await Bastion.database.models.guildMember.findOne({
attributes: [ 'experiencePoints' ],
where: {
userID: args.id,
guildID: message.guild.id
}
});
if (!guildMemberModel) {
return Bastion.emit('error', '', Bastion.i18n.error(message.guild.language, 'profileNotCreated', `<@${args.id}>`), message.channel);
}
args.points = `${parseInt(guildMemberModel.dataValues.experiencePoints) + parseInt(args.points)}`;
await Bastion.database.models.guildMember.update({
experiencePoints: args.points
},
{
where: {
userID: args.id,
guildID: message.guild.id
},
fields: [ 'experiencePoints' ]
});
await message.channel.send({
embed: {
color: Bastion.colors.GREEN,
description: `<@${args.id}> has been awarded with **${args.points}** experience points.`
}
}).catch(e => {
Bastion.log.error(e);
});
};
exports.config = {
aliases: [],
enabled: true,
guildOwnerOnly: true,
argsDefinitions: [
{ name: 'id', type: String, defaultOption: true },
{ name: 'points', alias: 'n', type: String }
]
};
exports.help = {
name: 'giveXP',
description: 'Give the specified amount of experience points to the specified user and increase their level.',
botPermission: '',
userTextPermission: '',
userVoicePermission: '',
usage: 'giveXP <@USER_MENTION | USER_ID> <-n POINTS>',
example: [ 'giveXP @user#0001 -n 100', 'giveXP 242621467230268813 -n 150' ]
};
|
JavaScript
| 0.000002
|
e14bb365dc5346e4680f102aabf5732a3305f345
|
Add Mat2d
|
js/AM.Math.js
|
js/AM.Math.js
|
AM.Math = AM.Math || {};
AM.Math.ToDeg = function (rad) {
return rad * (180 / Math.PI);
};
AM.Math.ToRad = function (deg) {
return deg * (Math.PI / 180);
};
AM.Math.Vec2d = function (x, y) {
this.x = x;
this.y = y;
};
AM.Math.Vec2d.prototype = {
x: 0,
y: 0,
subtract: function (otherVec) {
return new AM.Math.Vec2d(this.x - otherVec.x, this.y - otherVec.y);
},
add: function (otherVec) {
return new AM.Math.Vec2d(this.x + otherVec.x, this.y + otherVec.y);
},
scale: function (num) {
return new AM.Math.Vec2d(this.x * num, this.y * num);
},
dot: function Vec2d$dot(otherVec) {
return this.x * otherVec.x + this.y * otherVec.y;
},
magnitude: function Vec2d$magnitude() {
return Math.sqrt(this.dot(this));
},
norm: function Vec2d$norm() {
var mag = this.magnitude();
return new AM.Math.Vec2d(this.x / mag, this.y / mag);
},
angle: function Vec2d$angle(other) {
var dot = this.dot(other)
var angle = Math.acos(dot);
if (angle > Math.PI) {
angle = Math.PI * 2 - angle;
}
return angle;
},
rotate: function Vec2d$rotate(rads) {
var cos = Math.cos(rads);
var sin = Math.sin(rads);
var x = this.x * cos - this.y * sin;
var y = this.x * sin + this.y * cos;
return new AM.Math.Vec2d(x, y);
},
cross: function (otherVec) {
return this.x * otherVec.y - this.y * otherVec.x;
}
};
AM.Math.Line = function (pointA, pointB) {
this.N = pointB.subtract(pointA).norm();
this.A = pointA;
};
AM.Math.Line.prototype = {
N: null,
A: null,
vector2LineFromPoint: function (p) {
var p2A = this.A.subtract(p);
var compA = p2A.dot(this.N);
var proj = this.N.scale(compA);
return p2A.subtract(proj);
}
};
AM.Math.Mat2d = function(e00, e01, e10, e11){
this.mat = [[e00,e01],
[e10,e11]];
};
AM.Math.Mat2d.prototype = {
mat:[[0,0],[0,0]],
mult: function(m){
var e00 = this.mat[0][0]*m.mat[0][0] + this.mat[0][1]*m.mat[1][0];
var e01 = this.mat[0][0]*m.mat[0][1] + this.mat[0][1]*m.mat[1][1];
var e10 = this.mat[1][0]*m.mat[0][0] + this.mat[1][1]*m.mat[1][0];
var e11 = this.mat[1][0]*m.mat[0][1] + this.mat[1][1]*m.mat[1][1];
return new AM.Math.Mat2d(e00, e01, e10, e11);
},
multVec: function(v){
var x = this.mat[0][0]*v.x + this.mat[0][1]*v.y;
var y = this.mat[1][0]*v.x + this.mat[1][1]*v.y;
return new AM.Math.Vec2d(x,y);
}
}
|
AM.Math = AM.Math || {};
AM.Math.ToDeg = function (rad) {
return rad * (180 / Math.PI);
};
AM.Math.ToRad = function (deg) {
return deg * (Math.PI / 180);
};
AM.Math.Vec2d = function (x, y) {
this.x = x;
this.y = y;
};
AM.Math.Vec2d.prototype = {
x: 0,
y: 0,
subtract: function (otherVec) {
return new AM.Math.Vec2d(this.x - otherVec.x, this.y - otherVec.y);
},
add: function (otherVec) {
return new AM.Math.Vec2d(this.x + otherVec.x, this.y + otherVec.y);
},
scale: function (num) {
return new AM.Math.Vec2d(this.x * num, this.y * num);
},
dot: function Vec2d$dot(otherVec) {
return this.x * otherVec.x + this.y * otherVec.y;
},
magnitude: function Vec2d$magnitude() {
return Math.sqrt(this.dot(this));
},
norm: function Vec2d$norm() {
var mag = this.magnitude();
return new AM.Math.Vec2d(this.x / mag, this.y / mag);
},
angle: function Vec2d$angle(other) {
var dot = this.dot(other)
var angle = Math.acos(dot);
if (angle > Math.PI) {
angle = Math.PI * 2 - angle;
}
return angle;
},
rotate: function Vec2d$rotate(rads) {
var cos = Math.cos(rads);
var sin = Math.sin(rads);
var x = this.x * cos - this.y * sin;
var y = this.x * sin + this.y * cos;
return new AM.Math.Vec2d(x, y);
},
cross: function (otherVec) {
return this.x * otherVec.y - this.y * otherVec.x;
}
};
AM.Math.Line = function (pointA, pointB) {
this.N = pointB.subtract(pointA).norm();
this.A = pointA;
};
AM.Math.Line.prototype = {
N: null,
A: null,
vector2LineFromPoint: function (p) {
var p2A = this.A.subtract(p);
var compA = p2A.dot(this.N);
var proj = this.N.scale(compA);
return p2A.subtract(proj);
}
};
|
JavaScript
| 0.000006
|
34ef7196506047b06c3010a4a442fb0bd2a62b71
|
Remove Joi validation
|
routes.js
|
routes.js
|
const Reporter = require('./src/Reporter');
const PostReporter = require('./src/PostReport');
const Verification = require('./src/Verification');
const Joi = require('joi');
module.exports = [
{
method: 'GET',
path: '/report/',
handler: Reporter,
config: {
validate: {
query: {
hipchat: Joi.string().required(),
site: Joi.string().uri().required(),
}
}
}
},
{
method: 'POST',
path: '/report/',
handler: PostReporter,
},
{
method: 'GET',
path: '/verification/{hipchat}/',
handler: Verification,
config: {
validate: {
query: {
id: Joi.required(),
}
}
}
}
]
|
const Reporter = require('./src/Reporter');
const PostReporter = require('./src/PostReport');
const Verification = require('./src/Verification');
const Joi = require('joi');
module.exports = [
{
method: 'GET',
path: '/report/',
handler: Reporter,
config: {
validate: {
query: {
hipchat: Joi.string().required(),
site: Joi.string().uri().required(),
}
}
}
},
{
method: 'POST',
path: '/report/',
handler: PostReporter,
config: {
validate: {
payload: Joi.object().keys({
item: Joi.object().required(),
}),
}
}
},
{
method: 'GET',
path: '/verification/{hipchat}/',
handler: Verification,
config: {
validate: {
query: {
id: Joi.required(),
}
}
}
}
]
|
JavaScript
| 0
|
19073b16508fd3e0e3180e5372be4f75f7fbc66b
|
Fix GlobalSearch result z-index
|
components/AppLayout/GlobalSearch.js
|
components/AppLayout/GlobalSearch.js
|
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import { t } from 'ttag';
import {
Box,
InputAdornment,
TextField,
ClickAwayListener,
makeStyles,
} from '@material-ui/core';
import SearchIcon from '@material-ui/icons/Search';
const useStyles = makeStyles(theme => ({
root: {
flex: 1,
position: 'relative',
},
searchWrapper: {
padding: '0 8px',
width: '100%',
[theme.breakpoints.up('md')]: {
padding: '0 24px',
},
},
input: {
padding: '10px 0',
cursor: 'pointer',
},
adornment: {
color: ({ focus }) => (focus ? theme.palette.primary[500] : 'inherit'),
},
result: {
padding: '0 20px',
position: 'absolute',
zIndex: 2,
display: ({ value }) => (value ? 'block' : 'none'),
background: theme.palette.secondary[500],
width: '100%',
[theme.breakpoints.up('md')]: {
marginLeft: 24,
marginRight: 24,
width: 'calc(100% - 48px)',
},
},
resultEntry: {
cursor: 'pointer',
color: theme.palette.common.white,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: '10px 0',
'&:hover': {
color: theme.palette.primary[500],
},
'&:not(:first-child)': {
borderTop: `1px solid ${theme.palette.secondary[400]}`,
},
},
iconWithText: {
display: 'flex',
alignItems: 'center',
},
}));
function GlobalSearch({ onIconClick }) {
const router = useRouter();
const { query } = router;
const [expanded, setExpanded] = useState(false);
const [focus, setFocus] = useState(false);
const [value, setValue] = useState(router.query.q || '');
const classes = useStyles({ focus, value });
const navigate = type => () =>
router.push({ pathname: '/search', query: { type, q: value } });
useEffect(() => void (query.q !== value && setValue(query.q || '')), [
query.q,
]);
const input = (
<TextField
id="search"
variant="outlined"
InputProps={{
startAdornment: (
<InputAdornment className={classes.adornment} position="start">
<SearchIcon />
</InputAdornment>
),
classes: {
input: classes.input,
},
onFocus: () => setFocus(true),
}}
classes={{ root: classes.searchWrapper }}
value={value}
onChange={e => {
setValue(e.target.value);
if (!e.target.value && expanded) setExpanded(false);
}}
/>
);
return (
<ClickAwayListener onClickAway={() => setFocus(false)}>
<div className={classes.root}>
<Box display={['none', 'none', 'block']}>{input}</Box>
<Box display={['block', 'block', 'none']} textAlign="right">
{expanded ? (
input
) : (
<SearchIcon
onClick={() => {
setExpanded(!expanded);
onIconClick();
}}
/>
)}
</Box>
{!!value && focus && (
<div className={classes.result}>
<div className={classes.resultEntry} onClick={navigate('messages')}>
<div className={classes.iconWithText}>
<Box component={SearchIcon} mr={1.5} />
{value}
</div>
<div className={classes.right}>{t`in Messages`}</div>
</div>
<div className={classes.resultEntry} onClick={navigate('replies')}>
<div className={classes.iconWithText}>
<Box component={SearchIcon} mr={1.5} />
{value}
</div>
<div className={classes.right}>{t`in Replies`}</div>
</div>
</div>
)}
</div>
</ClickAwayListener>
);
}
export default GlobalSearch;
|
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import { t } from 'ttag';
import {
Box,
InputAdornment,
TextField,
ClickAwayListener,
makeStyles,
} from '@material-ui/core';
import SearchIcon from '@material-ui/icons/Search';
const useStyles = makeStyles(theme => ({
root: {
flex: 1,
position: 'relative',
},
searchWrapper: {
padding: '0 8px',
width: '100%',
[theme.breakpoints.up('md')]: {
padding: '0 24px',
},
},
input: {
padding: '10px 0',
cursor: 'pointer',
},
adornment: {
color: ({ focus }) => (focus ? theme.palette.primary[500] : 'inherit'),
},
result: {
padding: '0 20px',
position: 'absolute',
zIndex: 1,
display: ({ value }) => (value ? 'block' : 'none'),
background: theme.palette.secondary[500],
width: '100%',
[theme.breakpoints.up('md')]: {
marginLeft: 24,
marginRight: 24,
width: 'calc(100% - 48px)',
},
},
resultEntry: {
cursor: 'pointer',
color: theme.palette.common.white,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: '10px 0',
'&:hover': {
color: theme.palette.primary[500],
},
'&:not(:first-child)': {
borderTop: `1px solid ${theme.palette.secondary[400]}`,
},
},
iconWithText: {
display: 'flex',
alignItems: 'center',
},
}));
function GlobalSearch({ onIconClick }) {
const router = useRouter();
const { query } = router;
const [expanded, setExpanded] = useState(false);
const [focus, setFocus] = useState(false);
const [value, setValue] = useState(router.query.q || '');
const classes = useStyles({ focus, value });
const navigate = type => () =>
router.push({ pathname: '/search', query: { type, q: value } });
useEffect(() => void (query.q !== value && setValue(query.q || '')), [
query.q,
]);
const input = (
<TextField
id="search"
variant="outlined"
InputProps={{
startAdornment: (
<InputAdornment className={classes.adornment} position="start">
<SearchIcon />
</InputAdornment>
),
classes: {
input: classes.input,
},
onFocus: () => setFocus(true),
}}
classes={{ root: classes.searchWrapper }}
value={value}
onChange={e => {
setValue(e.target.value);
if (!e.target.value && expanded) setExpanded(false);
}}
/>
);
return (
<ClickAwayListener onClickAway={() => setFocus(false)}>
<div className={classes.root}>
<Box display={['none', 'none', 'block']}>{input}</Box>
<Box display={['block', 'block', 'none']} textAlign="right">
{expanded ? (
input
) : (
<SearchIcon
onClick={() => {
setExpanded(!expanded);
onIconClick();
}}
/>
)}
</Box>
{!!value && focus && (
<div className={classes.result}>
<div className={classes.resultEntry} onClick={navigate('messages')}>
<div className={classes.iconWithText}>
<Box component={SearchIcon} mr={1.5} />
{value}
</div>
<div className={classes.right}>{t`in Messages`}</div>
</div>
<div className={classes.resultEntry} onClick={navigate('replies')}>
<div className={classes.iconWithText}>
<Box component={SearchIcon} mr={1.5} />
{value}
</div>
<div className={classes.right}>{t`in Replies`}</div>
</div>
</div>
)}
</div>
</ClickAwayListener>
);
}
export default GlobalSearch;
|
JavaScript
| 0.000002
|
ea4350063182f28a3c45451ceb9758d025f96840
|
add markdown plugin for markdown to html conversion via marked
|
runner.js
|
runner.js
|
const fs = require('fs')
const path = require('path')
const glob = require('glob')
const matter = require('gray-matter')
const marked = require('marked')
const DEFAULT_OPTIONS = {
source: './content',
target: './public'
}
const data = {
files: {},
meta: {
title: 'test'
},
options: DEFAULT_OPTIONS
}
// util functions
const readFile = file => ({
path: file,
name: path.basename(file),
content: fs.readFileSync(file, {encoding: 'utf-8'})
})
// plugins
const readFiles = () => data => ({
files: glob.sync('./content/**/*.md').map(readFile)
})
const options = (options) => data => {
options = Object.assign(DEFAULT_OPTIONS, options)
return {options}
}
const meta = (meta) => data => ({meta})
const yamlFrontMatter = () => data => {
return {
files: data.files.map(file => {
const {data, content} = matter(file.content)
return Object.assign(file, {
meta: data,
content
})
})
}
}
const markdown = () => data => {
return {
files: data.files.map(file => {
return Object.assign(file, {
content: marked(file.content)
})
})
}
}
const render = template => data => {
return {
files: data.files.map(file => {
const pageData = Object.assign({}, data, {
page: file
})
return Object.assign(file, {
content: template(pageData)
})
})
}
}
const logData = () => data => console.log(JSON.stringify(data, null, 2))
const createIndexFile = () => data => {
return {
files: data.files.concat([{
path: './index.html',
name: 'index.html',
content: ''
}])
}
}
const writeFiles = () => data => {
data.files.forEach(file => {
const targetPath = path.join(data.options.target, path.relative(data.options.source, file.path))
fs.writeFileSync(targetPath, file.content)
})
}
// runner
const runner = () => {
let plugins = []
let data = {}
return {
use (plugin) {
plugins.push(plugin)
return this
},
build () {
plugins.forEach(plugin => {
data = Object.assign(data, plugin(data))
})
}
}
}
runner()
.use(options({
testOption: 'test'
}))
.use(meta({
title: 'Hello World!'
}))
.use(readFiles())
.use(createIndexFile())
.use(yamlFrontMatter())
.use(markdown())
.use(render(require('./templates/index.js')))
.use(writeFiles())
.use(logData())
.build()
|
const fs = require('fs')
const path = require('path')
const glob = require('glob')
const matter = require('gray-matter')
const DEFAULT_OPTIONS = {
source: './content',
target: './public'
}
const data = {
files: {},
meta: {
title: 'test'
},
options: DEFAULT_OPTIONS
}
// util functions
const readFile = file => ({
path: file,
name: path.basename(file),
content: fs.readFileSync(file, {encoding: 'utf-8'})
})
// plugins
const readFiles = () => data => ({
files: glob.sync('./content/**/*.md').map(readFile)
})
const options = (options) => data => {
options = Object.assign(DEFAULT_OPTIONS, options)
return {options}
}
const meta = (meta) => data => ({meta})
const yamlFrontMatter = () => data => {
return {
files: data.files.map(file => {
const {data, content} = matter(file.content)
return Object.assign(file, {
meta: data,
content
})
})
}
}
const render = template => data => {
return {
files: data.files.map(file => {
const pageData = Object.assign({}, data, {
page: file
})
return Object.assign(file, {
content: template(pageData)
})
})
}
}
const logData = () => data => console.log(JSON.stringify(data, null, 2))
const createIndexFile = () => data => {
return {
files: data.files.concat([{
path: './index.html',
name: 'index.html',
content: ''
}])
}
}
const writeFiles = () => data => {
data.files.forEach(file => {
const targetPath = path.join(data.options.target, path.relative(data.options.source, file.path))
fs.writeFileSync(targetPath, file.content)
})
}
// runner
const runner = () => {
let plugins = []
let data = {}
return {
use (plugin) {
plugins.push(plugin)
return this
},
build () {
plugins.forEach(plugin => {
data = Object.assign(data, plugin(data))
})
}
}
}
runner()
.use(options({
testOption: 'test'
}))
.use(meta({
title: 'Hello World!'
}))
.use(readFiles())
.use(createIndexFile())
.use(yamlFrontMatter())
.use(render(require('./templates/index.js')))
.use(writeFiles())
.use(logData())
.build()
|
JavaScript
| 0
|
b9a9338d074e868ebbe053e8bbc46aae8fd5edd2
|
undo last change... who am i kidding, these commits are just tests for webhooks.
|
src/map.js
|
src/map.js
|
/*!
** Created by Jacques Vincilione, Justin Johns - Lucien Consulting, INC
** Requires Google Maps API to be included.
**
** Standard MIT License
Copyright (c) 2015 Lucien Consulting, INC
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**
*/
(function () {
"use strict";
var map_marker = { version: "1.0" },
map;
/**
* [initMap initializes map with custom markers]
* @param {object} centerPoint [lat, long coordinates (IE: {lat: 24.2131, lng: 14.45245})]
* @param {integer} zoom [Integer of zoom level - Defaults to 12]
* @param {array} markers [Array of Map Objects]
* @param {string} elementId [DOM Element ID - Defaults to 'map-canvas']
*/
var initMap = function (centerPoint, zoom, markers, elementId, mapType) {
// throw error if google maps API is not included
if (!google.maps) {
throw new Error("This plugin requires the google maps api to be included on the page. Visit https://developers.google.com/maps/documentation/javascript/tutorial for instructions.");
}
// throw error is centerPoint is undefined
if (!centerPoint) {
throw new Error("mapConfig.centerPoint is not defined, and is required.");
}
// throw error if markers is not an array
if (!markers || markers.length < 1) {
throw new Error("mapConfig.markers is not a valid array.");
}
// set defaults if values are undefined/null
zoom = zoom || 12;
elementId = elementId || "map-canvas";
var mapOptions = {
zoom: zoom,
center: new google.maps.LatLng(centerPoint.lat, centerPoint.lng),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
map = new google.maps.Map(document.getElementById(elementId), mapOptions);
/*
markers requires an image, latLng in each object in the array
optional values:
mapSize (defaults to {w: 50, h: 50}), title (defaults to 'My Marker')
*/
for (var i = 0; i < markers.length; i++) {
var pos = {
lat: markers[i].latLng.lat,
lng: markers[i].latLng.lng
},
img = markers[i].image,
w = markers[i].size.w || 50,
h = markers[i].size.h || 50,
title = markers[i].title || "My Marker",
mapMarker;
if (!pos.lat || !img) {
throw new Error("mapConfig.markers.latLng or mapConfig.markers.image is not defined. Array Index = " + i);
}
mapMarker = new google.maps.Marker({
"position": new google.maps.LatLng(pos.lat, pos.lng),
"icon": new google.maps.MarkerImage(img, new google.maps.Size(w, h)),
"map": map,
"zindex": i,
"title": title
})
}
}
google.maps.event.addDomListener(window, 'load', function () {
initMap(mapConfig.centerPoint, mapConfig.zoom, mapConfig.markers, mapConfig.elementId);
});
}());
|
/*!
** Created by Jacques Vincilione, Justin Johns - Lucien Consulting, INC
** Requires Google Maps API to be included.
**
** Standard MIT License
Copyright (c) 2015 Lucien Consulting, INC
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**
*/
void function () {
"use strict";
var map_marker = { version: "1.0" },
map;
/**
* [initMap initializes map with custom markers]
* @param {object} centerPoint [lat, long coordinates (IE: {lat: 24.2131, lng: 14.45245})]
* @param {integer} zoom [Integer of zoom level - Defaults to 12]
* @param {array} markers [Array of Map Objects]
* @param {string} elementId [DOM Element ID - Defaults to 'map-canvas']
*/
var initMap = function (centerPoint, zoom, markers, elementId, mapType) {
// throw error if google maps API is not included
if (!google.maps) {
throw new Error("This plugin requires the google maps api to be included on the page. Visit https://developers.google.com/maps/documentation/javascript/tutorial for instructions.");
}
// throw error is centerPoint is undefined
if (!centerPoint) {
throw new Error("mapConfig.centerPoint is not defined, and is required.");
}
// throw error if markers is not an array
if (!markers || markers.length < 1) {
throw new Error("mapConfig.markers is not a valid array.");
}
// set defaults if values are undefined/null
zoom = zoom || 12;
elementId = elementId || "map-canvas";
var mapOptions = {
zoom: zoom,
center: new google.maps.LatLng(centerPoint.lat, centerPoint.lng),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
map = new google.maps.Map(document.getElementById(elementId), mapOptions);
/*
markers requires an image, latLng in each object in the array
optional values:
mapSize (defaults to {w: 50, h: 50}), title (defaults to 'My Marker')
*/
for (var i = 0; i < markers.length; i++) {
var pos = {
lat: markers[i].latLng.lat,
lng: markers[i].latLng.lng
},
img = markers[i].image,
w = markers[i].size.w || 50,
h = markers[i].size.h || 50,
title = markers[i].title || "My Marker",
mapMarker;
if (!pos.lat || !img) {
throw new Error("mapConfig.markers.latLng or mapConfig.markers.image is not defined. Array Index = " + i);
}
mapMarker = new google.maps.Marker({
"position": new google.maps.LatLng(pos.lat, pos.lng),
"icon": new google.maps.MarkerImage(img, new google.maps.Size(w, h)),
"map": map,
"zindex": i,
"title": title
})
}
}
google.maps.event.addDomListener(window, 'load', function () {
initMap(mapConfig.centerPoint, mapConfig.zoom, mapConfig.markers, mapConfig.elementId);
});
}();
|
JavaScript
| 0
|
43d3284c74ea9cd651b58d90665799440df5d65e
|
Update mainLucas.js
|
assetsLucas/js/mainLucas.js
|
assetsLucas/js/mainLucas.js
|
$( document ).ready(function() {
/*
//only for ajax navi
$(".masthead__menu-item").each(
function(){
$( this ).on( "click", function() {
$(".masthead__menu-item").removeClass("links-activeItem");
$( this ).addClass("links-activeItem");
});
}
);
*/
});
|
$( document ).ready(function() {
$(".masthead__menu-item").each(
function(){
$( this ).on( "click", function() {
//$(".masthead__menu-item").removeClass("links-activeItem");
//$( this ).addClass("links-activeItem");
//console.log("masthead__menu-item:I am caleld");
window.activeNaviItem = $( this );
console.log(window.activeNaviItem );
});
}
);
if(window.activeNaviItem)
{
$(window.activeNaviItem).addClass("links-activeItem");
}
});
|
JavaScript
| 0.000001
|
2e538754422f4844c854261c52aba8bc9ec87449
|
add param 'root' to MDSConsole.run callback
|
js/console.js
|
js/console.js
|
var MDSConsole = {
/**
* Private!
* Posts message to console.
*/
post: function(type, message) {
var logRecord = document.createElement('div');
logRecord.classList.add('run_script__console_record');
logRecord.textContent = message;
var console = document.getElementById('run_script__console');
console.appendChild(logRecord);
console.scrollTop = console.scrollHeight - console.clientHeight;
logRecord.classList.add('run_script__console_record--' + type);
},
log: function(message) { MDSConsole.post('log', message) },
info: function(message) { MDSConsole.post('info', message) },
warn: function(message) { MDSConsole.post('warn', message) },
system: function(message) { MDSConsole.post('system', message) },
/**
* Call this method when one of the subtasks completed with error. But script
* does not stopped.
*/
error: function(message) { MDSConsole.post('error', message) },
/**
* Call this method when one of the subtasks successfully completed.
*/
ok: function(message) { MDSConsole.post('ok', message) },
/**
* Script successful completed. Call this method at the and or your script.
*/
success: function(message) {
document.getElementById('run_script__state').classList.remove('fa-spin');
document.getElementById('run_script__state').classList.remove('fa-cog');
document.getElementById('run_script__state').classList.remove('run_script__state--run');
document.getElementById('run_script__state').classList.add('fa-check');
document.getElementById('run_script__state').classList.add('run_script__state--success');
if (message == null) {
message = 'The script completed successfully';
}
MDSConsole.post('success', message)
},
/**
* Script failed. Call this method when script finished by error.
*/
fail: function(message) {
if (message == null) {
message = 'The script failed';
}
document.getElementById('run_script__state').classList.remove('fa-spin');
document.getElementById('run_script__state').classList.remove('fa-cog');
document.getElementById('run_script__state').classList.remove('run_script__state--run');
document.getElementById('run_script__state').classList.add('fa-times');
document.getElementById('run_script__state').classList.add('run_script__state--fail');
MDSConsole.error(message);
},
run: function(optionsOrAction, action) {
if (typeof optionsOrAction === 'function') {
action = optionsOrAction;
optionsOrAction = {};
}
var options = MDSCommon.extend({
simpleFormat: true,
connectAndLogin: true
}, optionsOrAction);
if (options.simpleFormat) {
Mydataspace.registerFormatter('entities.get.res', new EntitySimplifier());
Mydataspace.registerFormatter('entities.change.res', new EntitySimplifier());
Mydataspace.registerFormatter('entities.create.res', new EntitySimplifier());
Mydataspace.registerFormatter('entities.getRoots.res', new EntitySimplifier());
Mydataspace.registerFormatter('entities.getMyRoots.res', new EntitySimplifier());
}
if (options.connectAndLogin && !Mydataspace.isLoggedIn()) {
MDSConsole.log('Connecting...');
Mydataspace.connect().then(function () {
MDSConsole.log('Connected! Logging in...');
return new Promise(function (resolve, reject) {
Mydataspace.on('login', function () {
MDSConsole.log('Logged In!');
resolve();
});
Mydataspace.on('unauthorized', function () {
reject(new Error('Unauthorized'));
});
});
}).then(function () {
return action(Mydataspace.getRoot(MDSConsole.root));
}).then(function (res) {
MDSConsole.success(res);
}, function (err) {
MDSConsole.fail(err.message);
});
}
}
};
|
var MDSConsole = {
/**
* Private!
* Posts message to console.
*/
post: function(type, message) {
var logRecord = document.createElement('div');
logRecord.classList.add('run_script__console_record');
logRecord.textContent = message;
var console = document.getElementById('run_script__console');
console.appendChild(logRecord);
console.scrollTop = console.scrollHeight - console.clientHeight;
logRecord.classList.add('run_script__console_record--' + type);
},
log: function(message) { MDSConsole.post('log', message) },
info: function(message) { MDSConsole.post('info', message) },
warn: function(message) { MDSConsole.post('warn', message) },
system: function(message) { MDSConsole.post('system', message) },
/**
* Call this method when one of the subtasks completed with error. But script
* does not stopped.
*/
error: function(message) { MDSConsole.post('error', message) },
/**
* Call this method when one of the subtasks successfully completed.
*/
ok: function(message) { MDSConsole.post('ok', message) },
/**
* Script successful completed. Call this method at the and or your script.
*/
success: function(message) {
document.getElementById('run_script__state').classList.remove('fa-spin');
document.getElementById('run_script__state').classList.remove('fa-cog');
document.getElementById('run_script__state').classList.remove('run_script__state--run');
document.getElementById('run_script__state').classList.add('fa-check');
document.getElementById('run_script__state').classList.add('run_script__state--success');
if (message == null) {
message = 'The script completed successfully';
}
MDSConsole.post('success', message)
},
/**
* Script failed. Call this method when script finished by error.
*/
fail: function(message) {
if (message == null) {
message = 'The script failed';
}
document.getElementById('run_script__state').classList.remove('fa-spin');
document.getElementById('run_script__state').classList.remove('fa-cog');
document.getElementById('run_script__state').classList.remove('run_script__state--run');
document.getElementById('run_script__state').classList.add('fa-times');
document.getElementById('run_script__state').classList.add('run_script__state--fail');
MDSConsole.error(message);
},
run: function(optionsOrAction, action) {
if (typeof optionsOrAction === 'function') {
action = optionsOrAction;
optionsOrAction = {};
}
var options = MDSCommon.extend({
simpleFormat: true,
connectAndLogin: true
}, optionsOrAction);
if (options.simpleFormat) {
Mydataspace.registerFormatter('entities.get.res', new EntitySimplifier());
Mydataspace.registerFormatter('entities.change.res', new EntitySimplifier());
Mydataspace.registerFormatter('entities.create.res', new EntitySimplifier());
Mydataspace.registerFormatter('entities.getRoots.res', new EntitySimplifier());
Mydataspace.registerFormatter('entities.getMyRoots.res', new EntitySimplifier());
}
if (options.connectAndLogin && !Mydataspace.isLoggedIn()) {
MDSConsole.log('Connecting...');
Mydataspace.connect().then(function () {
MDSConsole.log('Connected! Logging in...');
return new Promise(function (resolve, reject) {
Mydataspace.on('login', function () {
MDSConsole.log('Logged In!');
resolve();
});
Mydataspace.on('unauthorized', function () {
reject(new Error('Unauthorized'));
});
});
}).then(function () {
return action();
}).then(function (res) {
MDSConsole.success(res);
}, function (err) {
MDSConsole.fail(err.message);
});
}
}
};
|
JavaScript
| 0.000003
|
db37aed97b45e3d57013e15598bf15eeebc7fcb4
|
Allow setting arbitrary image
|
script.js
|
script.js
|
(function () {
var $sam, $top, parms;
function randomOffset() {
var range = 15;
return Math.floor(Math.random() * range) - Math.ceil(range / 2);
}
function wiggle() {
setDimensions();
setPosition();
}
function setDimensions() {
var scaleWidth, scaleHeight, scaleRatio, newWidth, newHeight;
scaleWidth = $top.width() / $sam.width();
scaleHeight = $top.height() / $sam.height();
scaleRatio = Math.min(scaleWidth, scaleHeight);
newWidth = $sam.width() * scaleRatio;
newHeight = $sam.height() * scaleRatio;
$sam.css({
width: newWidth,
height: newHeight
});
}
function setPosition() {
var baseLeft, baseTop, newTop, newLeft;
baseLeft = ($top.width() / 2) - ($sam.width() / 2);
baseTop = ($top.height() / 2) - ($sam.height() / 2);
newTop = baseTop + randomOffset() + 'px';
newLeft = baseLeft + randomOffset() + 'px';
$sam.css({
marginTop: newTop,
marginLeft: newLeft
});
}
function cacheQueries() {
$sam = $('img');
$top = $(window.top);
}
function setImage() {
if (parms['img']) {
$sam.attr('src', parms['img']);
}
}
function parseParameters() {
var rawParms;
parms = [];
rawParms = location.href.split('?')[1];
if (rawParms === undefined) {
return;
}
$.each(rawParms.split('&'), function() {
var pair, key, value;
pair = this.split('=');
key = pair[0];
value = pair[1];
parms[key] = value;
});
}
$(function () {
parseParameters();
cacheQueries();
setImage();
setInterval(wiggle, 50);
});
}(this));
|
(function () {
var $sam, $top;
function randomOffset() {
var range = 15;
return Math.floor(Math.random() * range) - Math.ceil(range / 2);
}
function wiggle() {
setDimensions();
setPosition();
}
function setDimensions() {
var scaleWidth, scaleHeight, scaleRatio, newWidth, newHeight;
scaleWidth = $top.width() / $sam.width();
scaleHeight = $top.height() / $sam.height();
scaleRatio = Math.min(scaleWidth, scaleHeight);
newWidth = $sam.width() * scaleRatio;
newHeight = $sam.height() * scaleRatio;
$sam.css({
width: newWidth,
height: newHeight
});
}
function setPosition() {
var baseLeft, baseTop, newTop, newLeft;
baseLeft = ($top.width() / 2) - ($sam.width() / 2);
baseTop = ($top.height() / 2) - ($sam.height() / 2);
newTop = baseTop + randomOffset() + 'px';
newLeft = baseLeft + randomOffset() + 'px';
$sam.css({
marginTop: newTop,
marginLeft: newLeft
});
}
function cacheQueries() {
$sam = $('img');
$top = $(window.top);
}
$(function () {
cacheQueries();
setInterval(wiggle, 50);
});
}(this));
|
JavaScript
| 0.000004
|
c33b9f0f6c34996d40dbc3854b4a248dc6b62972
|
Add background canvas
|
js/display.js
|
js/display.js
|
import { $$ } from 'util/dom';
import settings from 'settings';
var canvas = document.createElement('canvas');
export var ctx = canvas.getContext('2d');
var rows = settings.rows;
var cols = settings.cols;
var jewelSize = settings.jewelSize;
var firstRun = true;
function createBackground () {
var bg = document.createElement('canvas');
var ctx = bg.getContext('2d');
var x, y;
bg.classList.add('board-bg');
bg.width = cols * jewelSize;
bg.height = rows * jewelSize;
ctx.fillStyle = 'rgba(255,235,255,0.15)';
for (x = 0; x < cols; ++x) {
for (y = 0; y < cols; ++y) {
if ((x+y) % 2) {
ctx.fillRect(
x * jewelSize, y * jewelSize,
jewelSize, jewelSize
);
}
}
}
return bg;
}
function setup () {
var boardElement = $$('#game-screen .game-board')[0];
canvas.classList.add('board');
canvas.width = cols * jewelSize;
canvas.height = rows * jewelSize;
boardElement.appendChild(createBackground());
boardElement.appendChild(canvas);
}
export function initialize (callback) {
if (firstRun) {
setup();
firstRun = false;
}
callback();
}
|
import { $$ } from 'util/dom';
import settings from 'settings';
var canvas = document.createElement('canvas');
export var ctx = canvas.getContext('2d');
var rows = settings.rows;
var cols = settings.cols;
var jewelSize = settings.jewelSize;
var firstRun = true;
function setup () {
var boardElement = $$('#game-screen .game-board')[0];
canvas.classList.add('board');
canvas.width = cols * jewelSize;
canvas.height = rows * jewelSize;
boardElement.appendChild(canvas);
}
export function initialize (callback) {
if (firstRun) {
setup();
firstRun = false;
}
callback();
}
|
JavaScript
| 0.000001
|
26fd757bee1a2da4a9fae8566269622052afdb9a
|
allow multiple values in filters
|
script.js
|
script.js
|
$(function() {
var app = angular.module('app', []);
app.filter('slugify', function() {
return function(input) {
return input.replace(/[^\w]/g, '').replace(/\s+/g, '-').toLowerCase();
};
});
app.controller('Ctrl', function($scope, $http, $location, $filter) {
var all = [];
$http.get('data.tsv').then(function(response) {
$scope.filters = { };
var reverseFilters = {};
$scope.data = d3.tsv.parse(response.data, (function() {
var essentialColumns = ['Titre', 'Chapo', 'Date', 'Lien'];
return function(d) {
d.Date = new Date(d.Date.split('/').reverse()); // Transform date into Date object
// Get filters
_.each(d, function(value, key) {
if (essentialColumns.indexOf(key) < 0 && value.length > 0) {
d[key] = _.map(value.split(','), _.trim);
if ($scope.filters[key] == null) {
// Init filter
reverseFilters[$filter('slugify')(key)] = key;
$scope.filters[key] = {
values: ['--'],
value: $location.search()[$filter('slugify')(key)] || '--', // Try to load value from URL before using default
slug: $filter('slugify')(key)
};
}
$scope.filters[key].values = _.uniq(d[key].concat($scope.filters[key].values));
}
});
return d;
};
})());
// Make sure we're only using existing values
_.each($scope.filters, function(filter, key) {
if (filter.values.indexOf(filter.value) < 0) {
filter.value = '--'; // Reset to default
}
});
all = _.clone($scope.data);
$scope.filter();
});
$scope.filter = function() {
var template = { };
_.each($scope.filters, function(filter, key) {
if (filter.value !== '--') {
template[key] = [filter.value];
}
});
$scope.data = _(_.clone(all)).filter(template).sortByOrder('Date', 'desc').run();
};
$scope.updateURLAndFilter = function() {
// Update URL
_.each($scope.filters, function(filter, key) {
$location.search(filter.slug, filter.value === '--' ? null : filter.value);
});
// And filter
$scope.filter(true);
};
$scope.reset = function() {
// Reset every filter
_.each($scope.filters, function(filter) {
filter.value = '--';
});
$scope.updateURLAndFilter();
};
});
});
|
$(function() {
var app = angular.module('app', []);
app.filter('slugify', function() {
return function(input) {
return input.replace(/[^\w]/g, '').replace(/\s+/g, '-').toLowerCase();
};
});
app.controller('Ctrl', function($scope, $http, $location, $filter) {
var all = [];
$http.get('data.tsv').then(function(response) {
$scope.filters = { };
var reverseFilters = {};
$scope.data = d3.tsv.parse(response.data, (function() {
var essentialColumns = ['Titre', 'Chapo', 'Date', 'Lien'];
return function(d) {
d.Date = new Date(d.Date.split('/').reverse()); // Transform date into Date object
// Get filters
_.each(d, function(value, key) {
if (essentialColumns.indexOf(key) < 0 && value.length > 0) {
if ($scope.filters[key] == null) {
// Init filter
reverseFilters[$filter('slugify')(key)] = key;
$scope.filters[key] = {
values: ['--'],
value: $location.search()[$filter('slugify')(key)] || '--', // Try to load value from URL before using default
slug: $filter('slugify')(key)
};
}
$scope.filters[key].values = _.uniq([value].concat($scope.filters[key].values));
}
});
return d;
};
})());
// Make sure we're only using existing values
_.each($scope.filters, function(filter, key) {
if (filter.values.indexOf(filter.value) < 0) {
filter.value = '--'; // Reset to default
}
});
all = _.clone($scope.data);
$scope.filter();
});
$scope.filter = function() {
var template = { };
_.each($scope.filters, function(filter, key) {
if (filter.value !== '--') {
template[key] = filter.value;
}
});
$scope.data = _(_.clone(all)).filter(template).sortByOrder('Date', 'desc').run();
};
$scope.updateURLAndFilter = function() {
// Update URL
_.each($scope.filters, function(filter, key) {
$location.search(filter.slug, filter.value === '--' ? null : filter.value);
});
// And filter
$scope.filter(true);
};
$scope.reset = function() {
// Reset every filter
_.each($scope.filters, function(filter) {
filter.value = '--';
});
$scope.updateURLAndFilter();
};
});
});
|
JavaScript
| 0.000002
|
0bed76f5ab3dd1cda9304226ed09206812887064
|
Update gruppoc.js
|
js/gruppoc.js
|
js/gruppoc.js
|
gruppo.innerHTML ="<h3>26/5/2017 - Nuovo Badge</h1>Aggiunto un nuovo Badge: il Badge Navigatore. Si ottiene navigando nella piattaforma on line del corso per referenti di sostegno. Il tempo trascorso on line lo potete vedere del registro presenze."
gruppo.innerHTML += "<img src='http://www.alberghierocastelnuovocilento.gov.it/moodlekeys/pluginfile.php/41/badges/badgeimage/26/f1?refresh=9437'><br>"
gruppo.innerHTML += "<iframe width=\"100%\" height=\"200\" src=\"https://www.youtube.com/embed/Il4zpiGLxq0\" frameborder=\"0\" allowfullscreen></iframe></p><p><iframe width=\"100%\" height=\"200\" src=\"https://www.youtube.com/embed/hJdG664iams\" frameborder=\"0\" allowfullscreen></iframe></p><p><iframe width=\"100%\" height=\"200\" src=\"https://www.youtube.com/embed/hfRKsYbt4S0\" frameborder=\"0\" allowfullscreen></iframe>"
|
gruppo.innerHTML ="<h3>26/5/2017 - Nuovo Badge</h1>Aggiunto un nuovo Badge: il Badge Navigatore. Si ottiene navigando nella piattaforma on line del corso per referenti di sostegno. Il tempo trascorso on line lo potete vedere del registro presenze."
gruppo.innerHTML += "<iframe width=\"100%\" height=\"200\" src=\"https://www.youtube.com/embed/Il4zpiGLxq0\" frameborder=\"0\" allowfullscreen></iframe></p><p><iframe width=\"100%\" height=\"200\" src=\"https://www.youtube.com/embed/hJdG664iams\" frameborder=\"0\" allowfullscreen></iframe></p><p><iframe width=\"100%\" height=\"200\" src=\"https://www.youtube.com/embed/hfRKsYbt4S0\" frameborder=\"0\" allowfullscreen></iframe>"
|
JavaScript
| 0.000001
|
0ec5383ea4506399be04713c0809f948dd053e38
|
Change boolean-based options to real booleans
|
js/hipchat.js
|
js/hipchat.js
|
(function() {
// Creates an iframe with an embedded HipChat conversation window.
//
// Options:
// url - The url to the room to embed; required
// el - The container in which to insert the HipChat panel; required
// timezone - The timezone to use in the embedded room; required
// width - The width of the iframe; defaults to 100%
// height - The height of the iframe; defaults to 400px
var parametize = function(params) {
var key, toks = [];
for (key in params) {
toks.push(key + '=' + params[key]);
}
return toks.join('&');
};
return this.HipChat = function(options) {
if (options && options.url && options.el && options.timezone) {
var el = document.querySelector(options.el);
if (!el) return;
var params = {
anonymous: false,
timezone: options.timezone,
minimal: true
};
var url = options.url + (options.url.indexOf('?') > 0 ? '&' : '?') +
parametize(params);
if (url.indexOf('https://') !== 0) {
url = 'https://' + url;
}
var w = options.width || '100%';
var h = options.height || 600;
el.innerHTML = '<iframe src="' + url + '" frameborder="' + 0 +
'" width="' + w + '" height="' + h + '"></iframe>';
}
};
})();
|
(function() {
// Creates an iframe with an embedded HipChat conversation window.
//
// Options:
// url - The url to the room to embed; required
// el - The container in which to insert the HipChat panel; required
// timezone - The timezone to use in the embedded room; required
// width - The width of the iframe; defaults to 100%
// height - The height of the iframe; defaults to 400px
var parametize = function(params) {
var key, toks = [];
for (key in params) {
toks.push(key + '=' + params[key]);
}
return toks.join('&');
};
return this.HipChat = function(options) {
if (options && options.url && options.el && options.timezone) {
var el = document.querySelector(options.el);
if (!el) return;
var params = {
anonymous: 0,
timezone: options.timezone,
minimal: 1
};
var url = options.url + (options.url.indexOf('?') > 0 ? '&' : '?') +
parametize(params);
if (url.indexOf('https://') !== 0) {
url = 'https://' + url;
}
var w = options.width || '100%';
var h = options.height || 600;
el.innerHTML = '<iframe src="' + url + '" frameborder="' + 0 +
'" width="' + w + '" height="' + h + '"></iframe>';
}
};
})();
|
JavaScript
| 0.999921
|
bff7636d9936fef6905b07b3c8d1c82309de873d
|
Fix i18n import
|
src/translation/index.js
|
src/translation/index.js
|
import {t, init} from 'i18next-client';
export default {
translate: t,
init
};
|
import {t, init} from 'i18next';
export default {
translate: t,
init
};
|
JavaScript
| 0.000019
|
278193fd07101d0f0c92c88892731b144a02f770
|
fix card url
|
js/overlay.js
|
js/overlay.js
|
/* global TrelloPowerUp */
var Promise = TrelloPowerUp.Promise;
var t = TrelloPowerUp.iframe();
var gFormUrl = '';
var cardName = '';
var cardShortLink = '';
var userName = t.arg('user');
// this function we be called once on initial load
// and then called each time something changes
t.render(function(){
return Promise.all([
t.get('board', 'shared', 'url'),
t.card('name', 'url')
])
.spread(function(savedGFormUrl, cardData){
if(savedGFormUrl){
gFormUrl = savedGFormUrl;
} else {
document.getElementById('overlay-message')
.textContent = 'Please add form url on settings';
}
if(cardData){
cardName = cardData.name;
cardUrl = cardData.url;
}
})
.then(function(){
document.getElementsByTagName('iframe')[0].src = gFormUrl +
"?embedded=true&entry.995291397=" + cardName +
"&entry.33315152=" + userName +
"&entry.1600294234=" + cardUrl;
})
});
// close overlay if user clicks outside our content
document.addEventListener('click', function(e) {
if(e.target.tagName == 'BODY') {
t.closeOverlay().done();
}
});
// close overlay if user presses escape key
document.addEventListener('keyup', function(e) {
if(e.keyCode == 27) {
t.closeOverlay().done();
}
});
|
/* global TrelloPowerUp */
var Promise = TrelloPowerUp.Promise;
var t = TrelloPowerUp.iframe();
var gFormUrl = '';
var cardName = '';
var cardShortLink = '';
var userName = t.arg('user');
// this function we be called once on initial load
// and then called each time something changes
t.render(function(){
return Promise.all([
t.get('board', 'shared', 'url'),
t.card('name', 'shortLink')
])
.spread(function(savedGFormUrl, cardData){
if(savedGFormUrl){
gFormUrl = savedGFormUrl;
} else {
document.getElementById('overlay-message')
.textContent = 'Please add form url on settings';
}
if(cardData){
cardName = cardData.name;
cardUrl = cardData.shortLink;
}
})
.then(function(){
document.getElementsByTagName('iframe')[0].src = gFormUrl +
"?embedded=true&entry.995291397=" + cardName +
"&entry.33315152=" + userName +
"&entry.1600294234" + cardUrl;
})
});
// close overlay if user clicks outside our content
document.addEventListener('click', function(e) {
if(e.target.tagName == 'BODY') {
t.closeOverlay().done();
}
});
// close overlay if user presses escape key
document.addEventListener('keyup', function(e) {
if(e.keyCode == 27) {
t.closeOverlay().done();
}
});
|
JavaScript
| 0.000001
|
93dc8cc1043b757c2cb1215d82335a7328781245
|
Add pcr module initiation
|
src/pcr.js
|
src/pcr.js
|
var express = require('express');
var path = require('path');
var PCR = require('pcr');
var TOKEN = process.env.PCR_AUTH_TOKEN || 'public';
var pcr = new PCR(TOKEN);
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/', (req, res) => {
res.render('index');
});
app.listen(app.get('port'), () => {
console.log('Server running on port ' + app.get('port'));
});
|
var express = require('express');
var path = require('path');
var PCR = require('pcr');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/', (req, res) => {
res.render('index');
});
app.listen(app.get('port'), () => {
console.log('Server running on port ' + app.get('port'));
});
|
JavaScript
| 0
|
2878330894a28fd0a7ad3bf5e0f21f9cea3265a3
|
Improve element check + include scroll position object to set the current scrolling position
|
scroll.js
|
scroll.js
|
import viewport from './viewport';
import size from './size';
import isObject from './isObject';
import isWindow from './isWindow';
import isDOMElement from './isDOMElement';
import inDOM from './inDOM';
/**
* Find the current scroll position of a HTML Element
* @param {HTMLElement|window} [elm = viewport] - The HTML element to find the scrolling position from
* @return {Object} - The current scroll information
*/
export default function scroll(elm = window, scrollPos = null) {
let isWin = isWindow(elm);
if(!isWin) {
if(isObject(elm)) { [elm, scrollPos] = [window, elm]; }
if(isDOMElement(elm, 'html', 'body')) { elm = elm.ownerDocument; }
if(typeof elm.defaultView !== 'undfined') { elm = elm.defaultView; }
isWin = isWindow(elm);
if(!(isDOMElement(elm) && inDOM(elm)) || isWin) { return null; }
}
const view = isWin ? viewport(elm) : elm;
if(scrollPos) {
const { byX, byY, x, y } = scrollPos;
if(!isNaN(x)) { view.scrollTop = x; }
else if(!isNaN(byX)) { view.scrollTop += byX; }
if(!isNaN(y)) { view.scrollTop = y; }
else if(!isNaN(byY)) { view.scrollTop += byY; }
}
const s = size(elm);
return {
x: view.scrollLeft,
xMax: s.contentWidth - s.innerWidth,
y: view.scrollTop,
yMax: s.contentHeight - s.innerHeight
};
}
|
import viewport from './viewport';
/**
* Find the current scroll position of a HTML Element
* @param {HTMLElement|window} [elm = viewport] - The HTML element to find the scrolling position from
* @return {Object} - The current scroll information
*/
export default function scroll(elm = viewport) {
// Take the viewport if window is the element
if(elm === window) { elm = viewport; }
const width = elm.offsetParent ? elm.offsetWidth : window.innerWidth;
const height = elm.offsetParent ? elm.offsetHeight : window.innerHeight;
return {
top: elm.scrollTop,
maxTop: elm.scrollHeight - height,
left: elm.scrollLeft,
leftMax: elm.scrollWidth - width
};
}
|
JavaScript
| 0
|
c35681ea6b8a6e0a0d1c3e6f9b86f161767a1d41
|
Handle jQuery in noConflict mode.
|
js/scripts.js
|
js/scripts.js
|
// DOM Ready
jQuery(document).ready(function($) {
// SVG fallback
// toddmotto.com/mastering-svg-use-for-a-retina-web-fallbacks-with-png-script#update
if (!Modernizr.svg) {
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
if (/.*\.svg$/.test(imgs[i].src)) {
imgs[i].src = imgs[i].src.slice(0, -3) + 'png';
}
}
}
});
|
// DOM Ready
$(function() {
// SVG fallback
// toddmotto.com/mastering-svg-use-for-a-retina-web-fallbacks-with-png-script#update
if (!Modernizr.svg) {
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
if (/.*\.svg$/.test(imgs[i].src)) {
imgs[i].src = imgs[i].src.slice(0, -3) + 'png';
}
}
}
});
|
JavaScript
| 0
|
e4d905bd08aea8a3295f8da41997edb1784c7262
|
Make types strict-local.
|
src/utils/testHelpers.js
|
src/utils/testHelpers.js
|
/* @flow strict-local */
import type { Narrow } from '../types';
export const navStateWithNarrow = (narrow: Narrow): {| nav: mixed |} => ({
nav: {
index: 0,
routes: [
{
routeName: 'chat',
params: {
narrow,
},
},
],
},
});
export const defaultNav = {
index: 0,
routes: [{ routeName: 'chat' }],
};
export const otherNav = {
index: 1,
routes: [{ routeName: 'main' }, { routeName: 'account' }],
};
|
/* @flow */
import type { Narrow } from '../types';
export const navStateWithNarrow = (narrow: Narrow): Object => ({
nav: {
index: 0,
routes: [
{
routeName: 'chat',
params: {
narrow,
},
},
],
},
});
export const defaultNav = {
index: 0,
routes: [{ routeName: 'chat' }],
};
export const otherNav = {
index: 1,
routes: [{ routeName: 'main' }, { routeName: 'account' }],
};
|
JavaScript
| 0
|
4af0f0809a5c23f733dde4d08994a10c6ca62262
|
Add author and license comment
|
src/videojs-playcount.js
|
src/videojs-playcount.js
|
import videojs from 'video.js';
/**
* A video.js plugin to handle basic play counting for videos. By default, a
* `played` event will be triggered on the player if the video has played for a
* cumulative 10% of its total video length.
*
* Author: Nick Pafundi / Clover Sites
* License: MIT
*
* Options
* playTimer: Number of seconds necessary for a view to be considered a play.
* Note that this takes precedence over `playTimerPercent`. If the
* given video is shorter than `playTimer`, no plays will be
* counted.
* playTimerPercent: Percentage (as a decimal between 0 and 1) of a video
* necessary for a view to be considered a play. Note that
* the `playTimer` option takes precedence.
*
* Limitations
* This is only intended for basic play counting. Anyone with familiarity with
* JavaScript and a browser console could adjust values to artificially inflate
* the play count.
*/
const playcount = function(options) {
this.ready(function() {
options = options || {};
this.on('play', play);
this.on('pause', pause);
});
var playtime = 0;
var neededPlaytime, played, timer;
function play() {
var player = this;
calculateNeededPlaytime(this.duration());
// If the video has been restarted at 0 and was already played, reset the
// played flag to allow multiple plays
if (played && this.currentTime() === 0) {
resetInterval();
played = false;
playtime = 0;
}
// If the video hasn't completed a play (and no timer is running), set up a
// timer to track the play time.
if (!timer && !played) {
// Round everything to 500ms. Every time this interval ticks, add .5s to
// the total counted play time. Once we hit the needed play time for a
// play, trigger a 'played' event.
timer = setInterval(function() {
playtime += 0.5;
if (playtime >= neededPlaytime) {
played = true;
player.trigger('played');
resetInterval();
}
}, 500);
}
}
// On pause, reset the current timer
function pause() {
if (timer) resetInterval(timer);
}
// Clear and nullify the timer
function resetInterval() {
clearInterval(timer);
timer = null;
}
// Calculate the needed playtime based on any provided options.
function calculateNeededPlaytime(duration) {
// TODO: Move 0.1 to defaults for playTimerPercent and merge defaults with options
var percent = options.playTimerPercent || 0.1;
neededPlaytime = neededPlaytime || options.playTimer || (duration * percent);
}
};
// Register the plugin with video.js.
videojs.plugin('playcount', playcount);
export default playcount;
|
import videojs from 'video.js';
/**
* A video.js plugin to handle basic play counting for videos. By default, a
* `played` event will be triggered on the player if the video has played for a
* cumulative 10% of its total video length.
*
* Options
* playTimer: Number of seconds necessary for a view to be considered a play.
* Note that this takes precedence over `playTimerPercent`. If the
* given video is shorter than `playTimer`, no plays will be
* counted.
* playTimerPercent: Percentage (as a decimal between 0 and 1) of a video
* necessary for a view to be considered a play. Note that
* the `playTimer` option takes precedence.
*
* Limitations
* This is only intended for basic play counting. Anyone with familiarity with
* JavaScript and a browser console could adjust values to artificially inflate
* the play count.
*/
const playcount = function(options) {
this.ready(function() {
options = options || {};
this.on('play', play);
this.on('pause', pause);
});
var playtime = 0;
var neededPlaytime, played, timer;
function play() {
var player = this;
calculateNeededPlaytime(this.duration());
// If the video has been restarted at 0 and was already played, reset the
// played flag to allow multiple plays
if (played && this.currentTime() === 0) {
resetInterval();
played = false;
playtime = 0;
}
// If the video hasn't completed a play (and no timer is running), set up a
// timer to track the play time.
if (!timer && !played) {
// Round everything to 500ms. Every time this interval ticks, add .5s to
// the total counted play time. Once we hit the needed play time for a
// play, trigger a 'played' event.
timer = setInterval(function() {
playtime += 0.5;
if (playtime >= neededPlaytime) {
played = true;
player.trigger('played');
resetInterval();
}
}, 500);
}
}
// On pause, reset the current timer
function pause() {
if (timer) resetInterval(timer);
}
// Clear and nullify the timer
function resetInterval() {
clearInterval(timer);
timer = null;
}
// Calculate the needed playtime based on any provided options.
function calculateNeededPlaytime(duration) {
// TODO: Move 0.1 to defaults for playTimerPercent and merge defaults with options
var percent = options.playTimerPercent || 0.1;
neededPlaytime = neededPlaytime || options.playTimer || (duration * percent);
}
};
// Register the plugin with video.js.
videojs.plugin('playcount', playcount);
export default playcount;
|
JavaScript
| 0
|
9e104db2e1eea685f0f50e8a46b2a91c3b5b2755
|
Send error messages back to Slack
|
server.js
|
server.js
|
var config = require('config');
var express = require('express');
var bodyParser = require('body-parser');
var ircdispatcher = require('./lib/ircdispatcher');
var messageparser = require('./lib/messageparser');
var l = require('./lib/log')('Server');
var db = require('./lib/db');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/toirc', function(req, res){
l.debug('Got incoming msg to IRC: ', req.body);
messageparser.parseIrcMessage(req.body)
.then(function(message) {
return ircdispatcher.postMessage(message);
})
.then(function(result) {
if (result && result.sent)
l.verbose('IRC message sent to IRC server');
res.status(200).end();
}, function error (e) {
if (e.name === 'HttpError') {
// Send 200 so that Slack will display the message
res.status(200).json({text: 'Error: ' + e.message});
} else {
l.error('%s\nStack: "%s"', e.toString(), e.stack);
res.status(500);
}
})
.done();
});
var server = app.listen(config.server.port, function() {
db.load();
l.info('Listening on port ' + config.server.port);
});
|
var config = require('config');
var express = require('express');
var bodyParser = require('body-parser');
var ircdispatcher = require('./lib/ircdispatcher');
var messageparser = require('./lib/messageparser');
var l = require('./lib/log')('Server');
var db = require('./lib/db');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/toirc', function(req, res){
l.debug('Got incoming msg to IRC: ', req.body);
messageparser.parseIrcMessage(req.body)
.then(function(message) {
return ircdispatcher.postMessage(message);
})
.then(function(result) {
if (result && result.sent)
l.verbose('IRC message sent to IRC server');
res.status(200).end();
}, function error (e) {
if (e.name !== 'HttpError')
l.error('%s\nStack: "%s"', e.toString(), e.stack);
res.status(e.statusCode);
})
.done();
});
var server = app.listen(config.server.port, function() {
db.load();
l.info('Listening on port ' + config.server.port);
});
|
JavaScript
| 0
|
9e60007fd0ff804d9211a58a53437ee887f6491c
|
replace action of all matching forms
|
src/patterns/autosubmit.js
|
src/patterns/autosubmit.js
|
define([
'require',
'../lib/jquery',
'../lib/jquery.form',
'../lib/dist/underscore',
'./inject',
'./modal'
], function(require) {
// those two for error messages
var inject = require('./inject');
// can be called on a form or an element in a form
var init = function($el) {
// get parameters from markup
var $form = $el.is('form') ? $el : $el.parents('form').first(),
url = $form.attr('action');
// prepare ajax request and submit function
var params = {
error: function(jqXHR, textStatus, errorThrown) {
var msg = [jqXHR.status, textStatus,
$form.attr('action')].join(' '),
// XXX: error notification pattern!
$error = $('<div class="modal"><h3>Error</h3><div class="error message">'+msg+'</div></div>');
inject.append($error, $('body'));
console.error(url, jqXHR, textStatus, errorThrown);
},
success: function(data, textStatus, jqXHR) {
if (!data) return;
var $forms = $(data).find('form[id]');
$forms.each(function() {
var $form = $(this),
id = $(this).attr('id'),
$ourform = $('#' + id);
if ($ourform.length > 0) {
$ourform.attr({action: $form.attr('action')});
} else {
console.warn(
'Ignored form in respone data: not matching id', $form);
}
});
}
};
var submit = function(event) {
$form.ajaxSubmit(params);
};
// submit if a (specific) form element changed
$el.on("change", submit);
// debounced keyup submit, if enabled
if ($el.hasClass('auto-submit-keyup')) {
($el.is('input') ? $el : $el.find('input'))
.on("keyup", _.debounce(submit, 400));
}
$form.on('keyup', function(ev) {
if (ev.which === 13) {
ev.preventDefault();
submit(ev);
}
});
// XXX: test whether on webkit and enable only if supported
// XXX: add code to check whether the click actually changed
// something
($el.is('input[type=search]') ? $el : $el.find('input[type=search]'))
.on("click", submit);
// allow for chaining
return $el;
};
var pattern = {
markup_trigger: ".auto-submit, .auto-submit-keyup",
initialised_class: "auto-submit",
init: init
};
return pattern;
});
|
define([
'require',
'../lib/jquery',
'../lib/jquery.form',
'../lib/dist/underscore',
'./inject',
'./modal'
], function(require) {
// those two for error messages
var inject = require('./inject');
// can be called on a form or an element in a form
var init = function($el) {
// get parameters from markup
var $form = $el.is('form') ? $el : $el.parents('form').first(),
url = $form.attr('action');
// prepare ajax request and submit function
var params = {
error: function(jqXHR, textStatus, errorThrown) {
var msg = [jqXHR.status, textStatus,
$form.attr('action')].join(' '),
// XXX: error notification pattern!
$error = $('<div class="modal"><h3>Error</h3><div class="error message">'+msg+'</div></div>');
inject.append($error, $('body'));
console.error(url, jqXHR, textStatus, errorThrown);
},
success: function(data, textStatus, jqXHR) {
var ourid = $form.attr('id');
if (data && !ourid) {
console.warn('Ignored response data because our has no id', $form);
return;
}
var new_action = $(data).find('#' + ourid).attr('action');
if (new_action) {
$form.attr({action: new_action});
}
}
};
var submit = function(event) {
$form.ajaxSubmit(params);
};
// submit if a (specific) form element changed
$el.on("change", submit);
// debounced keyup submit, if enabled
if ($el.hasClass('auto-submit-keyup')) {
($el.is('input') ? $el : $el.find('input'))
.on("keyup", _.debounce(submit, 400));
}
$form.on('keyup', function(ev) {
if (ev.which === 13) {
ev.preventDefault();
submit(ev);
}
});
// XXX: test whether on webkit and enable only if supported
// XXX: add code to check whether the click actually changed
// something
($el.is('input[type=search]') ? $el : $el.find('input[type=search]'))
.on("click", submit);
// allow for chaining
return $el;
};
var pattern = {
markup_trigger: ".auto-submit, .auto-submit-keyup",
initialised_class: "auto-submit",
init: init
};
return pattern;
});
|
JavaScript
| 0.000001
|
d32380b9b5e10361a9ca0bbd938d50e3900e33be
|
Fix IE compatibility issue using latest Stanbol service.
|
src/xdr.js
|
src/xdr.js
|
// Based on [Julian Aubourg's xdr.js](https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js)
// Internet Explorer 8 & 9 don't support the cross-domain request protocol known as CORS.
// Their solution we use is called XDomainRequest. This module is a wrapper for
// XDR using jQuery ajaxTransport, jQuery's way to support such cases.
// Author: Szaby Grünwald @ Salzburg Research, 2011
/*global XDomainRequest:false console:false jQuery:false */
var root = this;
(function( jQuery ) {
if ( root.XDomainRequest ) {
jQuery.ajaxTransport(function( s ) {
if ( s.crossDomain && s.async ) {
if ( s.timeout ) {
s.xdrTimeout = s.timeout;
delete s.timeout;
}
var xdr;
return {
send: function( _, complete ) {
function callback( status, statusText, responses, responseHeaders ) {
xdr.onload = xdr.onerror = xdr.ontimeout = jQuery.noop;
xdr = undefined;
complete( status, statusText, responses, responseHeaders );
}
xdr = new XDomainRequest();
// For backends supporting header_* in the URI instead of real header parameters,
// use the dataType for setting the Accept request header. e.g. Stanbol supports this.
if(s.dataType){
var headerThroughUriParameters = "header_Accept=" + encodeURIComponent(s.dataType) + "&header_Content-Type=text/plain";
s.url = s.url + (s.url.indexOf("?") === -1 ? "?" : "&" ) + headerThroughUriParameters;
}
xdr.open( s.type, s.url );
xdr.onload = function(e1, e2) {
callback( 200, "OK", { text: xdr.responseText }, "Content-Type: " + xdr.contentType );
};
// XDR cannot differentiate between errors,
// we call every error 404. Could be changed to another one.
xdr.onerror = function(e) {
console.error(JSON.stringify(e));
callback( 404, "Not Found" );
};
if ( s.xdrTimeout ) {
xdr.ontimeout = function() {
callback( 0, "timeout" );
};
xdr.timeout = s.xdrTimeout;
}
xdr.send( ( s.hasContent && s.data ) || null );
},
abort: function() {
if ( xdr ) {
xdr.onerror = jQuery.noop();
xdr.abort();
}
}
};
}
});
}
})( jQuery );
|
// Based on [Julian Aubourg's xdr.js](https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js)
// Internet Explorer 8 & 9 don't support the cross-domain request protocol known as CORS.
// Their solution we use is called XDomainRequest. This module is a wrapper for
// XDR using jQuery ajaxTransport, jQuery's way to support such cases.
// Author: Szaby Grünwald @ Salzburg Research, 2011
/*global XDomainRequest:false console:false jQuery:false */
var root = this;
(function( jQuery ) {
if ( root.XDomainRequest ) {
jQuery.ajaxTransport(function( s ) {
if ( s.crossDomain && s.async ) {
if ( s.timeout ) {
s.xdrTimeout = s.timeout;
delete s.timeout;
}
var xdr;
return {
send: function( _, complete ) {
function callback( status, statusText, responses, responseHeaders ) {
xdr.onload = xdr.onerror = xdr.ontimeout = jQuery.noop;
xdr = undefined;
complete( status, statusText, responses, responseHeaders );
}
xdr = new XDomainRequest();
// For backends supporting header_* in the URI instead of real header parameters,
// use the dataType for setting the Accept request header. e.g. Stanbol supports this.
if(s.dataType){
var headerThroughUriParameters = "header_Accept=" + encodeURIComponent(s.dataType);
s.url = s.url + (s.url.indexOf("?") === -1 ? "?" : "&" ) + headerThroughUriParameters;
}
xdr.open( s.type, s.url );
xdr.onload = function(e1, e2) {
callback( 200, "OK", { text: xdr.responseText }, "Content-Type: " + xdr.contentType );
};
// XDR cannot differentiate between errors,
// we call every error 404. Could be changed to another one.
xdr.onerror = function(e) {
console.error(JSON.stringify(e));
callback( 404, "Not Found" );
};
if ( s.xdrTimeout ) {
xdr.ontimeout = function() {
callback( 0, "timeout" );
};
xdr.timeout = s.xdrTimeout;
}
xdr.send( ( s.hasContent && s.data ) || null );
},
abort: function() {
if ( xdr ) {
xdr.onerror = jQuery.noop();
xdr.abort();
}
}
};
}
});
}
})( jQuery );
|
JavaScript
| 0
|
2ea5769ac4a3d2fb338fca27ce66ce40762be596
|
add interpreter hashbang
|
server.js
|
server.js
|
#!/usr/bin/env node
'use strict';
// Configuration module provides all of the set-up necessary for
// starting the database and configuring the express application
const config = require('./config');
const db = config.mongoose.init();
const app = config.express.init();
// Once the express app is initialized, the API module will
// loop through and set up all of the route callbacks on the app.
const routes = require('./api');
routes.setRoutes(app);
app.listen(config.environment.PORT, function() {
console.log("app listening on port: " + config.environment.PORT);
});
|
'use strict';
// Configuration module provides all of the set-up necessary for
// starting the database and configuring the express application
const config = require('./config');
const db = config.mongoose.init();
const app = config.express.init();
// Once the express app is initialized, the API module will
// loop through and set up all of the route callbacks on the app.
const routes = require('./api');
routes.setRoutes(app);
app.listen(config.environment.PORT, function() {
console.log("app listening on port: " + config.environment.PORT);
});
|
JavaScript
| 0.000013
|
1fec746d2c7f453f5281dc72fc6dfbaf569f0e5a
|
Reorder code in top-down fashion
|
server.js
|
server.js
|
#!/usr/bin/env node
var express = require('express')
var request = require('request')
var app = express()
var slSystems = require('./src/slSystemsCrawler')
var Bacon = require('baconjs').Bacon
var _ = require('lodash')
var courts = require('./public/courts')
var webTimmi = require('./src/webTimmiCrawler')
var browserify = require('browserify-middleware')
app.use('/front.min.js', browserify(__dirname + '/public/front.js'))
app.use(express.static(__dirname + '/public'))
var cache = {}
app.get('/courts', freeCourts)
app.get('/locations', locations)
var port = process.env.PORT || 5000
app.listen(port, function () {
console.log('Server started at localhost:' + port)
})
function freeCourts(req, res) {
var isoDate = req.query.date || todayIsoDate()
var expirationInMin = 120
var currentTimeMinusDelta = new Date().getTime() - 1000 * 60 * expirationInMin
var cachedValue = cache[isoDate]
if (cachedValue && cachedValue.date > currentTimeMinusDelta) {
res.send(cachedValue)
} else {
fetch(isoDate).onValue(function (obj) {
cache[isoDate] = obj
res.send(obj)
})
}
}
function fetch(isoDate) {
return Bacon.combineTemplate({
meilahti: slSystems.getMeilahti(isoDate),
herttoniemi: slSystems.getHerttoniemi(isoDate),
kulosaari: slSystems.getKulosaari(isoDate),
merihaka: slSystems.getMerihaka(isoDate),
tali1: webTimmi.getTali1(isoDate),
tali2: webTimmi.getTali2(isoDate),
taivallahti1: webTimmi.getTaivallahti1(isoDate),
taivallahti2: webTimmi.getTaivallahti2(isoDate),
date: new Date().getTime()
}).map(function (allDataWithDate) {
var allData = _.omit(allDataWithDate, 'date')
return {
freeCourts: _.flatten((_.map(allData, _.identity))),
timestamp: allDataWithDate.date
}
})
}
function todayIsoDate() {
var now = new Date()
var isoDateTime = now.toISOString()
return isoDateTime.split('T')[0]
}
function locations(req, res) {
Bacon.combineAsArray(_.map(courts, function (val, key) {
return getLocation(val.address).map(function (location) {
return _.extend({title: key}, location, val)
})
})).onValue(function (val) { res.send(val) })
}
function getLocation(address) {
return Bacon.fromNodeCallback(request.get, {
url: 'http://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=false'
}).map('.body').map(JSON.parse).map('.results.0.geometry.location')
}
|
#!/usr/bin/env node
var express = require('express')
var request = require('request')
var app = express()
var slSystems = require('./src/slSystemsCrawler')
var Bacon = require('baconjs').Bacon
var _ = require('lodash')
var courts = require('./public/courts')
var webTimmi = require('./src/webTimmiCrawler')
var browserify = require('browserify-middleware')
app.use('/front.min.js', browserify(__dirname + '/public/front.js'))
app.use(express.static(__dirname + '/public'))
var cache = {}
app.get('/courts', function (req, res) {
var isoDate = req.query.date || todayIsoDate()
var expirationInMin = 120
var currentTimeMinusDelta = new Date().getTime() - 1000 * 60 * expirationInMin
var cachedValue = cache[isoDate]
if (cachedValue && cachedValue.date > currentTimeMinusDelta) {
res.send(cachedValue)
} else {
fetch(isoDate).onValue(function (obj) {
cache[isoDate] = obj
res.send(obj)
})
}
})
function fetch(isoDate) {
return Bacon.combineTemplate({
meilahti: slSystems.getMeilahti(isoDate),
herttoniemi: slSystems.getHerttoniemi(isoDate),
kulosaari: slSystems.getKulosaari(isoDate),
merihaka: slSystems.getMerihaka(isoDate),
tali1: webTimmi.getTali1(isoDate),
tali2: webTimmi.getTali2(isoDate),
taivallahti1: webTimmi.getTaivallahti1(isoDate),
taivallahti2: webTimmi.getTaivallahti2(isoDate),
date: new Date().getTime()
}).map(function (allDataWithDate) {
var allData = _.omit(allDataWithDate, 'date')
return {
freeCourts: _.flatten((_.map(allData, _.identity))),
timestamp: allDataWithDate.date
}
})
}
function todayIsoDate() {
var now = new Date()
var isoDateTime = now.toISOString()
return isoDateTime.split('T')[0]
}
app.get('/locations', function (req, res) {
Bacon.combineAsArray(_.map(courts, function (val, key) {
return getLocation(val.address).map(function (location) {
return _.extend({title: key}, location, val)
})
})).onValue(function (val) { res.send(val) })
})
function getLocation(address) {
return Bacon.fromNodeCallback(request.get, {
url: 'http://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=false'
}).map('.body').map(JSON.parse).map('.results.0.geometry.location')
}
var port = process.env.PORT || 5000
app.listen(port, function () {
console.log('Server started at localhost:' + port)
})
|
JavaScript
| 0.000001
|
f46055bb4ef88acd1a653e6a8ed3d3045cbf4bc5
|
Disable rollbar in localhost
|
server.js
|
server.js
|
// https://github.com/zeit/next.js/blob/master/examples/custom-server-koa/server.js
//
const Koa = require('koa');
const next = require('next');
const Rollbar = require('rollbar');
const send = require('koa-send');
// Server related config & credentials
//
const serverConfig = {
ROLLBAR_SERVER_TOKEN: process.env.ROLLBAR_SERVER_TOKEN,
ROLLBAR_ENV: process.env.ROLLBAR_ENV || 'localhost',
PORT: process.env.PORT || 3000,
};
const enableRollbar = !!serverConfig.ROLLBAR_SERVER_TOKEN;
const rollbar = new Rollbar({
enabled: enableRollbar,
captureUncaught: enableRollbar,
captureUnhandledRejections: enableRollbar,
accessToken: serverConfig.ROLLBAR_SERVER_TOKEN,
environment: serverConfig.ROLLBAR_ENV,
});
const app = next({ dev: process.env.NODE_ENV !== 'production' });
const routes = require('./routes');
const handler = routes.getRequestHandler(app);
app.prepare().then(() => {
const server = new Koa();
// Rollbar error handling
//
server.use(async (ctx, next) => {
try {
await next();
} catch (err) {
rollbar.error(err, ctx.request);
}
});
//
server.use(async (ctx, next) => {
if ('/' === ctx.path) {
await send(ctx, './static/index.html');
} else {
await next();
}
});
// Server-side routing
//
/* Required for hot-reload to work. */
server.use(async (ctx, next) => {
ctx.respond = false;
ctx.res.statusCode = 200;
handler(ctx.req, ctx.res);
await next();
});
server.listen(serverConfig.PORT, err => {
if (err) throw err;
console.log('Listening port', serverConfig.PORT); // eslint-disable-line
});
});
|
// https://github.com/zeit/next.js/blob/master/examples/custom-server-koa/server.js
//
const Koa = require('koa');
const next = require('next');
const Rollbar = require('rollbar');
const send = require('koa-send');
// Server related config & credentials
//
const serverConfig = {
ROLLBAR_SERVER_TOKEN: process.env.ROLLBAR_SERVER_TOKEN,
ROLLBAR_ENV: process.env.ROLLBAR_ENV || 'localhost',
PORT: process.env.PORT || 3000,
};
const rollbar = new Rollbar({
accessToken: serverConfig.ROLLBAR_SERVER_TOKEN,
captureUncaught: true,
captureUnhandledRejections: true,
environment: serverConfig.ROLLBAR_ENV,
});
const app = next({ dev: process.env.NODE_ENV !== 'production' });
const routes = require('./routes');
const handler = routes.getRequestHandler(app);
app.prepare().then(() => {
const server = new Koa();
// Rollbar error handling
//
server.use(async (ctx, next) => {
try {
await next();
} catch (err) {
rollbar.error(err, ctx.request);
}
});
//
server.use(async (ctx, next) => {
if ('/' === ctx.path) {
await send(ctx, './static/index.html');
} else {
await next();
}
});
// Server-side routing
//
/* Required for hot-reload to work. */
server.use(async (ctx, next) => {
ctx.respond = false;
ctx.res.statusCode = 200;
handler(ctx.req, ctx.res);
await next();
});
server.listen(serverConfig.PORT, err => {
if (err) throw err;
console.log('Listening port', serverConfig.PORT); // eslint-disable-line
});
});
|
JavaScript
| 0
|
5819d6474614e4ad9fb59c036505c6edabbed32d
|
enable minify
|
server.js
|
server.js
|
/*eslint-env node*/
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();
//var port = process.env.PORT || 3000;
var port = appEnv.port;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
//Compress
app.use(require('compression')());
//Minify
app.use(require('express-minify')());
// Routing
app.use(express.static(__dirname + '/www'));
// Chatroom
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;
io.on('connection', function (socket) {
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
data.avatar = socket.avatar;
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (userInfo) {
// we store the username in the socket session for this client
var username = userInfo.username
socket.username = username;
socket.avatar = userInfo.avatar;
// add the client's username to the global list
usernames[username] = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
// remove the username from global usernames list
if (addedUser) {
delete usernames[socket.username];
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});
/* Using WebSockets
var express = require('express');
var cfenv = require('cfenv');
var app = express();
var appEnv = cfenv.getAppEnv();
var server = require('http').createServer();
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ server:server });
app.use(express.static(__dirname + '/www'));
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
//ws.send(message);
//broadcast
wss.clients.forEach(function each(client) {
client.send(message);
});
});
//ws.send('Connection established');
});
server.on('request', app);
server.listen(appEnv.port, function () {
console.log('Listening on ' + appEnv.url);
});
*/
|
/*eslint-env node*/
// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();
//var port = process.env.PORT || 3000;
var port = appEnv.port;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
//Compress
app.use(require('compression')());
// Routing
app.use(express.static(__dirname + '/www'));
// Chatroom
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;
io.on('connection', function (socket) {
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
data.avatar = socket.avatar;
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (userInfo) {
// we store the username in the socket session for this client
var username = userInfo.username
socket.username = username;
socket.avatar = userInfo.avatar;
// add the client's username to the global list
usernames[username] = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
// remove the username from global usernames list
if (addedUser) {
delete usernames[socket.username];
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});
/* Using WebSockets
var express = require('express');
var cfenv = require('cfenv');
var app = express();
var appEnv = cfenv.getAppEnv();
var server = require('http').createServer();
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ server:server });
app.use(express.static(__dirname + '/www'));
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
//ws.send(message);
//broadcast
wss.clients.forEach(function each(client) {
client.send(message);
});
});
//ws.send('Connection established');
});
server.on('request', app);
server.listen(appEnv.port, function () {
console.log('Listening on ' + appEnv.url);
});
*/
|
JavaScript
| 0.000049
|
da0af6773f05d808cbf7f8d5b6a9d94bff44885e
|
Add graceful exit from SIGTERM (docker)
|
server.js
|
server.js
|
"use strict";
const path = require("path");
const env = process.env.NODE_ENV || "development";
const config = require("./config/config")(env);
const app = require("./app.js")(config);
const { logger } = require("commonlog-bunyan");
const port = config.port || 8000;
if (env === "test" || process.env.PMX) require("pmx").init({ http : true });
const server = app.listen(port);
server.on("clientError", (error, socket) => {
if (!socket.destroyed) {
socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
}
});
process.on("SIGTERM", () => {
logger.info("Quitting Postcode API");
process.exit(0);
});
logger.info("Postcode API listening on port", port);
module.exports = app;
|
"use strict";
const path = require("path");
const env = process.env.NODE_ENV || "development";
const config = require(path.join(__dirname, "config/config"))(env);
if (env === "test" || process.env.PMX) {
require("pmx").init({
http : true
});
}
const app = require(path.join(__dirname, "app.js"))(config);
const port = config.port || 8000;
const server = app.listen(port);
server.on("clientError", (error, socket) => {
if (!socket.destroyed) {
socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
}
});
console.log("Postcode API listening on port", port);
module.exports = app;
|
JavaScript
| 0
|
cd553620e7a7c21c378b8a63fd8ae00fa1c6dbc0
|
call setAttributeNS if args.length === 3
|
src/svg.js
|
src/svg.js
|
module.exports = function(p5) {
p5.prototype.querySVG = function(selector) {
var svg = this._graphics && this._graphics.svg;
if (!svg) {
return null;
}
var elements = svg.querySelectorAll(selector);
return elements.map(function(elt) {
return new p5.SVGElement(elt);
});
};
function SVGElement(element, pInst) {
if (!element) {
return null;
}
return p5.Element.apply(this, arguments);
};
SVGElement.prototype = Object.create(p5.Element.prototype);
SVGElement.prototype.query = function(selector) {
var elements = this.elt.querySelectorAll(selector);
return elements.map(function(elt) {
return new SVGElement(elt);
});
};
SVGElement.prototype.attribute = function() {
var args = arguments;
if (args.length === 3) {
this.elt.setAttributeNS.apply(this.elt, args);
return this;
}
p5.Element.prototype.attribute.apply(this, args);
};
p5.SVGElement = SVGElement;
};
|
module.exports = function(p5) {
p5.prototype.querySVG = function(selector) {
var svg = this._graphics && this._graphics.svg;
if (!svg) {
return null;
}
var elements = svg.querySelectorAll(selector);
return elements.map(function(elt) {
return new p5.SVGElement(elt);
});
};
function SVGElement(element, pInst) {
if (!element) {
return null;
}
return p5.Element.apply(this, arguments);
};
SVGElement.prototype = Object.create(p5.Element.prototype);
SVGElement.prototype.query = function(selector) {
var elements = this.elt.querySelectorAll(selector);
return elements.map(function(elt) {
return new SVGElement(elt);
});
};
p5.SVGElement = SVGElement;
};
|
JavaScript
| 0.000085
|
103749041853065c4f220b02dda87e8c87d7bd89
|
implement base api version
|
server.js
|
server.js
|
/**
* Created by godson on 4/9/15.
*/
//Includes
var express = require( 'express' );
var app = express();
var mongoose = require( 'mongoose' );
var morgan = require( 'morgan' );
var bodyParser = require( 'body-parser' );
var methodOverride = require( 'method-override' );
// configs
mongoose.connect('mongodb://localhost:27017/todo');
app.use(express.static(__dirname + '/web'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
// models
var Todo = mongoose.model('Todo', {
text : String
});
// routes
// get all todos
app.get('/api/todos', function(req, res) {
Todo.find(function(err, todos) {
if (err) {
res.send( err )
}
res.json(todos);
});
});
// create todo
app.post('/api/todos', function(req, res) {
Todo.create(
{
text : req.body.text,
done : false
},
function(err, todo) {
if (err) {
res.send( err );
}
Todo.find(function(err, todos) {
if (err) {
res.send( err )
}
res.json(todos);
});
}
);
});
// delete a todo
app.delete('/api/todos/:todo_id', function(req, res) {
Todo.remove(
{
_id : req.params.todo_id
},
function(err, todo) {
if (err) {
res.send( err );
}
Todo.find(function(err, todos) {
if (err) {
res.send( err )
}
res.json(todos);
});
}
);
});
// web
app.get('*', function(req, res) {
res.sendfile('./web/index.html');
});
// Server start
app.listen(8080);
console.log("App listening on port 8080");
|
/**
* Created by godson on 4/9/15.
*/
var express = require( 'express' );
var app = express();
var mongoose = require( 'mongoose' );
var morgan = require( 'morgan' );
var bodyParser = require( 'body-parser' );
var methodOverride = require( 'method-override' );
mongoose.connect('mongodb://localhost:27017/todo');
app.use(express.static(__dirname + '/web'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.listen(8080);
console.log("App listening on port 8080");
|
JavaScript
| 0
|
0b30ea866a01c6aabf8865d6c33ac3c41a9f141e
|
refactor scrape vars, and fs write outside loop
|
server.js
|
server.js
|
var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var app = express();
app.get('/scrape', function(req, res){
var url = [
'http://www.imdb.com/list/ls052535080/?start=1&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=101&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=201&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=301&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=401&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=501&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=601&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=701&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=801&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=901&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=1001&view=detail&sort=listorian:asc'
];
var list = [];
for(var i=0; i < url.length; i++) {
request(url[i], function(error, response, html) {
if(!error) {
var $ = cheerio.load(html);
$('.list_item').each(function(index) {
var data = $(this);
var title, year, rating, description, url;
var json = {
title : data.find('b a').text();
year : data.find('b span').text();
rating : data.find('.rating-rating .value').text();
description : data.find('.item_description').text();
url : data.find('b a').attr('href');
};
list.push(json);
});
}
});
}
if (list.length) {
fs.writeFile('list.json', JSON.stringify(list, null, 4), function(err){
console.log('Succesfully wrote to file, see list.json.');
});
} else {
console.log('Absolutely zero results successfully scraped!?');
}
});
app.listen('8081')
exports = module.exports = app;
|
var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var app = express();
app.get('/scrape', function(req, res){
var url = [
'http://www.imdb.com/list/ls052535080/?start=1&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=101&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=201&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=301&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=401&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=501&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=601&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=701&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=801&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=901&view=detail&sort=listorian:asc',
'http://www.imdb.com/list/ls052535080/?start=1001&view=detail&sort=listorian:asc'
];
var list = [];
for(var i=0; i < url.length; i++) {
request(url[i], function(error, response, html) {
if(!error) {
var $ = cheerio.load(html);
$('.list_item').each(function(index) {
var data = $(this);
var title, year, rating, description, url;
var json = {};
title = data.find('b a').text();
year = data.find('b span').text();
rating = data.find('.rating-rating .value').text();
description = data.find('.item_description').text();
url = data.find('b a').attr('href');
json.title = title;
json.year = year;
json.rating = rating;
json.description = description;
json.url = url;
list.push(json);
});
}
fs.writeFile('list.json', JSON.stringify(list, null, 4), function(err){
console.log('Succesfully wrote to file, see list.json.');
});
});
}
});
app.listen('8081')
exports = module.exports = app;
|
JavaScript
| 0
|
08d560fdaba4ca5c5a7319975ab0f86c76a7b7de
|
Send content-type header.
|
server.js
|
server.js
|
var fs = require('fs')
,Q = require('q')
,http = require('http')
,less = require('less')
,port = 8000
l = console.log;
var parser = new less.Parser();
http.createServer(function (req, res) {
var time = process.hrtime();
l("Start request");
readEntireBody(req)
.then(parseLess)
.then(outputCss(res))
.then(function() {
time = process.hrtime(time);
var ms = time[0]*1000 + time[1] / 1e6;
l("Finished request("+(Math.round(ms*10)/10)+"ms):" + req.url);
})
.fail(function(err) {
l("Got Error: " + err);
res.statusCode=500;
res.end(err)
});
}).listen(8000);
function readEntireBody(stream) {
var deferred = Q.defer()
var body = ''
stream.setEncoding('utf8')
stream.on('data', function (chunk) {
body += chunk
});
stream.on('end', function () {
deferred.resolve(body);
});
stream.on('close', function (err) {
deferred.reject(err);
});
return deferred.promise;
}
function parseLess(body) {
var deferred = Q.defer()
var parser = new less.Parser();
parser.parse(body, deferred.makeNodeResolver());
return deferred.promise;
}
function outputCss(res) {
return function (parseTree) {
var css = parseTree.toCSS();
res.writeHead(200, "Content-Type: text/css");
res.end(css);
return Q.fcall(function(){});
}
}
|
var fs = require('fs')
,Q = require('q')
,http = require('http')
,less = require('less')
,port = 8000
l = console.log;
var parser = new less.Parser();
http.createServer(function (req, res) {
var time = process.hrtime();
l("Start request");
readEntireBody(req)
.then(parseLess)
.then(outputCss(res))
.then(function() {
time = process.hrtime(time);
var ms = time[0]*1000 + time[1] / 1e6;
l("Finished request("+(Math.round(ms*10)/10)+"ms):" + req.url);
})
.fail(function(err) {
l("Got Error: " + err);
res.statusCode=500;
res.end(err)
});
}).listen(8000);
function readEntireBody(stream) {
var deferred = Q.defer()
var body = ''
stream.setEncoding('utf8')
stream.on('data', function (chunk) {
body += chunk
});
stream.on('end', function () {
deferred.resolve(body);
});
stream.on('close', function (err) {
deferred.reject(err);
});
return deferred.promise;
}
function parseLess(body) {
var deferred = Q.defer()
var parser = new less.Parser();
parser.parse(body, deferred.makeNodeResolver());
return deferred.promise;
}
function outputCss(res) {
return function (parseTree) {
var css = parseTree.toCSS();
res.statusCode = 200;
res.end(css);
return Q.fcall(function(){});
}
}
|
JavaScript
| 0
|
6fa172730aeeaf620006087a5007d07786102992
|
update parks data source
|
gmaps/app.js
|
gmaps/app.js
|
function initMap() {
// STARTER VARIABLES
// Raleigh parks data
var raleighParks = 'http://data-ral.opendata.arcgis.com/datasets/5a211ae2f9974f3b814438d5f3a5d783_4.geojson';
// Map style
var darkBaseStyle = new google.maps.StyledMapType(darkMatter, {name: 'Dark Base'});
// Map bounds (Empty)
var bounds = new google.maps.LatLngBounds();
// Interaction states
var clicked = false;
var hover = true;
// SETUP MAP
var map = new google.maps.Map(document.getElementById('map'), {
// center: {lat: 35.779590, lng: -78.638179},
// zoom: 13,
fullscreenControl: false,
mapTypeControlOptions: {
mapTypeIds: ['satellite','hybrid','dark_base']
}
});
map.setTilt(45);
map.mapTypes.set('dark_base', darkBaseStyle);
map.setMapTypeId('dark_base');
// PARKS DATA
// Load data
map.data.loadGeoJson(raleighParks);
// Style data based on zoom level
map.addListener('zoom_changed', function() {
var zoom = map.getZoom();
if(zoom <= 10){
map.data.setStyle({
fillOpacity: 0,
fillColor: 'turquoise',
strokeColor: 'whitesmoke',
strokeWeight: 1
});
} else {
map.data.setStyle({
fillOpacity: 0,
fillColor: 'turquoise',
strokeColor: 'whitesmoke',
strokeWeight: zoom/8
});
}
})
// ZOOM MAP TO DATA EXTENT
map.data.addListener('addfeature', function(e) {
processPoints(e.feature.getGeometry(), bounds.extend, bounds);
map.fitBounds(bounds);
});
// INTERACTION
// Click non-feature in map
map.addListener('click', function(){
map.data.revertStyle();
clicked = false;
hover = true;
});
// Mouseover
map.data.addListener('mouseover', function(e){
document.getElementById("info-box-hover").textContent = "Click for " + e.feature.getProperty("NAME");
if(hover && !clicked){
map.data.revertStyle();
map.data.overrideStyle(e.feature, {
fillOpacity: 0.5
});
}
});
map.data.addListener('mouseout', function(e){
document.getElementById("info-box-hover").textContent = "";
if(!clicked && hover){
map.data.revertStyle();
}
})
// Click data feature
map.data.addListener("click", function(e) {
clicked = true;
hover = false;
// Change style of clicked feature
map.data.revertStyle();
map.data.overrideStyle(e.feature, {
strokeWeight: 3,
strokeColor: 'turquoise'
});
// Zoom to clicked feature
bounds = new google.maps.LatLngBounds();
processPoints(e.feature.getGeometry(), bounds.extend, bounds);
map.fitBounds(bounds);
// Update info-box
document.getElementById("info-box-name").textContent = e.feature.getProperty("NAME");
document.getElementById("info-box-type").textContent = "Type: " + e.feature.getProperty("PARK_TYPE");
document.getElementById("info-box-developed").textContent = "Status: " + e.feature.getProperty("DEVELOPED");
document.getElementById("info-box-acres").textContent = "Size: " + e.feature.getProperty("MAP_ACRES").toFixed(2) + " ac.";
});
}
function processPoints(geometry, callback, thisArg) {
if (geometry instanceof google.maps.LatLng) {
callback.call(thisArg, geometry);
} else if (geometry instanceof google.maps.Data.Point) {
callback.call(thisArg, geometry.get());
} else {
geometry.getArray().forEach(function(g) {
processPoints(g, callback, thisArg);
});
}
}
|
function initMap() {
// STARTER VARIABLES
// Raleigh parks data
var raleighParks = 'http://data-ral.opendata.arcgis.com/datasets/5a211ae2f9974f3b814438d5f3a5d783_12.geojson';
// Map style
var darkBaseStyle = new google.maps.StyledMapType(darkMatter, {name: 'Dark Base'});
// Map bounds (Empty)
var bounds = new google.maps.LatLngBounds();
// Interaction states
var clicked = false;
var hover = true;
// SETUP MAP
var map = new google.maps.Map(document.getElementById('map'), {
// center: {lat: 35.779590, lng: -78.638179},
// zoom: 13,
fullscreenControl: false,
mapTypeControlOptions: {
mapTypeIds: ['satellite','hybrid','dark_base']
}
});
map.setTilt(45);
map.mapTypes.set('dark_base', darkBaseStyle);
map.setMapTypeId('dark_base');
// PARKS DATA
// Load data
map.data.loadGeoJson(raleighParks);
// Style data based on zoom level
map.addListener('zoom_changed', function() {
var zoom = map.getZoom();
if(zoom <= 10){
map.data.setStyle({
fillOpacity: 0,
fillColor: 'turquoise',
strokeColor: 'whitesmoke',
strokeWeight: 1
});
} else {
map.data.setStyle({
fillOpacity: 0,
fillColor: 'turquoise',
strokeColor: 'whitesmoke',
strokeWeight: zoom/8
});
}
})
// ZOOM MAP TO DATA EXTENT
map.data.addListener('addfeature', function(e) {
processPoints(e.feature.getGeometry(), bounds.extend, bounds);
map.fitBounds(bounds);
});
// INTERACTION
// Click non-feature in map
map.addListener('click', function(){
map.data.revertStyle();
clicked = false;
hover = true;
});
// Mouseover
map.data.addListener('mouseover', function(e){
document.getElementById("info-box-hover").textContent = "Click for " + e.feature.getProperty("NAME");
if(hover && !clicked){
map.data.revertStyle();
map.data.overrideStyle(e.feature, {
fillOpacity: 0.5
});
}
});
map.data.addListener('mouseout', function(e){
document.getElementById("info-box-hover").textContent = "";
if(!clicked && hover){
map.data.revertStyle();
}
})
// Click data feature
map.data.addListener("click", function(e) {
clicked = true;
hover = false;
// Change style of clicked feature
map.data.revertStyle();
map.data.overrideStyle(e.feature, {
strokeWeight: 3,
strokeColor: 'turquoise'
});
// Zoom to clicked feature
bounds = new google.maps.LatLngBounds();
processPoints(e.feature.getGeometry(), bounds.extend, bounds);
map.fitBounds(bounds);
// Update info-box
document.getElementById("info-box-name").textContent = e.feature.getProperty("NAME");
document.getElementById("info-box-type").textContent = "Type: " + e.feature.getProperty("PARK_TYPE");
document.getElementById("info-box-developed").textContent = "Status: " + e.feature.getProperty("DEVELOPED");
document.getElementById("info-box-acres").textContent = "Size: " + e.feature.getProperty("MAP_ACRES").toFixed(2) + " ac.";
});
}
function processPoints(geometry, callback, thisArg) {
if (geometry instanceof google.maps.LatLng) {
callback.call(thisArg, geometry);
} else if (geometry instanceof google.maps.Data.Point) {
callback.call(thisArg, geometry.get());
} else {
geometry.getArray().forEach(function(g) {
processPoints(g, callback, thisArg);
});
}
}
|
JavaScript
| 0
|
092bec3b97eca8c2fe5a0786a4cb1b20130d2251
|
accept 'magic 8 ball' as input
|
server.js
|
server.js
|
var bodyParser = require('body-parser');
var answers = require('./answers.js');
var express = require('express');
var request = require('request');
var app = express();
var port = process.env.PORT || 3000;
var postOptions = {
url: 'https://api.groupme.com/v3/bots/post',
method: 'POST'
};
app.use(bodyParser.json());
app.route('/')
.get(function(req, res) {
sayBot(res);
//res.end('Thanks');
})
.post(function(req, res) {
if(req.body.name.toLowerCase().indexOf('magic eight ball') < 0 && req.body.text.toLowerCase().indexOf('magic eight ball') > -1) {
setTimeout(sayBot(res), 4000);
}else if(req.body.name.toLowerCase().indexOf('magic 8 ball') < 0 && req.body.text.toLowerCase().indexOf('magic 8 ball') > -1) {
setTimeout(sayBot(res), 4000);
}else {
res.send('Thanks');
}
});
function sayBot(res) {
var botData = {
bot_id: process.env.BOT_ID,
text: answers[Math.floor(Math.random()*answers.length)]
};
postOptions.json = botData;
request(postOptions, function(error, response, body) {
res.end('Thanks');
});
}
app.listen(port, function(){
console.log('The magic happens on port ' + port);
});
exports.app = app;
|
var bodyParser = require('body-parser');
var answers = require('./answers.js');
var express = require('express');
var request = require('request');
var app = express();
var port = process.env.PORT || 3000;
var postOptions = {
url: 'https://api.groupme.com/v3/bots/post',
method: 'POST'
};
app.use(bodyParser.json());
app.route('/')
.get(function(req, res) {
sayBot(res);
//res.end('Thanks');
})
.post(function(req, res) {
if(req.body.name.toLowerCase().indexOf('magic eight ball') < 0 && req.body.text.toLowerCase().indexOf('magic eight ball') > -1) {
setTimeout(sayBot(res), 4000);
}else {
res.send('Thanks');
}
});
function sayBot(res) {
var botData = {
bot_id: process.env.BOT_ID,
text: answers[Math.floor(Math.random()*answers.length)]
};
postOptions.json = botData;
request(postOptions, function(error, response, body) {
res.end('Thanks');
});
}
app.listen(port, function(){
console.log('The magic happens on port ' + port);
});
exports.app = app;
|
JavaScript
| 0.999999
|
e66ebd9fd829a454a77f65c29fb9728c352afee3
|
update main file
|
server.js
|
server.js
|
'use strict';
var express = require('express'),
app = express(),
RouterRoot,
config = require('./config'),
routes = require('./routes'),
bodyParser = require('body-parser'),
session = require('express-session'),
mongoose = require('mongoose');
mongoose.connect(config.mongo_url, function(err) {
if (err) throw err;
console.log('Connect database successeful!!! ');
});
// Using middleware
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
app.use(session({
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
secret: 'Secret key'
}));
// Config express
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
// Using Router
RouterRoot = express.Router();
RouterRoot.get('/', routes.index);
RouterRoot.get('/login', routes.users.login);
RouterRoot.post('/login', routes.users.authen);
RouterRoot.get('/register', routes.users.register);
RouterRoot.post('/register', routes.users.reguser);
RouterRoot.get('/logout', routes.users.logout);
// RouterRoot.get('/admin', )
RouterRoot.post('/cates', routes.cates.add);
RouterRoot.get('/posts', routes.posts.read);
RouterRoot.post('/posts', routes.posts.create);
RouterRoot.put('/posts/:post_id', routes.posts.update);
RouterRoot.delete('/posts/:post_id', routes.posts.del);
RouterRoot.all('*', function(req, res) {
res.status(404).end();
});
// Declare router
app.use('/', RouterRoot);
app.listen( config.port, function() {
console.log('Express server running at ' + config.port);
});
|
'use strict';
var express = require('express'),
app = express(),
RouterRoot,
config = require('./config'),
routes = require('./routes'),
bodyParser = require('body-parser'),
session = require('express-session'),
mongoose = require('mongoose');
mongoose.connect(config.mongo_url, function(err) {
if (err) throw err;
console.log('Connect database successeful!!! ');
});
// Using middleware
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
app.use(session({
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
secret: 'Secret key'
}));
// Config express
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
// Using Router
RouterRoot = express.Router();
RouterRoot.get('/', routes.index);
RouterRoot.get('/login', routes.users.login);
RouterRoot.post('/login', routes.users.authen);
RouterRoot.get('/register', routes.users.register);
RouterRoot.post('/register', routes.users.reguser);
RouterRoot.get('/logout', routes.users.logout);
RouterRoot.post('/posts', routes.posts.create);
RouterRoot.get('/posts', routes.posts.read);
RouterRoot.put('/posts/:post_id', routes.posts.update);
RouterRoot.delete('/posts/:post_id', routes.posts.del);
RouterRoot.all('*', function(req, res) {
res.status(404).end();
});
// Declare router
app.use('/', RouterRoot);
app.listen( config.port, function() {
console.log('Express server running at ' + config.port);
});
|
JavaScript
| 0
|
0358d01f230707e64f9c7298d8a8d34593fb8943
|
Connect to mongo here so we only do it once
|
server.js
|
server.js
|
"use strict";
var express = require('express'),
pages = require('./routes/pages.js'),
signup = require('./routes/signup.js'),
flash = require('connect-flash'),
auth = require('./modules/auth.js'),
api = require('./modules/api.js'),
mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_CONNECTION_STRING);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
var app = express();
// Configuration
var secret = process.env.COOKIE_SECRET || 'secret';
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.compress());
app.use(express.methodOverride());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser(secret));
app.use(express.session({
secret: secret,
cookie: {
httpOnly: true
}
}));
app.use(auth);
app.use(flash());
if (app.get('env') === 'development') {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
} else {
app.use(express.errorHandler());
}
// Routes
app.get('/', pages.index);
app.get('/contact', pages.contact);
app.get('/login', pages.login);
app.post('/signup', signup.sendToMailchimp);
app.use(express.static(__dirname + '/dist'));
// Go
app.listen(process.env.port || 3000);
console.log("Express server started");
|
var express = require('express'),
pages = require('./routes/pages.js'),
signup = require('./routes/signup.js'),
flash = require('connect-flash'),
auth = require('./modules/auth.js');
var app = express();
// Configuration
var secret = process.env.COOKIE_SECRET || 'secret';
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.compress());
app.use(express.methodOverride());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser(secret));
app.use(express.session({
secret: secret,
cookie: {
httpOnly: true
}
}));
app.use(auth);
app.use(flash());
if (app.get('env') === 'development') {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
} else {
app.use(express.errorHandler());
}
// Routes
app.get('/', pages.index);
app.get('/contact', pages.contact);
app.get('/login', pages.login);
app.post('/signup', signup.sendToMailchimp);
app.use(express.static(__dirname + '/dist'));
// Go
app.listen(process.env.port || 3000);
console.log("Express server started");
|
JavaScript
| 0
|
02a2bef8ac023108a422d5bf7dd01ded0957fc11
|
Remove unused require
|
server.js
|
server.js
|
// Server
var http = require('http');
var app = require('express')();
var config = require('./src/config');
// DB
var mongoose = require('mongoose');
// Sub-apps
var api = require('./src/server/api');
var pages = require('./src/server/pages');
// Game-logic
// TODO Move!
var game = require('./lib/server/game').game;
var dict = require('./src/dictionary.json');
// Configure
if (app.get('env') === 'development') { config.development(app); }
if (app.get('env') === 'production') { config.production(app); }
config.all(app);
// MongoDB
mongoose.connect(app.get('db'));
// Create some games
game.create(Object.keys(dict));
// Save rooms to every page load
app.use(function (req, res, next) {
req.rooms = game.all();
next();
});
// Mount sub-apps
app.use('/', pages);
app.use('/api', api);
// Create server
var server = http.createServer(app);
// WebSocket
require('./src/server/websockets').listen(server, game);
// Start server
server.listen(app.get('port'), app.get('ipaddr'));
console.log(
'Listening on port %s:%d in %s mode...',
app.get('ipaddr'),
app.get('port'),
app.get('env'));
|
// TODO Remove?
require('./lib/utils/functional');
// Server
var http = require('http');
var app = require('express')();
var config = require('./src/config');
// DB
var mongoose = require('mongoose');
// Sub-apps
var api = require('./src/server/api');
var pages = require('./src/server/pages');
// Game-logic
// TODO Move!
var game = require('./lib/server/game').game;
var dict = require('./src/dictionary.json');
// Configure
if (app.get('env') === 'development') { config.development(app); }
if (app.get('env') === 'production') { config.production(app); }
config.all(app);
// MongoDB
mongoose.connect(app.get('db'));
// Create some games
game.create(Object.keys(dict));
// Save rooms to every page load
app.use(function (req, res, next) {
req.rooms = game.all();
next();
});
// Mount sub-apps
app.use('/', pages);
app.use('/api', api);
// Create server
var server = http.createServer(app);
// WebSocket
require('./src/server/websockets').listen(server, game);
// Start server
server.listen(app.get('port'), app.get('ipaddr'));
console.log(
'Listening on port %s:%d in %s mode...',
app.get('ipaddr'),
app.get('port'),
app.get('env'));
|
JavaScript
| 0.000001
|
3383f3e6ac2fb8c17409278be903176ef0c3498e
|
Fix the issue with synchronizing pull requests.
|
server.js
|
server.js
|
"use strict"
var format = require('python-format')
var request = require('request')
var port = +process.env.npm_package_config_webhookport
if (!port) {
console.error("Start the bot using 'npm start'.")
return
}
var secret = process.env.npm_package_config_secret
if (!secret) {
console.error("Secret not defined, please use 'npm config set psdevbot:secret value'.")
return
}
var Showdown = require('./showdown')
var parameters = {}
Object.keys(Showdown.keys).forEach(function (key) {
parameters[key] = process.env['npm_package_config_' + key]
})
var client = new Showdown(parameters)
client.connect()
var github = require('githubhook')({
port: port,
secret: secret,
logger: console
})
function shorten(url, callback) {
function shortenCallback(error, response, body) {
var shortenedUrl = url
if (!error && response.headers.location) {
shortenedUrl = response.headers.location
}
callback(shortenedUrl)
}
request.post('https://git.io', {form: {url: url}}, shortenCallback)
}
function getRepoName(repo) {
switch (repo) {
case 'Pokemon-Showdown':
return 'server'
case 'Pokemon-Showdown-Client':
return 'client'
default:
return repo
}
}
var escape = require('escape-html')
github.on('push', function push(repo, ref, result) {
var url = result.compare
var branch = /[^/]+$/.exec(ref)[0]
shorten(url, function pushShortened(url) {
var messages = []
var message = result.commits.length === 1 ?
"[{}] <font color='909090'>{}</font> pushed <b>{}</b> new commit to <font color='800080'>{}</font>: <a href='{4}'>{4}</a>" :
"[{}] <font color='909090'>{}</font> pushed <b>{}</b> new commits to <font color='800080'>{}</font>: <a href='{4}'>{4}</a>"
messages.push(format(
message,
escape(getRepoName(repo)),
escape(result.pusher.name),
escape(result.commits.length),
escape(branch),
escape(url)
))
result.commits.forEach(function (commit) {
messages.push(format(
"{}/<font color='800080'>{}</font> <font color='606060'>{}</font> <font color='909090'>{}</font>: {}",
escape(getRepoName(repo)),
escape(branch),
escape(commit.id.substring(0, 8)),
escape(commit.author.name),
escape(/.+/.exec(commit.message)[0])
))
})
client.report('!htmlbox ' + messages.join("<br>"))
})
})
github.on('pull_request', function pullRequest(repo, ref, result) {
var url = result.pull_request.html_url
var action = result.action
if (action === 'synchronize') {
action = 'updated'
}
shorten(url, function pullRequestShortened(url) {
client.report(format(
"!htmlbox [<font color='FFC0CB'>{}</font>] <font color='909090'>{}</font> {} pull request #{}: {} {}",
escape(getRepoName(repo)),
escape(result.pull_request.user.login),
escape(action),
escape(result.pull_request.number),
escape(result.pull_request.title),
escape(url)
))
})
})
github.listen()
|
"use strict"
var format = require('python-format')
var request = require('request')
var port = +process.env.npm_package_config_webhookport
if (!port) {
console.error("Start the bot using 'npm start'.")
return
}
var secret = process.env.npm_package_config_secret
if (!secret) {
console.error("Secret not defined, please use 'npm config set psdevbot:secret value'.")
return
}
var Showdown = require('./showdown')
var parameters = {}
Object.keys(Showdown.keys).forEach(function (key) {
parameters[key] = process.env['npm_package_config_' + key]
})
var client = new Showdown(parameters)
client.connect()
var github = require('githubhook')({
port: port,
secret: secret,
logger: console
})
function shorten(url, callback) {
function shortenCallback(error, response, body) {
var shortenedUrl = url
if (!error && response.headers.location) {
shortenedUrl = response.headers.location
}
callback(shortenedUrl)
}
request.post('https://git.io', {form: {url: url}}, shortenCallback)
}
function getRepoName(repo) {
switch (repo) {
case 'Pokemon-Showdown':
return 'server'
case 'Pokemon-Showdown-Client':
return 'client'
default:
return repo
}
}
var escape = require('escape-html')
github.on('push', function push(repo, ref, result) {
var url = result.compare
var branch = /[^/]+$/.exec(ref)[0]
shorten(url, function pushShortened(url) {
var messages = []
var message = result.commits.length === 1 ?
"[{}] <font color='909090'>{}</font> pushed <b>{}</b> new commit to <font color='800080'>{}</font>: <a href='{4}'>{4}</a>" :
"[{}] <font color='909090'>{}</font> pushed <b>{}</b> new commits to <font color='800080'>{}</font>: <a href='{4}'>{4}</a>"
messages.push(format(
message,
escape(getRepoName(repo)),
escape(result.pusher.name),
escape(result.commits.length),
escape(branch),
escape(url)
))
result.commits.forEach(function (commit) {
messages.push(format(
"{}/<font color='800080'>{}</font> <font color='606060'>{}</font> <font color='909090'>{}</font>: {}",
escape(getRepoName(repo)),
escape(branch),
escape(commit.id.substring(0, 8)),
escape(commit.author.name),
escape(/.+/.exec(commit.message)[0])
))
})
client.report('!htmlbox ' + messages.join("<br>"))
})
})
github.on('pull_request', function pullRequest(repo, ref, result) {
var url = result.pull_request.html_url
shorten(url, function pullRequestShortened(url) {
client.report(format(
"!htmlbox [<font color='FFC0CB'>{}</font>] <font color='909090'>{}</font> {} pull request #{}: {} {}",
escape(getRepoName(repo)),
escape(result.pull_request.user.login),
escape(result.action),
escape(result.pull_request.number),
escape(result.pull_request.title),
escape(url)
))
})
})
github.listen()
|
JavaScript
| 0
|
baf922280307a4b76e38cf96c151b7870836bd4f
|
remove console.log
|
server.js
|
server.js
|
#!/usr/bin/env node
const debug = require('debug')('trifid:')
const path = require('path')
const program = require('commander')
const ConfigHandler = require('trifid-core/lib/ConfigHandler')
const Trifid = require('trifid-core')
program
.option('-v, --verbose', 'verbose output', () => true)
.option('-c, --config <path>', 'configuration file', process.env.TRIFID_CONFIG)
.option('-p, --port <port>', 'listener port', parseInt)
.option('--sparql-endpoint-url <url>', 'URL of the SPARQL HTTP query interface')
.option('--dataset-base-url <url>', 'Base URL of the dataset')
.parse(process.argv)
const opts = program.opts()
// automatically switch to config-sparql if a SPARQL endpoint URL is given and no config file was defined
if (opts.sparqlEndpointUrl && !opts.config) {
opts.config = 'config-sparql.json'
} else if (!opts.config) {
opts.config = 'config.json'
}
// create a minimal configuration with a baseConfig pointing to the given config file
const config = {
baseConfig: path.join(process.cwd(), opts.config)
}
// add optional arguments to the configuration
if (opts.port) {
config.listener = {
port: opts.port
}
}
if (opts.sparqlEndpointUrl) {
config.sparqlEndpointUrl = opts.sparqlEndpointUrl
}
if (opts.datasetBaseUrl) {
config.datasetBaseUrl = opts.datasetBaseUrl
}
// load the configuration and start the server
const trifid = new Trifid()
trifid.configHandler.resolver.use('trifid', ConfigHandler.pathResolver(__dirname))
trifid.init(config).then(() => {
if (opts.verbose) {
debug('expanded config:')
debug(JSON.stringify(trifid.config, null, ' '))
}
return trifid.app()
}).catch((err) => {
debug(err)
})
|
#!/usr/bin/env node
const debug = require('debug')('trifid:')
const path = require('path')
const program = require('commander')
const ConfigHandler = require('trifid-core/lib/ConfigHandler')
const Trifid = require('trifid-core')
program
.option('-v, --verbose', 'verbose output', () => true)
.option('-c, --config <path>', 'configuration file', process.env.TRIFID_CONFIG)
.option('-p, --port <port>', 'listener port', parseInt)
.option('--sparql-endpoint-url <url>', 'URL of the SPARQL HTTP query interface')
.option('--dataset-base-url <url>', 'Base URL of the dataset')
.parse(process.argv)
const opts = program.opts()
// automatically switch to config-sparql if a SPARQL endpoint URL is given and no config file was defined
if (opts.sparqlEndpointUrl && !opts.config) {
opts.config = 'config-sparql.json'
} else if (!opts.config) {
opts.config = 'config.json'
}
// create a minimal configuration with a baseConfig pointing to the given config file
const config = {
baseConfig: path.join(process.cwd(), opts.config)
}
console.log('config', config)
// add optional arguments to the configuration
if (opts.port) {
config.listener = {
port: opts.port
}
}
if (opts.sparqlEndpointUrl) {
config.sparqlEndpointUrl = opts.sparqlEndpointUrl
}
if (opts.datasetBaseUrl) {
config.datasetBaseUrl = opts.datasetBaseUrl
}
// load the configuration and start the server
const trifid = new Trifid()
trifid.configHandler.resolver.use('trifid', ConfigHandler.pathResolver(__dirname))
trifid.init(config).then(() => {
if (opts.verbose) {
debug('expanded config:')
debug(JSON.stringify(trifid.config, null, ' '))
}
return trifid.app()
}).catch((err) => {
debug(err)
})
|
JavaScript
| 0.000006
|
2628e6b8b0d3b8abce81d9e584655fae2fac4ea2
|
update time interval
|
server.js
|
server.js
|
const http = require('http');
const app = require('./lib/app');
require('mongoose');
const findAndUpdate = require('./lib/update-user');
require('./lib/connection');
const server = http.createServer(app);
const port = process.env.PORT || 3000;
server.listen(port, () => {
console.log('server is running on ', server.address());
});
setInterval(findAndUpdate, 86400000);
|
const http = require('http');
const app = require('./lib/app');
require('mongoose');
const findAndUpdate = require('./lib/update-user');
// const User = require('./lib/models/user.model');
require('./lib/connection');
const server = http.createServer(app);
const port = process.env.PORT || 3000;
server.listen(port, () => {
console.log('server is running on ', server.address());
});
setInterval(findAndUpdate, 86400);
|
JavaScript
| 0.000004
|
bc9afa0314df8967faacfdf53ae7de0e842ac4e1
|
Support for Coffee Script 1.7.0
|
server.js
|
server.js
|
/*
* Start Nitro Server
*/
global.DEBUG = true;
// Include the CoffeeScript interpreter so that .coffee files will work
var coffee = require('coffee-script');
// Explicitly register the compiler if required. This became necessary in CS 1.7
if (typeof coffee.register !== 'undefined') coffee.register();
// Include our application file
var app = require('./app/init.coffee');
|
/*
* Windows Azure Setup
*/
global.DEBUG = true;
require('coffee-script');
require('./app/init.coffee');
|
JavaScript
| 0
|
17cf5d8b505d76fcd1870cd08e24d931ee8930a9
|
update grunt config
|
gruntFile.js
|
gruntFile.js
|
/* jshint ignore:start */
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Load grunt tasks and config automatically
// Read: https://github.com/firstandthird/load-grunt-config
require('load-grunt-config')(grunt, {
postProcess: function(config){
// Project settings
config.yeoman = {
// Configurable paths
root: '.',
src: 'src',
test: 'test',
dist: 'dist',
projectName: 'sstooltip',
outputName: 'sstooltip'
};
return config;
}
});
// For aliases, see grunt/aliases.js
};
|
/* jshint ignore:start */
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Load grunt tasks and config automatically
// Read: https://github.com/firstandthird/load-grunt-config
require('load-grunt-config')(grunt, {
postProcess: function(config){
// Project settings
config.yeoman = {
// Configurable paths
root: '.',
src: 'src',
test: 'test',
dist: 'dist',
projectName: 'sstooltip',
outputName: 'sstooltip'
};
return config;
}
});
};
|
JavaScript
| 0.000001
|
62c3bc3da6743ce2d69c6b9ec4835f18a416dc14
|
Fix routing of the application.
|
ui/src/index.js
|
ui/src/index.js
|
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom';
import { Provider } from 'react-redux';
import 'bootstrap/dist/css/bootstrap.css';
import registerServiceWorker from './registerServiceWorker';
import WsClient from './WsClient';
import configureStore from './configureStore';
import AppContainer from './App/AppContainer';
import { websocketConnected, websocketDisconnected } from './App/AppActions';
import './index.css';
const wsClient = new WsClient();
const store = configureStore(wsClient);
wsClient.setCallbacks({
onConnect: () => {
store.dispatch(websocketConnected());
// store.dispatch(fetchRocniky());
},
onClose: () => store.dispatch(websocketDisconnected())
});
try {
/* Start asynchronous connect to the websocket server.
WsClient will retry indefinitely if the connection cannot be established. */
wsClient.connect();
} catch (err) {
// Silently ignore any errors. They should have been dispatched from WsClient anyway.
}
/* Render a pathless <Route> so that 'location' is automatically injected as a 'prop'
into AppContainer and causes re-render on location change. See:
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md
*/
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<Route component={AppContainer} />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
|
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import 'bootstrap/dist/css/bootstrap.css';
import registerServiceWorker from './registerServiceWorker';
import WsClient from './WsClient';
import configureStore from './configureStore';
import AppContainer from './App/AppContainer';
import { websocketConnected, websocketDisconnected } from './App/AppActions';
import './index.css';
const wsClient = new WsClient();
const store = configureStore(wsClient);
wsClient.setCallbacks({
onConnect: () => store.dispatch(websocketConnected()),
onClose: () => store.dispatch(websocketDisconnected())
});
try {
/* Start asynchronous connect to the websocket server.
WsClient will retry indefinitely if the connection cannot be established. */
wsClient.connect();
} catch (err) {
// Silently ignore any errors. They should have been dispatched from WsClient anyway.
}
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<AppContainer />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
|
JavaScript
| 0
|
cdc8e94d470eb9bf9f7ba7d10f34b44da7f65a1c
|
Fix not passing ResizeObserver entries to measure method, closes #124
|
src/with-content-rect.js
|
src/with-content-rect.js
|
import { Component, createElement } from 'react'
import PropTypes from 'prop-types'
import ResizeObserver from 'resize-observer-polyfill'
import getTypes from './get-types'
import getContentRect from './get-content-rect'
function withContentRect(types) {
return WrappedComponent =>
class WithContentRect extends Component {
static propTypes = {
client: PropTypes.bool,
offset: PropTypes.bool,
scroll: PropTypes.bool,
bounds: PropTypes.bool,
margin: PropTypes.bool,
innerRef: PropTypes.func,
onResize: PropTypes.func,
}
state = {
contentRect: {
entry: {},
client: {},
offset: {},
scroll: {},
bounds: {},
margin: {},
},
}
_animationFrameID = null
_resizeObserver = null
_node = null
componentDidMount() {
this._resizeObserver = new ResizeObserver(this.measure)
if (this._node !== null) {
this._resizeObserver.observe(this._node)
}
}
componentWillUnmount() {
if (this._resizeObserver !== null) {
this._resizeObserver.disconnect()
this._resizeObserver = null
}
window.cancelAnimationFrame(this._animationFrameID)
}
measure = entries => {
const contentRect = getContentRect(
this._node,
types || getTypes(this.props)
)
if (entries) {
contentRect.entry = entries[0].contentRect
}
this._animationFrameID = window.requestAnimationFrame(() => {
if (this._resizeObserver !== null) {
this.setState({ contentRect })
}
})
if (typeof this.props.onResize === 'function') {
this.props.onResize(contentRect)
}
}
_handleRef = node => {
if (this._resizeObserver !== null) {
if (node !== null) {
this._resizeObserver.observe(node)
} else {
this._resizeObserver.unobserve(this._node)
}
}
this._node = node
if (typeof this.props.innerRef === 'function') {
this.props.innerRef(node)
}
}
render() {
const { innerRef, onResize, ...props } = this.props
return createElement(WrappedComponent, {
...props,
measureRef: this._handleRef,
measure: this.measure,
contentRect: this.state.contentRect,
})
}
}
}
export default withContentRect
|
import { Component, createElement } from 'react'
import PropTypes from 'prop-types'
import ResizeObserver from 'resize-observer-polyfill'
import getTypes from './get-types'
import getContentRect from './get-content-rect'
function withContentRect(types) {
return WrappedComponent =>
class WithContentRect extends Component {
static propTypes = {
client: PropTypes.bool,
offset: PropTypes.bool,
scroll: PropTypes.bool,
bounds: PropTypes.bool,
margin: PropTypes.bool,
innerRef: PropTypes.func,
onResize: PropTypes.func,
}
state = {
contentRect: {
entry: {},
client: {},
offset: {},
scroll: {},
bounds: {},
margin: {},
},
}
_animationFrameID = null
_resizeObserver = new ResizeObserver(() => {
this.measure()
})
componentWillUnmount() {
if (this._resizeObserver) {
this._resizeObserver.disconnect()
this._resizeObserver = null
}
window.cancelAnimationFrame(this._animationFrameID)
}
measure = entries => {
const contentRect = getContentRect(
this._node,
types || getTypes(this.props)
)
if (entries) {
contentRect.entry = entries[0].contentRect
}
this._animationFrameID = window.requestAnimationFrame(() => {
if (this._resizeObserver) {
this.setState({ contentRect })
}
})
if (typeof this.props.onResize === 'function') {
this.props.onResize(contentRect)
}
}
_handleRef = node => {
if (this._resizeObserver) {
if (node) {
this._resizeObserver.observe(node)
} else {
this._resizeObserver.unobserve(this._node)
}
}
this._node = node
if (typeof this.props.innerRef === 'function') {
this.props.innerRef(node)
}
}
render() {
const { innerRef, onResize, ...props } = this.props
return createElement(WrappedComponent, {
...props,
measureRef: this._handleRef,
measure: this.measure,
contentRect: this.state.contentRect,
})
}
}
}
export default withContentRect
|
JavaScript
| 0
|
2455b82f940f2e6561ca6a677c4c0ca6c179202f
|
resolve "after doc deleted , it can also find" bug
|
dao/DocDao.js
|
dao/DocDao.js
|
/**************************************
* 数据库操作类DocDao继承BaseDao
* 2016-7-25
**************************************/
var config = require('../config');
//基础类
var BaseDao = require('./BaseDao');
class DocDao extends BaseDao {
getList(options, callback) {
var page = options.page,
limit = options.limit,
order = options.order || -1;
this.model.find({ is_deleted: false })
.sort({ create_at: order })
.skip((page - 1) * limit)
.limit(limit)
.exec(callback);
}
getTitleById(id, callback) {
this.model.findOne({ _id: id }, '-_id title', function(err, post) {
if (!post) {
return callback(err, '');
}
callback(err, post.title);
});
}
getListByCategory(category, options, callback) {
var page = options.page,
limit = options.limit,
order = options.order || -1;
this.model.find({ category: category, is_deleted: false })
.sort({ create_at: order })
.skip((page - 1) * limit)
.limit(limit)
.exec(callback);
}
getByIdAndUpdateVisitCount(id, callback) {
this.model.findByIdAndUpdate({ _id: id }, { $inc: { visit_count: 1 } }, callback);
}
incCommentCount(id, callback) {
this.model.update({ _id: id }, { $inc: { comment_count: 1 } }, callback);
}
decCommentCount(id, callback) {
this.model.update({ _id: id }, { $inc: { comment_count: -1 } }, callback);
}
getSearchResult(key, options, callback) {
var page = options.page || 1,
page_size = options.page_size || 10,
order = options.order || -1;
this.model.find({ title: { $regex: key }, is_deleted: false })
.sort({ create_at: order })
.skip((page - 1) * page_size)
.limit(page_size)
.exec(callback);
}
getCountByLikeKey(key, callback) {
this.model.count({ title: { $regex: key }, is_deleted: false }, function(err, sumCount) {
if (err) {
return callback(err);
}
return callback(null, {
sum_count: sumCount,
page_count: Math.ceil(sumCount / config.page_num)
});
});
}
getArchives(options, callback) {
var page = options.page,
limit = options.limit,
order = options.order || -1;
this.model.find({ is_deleted: false }, 'title create_at')
.sort({ create_at: order })
.skip((page - 1) * limit)
.limit(limit)
.exec(callback);
}
count(callback) {
this.model.count({ is_deleted: false }, callback);
}
}
module.exports = DocDao;
|
/**************************************
* 数据库操作类DocDao继承BaseDao
* 2016-7-25
**************************************/
var config = require('../config');
//基础类
var BaseDao = require('./BaseDao');
class DocDao extends BaseDao {
getList(options, callback) {
var page = options.page,
limit = options.limit,
order = options.order || -1;
this.model.find({ is_deleted: false })
.sort({ create_at: order })
.skip((page - 1) * limit)
.limit(limit)
.exec(callback);
}
getTitleById(id, callback) {
this.model.findOne({ _id: id }, '-_id title', function(err, post) {
if (!post) {
return callback(err, '');
}
callback(err, post.title);
});
}
getListByCategory(category, options, callback) {
var page = options.page,
limit = options.limit,
order = options.order || -1;
this.model.find({ category: category })
.sort({ create_at: order })
.skip((page - 1) * limit)
.limit(limit)
.exec(callback);
}
getByIdAndUpdateVisitCount(id, callback) {
this.model.findByIdAndUpdate({ _id: id }, { $inc: { visit_count: 1 } }, callback);
}
incCommentCount(id, callback) {
this.model.update({ _id: id }, { $inc: { comment_count: 1 } }, callback);
}
decCommentCount(id, callback) {
this.model.update({ _id: id }, { $inc: { comment_count: -1 } }, callback);
}
getSearchResult(key, options, callback) {
var page = options.page || 1,
page_size = options.page_size || 10,
order = options.order || -1;
this.model.find({ title: { $regex: key } })
.sort({ create_at: order })
.skip((page - 1) * page_size)
.limit(page_size)
.exec(callback);
}
getCountByLikeKey(key, callback) {
this.model.count({ title: { $regex: key } }, function(err, sumCount) {
if (err) {
return callback(err);
}
return callback(null, {
sum_count: sumCount,
page_count: Math.ceil(sumCount / config.page_num)
});
});
}
getArchives(options, callback) {
var page = options.page,
limit = options.limit,
order = options.order || -1;
this.model.find({}, 'title create_at')
.sort({ create_at: order })
.skip((page - 1) * limit)
.limit(limit)
.exec(callback);
}
}
module.exports = DocDao;
|
JavaScript
| 0.000001
|
85c1b6c02d30e8117dc951328cb5cfa6e0c9a21a
|
Update documentation title
|
gruntfile.js
|
gruntfile.js
|
'use strict';
module.exports = function(grunt) {
var pkg = grunt.file.readJSON('package.json');
var docsRepo = 'https://github.com/medullan/jenkins-docker-vagrant-ansible.wiki.git';
var docManifest = {
title: "Jenkins Docker CI (Vagrant Ansible)",
github: pkg.repository.url,
files: []
};
// Project configuration.
grunt.initConfig({
pkg: pkg,
bfdocs: {
documentation: {
options: {
title: 'My Beautiful Documentation',
manifest: docManifest,
dest: 'docs/',
theme: 'default'
}
}
},
clean:{
docs: ['docs','jenkins-docker-vagrant-ansible.wiki']
},
gta: {
cloneWiki: {
command: 'clone ' + docsRepo,
options: {
stdout: true
}
}
},
'gh-pages': {
options: {
base: 'docs' ,
message: 'Generated by grunt gh-pages'
} ,
src: ['**/*']
}
});
require('load-grunt-tasks')(grunt);
// grunt task for refreshing the list of markdown files when cloned from wiki
grunt.registerTask('refreshFiles', 'Get refreshed list of files from wiki', function(){
var gruntConfigProp = 'bfdocs';
var markdown = [
'jenkins-docker-vagrant-ansible.wiki/Home.md',
'jenkins-docker-vagrant-ansible.wiki/*.md',
'!jenkins-docker-vagrant-ansible.wiki/_Footer.md'
];
var files = grunt.file.expand(markdown);
docManifest.files = files;
var bfdocs = grunt.config.get(gruntConfigProp);
bfdocs.documentation.options.manifest = docManifest;
grunt.config.set(gruntConfigProp, bfdocs);
grunt.log.subhead("Complete. Latest documents are ready for processing!");
});
grunt.registerTask('docs', ['clean', 'gta:cloneWiki', 'refreshFiles', 'bfdocs']);
grunt.registerTask('deploy', ['docs', 'gh-pages']);
// By default, generate and deploy website
grunt.registerTask('default', ['deploy']);
};
|
'use strict';
module.exports = function(grunt) {
var pkg = grunt.file.readJSON('package.json');
var docsRepo = 'https://github.com/medullan/jenkins-docker-vagrant-ansible.wiki.git';
var docManifest = {
title: "Vagrant Ansible Jenkins",
github: pkg.repository.url,
files: []
};
// Project configuration.
grunt.initConfig({
pkg: pkg,
bfdocs: {
documentation: {
options: {
title: 'My Beautiful Documentation',
manifest: docManifest,
dest: 'docs/',
theme: 'default'
}
}
},
clean:{
docs: ['docs','jenkins-docker-vagrant-ansible.wiki']
},
gta: {
cloneWiki: {
command: 'clone ' + docsRepo,
options: {
stdout: true
}
}
},
'gh-pages': {
options: {
base: 'docs' ,
message: 'Generated by grunt gh-pages'
} ,
src: ['**/*']
}
});
require('load-grunt-tasks')(grunt);
// grunt task for refreshing the list of markdown files when cloned from wiki
grunt.registerTask('refreshFiles', 'Get refreshed list of files from wiki', function(){
var gruntConfigProp = 'bfdocs';
var markdown = [
'jenkins-docker-vagrant-ansible.wiki/Home.md',
'jenkins-docker-vagrant-ansible.wiki/*.md',
'!jenkins-docker-vagrant-ansible.wiki/_Footer.md'
];
var files = grunt.file.expand(markdown);
docManifest.files = files;
var bfdocs = grunt.config.get(gruntConfigProp);
bfdocs.documentation.options.manifest = docManifest;
grunt.config.set(gruntConfigProp, bfdocs);
grunt.log.subhead("Complete. Latest documents are ready for processing!");
});
grunt.registerTask('docs', ['clean', 'gta:cloneWiki', 'refreshFiles', 'bfdocs']);
grunt.registerTask('deploy', ['docs', 'gh-pages']);
// By default, generate and deploy website
grunt.registerTask('default', ['deploy']);
};
|
JavaScript
| 0.000001
|
044c846923296c958cb44879bb8029e4a197c936
|
Fix lint warnings in gruntfile.js
|
gruntfile.js
|
gruntfile.js
|
'use strict'
var _ = require('lodash')
var webpack = require('webpack')
var mergeWebpackConfig = function (config) {
// Load webpackConfig only when using `grunt:webpack`
// load of grunt tasks is faster
var webpackConfig = require('./webpack.config')
return _.merge({}, webpackConfig, config, function (a, b) {
if (_.isArray(a)) {
return a.concat(b)
}
})
}
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
min: {
files: {
'dist/react-datepicker.css': 'src/stylesheets/datepicker.scss'
},
options: {
sourcemap: 'none',
style: 'expanded'
}
},
unmin: {
files: {
'dist/react-datepicker.min.css': 'src/stylesheets/datepicker.scss'
},
options: {
sourcemap: 'none',
style: 'compressed'
}
}
},
watch: {
eslint: {
files: ['**/*.jsx'],
tasks: ['eslint']
},
css: {
files: '**/*.scss',
tasks: ['sass']
},
karma: {
files: [
'src/**/*.jsx',
'src/**/*.js',
'test/**/*.jsx',
'test/**/*.js'
],
tasks: ['karma']
},
webpack: {
files: ['src/**/*.js', 'src/**/*.jsx'],
tasks: ['webpack']
}
},
scsslint: {
files: 'src/stylesheets/*.scss',
options: {
config: '.scss-lint.yml',
colorizeOutput: true
}
},
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true
}
},
eslint: {
files: ['**/*.jsx'],
options: {
configFile: '.eslintrc'
}
},
webpack: {
unmin: mergeWebpackConfig({
output: {
filename: 'react-datepicker.js'
}
}),
min: mergeWebpackConfig({
output: {
filename: 'react-datepicker.min.js'
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
]
}),
docs: require('./webpack.docs.config')
}
})
grunt.loadNpmTasks('grunt-contrib-sass')
grunt.loadNpmTasks('grunt-scss-lint')
grunt.loadNpmTasks('grunt-contrib-watch')
grunt.loadNpmTasks('grunt-webpack')
grunt.loadNpmTasks('grunt-karma')
grunt.loadNpmTasks('grunt-eslint')
grunt.registerTask('default', ['watch', 'scsslint'])
grunt.registerTask('travis', ['eslint', 'karma', 'scsslint'])
grunt.registerTask('build', ['scsslint', 'webpack', 'sass'])
}
|
"use strict";
var _ = require("lodash");
var webpack = require("webpack");
var mergeWebpackConfig = function(config) {
// Load webpackConfig only when using `grunt:webpack`
// load of grunt tasks is faster
var webpackConfig = require("./webpack.config");
return _.merge({}, webpackConfig, config, function(a, b) {
if (_.isArray(a)) {
return a.concat(b);
}
});
};
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
sass: {
min: {
files: {
"dist/react-datepicker.css": "src/stylesheets/datepicker.scss"
},
options: {
sourcemap: "none",
style: "expanded"
}
},
unmin: {
files: {
"dist/react-datepicker.min.css": "src/stylesheets/datepicker.scss"
},
options: {
sourcemap: "none",
style: "compressed"
}
}
},
watch: {
eslint: {
files: ["**/*.jsx"],
tasks: ["eslint"]
},
css: {
files: "**/*.scss",
tasks: ["sass"]
},
karma: {
files: [
"src/**/*.jsx",
"src/**/*.js",
"test/**/*.jsx",
"test/**/*.js"
],
tasks: ["karma"]
},
webpack: {
files: ["src/**/*.js", "src/**/*.jsx"],
tasks: ["webpack"]
}
},
scsslint: {
files: "src/stylesheets/*.scss",
options: {
config: ".scss-lint.yml",
colorizeOutput: true
}
},
karma: {
unit: {
configFile: "karma.conf.js",
singleRun: true
}
},
eslint: {
files: ["**/*.jsx"],
options: {
configFile: ".eslintrc"
}
},
webpack: {
unmin: mergeWebpackConfig({
output: {
filename: "react-datepicker.js"
}
}),
min: mergeWebpackConfig({
output: {
filename: "react-datepicker.min.js"
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
]
}),
docs: require("./webpack.docs.config")
}
});
grunt.loadNpmTasks("grunt-contrib-sass");
grunt.loadNpmTasks("grunt-scss-lint");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-webpack");
grunt.loadNpmTasks("grunt-karma");
grunt.loadNpmTasks("grunt-eslint");
grunt.registerTask("default", ["watch", "scsslint"]);
grunt.registerTask("travis", ["eslint", "karma", "scsslint"]);
grunt.registerTask("build", ["scsslint", "webpack", "sass"]);
};
|
JavaScript
| 0.000007
|
e8d71157623538e60f8bde7c04280d4e63b791c8
|
Return null when data not available
|
src/vfs.js
|
src/vfs.js
|
/**
* <h1>VFS Manager</h1>
*
* <h2>spaceStatus</h2>
*
* <table>
* <thead><td>Code</td><td>Status name</td></thead>
* <tr><td>0</td><td>UNKNOWN</td></tr>
* <tr><td>1</td><td>ABOVE</td></tr>
* <tr><td>2</td><td>BELOW</td></tr>
* </table>
*
* @module vfs
* @namespace TVB
* @title VFS Manager
* @requires tvblob
* @author Francesco Facconi [email protected]
*/
/**
* TVBLOB's VFS Manager Class
* @class vfs
* @namespace TVB
* @classDescription TVBLOB's VFS Manager Class
* @static
*/
TVB.vfs = {};
/**
* Get space status code (w.r.t. the minimum space threshold set for this storage).
* @method getStorageSpaceStatusCode
* @return {Number} spaceStatus Code
*/
TVB.vfs.getStorageSpaceStatusCode = function() {
try {
TVB.log("Vfs: getStorageSpaceStatusCode()");
var s = new LocalStorage();
return s.getStorageSpaceStatusCode();
} catch (e) {
TVB.error("Vfs: getStorageSpaceStatusCode: " + e.message);
throw e;
}
}
/**
* Get storage space status string (w.r.t. the minimum space threshold set for this storage).
* @method getStorageSpaceStatusName
* @return {String} spaceStatus Name
*/
TVB.vfs.getStorageSpaceStatusName = function() {
try {
TVB.log("Vfs: getStorageSpaceStatusName()");
var s = new LocalStorage();
return s.getStorageSpaceStatusName();
} catch (e) {
TVB.error("Vfs: getStorageSpaceStatusName: " + e.message);
throw e;
}
}
/**
* Get the local storage free space as string.
* @method getFreeSpaceAsString
* @return {String} a string that can be converted to long and represents free space, null if the information is not available
*/
TVB.vfs.getFreeSpaceAsString = function() {
try {
TVB.log("Vfs: getFreeSpaceAsString()");
var s = new LocalStorage();
return s.getFreeSpaceAsString();
} catch (e) {
TVB.error("Vfs: getFreeSpaceAsString: " + e.message);
throw e;
}
}
/**
* Get the local storage free space as string.
* @method getFreeSpaceAsString
* @return {Number} a float converted from the string that represents free space, null if the information is not available
*/
TVB.vfs.getFreeSpaceAsFloat = function() {
try {
TVB.log("Vfs: getFreeSpaceAsFloat()");
var s = new LocalStorage();
var c = s.getFreeSpaceAsString();
if (c == null) {
return null;
} else {
return parseInt(c);
}
} catch (e) {
TVB.error("Vfs: getFreeSpaceAsFloat: " + e.message);
throw e;
}
}
/**
* Get a formatted string that represents the local storage free space.
* @method getFreeSpaceAsFormattedString
* @return {String} a formatted string to show free space, null if the information is not available
*/
TVB.vfs.getFreeSpaceAsFormattedString = function() {
try {
TVB.log("Vfs: getFreeSpaceAsFormattedString()");
var s = new LocalStorage();
return s.getFreeSpaceAsFormattedString();
} catch (e) {
TVB.error("Vfs: getFreeSpaceAsFormattedString: " + e.message);
throw e;
}
}
|
/**
* <h1>VFS Manager</h1>
*
* <h2>spaceStatus</h2>
*
* <table>
* <thead><td>Code</td><td>Status name</td></thead>
* <tr><td>0</td><td>UNKNOWN</td></tr>
* <tr><td>1</td><td>ABOVE</td></tr>
* <tr><td>2</td><td>BELOW</td></tr>
* </table>
*
* @module vfs
* @namespace TVB
* @title VFS Manager
* @requires tvblob
* @author Francesco Facconi [email protected]
*/
/**
* TVBLOB's VFS Manager Class
* @class vfs
* @namespace TVB
* @classDescription TVBLOB's VFS Manager Class
* @static
*/
TVB.vfs = {};
/**
* Get space status code (w.r.t. the minimum space threshold set for this storage).
* @method getStorageSpaceStatusCode
* @return {Number} spaceStatus Code
*/
TVB.vfs.getStorageSpaceStatusCode = function() {
try {
TVB.log("Vfs: getStorageSpaceStatusCode()");
var s = new LocalStorage();
return s.getStorageSpaceStatusCode();
} catch (e) {
TVB.error("Vfs: getStorageSpaceStatusCode: " + e.message);
throw e;
}
}
/**
* Get storage space status string (w.r.t. the minimum space threshold set for this storage).
* @method getStorageSpaceStatusName
* @return {String} spaceStatus Name
*/
TVB.vfs.getStorageSpaceStatusName = function() {
try {
TVB.log("Vfs: getStorageSpaceStatusName()");
var s = new LocalStorage();
return s.getStorageSpaceStatusName();
} catch (e) {
TVB.error("Vfs: getStorageSpaceStatusName: " + e.message);
throw e;
}
}
/**
* Get the local storage free space as string.
* @method getFreeSpaceAsString
* @return {String} a string that can be converted to long and represents free space, null if the information is not available
*/
TVB.vfs.getFreeSpaceAsString = function() {
try {
TVB.log("Vfs: getFreeSpaceAsString()");
var s = new LocalStorage();
return s.getFreeSpaceAsString();
} catch (e) {
TVB.error("Vfs: getFreeSpaceAsString: " + e.message);
throw e;
}
}
/**
* Get the local storage free space as string.
* @method getFreeSpaceAsString
* @return {Number} a float converted from the string that represents free space, null if the information is not available
*/
TVB.vfs.getFreeSpaceAsFloat = function() {
try {
TVB.log("Vfs: getFreeSpaceAsFloat()");
var s = new LocalStorage();
return parseInt(s.getFreeSpaceAsString());
} catch (e) {
TVB.error("Vfs: getFreeSpaceAsFloat: " + e.message);
throw e;
}
}
/**
* Get a formatted string that represents the local storage free space.
* @method getFreeSpaceAsFormattedString
* @return {String} a formatted string to show free space, null if the information is not available
*/
TVB.vfs.getFreeSpaceAsFormattedString = function() {
try {
TVB.log("Vfs: getFreeSpaceAsFormattedString()");
var s = new LocalStorage();
return s.getFreeSpaceAsFormattedString();
} catch (e) {
TVB.error("Vfs: getFreeSpaceAsFormattedString: " + e.message);
throw e;
}
}
|
JavaScript
| 0.000006
|
3a89bdb8de259de02c1af9eb3e15f510307301dd
|
update listener
|
server.js
|
server.js
|
var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url");
var Firebase = require("firebase")
my_http.createServer(function(request,response){
var my_path = url.parse(request.url).pathme;
var full_path = path.join(process.cwd(),my_path);
path.exists(full_path, function(exists){
if(!exists){
response.writeHeader(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
}
else{
// a reference here doesn't open a connection until r/w ops are invoked
var fb = new Firebase("https://improvplusplus.firebaseio.com")
}
});
})
my_http.createServer(function(request,response){
var my_path = url.parse(request.url).pathname;
}).listen(0.0.0.0:3000);
|
var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url");
var Firebase = require("firebase")
my_http.createServer(function(request,response){
var my_path = url.parse(request.url).pathme;
var full_path = path.join(process.cwd(),my_path);
path.exists(full_path, function(exists){
if(!exists){
response.writeHeader(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
}
else{
// a reference here doesn't open a connection until r/w ops are invoked
var fb = new Firebase("https://improvplusplus.firebaseio.com")
}
});
})
my_http.createServer(function(request,response){
var my_path = url.parse(request.url).pathname;
load_file(my_path,response);
}).listen(0.0.0.0:3000);
|
JavaScript
| 0
|
e47153b7fd4c0b42d497a866cdbf9982bfc15dd7
|
add givataiim
|
data/index.js
|
data/index.js
|
var municipalities = {
"givataiim": {
"center": [
32.071151,
34.80989
],
"display": "\u05d2\u05d1\u05e2\u05ea\u05d9\u05d9\u05dd"
},
"jerusalem": {
"center": [
31.783476,
35.202637
],
"display": "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd",
"fb_link": "https://www.facebook.com/opentaba.jerusalem",
"server": "http://opentaba-server.herokuapp.com/",
"twitter_link": "https://twitter.com/opentaba_JLM"
}
};
|
var municipalities = {
"jerusalem": {
"center": [
31.783476,
35.202637
],
"display": "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd",
"fb_link": "https://www.facebook.com/opentaba.jerusalem",
"server": "http://opentaba-server.herokuapp.com/",
"twitter_link": "https://twitter.com/opentaba_JLM"
}
};
|
JavaScript
| 0.000002
|
7ead01022af37a4b67dd4069156bab23e20da4f1
|
Fix merge error
|
gruntfile.js
|
gruntfile.js
|
module.exports = function (grunt) {
var config = require("./config.js");
// Make sure that Grunt doesn't remove BOM from our utf8 files
// on read
grunt.file.preserveBOM = true;
// Helper function to load the config file
function loadConfig(path) {
var glob = require('glob');
var object = {};
var key;
glob.sync('*', {cwd: path}).forEach(function(option) {
key = option.replace(/\.js$/,'');
object[key] = require(path + option);
});
return object;
}
// Load task options
var gruntConfig = loadConfig('./tasks/options/');
// Package data
gruntConfig.pkg = grunt.file.readJSON("package.json");
// Project config
grunt.initConfig(gruntConfig);
// Load all grunt-tasks in package.json
require("load-grunt-tasks")(grunt);
// Register external tasks
grunt.loadTasks("tasks/");
// Task alias's
grunt.registerTask("default", ["clean", "less", "concat", "copy", "replace"]);
grunt.registerTask("css", ["less"]);
grunt.registerTask("base", ["clean:base", "concat:baseDesktop", "concat:basePhone", "concat:baseStringsDesktop", "concat:baseStringsPhone", "replace"]);
grunt.registerTask("ui", ["clean:ui", "concat:uiDesktop", "concat:uiPhone", "concat:uiStringsDesktop", "concat:uiStringsPhone", "replace", "less"]);
}
|
module.exports = function (grunt) {
var config = require("./config.js");
// Make sure that Grunt doesn't remove BOM from our utf8 files
// on read
grunt.file.preserveBOM = true;
// Helper function to load the config file
function loadConfig(path) {
var glob = require('glob');
var object = {};
var key;
glob.sync('*', {cwd: path}).forEach(function(option) {
key = option.replace(/\.js$/,'');
object[key] = require(path + option);
});
return object;
}
// Load task options
var gruntConfig = loadConfig('./tasks/options/');
// Package data
gruntConfig.pkg = grunt.file.readJSON("package.json");
{ expand: true, flatten: true, src: [desktopOutput + "css/*.css"], dest: desktopOutput + "css/" },
{ expand: true, flatten: true, src: [phoneOutput + "css/*.css"], dest: phoneOutput + "css/" },
// Project config
grunt.initConfig(gruntConfig);
// Load all grunt-tasks in package.json
require("load-grunt-tasks")(grunt);
// Register external tasks
grunt.loadTasks("tasks/");
// Task alias's
grunt.registerTask("default", ["clean", "less", "concat", "copy", "replace"]);
grunt.registerTask("css", ["less"]);
grunt.registerTask("base", ["clean:base", "concat:baseDesktop", "concat:basePhone", "concat:baseStringsDesktop", "concat:baseStringsPhone", "replace"]);
grunt.registerTask("ui", ["clean:ui", "concat:uiDesktop", "concat:uiPhone", "concat:uiStringsDesktop", "concat:uiStringsPhone", "replace", "less"]);
}
|
JavaScript
| 0.000006
|
868637fcdc8abf70ec98ac541dab7f07288303a3
|
Fix grunt watch
|
gruntfile.js
|
gruntfile.js
|
module.exports = function (grunt) {
grunt.initConfig({
browserify: {
client: {
src: ['src/**.js'],
dest: 'dist/m4n.js',
options: {
transform: ['babelify']
}
}
},
watch: {
javascript: {
tasks: ['default'],
files: ['src/**.js']
},
},
jshint: {
beforeconcat: ['gruntfile.js', 'src/**.js'],
options: {
esversion: 6
}
},
uglify: {
options: {
report: 'gzip'
},
default: {
files: {
'dist/m4n.min.js': ['dist/m4n.js']
}
}
},
clean: [
'dist/*'
],
env: {
prod: {
NODE_ENV : 'production',
BABEL_ENV : 'production'
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-env');
grunt.loadNpmTasks('grunt-browserify');
grunt.registerTask('default', ['clean', 'jshint', 'browserify']);
grunt.registerTask('production', ['env:prod', 'clean', 'jshint', 'browserify', 'uglify']);
};
|
module.exports = function (grunt) {
grunt.initConfig({
browserify: {
client: {
src: ['src/**.js'],
dest: 'dist/m4n.js',
options: {
transform: ['babelify']
}
}
},
watch: {
javascript: {
tasks: ['default']
},
},
jshint: {
beforeconcat: ['gruntfile.js', 'src/**.js'],
options: {
esversion: 6
}
},
uglify: {
options: {
report: 'gzip'
},
default: {
files: {
'dist/m4n.min.js': ['dist/m4n.js']
}
}
},
clean: [
'dist/*'
],
env: {
prod: {
NODE_ENV : 'production',
BABEL_ENV : 'production'
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-env');
grunt.loadNpmTasks('grunt-browserify');
grunt.registerTask('default', ['clean', 'jshint', 'browserify']);
grunt.registerTask('production', ['env:prod', 'clean', 'jshint', 'browserify', 'uglify']);
};
|
JavaScript
| 0
|
df20a743adfea63eec96f4da082d861ee7057f28
|
Fix minor typo
|
server.js
|
server.js
|
var express = require('express');
var passport = require('passport');
var Strategy = require('passport-local').Strategy;
var db = require('./db');
// Configure the local strategy for use by Passport.
//
// The local strategy requires a `verify` function which receives the credentials
// (`username` and `password`) submitted by the user. The function must verify
// that the password is correct and then invoke `cb` with a user object, which
// will be set at `req.user` in route handlers after authentication.
passport.use(new Strategy(
function(username, password, cb) {
db.users.findByUsername(username, function(err, user) {
if (err) { return cb(err); }
if (!user) { return cb(null, false); }
if (user.password != password) { return cb(null, false); }
return cb(null, user);
});
}));
// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session. The
// typical implementation of this is as simple as supplying the user ID when
// serializing, and querying the user record by ID from the database when
// deserializing.
passport.serializeUser(function(user, cb) {
cb(null, user.id);
});
passport.deserializeUser(function(id, cb) {
db.users.findById(id, function (err, user) {
if (err) { return cb(err); }
cb(null, user);
});
});
// Create a new Express application.
var app = express();
// Configure view engine to render EJS templates.
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());
// Define routes.
app.get('/',
function(req, res) {
res.render('home', { user: req.user });
});
app.get('/login',
function(req, res){
res.render('login');
});
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
app.get('/logout',
function(req, res){
req.logout();
res.redirect('/');
});
app.get('/profile',
require('connect-ensure-login').ensureLoggedIn(),
function(req, res){
res.render('profile', { user: req.user });
});
app.listen(3000);
|
var express = require('express');
var passport = require('passport');
var Strategy = require('passport-local').Strategy;
var db = require('./db');
// Configure the local strategy for use by Passport.
//
// The local strategy require a `verify` function which receives the credentials
// (`username` and `password`) submitted by the user. The function must verify
// that the password is correct and then invoke `cb` with a user object, which
// will be set at `req.user` in route handlers after authentication.
passport.use(new Strategy(
function(username, password, cb) {
db.users.findByUsername(username, function(err, user) {
if (err) { return cb(err); }
if (!user) { return cb(null, false); }
if (user.password != password) { return cb(null, false); }
return cb(null, user);
});
}));
// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session. The
// typical implementation of this is as simple as supplying the user ID when
// serializing, and querying the user record by ID from the database when
// deserializing.
passport.serializeUser(function(user, cb) {
cb(null, user.id);
});
passport.deserializeUser(function(id, cb) {
db.users.findById(id, function (err, user) {
if (err) { return cb(err); }
cb(null, user);
});
});
// Create a new Express application.
var app = express();
// Configure view engine to render EJS templates.
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());
// Define routes.
app.get('/',
function(req, res) {
res.render('home', { user: req.user });
});
app.get('/login',
function(req, res){
res.render('login');
});
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
app.get('/logout',
function(req, res){
req.logout();
res.redirect('/');
});
app.get('/profile',
require('connect-ensure-login').ensureLoggedIn(),
function(req, res){
res.render('profile', { user: req.user });
});
app.listen(3000);
|
JavaScript
| 0.999993
|
deb23418e8c603daf2a4484d6fe2dc85803c220c
|
bump service worker cache version
|
static/javascripts/sw.js
|
static/javascripts/sw.js
|
importScripts('/offline-google-analytics/offline-google-analytics-import.js');
goog.offlineGoogleAnalytics.initialize();
const cacheName = 'gcpnext17-v3';
const pathsToCache = [
'/',
'/faqs',
'/coc',
'/static/manifest.json',
'/static/stylesheets/fonts.min.css',
'/static/stylesheets/main.min.css',
'/static/javascripts/main.min.js',
'/static/javascripts/sw-register.min.js',
'/offline-google-analytics/offline-google-analytics-import.js',
'/static/images/logo.png',
'/static/images/gdg-logo.png',
'/static/fonts/droid-sans/bold.ttf',
'/static/fonts/droid-sans/regular.ttf',
'/static/fonts/quicksand/bold.woff2'
];
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open(cacheName)
.then(function(cache) {
return cache.addAll(pathsToCache);
})
.then(function() {
return self.skipWaiting();
})
);
});
self.addEventListener('activate', function(e) {
e.waitUntil(
caches.keys()
.then(function(cacheKeys) {
return Promise.all(cacheKeys.map(function(cacheKey) {
if (cacheKey !== cacheName) {
caches.delete(cacheKey);
}
}));
})
.then(function() {
self.clients.claim();
})
);
});
self.addEventListener('fetch', function(e) {
e.respondWith(
caches.match(e.request)
.then(function(response) {
return response || fetch(e.request);
})
);
});
|
importScripts('/offline-google-analytics/offline-google-analytics-import.js');
goog.offlineGoogleAnalytics.initialize();
const cacheName = 'gcpnext17-v2';
const pathsToCache = [
'/',
'/faqs',
'/coc',
'/static/manifest.json',
'/static/stylesheets/fonts.min.css',
'/static/stylesheets/main.min.css',
'/static/javascripts/main.min.js',
'/static/javascripts/sw-register.min.js',
'/offline-google-analytics/offline-google-analytics-import.js',
'/static/images/logo.png',
'/static/images/gdg-logo.png',
'/static/fonts/droid-sans/bold.ttf',
'/static/fonts/droid-sans/regular.ttf',
'/static/fonts/quicksand/bold.woff2'
];
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open(cacheName)
.then(function(cache) {
return cache.addAll(pathsToCache);
})
.then(function() {
return self.skipWaiting();
})
);
});
self.addEventListener('activate', function(e) {
e.waitUntil(
caches.keys()
.then(function(cacheKeys) {
return Promise.all(cacheKeys.map(function(cacheKey) {
if (cacheKey !== cacheName) {
caches.delete(cacheKey);
}
}));
})
.then(function() {
self.clients.claim();
})
);
});
self.addEventListener('fetch', function(e) {
e.respondWith(
caches.match(e.request)
.then(function(response) {
return response || fetch(e.request);
})
);
});
|
JavaScript
| 0
|
37b265495b04f113cf678508b59b57ec2adac04b
|
Revert back `before_punctuation` regex to stable one.
|
static/js/alert_words.js
|
static/js/alert_words.js
|
import _ from "lodash";
import * as people from "./people";
// For simplicity, we use a list for our internal
// data, since that matches what the server sends us.
let my_alert_words = [];
export function set_words(words) {
my_alert_words = words;
}
export function get_word_list() {
// People usually only have a couple alert
// words, so it's cheap to be defensive
// here and give a copy of the list to
// our caller (in case they want to sort it
// or something).
return [...my_alert_words];
}
export function has_alert_word(word) {
return my_alert_words.includes(word);
}
export function process_message(message) {
// Parsing for alert words is expensive, so we rely on the host
// to tell us there any alert words to even look for.
if (!message.alerted) {
return;
}
for (const word of my_alert_words) {
const clean = _.escapeRegExp(word);
const before_punctuation = "\\s|^|>|[\\(\\\".,';\\[]";
const after_punctuation = "(?=\\s)|$|<|[\\)\\\"\\?!:.,';\\]!]";
const regex = new RegExp(`(${before_punctuation})(${clean})(${after_punctuation})`, "ig");
message.content = message.content.replace(
regex,
(match, before, word, after, offset, content) => {
// Logic for ensuring that we don't muck up rendered HTML.
const pre_match = content.slice(0, offset);
// We want to find the position of the `<` and `>` only in the
// match and the string before it. So, don't include the last
// character of match in `check_string`. This covers the corner
// case when there is an alert word just before `<` or `>`.
const check_string = pre_match + match.slice(0, -1);
const in_tag = check_string.lastIndexOf("<") > check_string.lastIndexOf(">");
// Matched word is inside a HTML tag so don't perform any highlighting.
if (in_tag === true) {
return before + word + after;
}
return before + "<span class='alert-word'>" + word + "</span>" + after;
},
);
}
}
export function notifies(message) {
// We exclude ourselves from notifications when we type one of our own
// alert words into a message, just because that can be annoying for
// certain types of workflows where everybody on your team, including
// yourself, sets up an alert word to effectively mention the team.
return !people.is_current_user(message.sender_email) && message.alerted;
}
export const initialize = (params) => {
my_alert_words = params.alert_words;
};
|
import _ from "lodash";
import * as people from "./people";
// For simplicity, we use a list for our internal
// data, since that matches what the server sends us.
let my_alert_words = [];
export function set_words(words) {
my_alert_words = words;
}
export function get_word_list() {
// People usually only have a couple alert
// words, so it's cheap to be defensive
// here and give a copy of the list to
// our caller (in case they want to sort it
// or something).
return [...my_alert_words];
}
export function has_alert_word(word) {
return my_alert_words.includes(word);
}
export function process_message(message) {
// Parsing for alert words is expensive, so we rely on the host
// to tell us there any alert words to even look for.
if (!message.alerted) {
return;
}
for (const word of my_alert_words) {
const clean = _.escapeRegExp(word);
const before_punctuation = "(?<=\\s)|^|>|[\\(\\\".,';\\[]";
const after_punctuation = "(?=\\s)|$|<|[\\)\\\"\\?!:.,';\\]!]";
const regex = new RegExp(`(${before_punctuation})(${clean})(${after_punctuation})`, "ig");
message.content = message.content.replace(
regex,
(match, before, word, after, offset, content) => {
// Logic for ensuring that we don't muck up rendered HTML.
const pre_match = content.slice(0, offset);
// We want to find the position of the `<` and `>` only in the
// match and the string before it. So, don't include the last
// character of match in `check_string`. This covers the corner
// case when there is an alert word just before `<` or `>`.
const check_string = pre_match + match.slice(0, -1);
const in_tag = check_string.lastIndexOf("<") > check_string.lastIndexOf(">");
// Matched word is inside a HTML tag so don't perform any highlighting.
if (in_tag === true) {
return before + word + after;
}
return before + "<span class='alert-word'>" + word + "</span>" + after;
},
);
}
}
export function notifies(message) {
// We exclude ourselves from notifications when we type one of our own
// alert words into a message, just because that can be annoying for
// certain types of workflows where everybody on your team, including
// yourself, sets up an alert word to effectively mention the team.
return !people.is_current_user(message.sender_email) && message.alerted;
}
export const initialize = (params) => {
my_alert_words = params.alert_words;
};
|
JavaScript
| 0.000002
|
6ea40a277450276e69f3a31d56fb59bebc00c38b
|
Return null if no comment in database
|
static/js/controllers.js
|
static/js/controllers.js
|
'use strict';
/* The angular application controllers */
var mycomputerControllers = angular.module('mycomputerControllers', []);
/* This controller to get comment from beego api */
mycomputerControllers.controller('HomeController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
/* Get the comment objects */
$http.get('/api/comment').success(function(data) {
/* If the data is empty string, don't return objects */
if(typeof data.Id == "undefined") {
$scope.comments = null;
} else {
$scope.comments = data;
}
});
}]);
/* This controller to get user and items from beego api */
mycomputerControllers.controller('UserItemsController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
/* Get the user object */
$http.get('/api/' + $routeParams.username).success(function(data) {
/* If the data is empty string, don't return objects */
if(typeof data.Name == "undefined") {
$scope.user = null;
} else {
$scope.user = data;
}
});
/* Get the user item objects */
$http.get('/api/' + $routeParams.username +'/items').success(function(data) {
/* If the data is empty string, don't return objects */
if (typeof data[0].Username == "undefined") {
$scope.items = null;
} else {
$scope.items = data;
}
});
/* Determine whether pop up the form to add item or not */
$scope.adding = false;
}
]);
|
'use strict';
/* The angular application controllers */
var mycomputerControllers = angular.module('mycomputerControllers', []);
/* This controller to get comment from beego api */
mycomputerControllers.controller('HomeController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
/* Get the comment objects */
$http.get('/api/comment').success(function(data) {
/* If the data is empty string, don't return objects */
if(typeof data.Content == "undefined") {
$scope.comments = data;//null;
} else {
$scope.comments = data;
}
});
}]);
/* This controller to get user and items from beego api */
mycomputerControllers.controller('UserItemsController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
/* Get the user object */
$http.get('/api/' + $routeParams.username).success(function(data) {
/* If the data is empty string, don't return objects */
if(typeof data.Name == "undefined") {
$scope.user = null;
} else {
$scope.user = data;
}
});
/* Get the user item objects */
$http.get('/api/' + $routeParams.username +'/items').success(function(data) {
/* If the data is empty string, don't return objects */
if (typeof data[0].Username == "undefined") {
$scope.items = null;
} else {
$scope.items = data;
}
});
/* Determine whether pop up the form to add item or not */
$scope.adding = false;
}
]);
|
JavaScript
| 0.000003
|
9792bebf2021e8328ab611cf34ab416cc6817490
|
update service worker
|
static/service-worker.js
|
static/service-worker.js
|
self.addEventListener('install', function(event) {
event.waitUntil(
caches
.open('v2')
.then(function(cache) {
return cache.addAll([
'.',
'favicon.ico',
'manifest.json',
'img/code.png',
'img/coffee.png',
'img/logo16.png',
'img/logo32.png',
'img/logo48.png',
'img/logo62.png',
'img/logo72.png',
'img/logo96.png',
'img/logo144.png',
'img/logo168.png',
'img/logo192.png',
'audio/alarm.mp3'
]).then(function() {
self.skipWaiting()
})
})
)
})
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request).catch(function() {
return caches.match(event.request)
})
)
})
|
self.addEventListener('install', function(event) {
event.waitUntil(
caches
.open('v1')
.then(function(cache) {
return cache.addAll([
'.',
'favicon.ico',
'manifest.json',
'img/code.png',
'img/coffee.png',
'img/logo16.png',
'img/logo32.png',
'img/logo48.png',
'img/logo62.png',
'img/logo72.png',
'img/logo96.png',
'img/logo144.png',
'img/logo168.png',
'img/logo192.png',
'audio/alarm.mp3'
]).then(function() {
self.skipWaiting()
})
})
)
})
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request)
})
)
})
|
JavaScript
| 0.000003
|
eac1caef4bfe291c7983ceafbb0f375f0e290c9e
|
Update siisen.js
|
siisen.js
|
siisen.js
|
$(function() {
// run the currently selected effect
function runEffect() {
// get effect type from
var selectedEffect = $( "#effectTypes" ).val();
// most effect types need no options passed by default
var options = {};
// some effects have required parameters
if ( selectedEffect === "scale" ) {
options = { percent: 60 };
} else if ( selectedEffect === "size" ) {
options = { to: { width: 480, height: 385 } };
}
// run the effect
$( "#effect" ).show( selectedEffect, options, 1100, callback );
};
//callback function to bring a hidden box back
function callback() {
setTimeout(function() {
$( "#effect:visible" ).removeAttr( "style" ).fadeOut();
}, 10000 );
};
// set effect from select menu value
$( "#button" ).click(function() {
runEffect();
});
$( "#effect" ).hide();
//hide v_nav_bar
//$( "#v_nav_bar").show();
$(function() {
$( "#accordion" ).accordion();
})
});
$("#accordion").hide();
$( "#clickme" ).click(function() {
$( "#back" ).slideToggle( "slow", function() {
// Animation complete.
});
});
|
$(function() {
// run the currently selected effect
function runEffect() {
// get effect type from
var selectedEffect = $( "#effectTypes" ).val();
// most effect types need no options passed by default
var options = {};
// some effects have required parameters
if ( selectedEffect === "scale" ) {
options = { percent: 60 };
} else if ( selectedEffect === "size" ) {
options = { to: { width: 480, height: 385 } };
}
// run the effect
$( "#effect" ).show( selectedEffect, options, 1100, callback );
};
//callback function to bring a hidden box back
function callback() {
setTimeout(function() {
$( "#effect:visible" ).removeAttr( "style" ).fadeOut();
}, 10000 );
};
// set effect from select menu value
$( "#button" ).click(function() {
runEffect();
});
$( "#effect" ).hide();
//hide v_nav_bar
//$( "#v_nav_bar").show();
$(function() {
$( "#accordion" ).accordion();
})
});
// $("#accordion").hide();
$( "#clickme" ).click(function() {
$( "#back" ).slideToggle( "slow", function() {
// Animation complete.
});
});
|
JavaScript
| 0
|
a0f85e1024c04d929e2bfbec3492f40fa02e241d
|
Update logger.js
|
utils/logger.js
|
utils/logger.js
|
/*jslint node: true */
'use strict';
var fs = require('fs');
var path = require('path');
var winston = require('winston');
var pjson = require('../package.json');
var logDir = "logs";
var env = process.env.NODE_ENV || 'development';
var transports = [];
/* Define colours for error level highlighting */
var colours = {
debug: 'yellow',
verbose: 'green',
info: 'cyan',
warn: 'magenta',
error: 'red'
};
winston.addColors(colours);
/* Create log directory if missing */
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
/* Output everything to screen */
transports.push(new (winston.transports.Console)({level: 'debug', colorize: true, 'timestamp': false}));
/* Write to daily log file, using less detail in production */
winston.add(require('winston-daily-rotate-file'), {
name: 'file',
json: false,
filename: path.join(logDir, pjson.name),
datePattern: '.yyyy-MM-dd.txt',
level: env === 'development' ? 'debug' : 'info'
});
var logger = new winston.Logger({transports: transports});
module.exports = logger;
|
/*jslint node: true */
'use strict';
var fs = require('fs');
var path = require('path');
var winston = require('winston');
var pjson = require('../package.json');
var logDir = "logs";
var env = process.env.NODE_ENV || 'development';
var transports = [];
/* Define colours for error level highlighting */
var colours = {
debug: 'yellow',
verbose: 'green',
info: 'cyan',
warn: 'magenta',
error: 'red'
};
winston.addColors(colours);
/* Create log directory if missing */
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
/* Output everything to screen */
transports.push(new (winston.transports.Console)({level: 'warn', colorize: true, 'timestamp': false}));
/* Write to daily log file, using less detail in production */
winston.add(require('winston-daily-rotate-file'), {
name: 'file',
json: false,
filename: path.join(logDir, pjson.name),
datePattern: '.yyyy-MM-dd.txt',
level: env === 'development' ? 'debug' : 'info'
});
var logger = new winston.Logger({transports: transports});
module.exports = logger;
|
JavaScript
| 0.000001
|
eaa33416d21edb5bbc26204ea751a441526ebb14
|
update to the correct WAB version
|
config/wabapp-config.js
|
config/wabapp-config.js
|
define({
'wabVersion': '2.4',
'theme': {
'name': 'cmv'
},
'isRTL': false,
'httpProxy': {
'useProxy': false,
'alwaysUseProxy': false,
'url': '',
'rules': [{
'urlPrefix': '',
'proxyUrl': ''
}]
},
'geometryService': 'https://utility.arcgisonline.com/arcgis/rest/services/Geometry/GeometryServer',
'map': {
'id': 'map',
'2D': true,
'3D': false,
'itemId': '8bf7167d20924cbf8e25e7b11c7c502c', // ESRI Streets Basemap
'portalUrl': 'https://www.arcgis.com/'
}
});
|
define({
'wabVersion': '2.2',
'theme': {
'name': 'cmv'
},
'isRTL': false,
'httpProxy': {
'useProxy': false,
'alwaysUseProxy': false,
'url': '',
'rules': [{
'urlPrefix': '',
'proxyUrl': ''
}]
},
'geometryService': 'https://utility.arcgisonline.com/arcgis/rest/services/Geometry/GeometryServer',
'map': {
'id': 'map',
'2D': true,
'3D': false,
'itemId': '8bf7167d20924cbf8e25e7b11c7c502c', // ESRI Streets Basemap
'portalUrl': 'https://www.arcgis.com/'
}
});
|
JavaScript
| 0
|
b60bd6709441fc75c14aa90669aefe4dc443d15a
|
Add getQuestionnaires functionality, Fix putQuestionnaire
|
src/bl.js
|
src/bl.js
|
'use strict'
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectID;
module.exports = (mongodbUrl) => {
async function getQuestionnaires() {
// TODO: Mongodb-kutsu
return new Promise(function(resolve, reject){
let findQuestionnaires = function(db, callback) {
let resultsArray = new Array();
let cursor = db.collection('questionnaires').find( );
cursor.each(function(err, doc) {
if (doc !== null) {
resultsArray.push(doc);
} else {
callback(resultsArray);
}
});
};
MongoClient.connect(mongodbUrl, function(err, db) {
findQuestionnaires(db, function(resultsArray) {
db.close();
resolve(JSON.stringify(resultsArray));
});
});
});
}
async function putQuestionnaire(payload) {
return new Promise(function(resolve, reject){
let insertQuestionnaire = function(db, callback) {
db.collection('questionnaires').insertOne(payload, function(err, result) {
console.log("Inserted a questionnaire into the questionnaires collection.");
callback();
});
};
MongoClient.connect(mongodbUrl, function(err, db) {
insertQuestionnaire(db, function() {
db.close();
let returnJson = new Object();
returnJson.uuid = payload.uuid;
returnJson.created = payload.created;
returnJson.modified = payload.modified;
resolve(JSON.stringify(returnJson));
});
});
});
}
return {
getQuestionnaires: getQuestionnaires,
putQuestionnaire: putQuestionnaire
};
}
|
'use strict'
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectID;
module.exports = (mongodbUrl) => {
async function getQuestionnaires() {
// TODO: Mongodb-kutsu
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve("Hello World");
}, 1000)
});
}
async function putQuestionnaire(payload) {
return new Promise(function(resolve, reject){
let insertQuestionnaire = function(db, callback) {
db.collection('questionnaires').insertOne(payload, function(err, result) {
console.log("Inserted a questionnaire into the questionnaires collection.");
callback();
});
};
MongoClient.connect(mongodbUrl, function(err, db) {
insertQuestionnaire(db, function() {
db.close();
});
});
let returnJson = new Object();
returnJson.uuid = payload.uuid;
returnJson.created = payload.created;
returnJson.modified = payload.modified;
resolve(JSON.stringify(returnJson));
});
}
return {
getQuestionnaires: getQuestionnaires,
putQuestionnaire: putQuestionnaire
};
}
|
JavaScript
| 0.000007
|
b1d13f5a9f6b4bbf806dc19b1035a03286ad7571
|
update b
|
src/sk.js
|
src/sk.js
|
(function (global, factory) {
if (typeof module === "object" && typeof module.exports === "object") {
// CMD
// all dependencies need to passed as parameters manually,
// will not require here.
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as sk
// TODO how to define the jquery plugin here?
define('sk', ['jsface', 'jquery'], factory);
} else {
// in browser, global is window.
// all dependencies were loaded already.
// bootstrap and jquery's plugin are all attached to jquery,
// expose $sk and all components to window.
factory(global, jsface, jQuery);
}
}(typeof window !== "undefined" ? window : this, function (window, jsface, jQuery, DO_NOT_EXPOSE_SK_TO_GLOBAL) {
var _sk = window.$sk;
var $sk = {};
window.$sk = $sk;
$sk.noConflict = function () {
window.$sk = _sk;
return $sk;
};
// insert all source code here
// sk body here
$sk.a = function (array) {
return jQuery.isArray(array) ? array : [];
};
//just true return true, other return false
$sk.b = function (boolean) {
return String(boolean) == "true" && boolean != "true" && boolean;
};
$sk.d = function (date, defaultDate) {
var rtnDate = defaultDate ? defaultDate : new Date();
return (date instanceof Date) ? (date.toString() == "Invalid Date" ? rtnDate : date) : rtnDate;
};
//can be to Number than return value of number, other return 0
$sk.n = function (number) {
return isNaN(Number(number)) ? 0 : Number(number);
};
$sk.inValid = function (obj) {
if (obj === undefined || obj == null || isNaN(obj) ) {
return false;
} else {
return true;
}
};
$sk.o = function (object) {
return jQuery.isPlainObject(object) ? object : {};
};
$sk.s = function (string) {
return String(string);
};
// reset to old $sk
if (typeof DO_NOT_EXPOSE_SK_TO_GLOBAL != 'undefined' && DO_NOT_EXPOSE_SK_TO_GLOBAL === true) {
window.$sk = _sk;
}
return $sk;
}));
|
(function (global, factory) {
if (typeof module === "object" && typeof module.exports === "object") {
// CMD
// all dependencies need to passed as parameters manually,
// will not require here.
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as sk
// TODO how to define the jquery plugin here?
define('sk', ['jsface', 'jquery'], factory);
} else {
// in browser, global is window.
// all dependencies were loaded already.
// bootstrap and jquery's plugin are all attached to jquery,
// expose $sk and all components to window.
factory(global, jsface, jQuery);
}
}(typeof window !== "undefined" ? window : this, function (window, jsface, jQuery, DO_NOT_EXPOSE_SK_TO_GLOBAL) {
var _sk = window.$sk;
var $sk = {};
window.$sk = $sk;
$sk.noConflict = function () {
window.$sk = _sk;
return $sk;
};
// insert all source code here
// sk body here
$sk.a = function (array) {
return jQuery.isArray(array) ? array : [];
};
//just true return true, other return false
$sk.b = function (boolean) {
return boolean && String(boolean) == "true" && boolean != "true";
};
$sk.d = function (date, defaultDate) {
var rtnDate = defaultDate ? defaultDate : new Date();
return (date instanceof Date) ? (date.toString() == "Invalid Date" ? rtnDate : date) : rtnDate;
};
//can be to Number than return value of number, other return 0
$sk.n = function (number) {
return isNaN(Number(number)) ? 0 : Number(number);
};
$sk.inValid = function (obj) {
if (obj === undefined || obj == null || isNaN(obj) ) {
return false;
} else {
return true;
}
};
$sk.o = function (object) {
return jQuery.isPlainObject(object) ? object : {};
};
$sk.s = function (string) {
return String(string);
};
// reset to old $sk
if (typeof DO_NOT_EXPOSE_SK_TO_GLOBAL != 'undefined' && DO_NOT_EXPOSE_SK_TO_GLOBAL === true) {
window.$sk = _sk;
}
return $sk;
}));
|
JavaScript
| 0
|
6b14f1b3b912f204876fa172483e85ac61c50da6
|
Bring back some AudioManager methods but deprecate them
|
src/sound/manager.js
|
src/sound/manager.js
|
pc.extend(pc, function () {
'use strict';
/**
* @private
* @function
* @name pc.SoundManager.hasAudio
* @description Reports whether this device supports the HTML5 Audio tag API
* @returns true if HTML5 Audio tag API is supported and false otherwise
*/
function hasAudio() {
return (typeof Audio !== 'undefined');
}
/**
* @private
* @function
* @name pc.SoundManager.hasAudioContext
* @description Reports whether this device supports the Web Audio API
* @returns true if Web Audio is supported and false otherwise
*/
function hasAudioContext() {
return !!(typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined');
}
/**
* @private
* @name pc.SoundManager
* @class The SoundManager is used to load and play audio. As well as apply system-wide settings
* like global volume, suspend and resume.
* @description Creates a new sound manager.
*/
var SoundManager = function () {
if (hasAudioContext()) {
if (typeof AudioContext !== 'undefined') {
this.context = new AudioContext();
} else if (typeof webkitAudioContext !== 'undefined') {
this.context = new webkitAudioContext();
}
}
this.listener = new pc.Listener(this);
this._volume = 1;
this.suspended = false;
pc.events.attach(this);
};
SoundManager.hasAudio = hasAudio;
SoundManager.hasAudioContext = hasAudioContext;
SoundManager.prototype = {
suspend: function () {
this.suspended = true;
this.fire('suspend');
},
resume: function () {
this.suspended = false;
this.fire('resume');
},
destroy: function () {
this.fire('destroy');
if (this.context && this.context.close) {
this.context.close();
this.context = null;
}
},
getListener: function () {
console.warn('DEPRECATED: getListener is deprecated. Get the "listener" field instead.');
return this.listener;
},
getVolume: function () {
console.warn('DEPRECATED: getVolume is deprecated. Get the "volume" property instead.');
return this.volume;
},
setVolume: function (volume) {
console.warn('DEPRECATED: setVolume is deprecated. Set the "volume" property instead.');
this.volume = volume;
},
};
Object.defineProperty(SoundManager.prototype, 'volume', {
get: function () {
return this._volume;
},
set: function (volume) {
volume = pc.math.clamp(volume, 0, 1);
this._volume = volume;
this.fire('volumechange', volume);
}
});
// backwards compatibility
pc.AudioManager = SoundManager;
return {
SoundManager: SoundManager
};
}());
|
pc.extend(pc, function () {
'use strict';
/**
* @private
* @function
* @name pc.SoundManager.hasAudio
* @description Reports whether this device supports the HTML5 Audio tag API
* @returns true if HTML5 Audio tag API is supported and false otherwise
*/
function hasAudio() {
return (typeof Audio !== 'undefined');
}
/**
* @private
* @function
* @name pc.SoundManager.hasAudioContext
* @description Reports whether this device supports the Web Audio API
* @returns true if Web Audio is supported and false otherwise
*/
function hasAudioContext() {
return !!(typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined');
}
/**
* @private
* @name pc.SoundManager
* @class The SoundManager is used to load and play audio. As well as apply system-wide settings
* like global volume, suspend and resume.
* @description Creates a new sound manager.
*/
var SoundManager = function () {
if (hasAudioContext()) {
if (typeof AudioContext !== 'undefined') {
this.context = new AudioContext();
} else if (typeof webkitAudioContext !== 'undefined') {
this.context = new webkitAudioContext();
}
}
this.listener = new pc.Listener(this);
this._volume = 1;
this.suspended = false;
pc.events.attach(this);
};
SoundManager.hasAudio = hasAudio;
SoundManager.hasAudioContext = hasAudioContext;
SoundManager.prototype = {
suspend: function () {
this.suspended = true;
this.fire('suspend');
},
resume: function () {
this.suspended = false;
this.fire('resume');
},
destroy: function () {
this.fire('destroy');
if (this.context && this.context.close) {
this.context.close();
this.context = null;
}
}
};
Object.defineProperty(SoundManager.prototype, 'volume', {
get: function () {
return this._volume;
},
set: function (volume) {
volume = pc.math.clamp(volume, 0, 1);
this._volume = volume;
this.fire('volumechange', volume);
}
});
// backwards compatibility
pc.AudioManager = SoundManager;
return {
SoundManager: SoundManager
};
}());
|
JavaScript
| 0.000204
|
dd65459ef6de6d3ff2351cee3a0fac30a8c8e60b
|
Fix colour picker inputs' design (#7384)
|
assets/src/edit-story/components/colorPicker/editablePreview.js
|
assets/src/edit-story/components/colorPicker/editablePreview.js
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { EditableInput } from 'react-color/lib/components/common';
import { useCallback, useMemo, useRef, useLayoutEffect, useState } from 'react';
/**
* Internal dependencies
*/
import {
Text,
THEME_CONSTANTS,
useKeyDownEffect,
themeHelpers,
} from '../../../design-system';
const Preview = styled.button`
margin: 0;
padding: 0;
border: 1px solid ${({ theme }) => theme.colors.border.defaultNormal};
border-radius: 2px;
background: transparent;
color: ${({ theme }) => theme.colors.fg.primary};
width: 100%;
padding: 7px;
${({ theme }) =>
themeHelpers.focusableOutlineCSS(
theme.colors.border.focus,
theme.colors.bg.secondary
)};
`;
const Wrapper = styled.div`
input {
${({ theme }) =>
themeHelpers.focusableOutlineCSS(
theme.colors.border.focus,
theme.colors.bg.secondary
)};
}
`;
function EditablePreview({ label, value, width, format, onChange }) {
const [isEditing, setIsEditing] = useState(false);
const enableEditing = useCallback(() => setIsEditing(true), []);
const disableEditing = useCallback(() => setIsEditing(false), []);
const wrapperRef = useRef(null);
const editableRef = useRef();
const inputStyles = useMemo(
() => ({
input: {
textAlign: 'center',
textTransform: 'lowercase',
width: '100%',
padding: '8px 12px',
border: '1px solid #5E6668',
color: '#E4E5E6',
borderRadius: '2px',
background: 'transparent',
lineHeight: '18px',
},
wrap: {
lineHeight: 0,
maxWidth: `${width}px`,
},
}),
[width]
);
// Handle ESC keypress to toggle input field.
//eslint-disable-next-line react-hooks/exhaustive-deps
useKeyDownEffect(wrapperRef, { key: 'esc', editable: true }, disableEditing, [
isEditing,
]);
const handleOnBlur = (evt) => {
// Ignore reason: There's no practical way to simulate the else occuring
// istanbul ignore else
if (!evt.currentTarget.contains(evt.relatedTarget)) {
disableEditing();
}
};
useLayoutEffect(() => {
if (isEditing && editableRef.current) {
editableRef.current.input.focus();
editableRef.current.input.select();
editableRef.current.input.setAttribute('aria-label', label);
}
}, [isEditing, label]);
if (!isEditing) {
return (
<Preview
aria-label={label}
onClick={enableEditing}
onFocus={enableEditing}
>
<Text size={THEME_CONSTANTS.TYPOGRAPHY.PRESET_SIZES.SMALL}>
{format(value)}
</Text>
</Preview>
);
}
return (
<Wrapper ref={wrapperRef} tabIndex={-1} onBlur={handleOnBlur}>
<EditableInput
value={value}
ref={editableRef}
onChange={onChange}
onChangeComplete={disableEditing}
style={inputStyles}
/>
</Wrapper>
);
}
EditablePreview.propTypes = {
label: PropTypes.string,
value: PropTypes.string,
width: PropTypes.number.isRequired,
onChange: PropTypes.func.isRequired,
format: PropTypes.func.isRequired,
};
EditablePreview.defaultProps = {
label: '',
value: '',
};
export default EditablePreview;
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { EditableInput } from 'react-color/lib/components/common';
import { useCallback, useMemo, useRef, useLayoutEffect, useState } from 'react';
/**
* Internal dependencies
*/
import {
Text,
THEME_CONSTANTS,
useKeyDownEffect,
} from '../../../design-system';
const Preview = styled.button`
margin: 0;
padding: 0;
border: 1px solid ${({ theme }) => theme.colors.border.defaultNormal};
border-radius: 2px;
background: transparent;
color: ${({ theme }) => theme.colors.fg.primary};
width: 100%;
`;
function EditablePreview({ label, value, width, format, onChange }) {
const [isEditing, setIsEditing] = useState(false);
const enableEditing = useCallback(() => setIsEditing(true), []);
const disableEditing = useCallback(() => setIsEditing(false), []);
const wrapperRef = useRef(null);
const editableRef = useRef();
const inputStyles = useMemo(
() => ({
input: {
textAlign: 'center',
textTransform: 'lowercase',
width: '100%',
padding: '8px 12px',
border: '1px solid #5E6668',
color: '#E4E5E6',
borderRadius: '2px',
background: 'transparent',
lineHeight: '18px',
},
wrap: {
lineHeight: 0,
maxWidth: `${width}px`,
},
}),
[width]
);
// Handle ESC keypress to toggle input field.
//eslint-disable-next-line react-hooks/exhaustive-deps
useKeyDownEffect(wrapperRef, { key: 'esc', editable: true }, disableEditing, [
isEditing,
]);
const handleOnBlur = (evt) => {
// Ignore reason: There's no practical way to simulate the else occuring
// istanbul ignore else
if (!evt.currentTarget.contains(evt.relatedTarget)) {
disableEditing();
}
};
useLayoutEffect(() => {
if (isEditing && editableRef.current) {
editableRef.current.input.focus();
editableRef.current.input.select();
editableRef.current.input.setAttribute('aria-label', label);
}
}, [isEditing, label]);
if (!isEditing) {
return (
<Preview aria-label={label} onClick={enableEditing}>
<Text size={THEME_CONSTANTS.TYPOGRAPHY.PRESET_SIZES.SMALL}>
{format(value)}
</Text>
</Preview>
);
}
return (
<div ref={wrapperRef} tabIndex={-1} onBlur={handleOnBlur}>
<EditableInput
value={value}
ref={editableRef}
onChange={onChange}
onChangeComplete={disableEditing}
style={inputStyles}
/>
</div>
);
}
EditablePreview.propTypes = {
label: PropTypes.string,
value: PropTypes.string,
width: PropTypes.number.isRequired,
onChange: PropTypes.func.isRequired,
format: PropTypes.func.isRequired,
};
EditablePreview.defaultProps = {
label: '',
value: '',
};
export default EditablePreview;
|
JavaScript
| 0
|
7a9a6f2f5a2b1e1e9dac51b09cd59e533e379222
|
Fix formatting errors.
|
public/angular/js/app.js
|
public/angular/js/app.js
|
require('./angular', { expose: 'angular' });
require('./angular-ui-router');
require('./ui-bootstrap');
require('./ui-bootstrap-templates');
require('./angular-resource');
angular.module('Aggie', ['ui.router', 'ui.bootstrap', 'ngResource'])
.config(['$urlRouterProvider', '$locationProvider',
function($urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
}
])
.run(['$rootScope', '$location', 'AuthService', function ($rootScope, $location, AuthService) {
$rootScope.$watch('currentUser', function(currentUser) {
if (!currentUser) { AuthService.getCurrentUser() }
});
var needsAuth = function () {
return [].indexOf($location.path()) != -1;
};
$rootScope.$on('$stateChangeStart', function (event, next, current) {
if (needsAuth() && !$rootScope.currentUser) {
$location.path('/login');
}
});
}]);
// Services
require('./services/auth');
require('./services/factories');
require('./services/flash');
// Controllers
require('./controllers/application');
require('./controllers/login');
require('./controllers/navbar');
require('./controllers/password_reset');
require('./controllers/password_reset_modal');
require('./controllers/report');
require('./controllers/show_report');
// Routes
require('./routes');
// Filters
require('./filters/report');
// Directives
require('./directives/aggie-table');
|
require('./angular', { expose: 'angular' });
require('./angular-ui-router');
require('./ui-bootstrap');
require('./ui-bootstrap-templates');
require('./angular-resource');
angular.module('Aggie', ['ui.router', 'ui.bootstrap', 'ngResource'])
.config(['$urlRouterProvider', '$locationProvider',
function($urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise('/');
}
])
.run(['$rootScope', '$location', 'AuthService', function ($rootScope, $location, AuthService) {
$rootScope.$watch('currentUser', function(currentUser) {
if (!currentUser) { AuthService.getCurrentUser() }
});
var needsAuth = function () {
return [].indexOf($location.path()) != -1;
};
$rootScope.$on('$stateChangeStart', function (event, next, current) {
if (needsAuth() && !$rootScope.currentUser) {
$location.path('/login');
}
});
}]);
// Services
require('./services/auth');
require('./services/factories');
require('./services/flash');
//Controllers
require('./controllers/application');
require('./controllers/login');
require('./controllers/navbar');
require('./controllers/password_reset');
require('./controllers/password_reset_modal');
require('./controllers/report');
require('./controllers/show_report');
// Routes
require('./routes');
// Filters
require('./filters/report');
// Directives
require('./directives/aggie-table');
|
JavaScript
| 0.000013
|
342e75ffe939deb48350f37b533479d38622ce46
|
enhance the regex entension (a bit)
|
js/jquery.inputmask.regex.extensions.js
|
js/jquery.inputmask.regex.extensions.js
|
/*
Input Mask plugin extensions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 - 2013 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.0
Regex extensions on the jquery.inputmask base
Allows for using regular expressions as a mask
*/
(function ($) {
$.extend($.inputmask.defaults.aliases, { // $(selector).inputmask("Regex", { regex: "[0-9]*"}
'Regex': {
mask: "r",
greedy: false,
repeat: 10, //needs to be computed
regex: null,
regexSplit: null,
definitions: {
'r': {
validator: function (chrs, buffer, pos, strict, opts) {
function analyseRegex() { //ENHANCE ME
var regexSplitRegex = "\\[.*?\]\\*";
opts.regexSplit = opts.regex.match(new RegExp(regexSplitRegex, "g"));
//if (opts.regex.indexOf("*") != (opts.regex.length - 1)) {
// opts.regex += "{1}";
//}
//opts.regexSplit.push(opts.regex);
}
if (opts.regexSplit == null) {
analyseRegex();
}
var cbuffer = buffer.slice(), regexPart = "", isValid = false;
cbuffer.splice(pos, 0, chrs);
var bufferStr = cbuffer.join('');
for (var i = 0; i < opts.regexSplit.length; i++) {
regexPart += opts.regexSplit[i];
var exp = new RegExp("^" + regexPart + "$");
isValid = exp.test(bufferStr);
console.log(bufferStr + ' ' + isValid + ' ' + regexPart);
if (isValid) break;
}
return isValid;
},
cardinality: 1
}
}
}
});
})(jQuery);
|
/*
Input Mask plugin extensions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 - 2013 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.0
Regex extensions on the jquery.inputmask base
Allows for using regular expressions as a mask
*/
(function ($) {
$.extend($.inputmask.defaults.aliases, { // $(selector).inputmask("Regex", { regex: "[0-9]*"}
'Regex': {
mask: "r",
greedy: false,
repeat: 10, //needs to be computed
regex: null,
regexSplit: null,
definitions: {
'r': {
validator: function (chrs, buffer, pos, strict, opts) {
function analyseRegex() { //ENHANCE ME
opts.regexSplit = [];
if (opts.regex.indexOf("*") != (opts.regex.length - 1)) {
opts.regex += "{1}";
}
opts.regexSplit.push(opts.regex);
}
if (opts.regexSplit == null) {
analyseRegex();
}
var cbuffer = buffer.slice(), regexPart = "", isValid = false;
cbuffer.splice(pos, 0, chrs);
var bufferStr = cbuffer.join('');
for (var i = 0; i < opts.regexSplit.length; i++) {
regexPart += opts.regexSplit[i];
var exp = new RegExp("^" + regexPart + "$");
isValid = exp.test(bufferStr);
console.log(bufferStr + ' ' + isValid);
if (isValid) break;
}
return isValid;
},
cardinality: 1
}
}
}
});
})(jQuery);
|
JavaScript
| 0.000001
|
70a16cf788011386a10affcf47ecb133c2072fab
|
Reset now clone the initialState instead of linking items to the initialState
|
src/storage/store.js
|
src/storage/store.js
|
// @flow
import clone from 'clone';
import type { StorableType } from './storable';
import storableFactory from './storable';
export type StoreType = {
name: string,
reset: () => StoreType,
addStorable: (item: StorableType) => StoreType,
add: (item: Object) => StoreType,
remove: (id: number) => StoreType,
update: (id: number, next: StorableType) => StoreType,
get: (id: number) => ?StorableType,
all: () => Array<StorableType>,
createStorable: (object: Object) => StorableType
};
const cloneArrayOfStorable = (state: Array<StorableType>) : Array<StorableType> => {
return state.map((storable: StorableType) => storable.clone());
};
const createStore = (name: string, initialState: Array<StorableType> = []):StoreType => {
let items: Array<StorableType> = cloneArrayOfStorable(initialState);
let storeInitialState: Array<StorableType> = cloneArrayOfStorable(initialState);
const store: StoreType = {
/**
* @var string
*/
name: name,
/**
* Restore the initial state of the store
* @returns {StoreType}
*/
reset: () => {
items = cloneArrayOfStorable(storeInitialState);
return store;
},
/**
* Add a storable to the store
* @param entity
* @returns {StoreType}
*/
addStorable: (entity: StorableType): StoreType => {
items = [
...items,
entity
];
return store;
},
/**
* Convert an object into a storable and add it to the store
* @param entity
* @returns {StoreType}
*/
add: (entity: Object): StoreType => {
items = [
...items,
storableFactory.createStorable(entity)
];
return store;
},
/**
* Remove the storable from the store
* @param id
* @returns {StoreType}
*/
remove: (id: number): StoreType => {
items = items.filter((entity: StorableType) => entity.getData().id !== id);
return store;
},
/**
* Update the storable with a new storable
* @param id
* @param next
* @returns {StoreType}
*/
update: (id: number, next: StorableType):StoreType => {
items = items.map((storable: StorableType) => {
if(storable.getData().id !== id){
return storable;
}
return next;
});
return store;
},
/**
* Return the storable having the given ID
* @param id
* @returns {StorableType}
*/
get: (id: number): ?StorableType => {
return items.find((entity: StorableType):boolean => entity.getData().id === id);
},
/**
* Return the store
* @returns {Array<StorableType>}
*/
all: (): Array<StorableType> => items,
/**
* Create a storable
* @returns {StorableType}
*/
createStorable: storableFactory.createStorable,
};
return store;
};
export default {
createStore,
createStorable: storableFactory.createStorable
}
|
// @flow
import clone from 'clone';
import type { StorableType } from './storable';
import storableFactory from './storable';
export type StoreType = {
name: string,
reset: () => StoreType,
addStorable: (item: StorableType) => StoreType,
add: (item: Object) => StoreType,
remove: (id: number) => StoreType,
update: (id: number, next: StorableType) => StoreType,
get: (id: number) => ?StorableType,
all: () => Array<StorableType>,
createStorable: (object: Object) => StorableType
};
const cloneArrayOfStorable = (state: Array<StorableType>) : Array<StorableType> => {
return state.map((storable: StorableType) => storable.clone());
};
const createStore = (name: string, initialState: Array<StorableType> = []):StoreType => {
let items: Array<StorableType> = cloneArrayOfStorable(initialState);
let storeInitialState: Array<StorableType> = cloneArrayOfStorable(initialState);
const store: StoreType = {
/**
* @var string
*/
name: name,
/**
* Restore the initial state of the store
* @returns {StoreType}
*/
reset: () => {
items = Array.from(storeInitialState);
return store;
},
/**
* Add a storable to the store
* @param entity
* @returns {StoreType}
*/
addStorable: (entity: StorableType): StoreType => {
items = [
...items,
entity
];
return store;
},
/**
* Convert an object into a storable and add it to the store
* @param entity
* @returns {StoreType}
*/
add: (entity: Object): StoreType => {
items = [
...items,
storableFactory.createStorable(entity)
];
return store;
},
/**
* Remove the storable from the store
* @param id
* @returns {StoreType}
*/
remove: (id: number): StoreType => {
items = items.filter((entity: StorableType) => entity.getData().id !== id);
return store;
},
/**
* Update the storable with a new storable
* @param id
* @param next
* @returns {StoreType}
*/
update: (id: number, next: StorableType):StoreType => {
items = items.map((storable: StorableType) => {
if(storable.getData().id !== id){
return storable;
}
return next;
});
return store;
},
/**
* Return the storable having the given ID
* @param id
* @returns {StorableType}
*/
get: (id: number): ?StorableType => {
return items.find((entity: StorableType):boolean => entity.getData().id === id);
},
/**
* Return the store
* @returns {Array<StorableType>}
*/
all: (): Array<StorableType> => items,
/**
* Create a storable
* @returns {StorableType}
*/
createStorable: storableFactory.createStorable,
};
return store;
};
export default {
createStore,
createStorable: storableFactory.createStorable
}
|
JavaScript
| 0
|
a21187728b8298849aee644764d271c79821409d
|
use plugins instead of `renderFile` in write task
|
generator.js
|
generator.js
|
'use strict';
var fs = require('fs');
var path = require('path');
var argv = require('minimist')(process.argv.slice(2));
var utils = require('./lib/utils');
/**
* This is an example generator, but it can also be used
* to extend other generators.
*/
module.exports = function(generate, base, env) {
var dest = argv.dest || process.cwd();
var async = utils.async;
var glob = utils.glob;
/**
* TODO: User help and defaults
*/
generate.register('defaults', function(app) {
app.task('init', function(cb) {
app.build(['prompt', 'templates'], cb);
});
app.task('help', function(cb) {
console.log('Would you like to choose a generator to run?');
console.log('(implement me!)')
cb();
});
app.task('error', function(cb) {
console.log('generate > error (implement me!)');
cb();
});
});
/**
* Readme task
*/
generate.task('readme', function(cb) {
console.log('generate > readme');
cb();
});
/**
* Data store tasks
*/
generate.register('store', function(app) {
app.task('del', function(cb) {
generate.store.del({ force: true });
console.log('deleted data store');
cb();
});
});
/**
* Default configuration settings
*/
generate.task('defaultConfig', function(cb) {
generate.engine(['md', 'text'], require('engine-base'));
generate.data({year: new Date().getFullYear()});
cb();
});
/**
* User prompts
*/
generate.task('prompt', function(cb) {
var opts = { save: false, force: true };
var pkg = env.user.pkg;
if (!pkg || env.user.isEmpty || env.argv.raw.init) {
pkg = { name: utils.project(process.cwd()) };
forceQuestions(generate);
}
generate.questions.setData(pkg);
generate.ask(opts, function(err, answers) {
if (err) return cb(err);
if (!pkg) answers = {};
answers.varname = utils.namify(answers.name);
generate.set('answers', answers);
cb();
});
});
/**
* Load templates to be rendered
*/
generate.task('templates', ['defaultConfig'], function(cb) {
var opts = { cwd: env.config.cwd, dot: true };
glob('templates/*', opts, function(err, files) {
if (err) return cb(err);
async.each(files, function(name, next) {
var fp = path.join(opts.cwd, name);
var contents = fs.readFileSync(fp);
generate.template(name, {contents: contents, path: fp});
next();
}, cb);
});
});
generate.plugin('render', function() {
var data = generate.get('answers');
return generate.renderFile('text', data);
});
/**
* Write files to disk
*/
generate.task('write', function() {
return generate.toStream('templates')
.on('error', console.log)
.pipe(generate.pipeline())
.on('error', console.log)
.pipe(generate.dest(rename(dest)));
});
/**
* Generate a new project
*/
generate.task('project', ['prompt', 'templates', 'write']);
/**
* Default task to be run
*/
generate.task('default', function(cb) {
generate.build('defaults:help', cb);
});
};
function forceQuestions(generate) {
generate.questions.options.forceAll = true;
}
/**
* Rename template files
*/
function rename(dest) {
return function(file) {
file.base = file.dest || dest || '';
file.path = path.join(file.base, file.basename);
file.basename = file.basename.replace(/^_/, '.');
file.basename = file.basename.replace(/^\$/, '');
return file.base;
};
}
|
'use strict';
var fs = require('fs');
var path = require('path');
var argv = require('minimist')(process.argv.slice(2));
var utils = require('./lib/utils');
/**
* This is an example generator, but it can also be used
* to extend other generators.
*/
module.exports = function(generate, base, env) {
var dest = argv.dest || process.cwd();
var async = utils.async;
var glob = utils.glob;
/**
* TODO: User help and defaults
*/
generate.register('defaults', function(app) {
app.task('init', function(cb) {
app.build(['prompt', 'templates'], cb);
});
app.task('help', function(cb) {
console.log('Would you like to choose a generator to run?');
console.log('(implement me!)')
cb();
});
app.task('error', function(cb) {
console.log('generate > error (implement me!)');
cb();
});
});
/**
* Readme task
*/
generate.task('readme', function(cb) {
console.log('generate > readme');
cb();
});
/**
* Data store tasks
*/
generate.register('store', function(app) {
app.task('del', function(cb) {
generate.store.del({ force: true });
console.log('deleted data store');
cb();
});
});
/**
* Default configuration settings
*/
generate.task('defaultConfig', function(cb) {
if (!generate.templates) {
generate.create('templates');
}
generate.engine(['md', 'text'], require('engine-base'));
generate.data({year: new Date().getFullYear()});
cb();
});
/**
* User prompts
*/
generate.task('prompt', function(cb) {
var opts = { save: false, force: true };
var pkg = env.user.pkg;
if (!pkg || env.user.isEmpty || env.argv.raw.init) {
pkg = { name: utils.project(process.cwd()) };
forceQuestions(generate);
}
generate.questions.setData(pkg || {});
generate.ask(opts, function(err, answers) {
if (err) return cb(err);
if (!pkg) answers = {};
answers.name = answers.name || utils.project();
answers.varname = utils.namify(answers.name);
generate.set('answers', answers);
cb();
});
});
/**
* Load templates to be rendered
*/
generate.task('templates', ['defaultConfig'], function(cb) {
var opts = { cwd: env.config.cwd, dot: true };
glob('templates/*', opts, function(err, files) {
if (err) return cb(err);
async.each(files, function(name, next) {
var fp = path.join(opts.cwd, name);
var contents = fs.readFileSync(fp);
generate.template(name, {contents: contents, path: fp});
next();
}, cb);
});
});
/**
* Write files to disk
*/
generate.task('write', function() {
var data = generate.get('answers');
return generate.toStream('templates')
.pipe(generate.renderFile('text', data))
.pipe(generate.dest(rename(dest)));
});
/**
* Generate a new project
*/
generate.task('project', ['prompt', 'templates', 'write']);
/**
* Default task to be run
*/
generate.task('default', function(cb) {
generate.build('defaults:help', cb);
});
};
function forceQuestions(generate) {
generate.questions.options.forceAll = true;
}
/**
* Rename template files
*/
function rename(dest) {
return function(file) {
file.base = file.dest || dest || '';
file.path = path.join(file.base, file.basename);
file.basename = file.basename.replace(/^_/, '.');
file.basename = file.basename.replace(/^\$/, '');
return file.base;
};
}
|
JavaScript
| 0.000001
|
cf864ca3ce92a971e98e758e90877f999bd9d0d4
|
Reduce highWaterMark
|
src/stream/JlTransform.js
|
src/stream/JlTransform.js
|
const Transform = require('stream').Transform;
class JlTransform extends Transform
{
constructor(inputType, outputType)
{
super({
objectMode: true,
highWaterMark: 1
});
this.inputType = inputType;
this.outputType = outputType;
}
}
JlTransform.RAW = 'JlTransform.RAW';
JlTransform.ANY = 'JlTransform.ANY';
JlTransform.OBJECTS = 'JlTransform.OBJECTS';
JlTransform.ARRAYS_OF_OBJECTS = 'JlTransform.ARRAYS_OF_OBJECTS';
module.exports = JlTransform;
|
const Transform = require('stream').Transform;
class JlTransform extends Transform
{
constructor(inputType, outputType)
{
super({
objectMode: true
});
this.inputType = inputType;
this.outputType = outputType;
}
}
JlTransform.RAW = 'JlTransform.RAW';
JlTransform.ANY = 'JlTransform.ANY';
JlTransform.OBJECTS = 'JlTransform.OBJECTS';
JlTransform.ARRAYS_OF_OBJECTS = 'JlTransform.ARRAYS_OF_OBJECTS';
module.exports = JlTransform;
|
JavaScript
| 0.99775
|
d8ebde24db4d6e7dccf3d1f87a9d0ea128d8b60f
|
Fix 2 spaces -> 4 spaces
|
karma.conf.js
|
karma.conf.js
|
// Karma configuration
var istanbul = require('browserify-istanbul');
'use strict';
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['browserify', 'mocha', 'chai', 'sinon'],
// list of files / patterns to load in the browser
files: [
'./libs/angular/angular.js',
'./libs/angular-mocks/angular-mocks.js', // for angular.mock.module and inject.
'./app/**/*.js'
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'./app/**/!(*spec)*.js': ['browserify']
},
// karma-browserify configuration
browserify: {
debug: true,
transform: ['debowerify', 'html2js-browserify', istanbul({
'ignore': ['**/*.spec.js', '**/libs/**']
})],
// don't forget to register the extensions
extensions: ['.js']
},
// test results reporter to use
// possible values: 'dots', 'progress', 'spec'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['spec', 'coverage'],
coverageReporter: {
type: 'html',
dir: './reports/coverage'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [
// 'Chrome',
'PhantomJS'
],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
// Karma configuration
var istanbul = require('browserify-istanbul');
'use strict';
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['browserify', 'mocha', 'chai', 'sinon'],
// list of files / patterns to load in the browser
files: [
'./libs/angular/angular.js',
'./libs/angular-mocks/angular-mocks.js', // for angular.mock.module and inject.
'./app/**/*.js'
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'./app/**/!(*spec)*.js': ['browserify']
},
// karma-browserify configuration
browserify: {
debug: true,
transform: ['debowerify', 'html2js-browserify', istanbul({
'ignore': ['**/*.spec.js', '**/libs/**']
})],
// don't forget to register the extensions
extensions: ['.js']
},
// test results reporter to use
// possible values: 'dots', 'progress', 'spec'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['spec', 'coverage'],
coverageReporter: {
type: 'html',
dir: './reports/coverage'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [
// 'Chrome',
'PhantomJS'
],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
JavaScript
| 0.999997
|
2593ce5d53bd1b5765cf4ffe5edb44e837f809de
|
fix recursion
|
getTables.js
|
getTables.js
|
module.exports = getTables;
function getTables(dynamodb, tables, params, pageSize, cb) {
params.Limit = pageSize;
dynamodb.listTables(params, function (err, data) {
if (err) {
cb(err)
} else if (data.LastEvaluatedTableName) {
params.ExclusiveStartTableName = data.LastEvaluatedTableName;
tables = tables.concat(data.TableNames);
getTables(dynamodb, tables, params, pageSize, cb);
} else {
tables = tables.concat(data.TableNames);
cb(null, tables);
}
});
}
|
module.exports = function(dynamodb, tables, params, pageSize, cb){
params.Limit = pageSize;
dynamodb.listTables(params, function(err, data) {
if (err) {
cb(err)
} else if (data.LastEvaluatedTableName){
params.ExclusiveStartTableName = data.LastEvaluatedTableName;
tables = tables.concat( data.TableNames );
getTables(dynamodb, tables, params, pageSize, cb);
}else {
tables = tables.concat( data.TableNames );
cb( null, tables );
}
});
}
|
JavaScript
| 0.00013
|
ff168bf7d0aae48913028422b86f77cf75ef1c89
|
Update dynamic_form_utils.js
|
autofill/dynamic_form_utils.js
|
autofill/dynamic_form_utils.js
|
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
function DynamicallyChangeForm() {
RemoveForm('form1');
var new_form = AddNewFormAndFields();
document.getElementsByTagName('body')[0].appendChild(new_form);
}
//* Removes the initial form. */
function RemoveForm(form_id) {
var initial_form = document.getElementById(form_id);
initial_form.parentNode.removeChild(initial_form);
initial_form.innerHTML = '';
initial_form.remove();
}
/** Adds a new form and fields for the dynamic form. */
function AddNewFormAndFields() {
var new_form = document.createElement('form');
new_form.setAttribute('method', 'post');
new_form.setAttribute('action', 'https://example.com/')
new_form.setAttribute('name', 'addr1.1');
new_form.setAttribute('id', 'form1');
var i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'firstname');
i.setAttribute('id', 'firstname');
i.setAttribute('autocomplete', 'given-name');
new_form.appendChild(i);
i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'address1');
i.setAttribute('id', 'address1');
i.setAttribute('autocomplete', 'address-line1');
new_form.appendChild(i);
i = document.createElement('select');
i.setAttribute('name', 'state');
i.setAttribute('id', 'state');
i.setAttribute('autocomplete', 'region');
i.options[0] = new Option('CA', 'CA');
i.options[1] = new Option('MA', 'MA');
i.options[2] = new Option('TX', 'TX');
i.options[3] = new Option('DC', 'DC');
new_form.appendChild(i);
i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'city');
i.setAttribute('id', 'city');
i.setAttribute('autocomplete', 'locality');
new_form.appendChild(i);
i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'zip');
i.setAttribute('id', 'zip');
i.setAttribute('autocomplete', 'postal-code');
new_form.appendChild(i);
i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'company');
i.setAttribute('id', 'company');
i.setAttribute('autocomplete', 'organization');
new_form.appendChild(i);
i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'email');
i.setAttribute('id', 'email');
i.setAttribute('autocomplete', 'email');
new_form.appendChild(i);
i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'phone');
i.setAttribute('id', 'phone');
i.setAttribute('autocomplete', 'tel');
new_form.appendChild(i);
return new_form;
}
|
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
function DynamicallyChangeForm() {
RemoveForm('form1');
var new_form = AddNewFormAndFields();
document.getElementsByTagName('body')[0].appendChild(new_form);
}
//* Removes the initial form. */
function RemoveForm(form_id) {
var initial_form = document.getElementById(form_id);
initial_form.parentNode.removeChild(initial_form);
initial_form.innerHTML = '';
initial_form.remove();
}
/** Adds a new form and fields for the dynamic form. */
function AddNewFormAndFields() {
var new_form = document.createElement('form');
new_form.setAttribute('method', 'post');
new_form.setAttribute('action', 'https://example.com/')
new_form.setAttribute('name', 'addr1.1');
new_form.setAttribute('id', 'form1');
var i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'firstname');
i.setAttribute('id', 'firstname');
i.setAttribute('autocomplete', 'given-name');
new_form.appendChild(i);
i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'address1');
i.setAttribute('id', 'address1');
i.setAttribute('autocomplete', 'address-line1');
new_form.appendChild(i);
i = document.createElement('select');
i.setAttribute('name', 'state');
i.setAttribute('id', 'state');
i.setAttribute('autocomplete', 'region');
i.options[0] = new Option('CA', 'CA');
i.options[1] = new Option('MA', 'MA');
i.options[2] = new Option('TX', 'TX');
i.options[3] = new Option('DC', 'DC');
new_form.appendChild(i);
i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'city');
i.setAttribute('id', 'city');
i.setAttribute('autocomplete', 'locality');
new_form.appendChild(i);
i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'company');
i.setAttribute('id', 'company');
i.setAttribute('autocomplete', 'organization');
new_form.appendChild(i);
i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'email');
i.setAttribute('id', 'email');
i.setAttribute('autocomplete', 'email');
new_form.appendChild(i);
i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'phone');
i.setAttribute('id', 'phone');
i.setAttribute('autocomplete', 'tel');
new_form.appendChild(i);
return new_form;
}
|
JavaScript
| 0.000002
|
81893cd1f3d41bedc9b65241d189c5151c100ad7
|
remove unnecessary release npm scripts (#141)
|
src/tasks/package.js
|
src/tasks/package.js
|
/* eslint-disable no-template-curly-in-string */
const path = require('path');
const meta = require('user-meta');
const gitUsername = require('git-username');
const { json, install } = require('mrm-core');
const packages = ['schema-utils', 'loader-utils'];
const devPackages = [
// Utilities
'del',
'del-cli',
'cross-env',
'memory-fs',
'standard-version',
'@commitlint/cli',
'@commitlint/config-conventional',
'conventional-github-releaser',
'husky',
// Jest
'jest',
'babel-jest',
// Babel
'babel-cli',
'babel-polyfill',
'babel-preset-env',
'babel-plugin-transform-object-rest-spread',
// ESLint
'eslint',
'eslint-plugin-import',
'eslint-plugin-prettier',
'@webpack-contrib/eslint-config-webpack',
'lint-staged',
'pre-commit',
'prettier',
// Webpack
'webpack',
];
module.exports = (config) => {
const { name } = meta;
const github = gitUsername();
const packageName = path.basename(process.cwd());
const repository = `${github}/${packageName}`;
const file = json('package.json');
const existing = file.get();
json('package.json')
.set({
name: `${packageName}`,
version: existing.version || '1.0.0',
description: existing.description || '',
license: existing.license || 'MIT',
repository: `${repository}`,
author: existing.author || `${name}`,
homepage: `https://github.com/${repository}`,
bugs: `https://github.com/${repository}/issues`,
bin: existing.bin || '',
main: existing.main || 'dist/cjs.js',
engines: {
node: `>= ${config.maintLTS} <7.0.0 || >= ${config.activeLTS}`,
},
scripts: {
start: 'npm run build -- -w',
build:
"cross-env NODE_ENV=production babel src -d dist --ignore 'src/**/*.test.js' --copy-files",
clean: 'del-cli dist',
commitlint: 'commitlint',
commitmsg: 'commitlint -e $GIT_PARAMS',
lint: 'eslint --cache src test',
'ci:lint:commits':
'commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}',
'lint-staged': 'lint-staged',
prebuild: 'npm run clean',
prepublish: 'npm run build',
release: 'standard-version',
security: 'npm audit',
test: 'jest',
'test:watch': 'jest --watch',
'test:coverage': "jest --collectCoverageFrom='src/**/*.js' --coverage",
'ci:lint': 'npm run lint && npm run security',
'ci:test': 'npm run test -- --runInBand',
'ci:coverage': 'npm run test:coverage -- --runInBand',
defaults: 'webpack-defaults',
},
files: existing.files || ['dist/', 'lib/', 'index.js'],
peerDependencies: existing.peerDependencies || { webpack: '^4.3.0' },
dependencies: existing.dependencies || {},
devDependencies: existing.devDependencies || {},
keywords: existing.keywords || ['webpack'],
jest: { testEnvironment: 'node' },
'pre-commit': 'lint-staged',
'lint-staged': {
'*.js': ['eslint --fix', 'git add'],
},
})
.save();
install(packages, { dev: false });
install(devPackages);
};
|
/* eslint-disable no-template-curly-in-string */
const path = require('path');
const meta = require('user-meta');
const gitUsername = require('git-username');
const { json, install } = require('mrm-core');
const packages = ['schema-utils', 'loader-utils'];
const devPackages = [
// Utilities
'del',
'del-cli',
'cross-env',
'memory-fs',
'standard-version',
'@commitlint/cli',
'@commitlint/config-conventional',
'conventional-github-releaser',
'husky',
// Jest
'jest',
'babel-jest',
// Babel
'babel-cli',
'babel-polyfill',
'babel-preset-env',
'babel-plugin-transform-object-rest-spread',
// ESLint
'eslint',
'eslint-plugin-import',
'eslint-plugin-prettier',
'@webpack-contrib/eslint-config-webpack',
'lint-staged',
'pre-commit',
'prettier',
// Webpack
'webpack',
];
module.exports = (config) => {
const { name } = meta;
const github = gitUsername();
const packageName = path.basename(process.cwd());
const repository = `${github}/${packageName}`;
const file = json('package.json');
const existing = file.get();
json('package.json')
.set({
name: `${packageName}`,
version: existing.version || '1.0.0',
description: existing.description || '',
license: existing.license || 'MIT',
repository: `${repository}`,
author: existing.author || `${name}`,
homepage: `https://github.com/${repository}`,
bugs: `https://github.com/${repository}/issues`,
bin: existing.bin || '',
main: existing.main || 'dist/cjs.js',
engines: {
node: `>= ${config.maintLTS} <7.0.0 || >= ${config.activeLTS}`,
},
scripts: {
start: 'npm run build -- -w',
build:
"cross-env NODE_ENV=production babel src -d dist --ignore 'src/**/*.test.js' --copy-files",
clean: 'del-cli dist',
commitlint: 'commitlint',
commitmsg: 'commitlint -e $GIT_PARAMS',
lint: 'eslint --cache src test',
'ci:lint:commits':
'commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}',
'lint-staged': 'lint-staged',
prebuild: 'npm run clean',
prepublish: 'npm run build',
release: 'standard-version',
'release:ci': 'conventional-github-releaser -p angular',
'release:validate':
'commitlint --from=$(git describe --tags --abbrev=0) --to=$(git rev-parse HEAD)',
security: 'npm audit',
test: 'jest',
'test:watch': 'jest --watch',
'test:coverage': "jest --collectCoverageFrom='src/**/*.js' --coverage",
'ci:lint': 'npm run lint && npm run security',
'ci:test': 'npm run test -- --runInBand',
'ci:coverage': 'npm run test:coverage -- --runInBand',
defaults: 'webpack-defaults',
},
files: existing.files || ['dist/', 'lib/', 'index.js'],
peerDependencies: existing.peerDependencies || { webpack: '^4.3.0' },
dependencies: existing.dependencies || {},
devDependencies: existing.devDependencies || {},
keywords: existing.keywords || ['webpack'],
jest: { testEnvironment: 'node' },
'pre-commit': 'lint-staged',
'lint-staged': {
'*.js': ['eslint --fix', 'git add'],
},
})
.save();
install(packages, { dev: false });
install(devPackages);
};
|
JavaScript
| 0
|
42fa3ea0516cf927339cf66b97e7b534980f17d3
|
Update the namespace and update url.
|
gistfile1.js
|
gistfile1.js
|
// ==UserScript==
// @name Pocketcasts Utils
// @namespace https://gist.github.com/MaienM/e477e0f4e8ec3c1836a7/raw/25712be7ef9e7008549b4e0aa9dff7bb3871f1fc/gistfile1.js
// @updateURL https://gist.githubusercontent.com/MaienM/e477e0f4e8ec3c1836a7/raw/25712be7ef9e7008549b4e0aa9dff7bb3871f1fc/gistfile1.js
// @version 0.1
// @description Some utilities for pocketcasts
// @author MaienM
// @match https://play.pocketcasts.com/*
// @grant none
// ==/UserScript==
// Get the MutationObserver class for this browser.
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
if (MutationObserver == null) {
console.error("Your piece of shit browser does not support MutationObserver.");
}
$(function() {
/*
* Add a show-all button next to the show-more button.
*/
// Create the button.
var showAll = $('<div class="show_all show_more">Show all</div>');
// Handle it's click.
$(showAll).on('click', function() {
var showMore = $('div.show_more:not(.show_all)');
// Every time the episodes list changes, click show more if there is still more to show.
var listObserver = new MutationObserver(function(mutations, observer) {
if ($(showMore).is(':visible')) {
$(showMore).click();
} else {
listObserver.disconnect();
}
});
listObserver.observe($('#podcast_show div.episodes_list')[0], {
subtree: true,
childList: true,
});
// Click it once to start.
$(showMore).click();
});
// When needed, add it to the page.
var pageObserver = new MutationObserver(function(mutations, observer) {
var showMore = $('.show_more');
if ($(showMore).length > 0 && $('.show_all').length == 0) {
// Add the button.
$(showMore).after(showAll);
// When the more button's visiblity changes, update the visibility of the all button as well.
var showObserver = new MutationObserver(function(mutations, observer) {
if ($(showMore).is(':visible')) {
$(showAll).show();
} else {
$(showAll).hide();
}
});
showObserver.observe(showMore[0], {
attributes: true,
});
}
});
pageObserver.observe($('#content_middle')[0], {
subtree: true,
childList: true,
});
});
|
// ==UserScript==
// @name Pocketcasts Utils
// @namespace http://waxd.nl
// @version 0.1
// @description Some utilities for pocketcasts
// @author MaienM
// @match https://play.pocketcasts.com/*
// @grant none
// ==/UserScript==
// Get the MutationObserver class for this browser.
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
if (MutationObserver == null) {
console.error("Your piece of shit browser does not support MutationObserver.");
}
$(function() {
/*
* Add a show-all button next to the show-more button.
*/
// Create the button.
var showAll = $('<div class="show_all show_more">Show all</div>');
// Handle it's click.
$(showAll).on('click', function() {
var showMore = $('div.show_more:not(.show_all)');
// Every time the episodes list changes, click show more if there is still more to show.
var listObserver = new MutationObserver(function(mutations, observer) {
if ($(showMore).is(':visible')) {
$(showMore).click();
} else {
listObserver.disconnect();
}
});
listObserver.observe($('#podcast_show div.episodes_list')[0], {
subtree: true,
childList: true,
});
// Click it once to start.
$(showMore).click();
});
// When needed, add it to the page.
var pageObserver = new MutationObserver(function(mutations, observer) {
var showMore = $('.show_more');
if ($(showMore).length > 0 && $('.show_all').length == 0) {
// Add the button.
$(showMore).after(showAll);
// When the more button's visiblity changes, update the visibility of the all button as well.
var showObserver = new MutationObserver(function(mutations, observer) {
if ($(showMore).is(':visible')) {
$(showAll).show();
} else {
$(showAll).hide();
}
});
showObserver.observe(showMore[0], {
attributes: true,
});
}
});
pageObserver.observe($('#content_middle')[0], {
subtree: true,
childList: true,
});
});
|
JavaScript
| 0
|
b9c1e04c795efc5ff4209d01174b82c72c1c4483
|
remove coverage from karma.conf
|
karma.conf.js
|
karma.conf.js
|
'use strict';
// Karma configuration
// Generated on Wed Feb 17 2016 17:56:06 GMT+0100 (CET)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
// bower:js
'app/bower_components/angular/angular.js',
'app/bower_components/angular-animate/angular-animate.js',
'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-ui-router/release/angular-ui-router.js',
'app/bower_components/jquery/dist/jquery.js',
'app/bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
'app/bower_components/ng-lodash/build/ng-lodash.js',
// endbower
'app/index.js',
'app/src/**/*.module.js',
'app/src/**/*.js',
'app/src/**/*.html',
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'app/src/**/*.html': ['ng-html2js'],
},
ngHtml2JsPreprocessor: {
// strip this from the file path
stripPrefix: 'app/',
// create a single module that contains templates from all the files
moduleName: 'templates'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS', 'Chrome', 'Firefox', 'Safari'], // Chrome, Firefox, Safari
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
});
};
|
'use strict';
// Karma configuration
// Generated on Wed Feb 17 2016 17:56:06 GMT+0100 (CET)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
// bower:js
'app/bower_components/angular/angular.js',
'app/bower_components/angular-animate/angular-animate.js',
'app/bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/angular-ui-router/release/angular-ui-router.js',
'app/bower_components/jquery/dist/jquery.js',
'app/bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
'app/bower_components/ng-lodash/build/ng-lodash.js',
// endbower
'app/index.js',
'app/src/**/*.module.js',
'app/src/**/*.js',
'app/src/**/*.html',
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'app/src/**/*.html': ['ng-html2js'],
'app/src/**/!(*.spec).js': ['coverage'],
'app/index.js': ['coverage']
},
ngHtml2JsPreprocessor: {
// strip this from the file path
stripPrefix: 'app/',
// create a single module that contains templates from all the files
moduleName: 'templates'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
coverageReporter: {
type: 'html',
// output coverage reports
dir: 'coverage/'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS', 'Chrome', 'Firefox', 'Safari'], // Chrome, Firefox, Safari
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
});
};
|
JavaScript
| 0
|
d9c09eb3e9535a642ed7ded0b8059fe3b67187be
|
add working map
|
public/js/application.js
|
public/js/application.js
|
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'https://data.cityofnewyork.us/resource/erm2-nwe9.json?descriptor=Loud%20Music/Party',
dataType: 'json',
cache: true,
success: function(data, textStatus, jqXHR){
console.log(data)
},
fail: function(jqXHR, textStatus, errorThrown){
console.log(textStatus)
}
});
L.mapbox.accessToken = 'pk.eyJ1Ijoiam1jYXN0cm8iLCJhIjoiY2llcjl2N2x6MDFneHNtbHpubjR3enhlZCJ9.3A7IZVloogRznOfadjSoGg';
var map = L.mapbox.map('map', 'jmcastro.cier6sgeg01h9silzqx44aeaw')
.setView([40, -74.50], 9);
});
|
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'https://data.cityofnewyork.us/resource/erm2-nwe9.json?descriptor=Loud%20Music/Party',
dataType: 'json',
cache: true,
success: function(data, textStatus, jqXHR){
console.log(data)
},
fail: function(jqXHR, textStatus, errorThrown){
console.log(textStatus)
}
})
});
|
JavaScript
| 0.000001
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.