commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
b56d78047b8865e382810b750abc61db381160b9 | tasks/spritesheet.js | tasks/spritesheet.js | module.exports = function(grunt) {"use strict";
var Builder = require('../').Builder;
grunt.registerMultiTask("spritesheet", "Compile images to sprite sheet", function() {
var helpers = require('grunt-lib-contrib').init(grunt);
var options = helpers.options(this);
var done = this.async()
grunt.verbose.writeflags(options, "Options");
// TODO: ditch this when grunt v0.4 is released
this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target);
var srcFiles;
var images;
grunt.util.async.forEachSeries(this.files, function(file, callback) {
var builder;
var dir = '';
//grunt.task.expand( './..' );
srcFiles = grunt.file.expandFiles(file.src);
for(var i = 0; i < srcFiles.length; i++) {
srcFiles[i] = dir + srcFiles[i];
}
options.images = srcFiles;
options.outputDirectory = dir + file.dest;
builder = Builder.fromGruntTask(options);
builder.build(callback);
}, done);
});
};
| module.exports = function(grunt) {"use strict";
var Builder = require('../').Builder;
grunt.registerMultiTask("spritesheet", "Compile images to sprite sheet", function() {
var helpers = require('grunt-lib-contrib').init(grunt);
var options = helpers.options(this);
var done = this.async()
grunt.verbose.writeflags(options, "Options");
// TODO: ditch this when grunt v0.4 is released
this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target);
var srcFiles;
var images;
grunt.util.async.forEachSeries(this.files, function(file, callback) {
var builder;
var dir = '';
//grunt.task.expand( './..' );
srcFiles = grunt.file.expand(file.src);
for(var i = 0; i < srcFiles.length; i++) {
srcFiles[i] = dir + srcFiles[i];
}
options.images = srcFiles;
options.outputDirectory = dir + file.dest;
builder = Builder.fromGruntTask(options);
builder.build(callback);
}, done);
});
};
| Move from `expandFiles` to grunt 0.4's `expand` This largely fixes 0.4 compatibility for me | Move from `expandFiles` to grunt 0.4's `expand`
This largely fixes 0.4 compatibility for me | JavaScript | mit | richardbutler/node-spritesheet |
fb7d7d4b2a4c4015c9193064dcb41a44df70c312 | client/templates/posts/posts_list.js | client/templates/posts/posts_list.js | var postsData = [
{
title: 'Introducing Telescope',
url: 'http://sachagreif.com/introducing-telescope/'
},
{
title: 'Meteor',
url: 'http://meteor.com'
},
{
title: 'The Meteor Book',
url: 'http://themeteorbook.com'
}
];
Template.postsList.helpers({
posts: function() {
return Posts.find();
}
}); | var postsData = [
{
title: 'Introducing Telescope',
url: 'http://sachagreif.com/introducing-telescope/'
},
{
title: 'Meteor',
url: 'http://meteor.com'
},
{
title: 'The Meteor Book',
url: 'http://themeteorbook.com'
}
];
Template.postsList.helpers({
posts: function() {
return Posts.find({}, {sort: {submitted: -1}});
}
}); | Sort posts by submitted timestamp | Sort posts by submitted timestamp
| JavaScript | mit | valgalin/microscope,valgalin/microscope |
c6f398add9622d5dd84b8347a4f85fa98da6c5ad | spec/import-notebook-spec.js | spec/import-notebook-spec.js | "use babel";
// const { dialog } = require("electron").remote;
const { existsSync } = require("fs");
import { _loadNotebook } from "../lib/import-notebook";
import { waitAsync } from "./helpers/test-utils";
describe("Import notebook", () => {
const sampleNotebook = require.resolve("./helpers/test-notebook.ipynb");
beforeEach(
waitAsync(async () => {
await atom.packages.activatePackage("language-python");
await _loadNotebook(sampleNotebook);
})
);
it("Should import a notebook and convert it to a script", () => {
const editor = atom.workspace.getActiveTextEditor();
const code = editor.getText();
expect(code.split("\n")).toEqual([
"# %%",
"import pandas as pd",
"# %%",
"pd.util.testing.makeDataFrame()",
"# %%",
""
]);
});
});
| "use babel";
// const { dialog } = require("electron").remote;
const { existsSync } = require("fs");
const { EOL } = require("os");
import { _loadNotebook } from "../lib/import-notebook";
import { waitAsync } from "./helpers/test-utils";
describe("Import notebook", () => {
const sampleNotebook = require.resolve("./helpers/test-notebook.ipynb");
beforeEach(
waitAsync(async () => {
await atom.packages.activatePackage("language-python");
await _loadNotebook(sampleNotebook);
})
);
it("Should import a notebook and convert it to a script", () => {
const editor = atom.workspace.getActiveTextEditor();
const code = editor.getText();
expect(code.split(EOL)).toEqual([
"# %%",
"import pandas as pd",
"# %%",
"pd.util.testing.makeDataFrame()",
"# %%",
""
]);
});
});
| Use platform EOL for newlines | Use platform EOL for newlines
- Fixes test for Windows
| JavaScript | mit | nteract/hydrogen,nteract/hydrogen |
a7f2519f6b94ead24084978a611c8f799abf760b | lib/handlers/PostHandler.js | lib/handlers/PostHandler.js | 'use strict';
const BaseHandler = require('./BaseHandler');
const ERRORS = require('../constants').ERRORS;
const EVENT_ENDPOINT_CREATED = require('../constants').EVENT_ENDPOINT_CREATED;
class PostHandler extends BaseHandler {
/**
* Create a file in the DataStore.
*
* @param {object} req http.incomingMessage
* @param {object} res http.ServerResponse
* @return {function}
*/
send(req, res) {
return this.store.create(req)
.then((File) => {
const url = `http://${req.headers.host}${this.store.path}/${File.id}`;
this.emit(EVENT_ENDPOINT_CREATED, { url });
return super.send(res, 201, { Location: url });
})
.catch((error) => {
console.warn('[PostHandler]', error);
const status_code = error.status_code || ERRORS.UNKNOWN_ERROR.status_code;
const body = error.body || `${ERRORS.UNKNOWN_ERROR.body}${error.message || ''}\n`;
return super.send(res, status_code, {}, body);
});
}
}
module.exports = PostHandler;
| 'use strict';
const BaseHandler = require('./BaseHandler');
const ERRORS = require('../constants').ERRORS;
const EVENT_ENDPOINT_CREATED = require('../constants').EVENT_ENDPOINT_CREATED;
class PostHandler extends BaseHandler {
/**
* Create a file in the DataStore.
*
* @param {object} req http.incomingMessage
* @param {object} res http.ServerResponse
* @return {function}
*/
send(req, res) {
return this.store.create(req)
.then((File) => {
const url = `//${req.headers.host}${this.store.path}/${File.id}`;
this.emit(EVENT_ENDPOINT_CREATED, { url });
return super.send(res, 201, { Location: url });
})
.catch((error) => {
console.warn('[PostHandler]', error);
const status_code = error.status_code || ERRORS.UNKNOWN_ERROR.status_code;
const body = error.body || `${ERRORS.UNKNOWN_ERROR.body}${error.message || ''}\n`;
return super.send(res, status_code, {}, body);
});
}
}
module.exports = PostHandler;
| Remove HTTP as part of POST handler response | Remove HTTP as part of POST handler response | JavaScript | mit | tus/tus-node-server |
d22e1cc72041a3453f7a54bfb989ca71bd76c96a | webpack.config.client.production.js | webpack.config.client.production.js | const webpack = require('webpack')
const path = require('path')
const Dotenv = require('dotenv-webpack')
const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin')
const WebpackChunkHash = require('webpack-chunk-hash')
module.exports = {
entry: {
client: './src/client'
},
target: 'web',
module: {
rules: [{
test: /\.jsx?$/,
use: 'babel-loader',
include: [
path.join(__dirname, 'src')
]
}]
},
resolve: {
extensions: ['.json', '.js', '.jsx'],
alias: {
api: path.resolve(__dirname, 'src/api/')
}
},
plugins: [
new webpack.HashedModuleIdsPlugin(),
new webpack.NoEmitOnErrorsPlugin()
new webpack.ProvidePlugin({
fetch: 'isomorphic-fetch'
}),
new Dotenv({
path: './.env',
safe: false
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function include(module) {
return module.context && module.context.indexOf('node_modules') !== -1
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'client.manifest',
}),
new WebpackChunkHash(),
new ChunkManifestPlugin({
filename: 'client.chunk-manifest.json',
manifestVariable: 'webpackManifest'
})
],
output: {
path: path.join(__dirname, 'dist'),
publicPath: 'dist/',
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js'
}
}
| const webpack = require('webpack')
const path = require('path')
const Dotenv = require('dotenv-webpack')
const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin')
const WebpackChunkHash = require('webpack-chunk-hash')
module.exports = {
entry: {
client: './src/client'
},
target: 'web',
module: {
rules: [{
test: /\.jsx?$/,
use: 'babel-loader',
include: [
path.join(__dirname, 'src')
]
}]
},
resolve: {
extensions: ['.json', '.js', '.jsx'],
alias: {
api: path.resolve(__dirname, 'src/api/')
}
},
plugins: [
new webpack.HashedModuleIdsPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.ProvidePlugin({
fetch: 'isomorphic-fetch'
}),
new Dotenv({
path: './.env',
safe: false
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function include(module) {
return module.context && module.context.indexOf('node_modules') !== -1
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
}),
new WebpackChunkHash(),
new ChunkManifestPlugin({
filename: 'chunk-manifest.json',
manifestVariable: 'webpackManifest'
})
],
output: {
path: path.join(__dirname, 'dist'),
publicPath: 'dist/',
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js'
}
}
| Fix syntax error, rename manifest | Fix syntax error, rename manifest
| JavaScript | mit | madeagency/reactivity |
b331d9b5cb1ce6122737a4b1136f0ae83449d282 | lib/info-iframe-receiver.js | lib/info-iframe-receiver.js | 'use strict';
var inherits = require('inherits')
, EventEmitter = require('events').EventEmitter
, JSON3 = require('json3')
, XHRLocalObject = require('./transport/sender/xhr-local')
, InfoAjax = require('./info-ajax')
;
function InfoReceiverIframe(transUrl, baseUrl) {
var self = this;
EventEmitter.call(this);
this.ir = new InfoAjax(baseUrl, XHRLocalObject);
this.ir.once('finish', function(info, rtt) {
self.ir = null;
self.emit('message', JSON3.stringify([info, rtt]));
});
}
inherits(InfoReceiverIframe, EventEmitter);
InfoReceiverIframe.transportName = 'iframe-info-receiver';
InfoReceiverIframe.prototype.close = function() {
if (this.ir) {
this.ir.close();
this.ir = null;
}
this.removeAllListeners();
};
module.exports = InfoReceiverIframe;
| 'use strict';
var inherits = require('inherits')
, EventEmitter = require('events').EventEmitter
, JSON3 = require('json3')
, XHRLocalObject = require('./transport/sender/xhr-local')
, InfoAjax = require('./info-ajax')
;
function InfoReceiverIframe(transUrl) {
var self = this;
EventEmitter.call(this);
this.ir = new InfoAjax(transUrl, XHRLocalObject);
this.ir.once('finish', function(info, rtt) {
self.ir = null;
self.emit('message', JSON3.stringify([info, rtt]));
});
}
inherits(InfoReceiverIframe, EventEmitter);
InfoReceiverIframe.transportName = 'iframe-info-receiver';
InfoReceiverIframe.prototype.close = function() {
if (this.ir) {
this.ir.close();
this.ir = null;
}
this.removeAllListeners();
};
module.exports = InfoReceiverIframe;
| Fix iframe info receiver using wrong url | Fix iframe info receiver using wrong url
| JavaScript | mit | modulexcite/sockjs-client,the1sky/sockjs-client,bulentv/sockjs-client,webmechanicx/sockjs-client,vkorehov/sockjs-client,jmptrader/sockjs-client,JohnKossa/sockjs-client,sockjs/sockjs-client,woosoobar/sockjs-client,bulentv/sockjs-client,jmptrader/sockjs-client,reergymerej/sockjs-client,arusakov/sockjs-client,modulexcite/sockjs-client,sockjs/sockjs-client,sockjs/sockjs-client,woosoobar/sockjs-client,JohnKossa/sockjs-client,the1sky/sockjs-client,webmechanicx/sockjs-client,reergymerej/sockjs-client,vkorehov/sockjs-client,arusakov/sockjs-client |
97f8f233846493d5809dd63155fe156acb635c43 | lib/assets/javascripts/views/shared/create_account_form.js | lib/assets/javascripts/views/shared/create_account_form.js | import ariatiseForm from '../../utils/ariatiseForm';
import { togglisePasswords } from '../../utils/passwordHelper';
import validateOrgSelection from '../shared/my_org';
import { isValidText } from '../../utils/isValidInputType';
$(() => {
const options = { selector: '#create-account-form' };
ariatiseForm(options);
togglisePasswords(options);
$('#create_account_form').on('submit', (e) => {
// Additional validation to force the user to choose an org or type something for other
if (validateOrgSelection()) {
$('#help-org').hide();
} else {
e.preventDefault();
$('#help-org').show();
}
});
});
| import ariatiseForm from '../../utils/ariatiseForm';
import { togglisePasswords } from '../../utils/passwordHelper';
import { validateOrgSelection } from '../shared/my_org';
$(() => {
const options = { selector: '#create-account-form' };
ariatiseForm(options);
togglisePasswords(options);
$('#create_account_form').on('submit', (e) => {
// Additional validation to force the user to choose an org or type something for other
if (validateOrgSelection()) {
$('#help-org').hide();
} else {
e.preventDefault();
$('#help-org').show();
}
});
});
| Fix lint issues in JS | Fix lint issues in JS
| JavaScript | mit | CDLUC3/dmptool,DigitalCurationCentre/roadmap,DMPRoadmap/roadmap,DigitalCurationCentre/roadmap,CDLUC3/dmptool,DigitalCurationCentre/roadmap,CDLUC3/dmptool,CDLUC3/roadmap,CDLUC3/roadmap,DMPRoadmap/roadmap,CDLUC3/roadmap,CDLUC3/dmptool,DMPRoadmap/roadmap,CDLUC3/roadmap |
9263492051ac911f429e9585afce5568fe2eb8ff | app/scripts/app.js | app/scripts/app.js | 'use strict';
angular
.module('visualizerApp', [
'ngRoute',
'angularFileUpload',
'angularMoment',
'angularPeity'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/read/'
})
.when('/read/', {
templateUrl: 'views/read.html',
controller: 'ReadController',
activetab: 'read'
})
.when('/display/', {
templateUrl: 'views/display.html',
controller: 'DisplayController',
activetab: 'display'
})
.otherwise({
redirectTo: '/'
});
});
angular.module('visualizerApp')
.filter('limitToFrom', function() {
return function(arr, offset, limit) {
if (!angular.isArray(arr))
return arr;
var start = offset;
var end = start + limit;
start = Math.max(Math.min(start, arr.length), 0);
end = Math.max(Math.min(end, arr.length), 0);
return arr.slice(start, end);
};
});
jQuery.fn.peity.defaults.pie = {
diameter: 16,
fill: ['#ff9900', '#ffd592', '#fff4dd']
};
| 'use strict';
angular
.module('visualizerApp', [
'ngRoute',
'angularFileUpload',
'angularMoment',
'angularPeity'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/read/'
})
.when('/read/', {
templateUrl: 'views/read.html',
controller: 'ReadController',
activetab: 'read'
})
.when('/display/', {
templateUrl: 'views/display.html',
controller: 'DisplayController',
activetab: 'display'
})
.when('/display/:owner/:repo/', {
templateUrl: 'views/display.html',
controller: 'DisplayController',
activetab: 'display'
})
.otherwise({
redirectTo: '/'
});
});
angular.module('visualizerApp')
.filter('limitToFrom', function() {
return function(arr, offset, limit) {
if (!angular.isArray(arr))
return arr;
var start = offset;
var end = start + limit;
start = Math.max(Math.min(start, arr.length), 0);
end = Math.max(Math.min(end, arr.length), 0);
return arr.slice(start, end);
};
});
jQuery.fn.peity.defaults.pie = {
diameter: 16,
fill: ['#ff9900', '#ffd592', '#fff4dd']
};
| Add routing for specified repos | Add routing for specified repos
| JavaScript | mit | PRioritizer/PRioritizer-visualizer,PRioritizer/PRioritizer-visualizer |
21d3e05ce05ee3d0e8eb2237c43335d8e4d12d8d | samples/fortytwo_test.js | samples/fortytwo_test.js | define(['chai', 'mocha', 'samples/fortytwo'], function(chai, mocha, fortytwo) {
'use strict';
var expect = chai.expect;
describe('fortytwo', function() {
it('should return fortytwo', function() {
expect(fortytwo.fortytwo()).to.equal(42);
});
});
});
| define(['chai',
'mocha',
'samples/fortytwo'],
function(chai,
unusedMocha,
fortytwo) {
'use strict';
var expect = chai.expect;
describe('fortytwo', function() {
it('should return fortytwo', function() {
expect(fortytwo.fortytwo()).to.equal(42);
});
});
});
| Align the variables slightly differently. | Align the variables slightly differently.
| JavaScript | mit | solventz/js |
07d28940c615563b434c7a982bd89c8fc9356f15 | lib/event_bus/in_memory/receiver.js | lib/event_bus/in_memory/receiver.js | var inherit = require("../../inherit");
var CommonEventBusReceiver = require("../common/receiver");
var InMemoryEventBus;
inherit(InMemoryEventBusReceiver, CommonEventBusReceiver);
function InMemoryEventBusReceiver(options) {
CommonEventBusReceiver.call(this, options);
InMemoryEventBus = InMemoryEventBus || require("../in_memory");
}
InMemoryEventBusReceiver.prototype.start = function (callback) {
var self = this;
self.queue = InMemoryEventBus.registerQueue({
name: self.queueName,
logger: self.logger
});
self.queue.registerHandler(function (event, callback) {
self._handleEvent(event, callback);
});
callback();
};
module.exports = InMemoryEventBusReceiver;
| var inherit = require("../../inherit");
var CommonEventBusReceiver = require("../common/receiver");
var InMemoryEventBus;
inherit(InMemoryEventBusReceiver, CommonEventBusReceiver);
function InMemoryEventBusReceiver(options) {
CommonEventBusReceiver.call(this, options);
InMemoryEventBus = InMemoryEventBus || require("../in_memory");
}
InMemoryEventBusReceiver.prototype.initialize = function (callback) {
callback();
};
InMemoryEventBusReceiver.prototype.start = function (callback) {
var self = this;
self.queue = InMemoryEventBus.registerQueue({
name: self.queueName,
logger: self.logger
});
self.queue.registerHandler(function (event, callback) {
self._handleEvent(event, callback);
});
callback();
};
module.exports = InMemoryEventBusReceiver;
| Add intiialize method to InMemoryEventBusReceiver | Add intiialize method to InMemoryEventBusReceiver
| JavaScript | mit | jbpros/plutonium |
412c8f46f99efeb830bc5683fb238c0fb9990f18 | generators/app/templates/src/__tools-jest._jest.config.js | generators/app/templates/src/__tools-jest._jest.config.js | // https://github.com/thymikee/jest-preset-angular#brief-explanation-of-config
module.exports = {
preset: 'jest-preset-angular',
roots: ['src'],
coverageDirectory: 'reports',
setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
moduleNameMapper: {
'@app/(.*)': '<rootDir>/src/app/$1',
'@env': '<rootDir>/src/environments/environment'
},
// Do not ignore librairies such as ionic, ionic-native or bootstrap to transform them during unit testing.
<%
var excludedLibrairies = ['jest-test'];
if (props.target.includes('cordova')) { excludedLibrairies.push('@ionic-native'); }
if (props.ui === 'ionic') { excludedLibrairies.push('@ionic'); }
if (props.ui === 'bootstrap') { excludedLibrairies.push('@ng-bootstrap'); }
-%>
transformIgnorePatterns: ['node_modules/(?!(<%- excludedLibrairies.join('|') %>))']
};
| // https://github.com/thymikee/jest-preset-angular#brief-explanation-of-config
module.exports = {
preset: 'jest-preset-angular',
roots: ['src'],
coverageDirectory: 'reports',
setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
moduleNameMapper: {
'@app/(.*)': '<rootDir>/src/app/$1',
'@env': '<rootDir>/src/environments/environment'
},
// Do not ignore librairies such as ionic, ionic-native or bootstrap to transform them during unit testing.
<% const excludedLibrairies = ['jest-test']
if (props.target.includes('cordova')) { excludedLibrairies.push('@ionic-native'); }
if (props.ui === 'ionic') { excludedLibrairies.push('@ionic'); }
if (props.ui === 'bootstrap') { excludedLibrairies.push('@ng-bootstrap'); } -%>
transformIgnorePatterns: ['node_modules/(?!(<%- excludedLibrairies.join('|') %>))']
};
| Include libraries for transformation with Jest | Include libraries for transformation with Jest
| JavaScript | mit | angular-starter-kit/generator-ngx-app,angular-starter-kit/generator-ngx-app,ngx-rocket/generator-ngx-rocket,ngx-rocket/generator-ngx-rocket,ngx-rocket/generator-ngx-rocket,ngx-rocket/generator-ngx-rocket,angular-starter-kit/generator-ngx-app,angular-starter-kit/generator-ngx-app |
181d2ce8bcffc566f3a3be9d7fca412195ed65f9 | client/views/settings/users/enroll/autoform.js | client/views/settings/users/enroll/autoform.js | AutoForm.addHooks('usersEnrollForm', {
onError (formType, error) {
// Show the error to end user
// TODO: add internationalization support for specefic error type(s)
FlashMessages.sendError(`${error.error}: ${error.reason}`, { autoHide: false });
}
});
| AutoForm.addHooks('usersEnrollForm', {
onError (formType, error) {
// Show the error to end user
// TODO: add internationalization support for specefic error type(s)
// Make sure there is an error type, otherwise don't show error
// to prevent 'unknown' or undefined error messages from triggering flash message
if (error.error) {
FlashMessages.sendError(`${error.error}: ${error.reason}`, { autoHide: false });
}
}
});
| Make sure error type exists before flash message | Make sure error type exists before flash message
| JavaScript | agpl-3.0 | GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing |
e05609d5ec95f804daf0e403647b98483abc4fb5 | extensions/markdown/media/loading.js | extensions/markdown/media/loading.js | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// @ts-check
'use strict';
(function () {
const unloadedStyles = [];
const onStyleLoadError = (event) => {
const source = event.target.dataset.source;
unloadedStyles.push(source);
};
window.addEventListener('DOMContentLoaded', () => {
for (const link of document.getElementsByClassName('code-user-style')) {
if (link.dataset.source) {
link.onerror = onStyleLoadError;
}
}
})
window.addEventListener('load', () => {
if (!unloadedStyles.length) {
return;
}
const args = [unloadedStyles];
window.parent.postMessage({
command: 'did-click-link',
data: `command:_markdown.onPreviewStyleLoadError?${encodeURIComponent(JSON.stringify(args))}`
}, '*');
});
}()); | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// @ts-check
'use strict';
(function () {
const unloadedStyles = [];
const onStyleLoadError = (event) => {
const source = event.target.dataset.source;
unloadedStyles.push(source);
};
window.addEventListener('DOMContentLoaded', () => {
for (const link of document.getElementsByClassName('code-user-style')) {
if (link.dataset.source) {
link.onerror = onStyleLoadError;
}
}
})
window.addEventListener('load', () => {
if (!unloadedStyles.length) {
return;
}
window.parent.postMessage({
command: '_markdown.onPreviewStyleLoadError',
args: [unloadedStyles]
}, '*');
});
}()); | Fix markdown style load error | Fix markdown style load error
| JavaScript | mit | microlv/vscode,landonepps/vscode,eamodio/vscode,eamodio/vscode,0xmohit/vscode,the-ress/vscode,landonepps/vscode,joaomoreno/vscode,0xmohit/vscode,0xmohit/vscode,rishii7/vscode,eamodio/vscode,0xmohit/vscode,microlv/vscode,landonepps/vscode,Microsoft/vscode,0xmohit/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,microlv/vscode,the-ress/vscode,microlv/vscode,microlv/vscode,rishii7/vscode,cleidigh/vscode,microsoft/vscode,the-ress/vscode,DustinCampbell/vscode,cleidigh/vscode,Microsoft/vscode,joaomoreno/vscode,rishii7/vscode,rishii7/vscode,joaomoreno/vscode,rishii7/vscode,cleidigh/vscode,joaomoreno/vscode,eamodio/vscode,Microsoft/vscode,joaomoreno/vscode,eamodio/vscode,rishii7/vscode,hoovercj/vscode,0xmohit/vscode,the-ress/vscode,DustinCampbell/vscode,the-ress/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,hoovercj/vscode,DustinCampbell/vscode,microsoft/vscode,joaomoreno/vscode,cleidigh/vscode,hoovercj/vscode,mjbvz/vscode,hoovercj/vscode,mjbvz/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,DustinCampbell/vscode,joaomoreno/vscode,DustinCampbell/vscode,DustinCampbell/vscode,rishii7/vscode,Microsoft/vscode,0xmohit/vscode,hoovercj/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,DustinCampbell/vscode,hoovercj/vscode,cleidigh/vscode,landonepps/vscode,rishii7/vscode,Microsoft/vscode,cleidigh/vscode,hoovercj/vscode,rishii7/vscode,cleidigh/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,mjbvz/vscode,cleidigh/vscode,the-ress/vscode,mjbvz/vscode,the-ress/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,cleidigh/vscode,hoovercj/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,DustinCampbell/vscode,Microsoft/vscode,eamodio/vscode,joaomoreno/vscode,the-ress/vscode,mjbvz/vscode,cleidigh/vscode,the-ress/vscode,cleidigh/vscode,mjbvz/vscode,0xmohit/vscode,DustinCampbell/vscode,eamodio/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,the-ress/vscode,microsoft/vscode,eamodio/vscode,rishii7/vscode,0xmohit/vscode,landonepps/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,Microsoft/vscode,microlv/vscode,Microsoft/vscode,microlv/vscode,mjbvz/vscode,microlv/vscode,DustinCampbell/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,hoovercj/vscode,joaomoreno/vscode,mjbvz/vscode,cleidigh/vscode,microsoft/vscode,the-ress/vscode,eamodio/vscode,microsoft/vscode,landonepps/vscode,joaomoreno/vscode,landonepps/vscode,DustinCampbell/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,joaomoreno/vscode,0xmohit/vscode,landonepps/vscode,microsoft/vscode,rishii7/vscode,0xmohit/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,hoovercj/vscode,joaomoreno/vscode,landonepps/vscode,mjbvz/vscode,rishii7/vscode,microlv/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,eamodio/vscode,Microsoft/vscode,microsoft/vscode,hoovercj/vscode,cleidigh/vscode,landonepps/vscode,mjbvz/vscode,hoovercj/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,DustinCampbell/vscode,mjbvz/vscode,microlv/vscode,rishii7/vscode,Krzysztof-Cieslak/vscode,landonepps/vscode,microlv/vscode,DustinCampbell/vscode,landonepps/vscode,the-ress/vscode,Microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,0xmohit/vscode,joaomoreno/vscode,eamodio/vscode,hoovercj/vscode,cleidigh/vscode,rishii7/vscode,the-ress/vscode,joaomoreno/vscode,cleidigh/vscode,DustinCampbell/vscode,eamodio/vscode,landonepps/vscode,Microsoft/vscode,eamodio/vscode,joaomoreno/vscode,0xmohit/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,rishii7/vscode,0xmohit/vscode,joaomoreno/vscode,Microsoft/vscode,Microsoft/vscode,mjbvz/vscode,hoovercj/vscode,0xmohit/vscode,0xmohit/vscode,microsoft/vscode,mjbvz/vscode,landonepps/vscode,rishii7/vscode,the-ress/vscode,hoovercj/vscode,mjbvz/vscode,hoovercj/vscode,cleidigh/vscode,0xmohit/vscode,microsoft/vscode,rishii7/vscode |
4227a56fe23fdd3c43128c4e86df4e532cd24993 | __tests__/end-to-end/e2e-constants.js | __tests__/end-to-end/e2e-constants.js | export const ENTER_UNICODE = '\u000d';
export const SIMPLE_TEST_TIMEOUT = 10 * 1000;
const NIGHTMARE_ACTION_TIMEOUT = (process.env.CIRCLECI ? 4 : 2) * 1000;
export const NIGHTMARE_CONFIG = {
waitTimeout: NIGHTMARE_ACTION_TIMEOUT,
gotoTimeout: NIGHTMARE_ACTION_TIMEOUT,
loadTimeout: NIGHTMARE_ACTION_TIMEOUT,
executionTimeout: NIGHTMARE_ACTION_TIMEOUT,
// This one decides whether nightmarejs actually opens a window for the browser it tests in
show: process.env.ELECTRON_SHOW_DISPLAY === '1',
};
| export const ENTER_UNICODE = '\u000d';
export const SIMPLE_TEST_TIMEOUT = 10 * 1000;
const NIGHTMARE_ACTION_TIMEOUT = (process.env.CIRCLECI ? 6 : 2) * 1000;
export const NIGHTMARE_CONFIG = {
waitTimeout: NIGHTMARE_ACTION_TIMEOUT,
gotoTimeout: NIGHTMARE_ACTION_TIMEOUT,
loadTimeout: NIGHTMARE_ACTION_TIMEOUT,
executionTimeout: NIGHTMARE_ACTION_TIMEOUT,
// This one decides whether nightmarejs actually opens a window for the browser it tests in
show: process.env.ELECTRON_SHOW_DISPLAY === '1',
};
| Increase nightmare action timeout on CI for e2e tests | Increase nightmare action timeout on CI for e2e tests
| JavaScript | mit | thegazelle-ad/gazelle-front-end,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-front-end,thegazelle-ad/gazelle-server |
007d247a719af3e9149a915a33034742efb98c0c | src/components/stream-app.js | src/components/stream-app.js | 'use strict';
var React = require('react');
var io = require('socket.io-client');
var TwitterStreamList = require('./stream-list');
var TwitterStreamApp = React.createClass({
getInitialState: function() {
return {
tweets: []
};
},
componentDidMount: function() {
var socket = io();
socket.on('tweet', function(tweet) {
var tweets = this.state.tweets.slice();
tweets.unshift(tweet);
this.setState({ tweets: tweets });
}.bind(this));
},
render: function() {
return (
<div className="TwitterStream">
<TwitterStreamList data={this.state.tweets}/>
</div>
);
}
});
module.exports = TwitterStreamApp;
| 'use strict';
var React = require('react');
var io = require('socket.io-client');
var TwitterStreamList = require('./stream-list');
var TwitterStreamApp = React.createClass({
getInitialState: function() {
return {
tweets: []
};
},
onTweetReceived: function(tweet) {
var tweets = this.state.tweets.slice();
tweets.unshift(tweet);
this.setState({ tweets: tweets });
},
componentDidMount: function() {
this.socket = io();
this.socket.on('tweet', this.onTweetReceived);
},
this.setState({ tweets: tweets });
}.bind(this));
},
render: function() {
return (
<div className="TwitterStream">
<TwitterStreamList data={this.state.tweets}/>
</div>
);
}
});
module.exports = TwitterStreamApp;
| Move setState logic on new tweet to component method | Move setState logic on new tweet to component method
| JavaScript | mit | bjarneo/TwitterStream,bjarneo/TwitterStream |
0334e6c0138bfef3b11c400d3da58633c8697257 | library/CM/Page/Abstract.js | library/CM/Page/Abstract.js | /**
* @class CM_Page_Abstract
* @extends CM_Component_Abstract
*/
var CM_Page_Abstract = CM_Component_Abstract.extend({
/** @type String */
_class: 'CM_Page_Abstract',
/** @type String[] */
_stateParams: [],
/** @type String|Null */
_fragment: null,
_ready: function() {
this._fragment = window.location.pathname + window.location.search;
// @todo routeToState
CM_Component_Abstract.prototype._ready.call(this);
},
/**
* @returns {String|Null}
*/
getFragment: function() {
return this._fragment;
},
/**
* @returns {String[]}
*/
getStateParams: function() {
return this._stateParams;
},
/**
* @param {Object} state
* @param {String} fragment
*/
routeToState: function(state, fragment) {
this._fragment = fragment;
this._changeState(state);
},
/**
* @param {Object} state
*/
_changeState: function(state) {
}
});
| /**
* @class CM_Page_Abstract
* @extends CM_Component_Abstract
*/
var CM_Page_Abstract = CM_Component_Abstract.extend({
/** @type String */
_class: 'CM_Page_Abstract',
/** @type String[] */
_stateParams: [],
/** @type String|Null */
_fragment: null,
_ready: function() {
var location = window.location;
var params = queryString.parse(location.search);
var state = _.pick(params, _.intersection(_.keys(params), this.getStateParams()));
this.routeToState(state, location.pathname + location.search);
CM_Component_Abstract.prototype._ready.call(this);
},
/**
* @returns {String|Null}
*/
getFragment: function() {
return this._fragment;
},
/**
* @returns {String[]}
*/
getStateParams: function() {
return this._stateParams;
},
/**
* @param {Object} state
* @param {String} fragment
*/
routeToState: function(state, fragment) {
this._fragment = fragment;
this._changeState(state);
},
/**
* @param {Object} state
*/
_changeState: function(state) {
}
});
| Call "routeToState" on page's ready() | Call "routeToState" on page's ready()
| JavaScript | mit | vogdb/cm,cargomedia/CM,mariansollmann/CM,vogdb/cm,njam/CM,christopheschwyzer/CM,njam/CM,tomaszdurka/CM,tomaszdurka/CM,mariansollmann/CM,alexispeter/CM,njam/CM,fauvel/CM,njam/CM,fvovan/CM,alexispeter/CM,zazabe/cm,fvovan/CM,vogdb/cm,zazabe/cm,christopheschwyzer/CM,fauvel/CM,zazabe/cm,alexispeter/CM,njam/CM,mariansollmann/CM,zazabe/cm,tomaszdurka/CM,tomaszdurka/CM,fauvel/CM,mariansollmann/CM,christopheschwyzer/CM,vogdb/cm,vogdb/cm,cargomedia/CM,cargomedia/CM,fvovan/CM,fauvel/CM,fauvel/CM,fvovan/CM,alexispeter/CM,cargomedia/CM,tomaszdurka/CM,christopheschwyzer/CM |
d192bf8fcb996c5d4d0a86e6fab2e0c4fac3bc8a | src/functions/run.js | src/functions/run.js | 'use strict'
const { addGenErrorHandler } = require('../errors')
const { getParams } = require('./params')
const { stringifyConfigFunc } = require('./tokenize')
// Process config function, i.e. fires it and returns its value
const runConfigFunc = function ({
configFunc,
mInput,
mInput: { serverParams },
params,
}) {
// If this is not config function, returns as is
if (typeof configFunc !== 'function') { return configFunc }
const paramsA = getParams(mInput, { params, serverParams, mutable: false })
return configFunc(paramsA)
}
const eRunConfigFunc = addGenErrorHandler(runConfigFunc, {
message: ({ configFunc }) =>
`Function failed: '${stringifyConfigFunc({ configFunc })}'`,
reason: 'CONFIG_RUNTIME',
})
module.exports = {
runConfigFunc: eRunConfigFunc,
}
| 'use strict'
const { addGenPbHandler } = require('../errors')
const { getParams } = require('./params')
const { stringifyConfigFunc } = require('./tokenize')
// Process config function, i.e. fires it and returns its value
const runConfigFunc = function ({
configFunc,
mInput,
mInput: { serverParams },
params,
}) {
// If this is not config function, returns as is
if (typeof configFunc !== 'function') { return configFunc }
const paramsA = getParams(mInput, { params, serverParams, mutable: false })
return configFunc(paramsA)
}
const eRunConfigFunc = addGenPbHandler(runConfigFunc, {
message: ({ configFunc }) =>
`Function failed: '${stringifyConfigFunc({ configFunc })}'`,
reason: 'CONFIG_RUNTIME',
extra: ({ configFunc }) => ({ value: stringifyConfigFunc({ configFunc }) }),
})
module.exports = {
runConfigFunc: eRunConfigFunc,
}
| Improve error handling of config functions | Improve error handling of config functions
| JavaScript | apache-2.0 | autoserver-org/autoserver,autoserver-org/autoserver |
f04c6bf92ee6e09bb2fa0b1686bfdc5fc8c98ffd | lighthouse-inline-images.js | lighthouse-inline-images.js | // ==UserScript==
// @name Lighthouse Inline Image Attachments
// @namespace headinsky.dk
// @description Show image attachments for Lighthouse tickets inline
// @include https://*.lighthouseapp.com/*
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==
var width = $("div#main div.attachments").width();
$("ul.attachment-list li.aimg a").each(function()
{
img = document.createElement('img');
img.setAttribute('src', this.getAttribute('href'));
img.setAttribute('style','max-width: ' + (width-45) + 'px;');
this.replaceChild(img, this.firstChild);
});
| // ==UserScript==
// @name Lighthouse Inline Image Attachments
// @namespace headinsky.dk
// @description Show image attachments for Lighthouse tickets inline
// @include https://*.lighthouseapp.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==
var width = $("div#main div.attachments").width();
$("ul.attachment-list li.aimg a").each(function()
{
img = document.createElement('img');
img.setAttribute('src', this.getAttribute('href'));
img.setAttribute('style','max-width: ' + (width-45) + 'px;');
this.replaceChild(img, this.firstChild);
});
| Use optimized jQuery from Google APIs | Use optimized jQuery from Google APIs | JavaScript | mit | kasperg/lighthouse-inline-images |
7eca0341a136b75907c58287a8d16f625be85e31 | src/http/pdf-http.js | src/http/pdf-http.js | const ex = require('../util/express');
const pdfCore = require('../core/pdf-core');
const getRender = ex.createRoute((req, res) => {
const opts = {
// TODO: add all params here
};
return pdfCore.render(req.query)
.then((data) => {
res.set('content-type', 'application/pdf');
res.send(data);
});
});
const postRender = ex.createRoute((req, res) => {
return pdfCore.render(req.body)
.then((data) => {
res.set('content-type', 'application/pdf');
res.send(data);
});
});
module.exports = {
getRender,
postRender
};
| const ex = require('../util/express');
const pdfCore = require('../core/pdf-core');
const getRender = ex.createRoute((req, res) => {
const opts = {
url: req.query.url,
scrollPage: req.query.scrollPage,
emulateScreenMedia: req.query.emulateScreenMedia,
waitFor: req.query.waitFor,
viewport: {
width: req.query['viewport.width'],
height: req.query['viewport.height'],
deviceScaleFactor: req.query['viewport.deviceScaleFactor'],
isMobile: req.query['viewport.isMobile'],
hasTouch: req.query['viewport.hasTouch'],
isLandscape: req.query['viewport.isLandscape'],
},
goto: {
timeout: req.query['goto.timeout'],
waitUntil: req.query['goto.waitUntil'],
networkIdleInflight: req.query['goto.networkIdleInflight'],
networkIdleTimeout: req.query['goto.networkIdleTimeout'],
},
pdf: {
scale: req.query['pdf.scale'],
displayHeaderFooter: req.query['pdf.displayHeaderFooter'],
landscape: req.query['pdf.landscape'],
pageRanges: req.query['pdf.pageRanges'],
format: req.query['pdf.format'],
width: req.query['pdf.width'],
height: req.query['pdf.height'],
margin: {
top: req.query['pdf.margin.top'],
right: req.query['pdf.margin.right'],
bottom: req.query['pdf.margin.bottom'],
left: req.query['pdf.margin.left'],
},
printBackground: req.query['pdf.printBackground'],
},
};
return pdfCore.render(opts)
.then((data) => {
res.set('content-type', 'application/pdf');
res.send(data);
});
});
const postRender = ex.createRoute((req, res) => {
return pdfCore.render(req.body)
.then((data) => {
res.set('content-type', 'application/pdf');
res.send(data);
});
});
module.exports = {
getRender,
postRender
};
| Implement parameters for GET request | Implement parameters for GET request
| JavaScript | mit | alvarcarto/url-to-pdf-api,alvarcarto/url-to-pdf-api |
f016db1ff759c47e602e0aaa0984bfbcd694438b | src/main/webapp/components/BuildSnapshotContainer.js | src/main/webapp/components/BuildSnapshotContainer.js | import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
import {Wrapper} from "./Wrapper";
/**
* Container Component for BuildSnapshots.
*
* @param {*} props input property containing an array of build data to be
* rendered through BuildSnapshot.
*/
export const BuildSnapshotContainer = React.memo((props) => {
const SOURCE = '/data';
const [data, setData] = React.useState([]);
/**
* Fetch data when component is mounted.
* Pass in empty array as second paramater to prevent
* infinite callbacks as component refreshes.
* @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a>
*/
React.useEffect(() => {
fetch(SOURCE).then(res => setData(res.json()));
}, []);
return (
<Wrapper>
{data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)}
</Wrapper>
);
}
);
| import * as React from "react";
import {BuildSnapshot} from "./BuildSnapshot";
import {Wrapper} from "./Wrapper";
/**
* Container Component for BuildSnapshots.
*
* @param {*} props input property containing an array of build data to be
* rendered through BuildSnapshot.
*/
export const BuildSnapshotContainer = React.memo((props) => {
const SOURCE = '/data';
const [data, setData] = React.useState([]);
/**
* Fetch data when component is mounted.
* Pass in empty array as second paramater to prevent
* infinite callbacks as component refreshes.
*
* @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a>
*/
React.useEffect(() => {
fetch(SOURCE).then(res => setData(res.json()));
}, []);
return (
<Wrapper>
{data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)}
</Wrapper>
);
}
);
| Add space between comment summary and @see | Add space between comment summary and @see | JavaScript | apache-2.0 | googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020 |
85af498cbc8f3bad4fc8d15e0332fe46cdbf7d73 | js/components/module-container.js | js/components/module-container.js | (function(app) {
'use strict';
var jCore = require('jcore');
var helper = app.helper || require('../helper.js');
var Module = app.Module || require('./module.js');
var ModuleContainer = helper.inherits(function(props) {
ModuleContainer.super_.call(this);
this.modules = this.prop([]);
this.element = this.prop(props.element);
this.deleter = ModuleContainer.prototype.deleter.bind(this);
}, jCore.Component);
ModuleContainer.prototype.loadModule = function(props) {
props.deleter = this.deleter;
var module = new Module(props);
this.modules().push(module);
module.parentElement(this.element());
module.redraw();
return module.loadComponent().then(function() {
return module;
});
};
ModuleContainer.prototype.deleter = function(module) {
var modules = this.modules();
var index = modules.indexOf(module);
if (index === -1)
return;
modules.splice(index, 1);
};
if (typeof module !== 'undefined' && module.exports)
module.exports = ModuleContainer;
else
app.ModuleContainer = ModuleContainer;
})(this.app || (this.app = {}));
| (function(app) {
'use strict';
var jCore = require('jcore');
var helper = app.helper || require('../helper.js');
var Module = app.Module || require('./module.js');
var ModuleContainer = helper.inherits(function(props) {
ModuleContainer.super_.call(this);
this.modules = this.prop([]);
this.element = this.prop(props.element);
this.deleter = ModuleContainer.prototype.deleter.bind(this);
}, jCore.Component);
ModuleContainer.prototype.loadModule = function(props) {
props.deleter = this.deleter;
var module = new Module(props);
this.modules().push(module);
module.parentElement(this.element());
module.redraw();
return module.loadComponent().then(function() {
return module;
});
};
ModuleContainer.prototype.toFront = function(module) {
var modules = this.modules();
var index = modules.indexOf(module);
if (index === -1)
return;
modules.splice(index, 1);
modules.push(module);
};
ModuleContainer.prototype.deleter = function(module) {
var modules = this.modules();
var index = modules.indexOf(module);
if (index === -1)
return;
modules.splice(index, 1);
};
if (typeof module !== 'undefined' && module.exports)
module.exports = ModuleContainer;
else
app.ModuleContainer = ModuleContainer;
})(this.app || (this.app = {}));
| Add method to move a module on top of others | Add method to move a module on top of others
| JavaScript | mit | ionstage/modular,ionstage/modular |
2bf536eb1d383b479c0df0477cde3bd5ceb76290 | keyhole/static/keyhole/js/main.js | keyhole/static/keyhole/js/main.js | (function($) {
function init_editor(e) {
var editor = $(e);
var selector = editor.data('selector');
editor.cropit({
imageState: {
src: editor.data('original-image')
}
});
$("body").on('click', '#' + selector + '_btn', function(e) {
e.preventDefault();
e.stopPropagation();
// Move cropped image data to hidden input
var imageData = editor.cropit('export');
$('#' + selector).val(imageData);
return false;
});
}
$(document).ready(function() {
var editors = $('.image-editor');
$.each(editors, function(index, value) {
init_editor(value);
});
});
})(django.jQuery);
| (function($) {
function init_editor(e) {
var editor = $(e);
var selector = editor.data('selector');
editor.cropit({
imageState: {
src: editor.data('original-image')
}
});
$("form[class*='form'").submit(function( event ) {
// Move cropped image data to hidden input
var imageData = editor.cropit('export');
$('#' + selector).val(imageData);
});
}
$(document).ready(function() {
var editors = $('.image-editor');
$.each(editors, function(index, value) {
init_editor(value);
});
});
})(django.jQuery);
| Save cropped image on submit and not by clicking on the button. | Save cropped image on submit and not by clicking on the button. | JavaScript | mit | BontaVlad/DjangoKeyhole,BontaVlad/DjangoKeyhole |
cf248f613e7334acc46629787c1134aadc07801d | src/reducers/root.js | src/reducers/root.js | import { LOAD_PAGE, LOAD_PAGE_REQUEST } from '../actions/constants'
const initialState = {
page: 1,
photos: [],
loading: true
}
export default function (state = initialState, action) {
switch (action.type) {
case LOAD_PAGE_REQUEST:
return Object.assign({}, state, {
loading: true
})
case LOAD_PAGE:
return Object.assign({}, state, {
page: action.payload.page,
photos: action.payload.photos,
loading: false
})
default:
return state
}
}
| import { LOAD_PAGE, LOAD_PAGE_REQUEST } from '../actions/constants'
const initialState = {
page: 1,
photos: [],
loading: true
}
export default function (state = initialState, action) {
switch (action.type) {
case LOAD_PAGE_REQUEST:
return {
...state,
loading: true
}
case LOAD_PAGE:
return {
...state,
page: action.payload.page,
photos: action.payload.photos,
loading: false
}
default:
return state
}
}
| Use object spread operator instead of Object.assign | Use object spread operator instead of Object.assign
| JavaScript | mit | stackia/unsplash-trending,stackia/unsplash-trending |
2af6a80603f3b17106fb11a15b02636d18540fc3 | src/shared/config.js | src/shared/config.js | import { InjectionToken } from 'yabf'
import { LOG_LEVEL } from '../services'
export const OPTION_PATH_FILE_TOKEN = new InjectionToken()
export const APP_LOG_LEVEL_TOKEN = new InjectionToken()
export const APP_LOG_LEVEL = LOG_LEVEL.ALL
| import { InjectionToken } from 'yabf'
import { LOG_LEVEL } from '../services'
export const OPTION_PATH_FILE_TOKEN = new InjectionToken()
export const APP_LOG_LEVEL_TOKEN = new InjectionToken()
export const APP_LOG_LEVEL = LOG_LEVEL.ERROR
| Set log level to ERROR | Set log level to ERROR
| JavaScript | apache-2.0 | Mindsers/configfile |
e2695a633c0fef9ef0402ba765f4e7322574f324 | language-command.js | language-command.js | var _ = require('lodash');
var os = require('os');
var path = require('path');
var crypto = require('crypto');
var commands = require('./commands.json');
/**
* Look up the command for executing a file in any language.
*
* @param {String} language
* @param {String} file
* @param {String} args
* @return {String}
*/
module.exports = function (language, file, args) {
// Unsupported language.
if (!commands[language]) {
return;
}
// Render the language using EJS to enable support for inline JavaScript.
return _.template(commands[language], {
file: file,
tmpdir: os.tmpdir(),
tmpfile: path.join(os.tmpdir(), crypto.randomBytes(32).toString('hex')),
dirname: path.dirname,
extname: path.extname,
basename: path.basename,
type: os.type(),
arch: os.arch(),
platform: os.platform(),
sep: path.sep,
join: path.join,
delimiter: path.delimiter,
args: args
});
};
| var _ = require('lodash');
var os = require('os');
var path = require('path');
var crypto = require('crypto');
var commands = require('./commands.json');
/**
* Look up the command for executing a file in any language.
*
* @param {String} language
* @param {String} file
* @param {Array} args
* @return {String}
*/
module.exports = function (language, file, args) {
// Unsupported language.
if (!commands[language]) {
return;
}
// Render the language using EJS to enable support for inline JavaScript.
return _.template(commands[language], {
file: file,
tmpdir: os.tmpdir(),
tmpfile: path.join(os.tmpdir(), crypto.randomBytes(32).toString('hex')),
dirname: path.dirname,
extname: path.extname,
basename: path.basename,
type: os.type(),
arch: os.arch(),
platform: os.platform(),
sep: path.sep,
join: path.join,
delimiter: path.delimiter,
args: Array.isArray(args) ? args.map(JSON.stringify).join(' ') : args
});
};
| Support an array of arguments. | Support an array of arguments.
| JavaScript | mit | blakeembrey/node-language-command |
65b836b5c005faba6335ce65cc31a95e0d74251d | app/assets/javascripts/map-overlay.js | app/assets/javascripts/map-overlay.js | (function($) {
if (!$.cookie('first_time_visitor')) {
$.cookie('first_time_visitor', true, { expires: 1000, path: '/' });
var $overlayWrapper = $('.overlay-wrapper');
$overlayWrapper.show();
setTimeout(function() {
$overlayWrapper.addClass('in');
}, 0);
$overlayWrapper.find('.close-btn, .go').click(function () {
if ($.support.transition.end) {
$overlayWrapper.one($.support.transition.end, function() {
$overlayWrapper.hide();
});
}
$overlayWrapper.removeClass('in');
});
}
})(jQuery); | (function($) {
if (!$.cookie('first_time_visitor')) {
$.cookie('first_time_visitor', true, { expires: 1000, path: '/' });
var $overlayWrapper = $('.overlay-wrapper');
$overlayWrapper.show();
setTimeout(function() {
$overlayWrapper.addClass('in');
}, 0);
$overlayWrapper.find('.close-btn, .go').click(function () {
if ($.support.transition && $.support.transition.end) {
$overlayWrapper.one($.support.transition.end, function() {
$overlayWrapper.hide();
});
}
$overlayWrapper.removeClass('in');
});
}
})(jQuery); | Fix missing transition variable in map overlay. | Fix missing transition variable in map overlay.
| JavaScript | agpl-3.0 | sozialhelden/wheelmap,sozialhelden/wheelmap,sozialhelden/wheelmap,sozialhelden/wheelmap,sozialhelden/wheelmap |
5b288f095f8b7ed76a9f8331f1c330119e8d9786 | feeds.js | feeds.js | "use strict";
var BlogController = require('./controllers/blog');
var BloggerController = require('./controllers/blogger');
var RSS = require('rss');
exports.serveRoutes = function(router) {
router.get('/main', function(req, res) {
var mainFeed = new RSS({
title: "CS Blogs Main Feed",
description: "All of the blog posts from bloggers on CSBlogs.com",
feed_url: "http://feeds.csblogs.com/main",
site_url: "http://csblogs.com",
});
BlogController.getAllBlogs({}, function(blogs, error) {
blogs.forEach(function(blog) {
mainFeed.item({
title: blog.title,
description: blog.summary,
url: blog.link,
guid: blog.link,
author: "CS Blogs User",
date: blog.pubDate
});
});
});
res.header('Content-Type','application/rss+xml');
res.send(mainFeed.xml({indent: true}));
});
};
| "use strict";
var BlogController = require('./controllers/blog');
var BloggerController = require('./controllers/blogger');
var RSS = require('rss');
exports.serveRoutes = function(router) {
router.get('/main', function(req, res) {
var mainFeed = new RSS({
title: "CS Blogs Main Feed",
description: "All of the blog posts from bloggers on CSBlogs.com",
feed_url: "http://feeds.csblogs.com/main",
site_url: "http://csblogs.com",
});
BlogController.getAllBlogs({}, function(blogs, error) {
blogs.forEach(function(blog) {
mainFeed.item({
title: blog.title,
description: blog.summary,
url: blog.link,
guid: blog.link,
author: "CS Blogs User",
date: blog.pubDate
});
});
res.header('Content-Type','application/rss+xml');
res.send(mainFeed.xml({indent: true}));
});
});
};
| Fix for sending XML before async call returns | Fix for sending XML before async call returns
| JavaScript | mit | robcrocombe/csblogs,csblogs/csblogs-web-app,csblogs/csblogs-web-app |
b06898cf54a898a03817599f46c074e2c8901c73 | lib/capabilities.js | lib/capabilities.js | import Oasis from "oasis";
import { services } from "conductor/services";
import { copy } from "conductor/lang";
import { a_indexOf } from "oasis/shims";
function ConductorCapabilities() {
this.capabilities = [
'xhr', 'metadata', 'render', 'data', 'lifecycle', 'height',
'nestedWiretapping' ];
this.services = copy(services);
}
ConductorCapabilities.prototype = {
defaultCapabilities: function () {
return this.capabilities;
},
defaultServices: function () {
return this.services;
},
addDefaultCapability: function (capability, service) {
if (!service) { service = Oasis.Service; }
this.capabilities.push(capability);
this.services[capability] = service;
},
removeDefaultCapability: function (capability) {
var index = a_indexOf.call(this.capabilities, capability);
if (index) {
return this.capabilities.splice(index, 1);
}
}
};
export default ConductorCapabilities;
| import Oasis from "oasis";
import { services } from "conductor/services";
import { copy } from "conductor/lang";
import { a_indexOf } from "oasis/shims";
function ConductorCapabilities() {
this.capabilities = [
'xhr', 'metadata', 'render', 'data', 'lifecycle', 'height',
'nestedWiretapping' ];
this.services = copy(services);
}
ConductorCapabilities.prototype = {
defaultCapabilities: function () {
return this.capabilities;
},
defaultServices: function () {
return this.services;
},
addDefaultCapability: function (capability, service) {
if (!service) { service = Oasis.Service; }
this.capabilities.push(capability);
this.services[capability] = service;
},
removeDefaultCapability: function (capability) {
var index = a_indexOf.call(this.capabilities, capability);
if (index !== -1) {
return this.capabilities.splice(index, 1);
}
}
};
export default ConductorCapabilities;
| Fix index check in `removeDefaultCapability`. | Fix index check in `removeDefaultCapability`.
| JavaScript | mit | tildeio/conductor.js |
5caf144cad6ef3362ebf15afb112cc8e62a142f5 | Resources/Private/Javascripts/Modules/Module.js | Resources/Private/Javascripts/Modules/Module.js | /**
* Defines a dummy module
*
* @module Modules/Module
*/
var App;
/**
* App
* @param el
* @constructor
*/
App = function(el) {
'use strict';
this.el = el;
};
/**
* Function used to to render the App
*
* @memberof module:Modules/Module
* @returns {Object} the App itself.
*/
App.prototype.render = function() {
'use strict';
// Return false if not 'el' was set in the app.
if(!this.el) {
return false;
}
this.el.innerHTML = 'App is rendered properly!';
};
module.exports = App;
| /**
* Defines a dummy module
*
* @module Modules/Module
*/
var App;
/**
* App
* @param el
* @constructor
*/
App = function(el) {
'use strict';
this.el = el;
};
/**
* Function used to to render the App
*
* @memberof module:Modules/Module
* @returns {Object} The App itself.
*/
App.prototype.render = function() {
'use strict';
// Return false if not 'el' was set in the app.
if(!this.el) {
return false;
}
this.el.innerHTML = 'App is rendered properly!';
return this;
};
module.exports = App;
| Make sure the example App modules render method returns the module | [TASK] Make sure the example App modules render method returns the module
| JavaScript | mit | t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template |
53374261765f24b58db7bc71337d9f7eb7900433 | lib/cli/index.js | lib/cli/index.js | 'use strict';
var path = require('path');
var program = require('commander');
var jsdoctest = require('../..');
var packageJson = require('../../package.json');
/**
* The main command-line utility's entry point.
*
* @param {Array.<String>} The `process.argv` array.
*/
exports.run = function(argv) {
program
.usage('[FILES...]')
.version(packageJson.version);
program.parse(argv);
if(program.args.length === 0) {
program.displayUsage();
process.exit(1);
}
// Base test running case
for(var i = 0, len = program.args.length; i < len; i++) {
var fileName = program.args[i];
var failed = jsdoctest.run(path.join(process.cwd(), fileName));
if(failed) {
exports._fail(new Error('Tests failed'));
} else {
console.log('Tests passed');
}
}
};
/**
* Prints an error to stderr and exits.
*/
exports._fail = function fail(err) {
console.error(err.message);
process.exit(err.code || 1);
};
| 'use strict';
var path = require('path');
var program = require('commander');
var jsdoctest = require('../..');
var packageJson = require('../../package.json');
/**
* The main command-line utility's entry point.
*
* @param {Array.<String>} The `process.argv` array.
*/
exports.run = function(argv) {
program
.usage('[FILES...]')
.version(packageJson.version);
program.parse(argv);
if(program.args.length === 0) {
program.help();
}
// Base test running case
for(var i = 0, len = program.args.length; i < len; i++) {
var fileName = program.args[i];
var failed = jsdoctest.run(path.join(process.cwd(), fileName));
if(failed) {
exports._fail(new Error('Tests failed'));
} else {
console.log('Tests passed');
}
}
};
/**
* Prints an error to stderr and exits.
*/
exports._fail = function fail(err) {
console.error(err.message);
process.exit(err.code || 1);
};
| Fix help message on wrong calls | Fix help message on wrong calls
This fixes the display of usage information when the program is called
without arguments.
| JavaScript | mit | yamadapc/jsdoctest,yamadapc/jsdoctest |
1a149064f53560e72c3ff763683011e29e67604c | www/js/keyManager.js | www/js/keyManager.js | function displayKeys() {
// Retrieve all keyPairs
var sql = "select K.name from key K";
dbRetrieve(sql, [], function(res) {
// Populate key list
var html = '<hr>';
for (var i = 0; i < res.rows.length; ++i) {
var keyName = res.rows.item(i).name;
html += '<span onclick="showPubKey($(this).text());">' + keyName + '</span><br/><hr>';
}
// Update GUI
document.getElementById("key_list").innerHTML = html;
});
}
function showPubKey(keyName) {
// Retrieve all keyPairs
var sql = "select K.keyPair from key K where K.name = ?";
dbRetrieve(sql, [keyName.toString()], function(res) {
if (res.rows.length === 1) {
// Extract public key and create qr-code
var key = buf2hex(cryptoJS.publicKey(hex2buf(res.rows.item(0).keyPair)));
alert(key);
cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, key,
function (success) {
alert('succes');
alert("Encode succes: " + success);
},
function (fail) {
alert('fail');
alert("Encoding failed: " + fail);
}
);
}
});
} | function displayKeys() {
// Retrieve all keyPairs
var sql = "select K.name from key K";
dbRetrieve(sql, [], function(res) {
// Populate key list
var html = '<hr>';
for (var i = 0; i < 1; ++i) {
var keyName = res.rows.item(i).name;
html += '<button onclick="showPubKey(this.innerHTML);">' + keyName + '</button>';
}
// Update GUI
document.getElementById("key_list").innerHTML = html;
});
}
function showPubKey(keyName) {
// Retrieve all keyPairs
var sql = "select K.keyPair from key K where K.name = ?";
dbRetrieve(sql, [keyName.toString()], function(res) {
if (res.rows.length === 1) {
// Extract public key and create qr-code
var key = buf2hex(cryptoJS.publicKey(hex2buf(res.rows.item(0).keyPair)));
alert(key);
cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, key,
function (success) {
alert('succes');
alert("Encode succes: " + success);
},
function (fail) {
alert('fail');
alert("Encoding failed: " + fail);
}
);
}
});
} | Print key on click (try 5 - button) | Print key on click (try 5 - button)
| JavaScript | agpl-3.0 | lromerio/cothority-mobile,lromerio/cothority-mobile |
7cf7979e06f0774f46d133e070887cb29957c9d5 | index.js | index.js | "use strict";
// modified from https://github.com/es-shims/es6-shim
var keys = Object.keys || require('object-keys');
var assignShim = function assign(target, source) {
return keys(source).reduce(function (target, key) {
target[key] = source[key];
return target;
}, target);
};
assignShim.shim = function shimObjectAssign() {
if (!Object.assign) {
Object.assign = assignShim;
}
return Object.assign || assignShim;
};
module.exports = assignShim;
| "use strict";
// modified from https://github.com/es-shims/es6-shim
var keys = Object.keys || require('object-keys');
var assignShim = function assign(target, source) {
var props = keys(source);
for (var i = 0; i < props.length; ++i) {
target[props[i]] = source[props[i]];
}
return target;
};
assignShim.shim = function shimObjectAssign() {
if (!Object.assign) {
Object.assign = assignShim;
}
return Object.assign || assignShim;
};
module.exports = assignShim;
| Use a for loop, because ES3 browsers don't have "reduce" | Use a for loop, because ES3 browsers don't have "reduce"
| JavaScript | mit | ljharb/object.assign,es-shims/object.assign,reggi/object.assign |
c72a5d2988107208b2a344df2b55656f81ca545d | index.js | index.js | 'use strict';
var mote = require('mote');
exports.name = 'mote';
exports.outputFormat = 'html';
exports.compile = function (str, options) {
return mote.compile(str);
};
| 'use strict';
var mote = require('mote');
exports.name = 'mote';
exports.outputFormat = 'html';
exports.compile = mote.compile;
| Make compile use mote's compile | refactor(~): Make compile use mote's compile | JavaScript | mit | jstransformers/jstransformer-mote |
73d5d2b89ef60ffc1035e2a3787ae86c5f360725 | index.js | index.js | /**
* Copyright (c) 2016, Christopher Ramírez
* All rights reserved.
*
* This source code is licensed under the MIT license.
*/
'use strict'
const validIdNumberRegExp = /^(\d{3})[ -]?(\d{6})[ -]?(\d{4}\S{1})$/
class NicaraguanId {
constructor(number) {
this.fullName = undefined
this.birthPlace = undefined
this.birthDate = undefined
this.validSince = undefined
this.validThrough = undefined
this.setNewNumber(number)
}
checkNumber(number) {
if (!validIdNumberRegExp.test(number)) {
throw `${number} is an invalid nicaraguan ID number.`
}
}
setNewNumber(number) {
this.checkNumber(number)
let [_, cityId, birthDigits, consecutive] = validIdNumberRegExp.exec(number)
this.number = number
this.cityId = cityId
this.birthDigits = birthDigits
this.consecutive = consecutive
this.birthDate = dateFromSixIntDigits(this.birthDigits)
}
}
function dateFromSixIntDigits(sixIntDigits) {
const dateFormat = /^(\d{2})(\d{2})(\d{2})$/
let [_, day, month, year] = dateFormat.exec(this.birthDigits)
return new Date(parseInt(year), parseInt(month) -1, parseInt(day))
}
module.exports.NicaraguanId = NicaraguanId
| /**
* Copyright (c) 2016, Christopher Ramírez
* All rights reserved.
*
* This source code is licensed under the MIT license.
*/
'use strict'
const validIdNumberRegExp = /^(\d{3})[ -]?(\d{6})[ -]?(\d{4}\S{1})$/
class NicaraguanId {
constructor(number) {
this.fullName = undefined
this.birthPlace = undefined
this.birthDate = undefined
this.validSince = undefined
this.validThrough = undefined
this.setNewNumber(number)
}
setNewNumber(number) {
this.checkNumber(number)
let [_, cityId, birthDigits, consecutive] = validIdNumberRegExp.exec(number)
this.number = number
this.cityId = cityId
this.birthDigits = birthDigits
this.consecutive = consecutive
this.birthDate = dateFromSixIntDigits(this.birthDigits)
}
checkNumber(number) {
if (!validIdNumberRegExp.test(number)) {
throw `${number} is an invalid nicaraguan ID number.`
}
}
}
function dateFromSixIntDigits(sixIntDigits) {
const dateFormat = /^(\d{2})(\d{2})(\d{2})$/
let [_, day, month, year] = dateFormat.exec(this.birthDigits)
return new Date(parseInt(year), parseInt(month) -1, parseInt(day))
}
module.exports.NicaraguanId = NicaraguanId
| Move checkNumber function to the buttom of class implementation. | Move checkNumber function to the buttom of class implementation.
| JavaScript | mit | christopher-ramirez/nic-id |
a16f274a861655f73ad07adff88196540aacd698 | emoji.js | emoji.js | Emoji = {};
Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/';
Emoji.convert = function (str) {
if (typeof str !== 'string') {
return '';
}
return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) {
var imgName = match.slice(1, -1),
path = Emoji.baseImagePath + imgName + '.png';
return '<img class="emoji" alt="' + match + '" src="' + path + '"/>';
});
};
// borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js
if (Package.templating) {
var Template = Package.templating.Template;
var Blaze = Package.blaze.Blaze; // implied by `templating`
var HTML = Package.htmljs.HTML; // implied by `blaze`
Blaze.Template.registerHelper('emoji', new Template('emoji', function () {
var view = this,
content = '';
if (view.templateContentBlock) {
// this is for the block usage eg: {{#emoji}}:smile:{{/emoji}}
content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING);
}
else {
// this is for the direct usage eg: {{> emoji ':blush:'}}
content = view.parentView.dataVar.get();
}
return HTML.Raw(Emoji.convert(content));
}));
} | Emoji = {};
Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/';
Emoji.convert = function (str) {
if (typeof str !== 'string') {
return '';
}
return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) {
var imgName = match.slice(1, -1),
path = Emoji.baseImagePath + imgName + '.png';
return '<img class="emoji" alt="' + match + '" src="' + path + '" draggable="false" />';
});
};
// borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js
if (Package.templating) {
var Template = Package.templating.Template;
var Blaze = Package.blaze.Blaze; // implied by `templating`
var HTML = Package.htmljs.HTML; // implied by `blaze`
Blaze.Template.registerHelper('emoji', new Template('emoji', function () {
var view = this,
content = '';
if (view.templateContentBlock) {
// this is for the block usage eg: {{#emoji}}:smile:{{/emoji}}
content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING);
}
else {
// this is for the direct usage eg: {{> emoji ':blush:'}}
content = view.parentView.dataVar.get();
}
return HTML.Raw(Emoji.convert(content));
}));
} | Add draggable attr to <img>s and set it to false | Add draggable attr to <img>s and set it to false
| JavaScript | mit | dmfrancisco/meteor-twemoji |
b71c2f7fbf9d7aa16ef5c7e702f19ad50a9dc6d0 | index.js | index.js | #!/usr/bin/env node
'use strict'; /*jslint node: true, es5: true, indent: 2 */
var Parser = exports.Parser = require('./parser');
var Stringifier = exports.Stringifier = require('./stringifier');
// function logEvents(emitter, prefix, names) {
// names.forEach(function(name) {
// emitter.on(name, function(/*...*/) {
// console.error(prefix + ':' + name, arguments);
// });
// });
// }
if (require.main === module) {
var argv = require('optimist')
.usage([
'Consolidate any tabular format.',
'',
' argv will be passed directly to the Stringifier constructor.',
' process.stdin will be set to utf8',
].join('\n'))
.argv;
var parser = new Parser();
var stringifier = new Stringifier(argv);
process.stdin.setEncoding('utf8');
process.stdin.pipe(parser).pipe(stringifier).pipe(process.stdout);
}
| #!/usr/bin/env node
'use strict'; /*jslint node: true, es5: true, indent: 2 */
var Parser = exports.Parser = require('./parser');
var Stringifier = exports.Stringifier = require('./stringifier');
// function logEvents(emitter, prefix, names) {
// names.forEach(function(name) {
// emitter.on(name, function(/*...*/) {
// console.error(prefix + ':' + name, arguments);
// });
// });
// }
if (require.main === module) {
var optimist = require('optimist')
.usage([
'Consolidate any tabular format.',
'',
' argv will be passed directly to the Stringifier constructor.',
' process.stdin will be set to utf8',
'',
' cat data.tsv | sv > data.csv'
].join('\n'));
var parser = new Parser();
var stringifier = new Stringifier(optimist.argv);
if (process.stdin.isTTY) {
optimist.showHelp();
console.error("You must supply data via STDIN");
}
else {
process.stdin.setEncoding('utf8');
process.stdin.pipe(parser).pipe(stringifier).pipe(process.stdout);
}
}
| Check for process.stdin.isTTY when run directly | Check for process.stdin.isTTY when run directly
| JavaScript | mit | chbrown/sv,chbrown/sv |
e6c66260031b793e25b2c4c50859699b9d0d7e17 | index.js | index.js | "use strict"
var fs = require("fs")
var path = require("path")
var dz = require("dezalgo")
var npa = require("npm-package-arg")
module.exports = function (spec, where, cb) {
if (where instanceof Function) cb = where, where = null
if (where == null) where = "."
cb = dz(cb)
try {
var dep = npa(spec)
}
catch (e) {
return cb(e)
}
var specpath = path.resolve(where, dep.type == "local" ? dep.spec : spec)
fs.stat(specpath, function (er, s) {
if (er) return finalize()
if (!s.isDirectory()) return finalize("local")
fs.stat(path.join(specpath, "package.json"), function (er) {
finalize(er ? null : "directory")
})
})
function finalize(type) {
if (type != null) dep.type = type
if (dep.type == "local" || dep.type == "directory") dep.spec = specpath
cb(null, dep)
}
}
| "use strict"
var fs = require("fs")
var path = require("path")
var dz = require("dezalgo")
var npa = require("npm-package-arg")
module.exports = function (spec, where, cb) {
if (where instanceof Function) cb = where, where = null
if (where == null) where = "."
cb = dz(cb)
try {
var dep = npa(spec)
}
catch (e) {
return cb(e)
}
var specpath = dep.type == "local"
? path.resolve(where, dep.spec)
: path.resolve(spec)
fs.stat(specpath, function (er, s) {
if (er) return finalize()
if (!s.isDirectory()) return finalize("local")
fs.stat(path.join(specpath, "package.json"), function (er) {
finalize(er ? null : "directory")
})
})
function finalize(type) {
if (type != null) dep.type = type
if (dep.type == "local" || dep.type == "directory") dep.spec = specpath
cb(null, dep)
}
}
| Resolve ONLY file:// deps relative to package root, everything else CWD | Resolve ONLY file:// deps relative to package root, everything else CWD
| JavaScript | isc | npm/realize-package-specifier |
922e3caa9810b45a173524a4f9b7b451835c86c0 | index.js | index.js | 'use strict'
var svg = require('virtual-dom/virtual-hyperscript/svg')
var bezier = require('bezier-easing')
var Size = require('create-svg-size')
var Circle = require('./circle')
var Mask = require('./mask')
module.exports = function CircleBounce (data) {
return function render (time) {
var mask = Mask(renderInner(data.radius, time))
var outer = renderOuter(data.radius, time, data.fill, mask.id)
var options = Size({x: data.radius * 2, y: data.radius * 2})
return svg('svg', options, [
mask.vtree,
outer
])
}
}
function renderInner (radius, time) {
var coefficient = curve(time < 0.5 ? time : 1 - time)
return Circle({
radius: radius * coefficient,
center: radius
})
}
function renderOuter (radius, time, fill, mask) {
var coefficent = curve(time < 0.5 ? 1 - time : time)
return Circle({
id: 'circle-bounce-circle',
radius: radius * coefficent,
center: radius,
fill: fill,
mask: mask
})
}
function curve (value) {
return bezier(.10, 0.45, .9, .45).get(value)
}
| 'use strict'
var svg = require('virtual-dom/virtual-hyperscript/svg')
var bezier = require('bezier-easing')
var Size = require('create-svg-size')
var Circle = require('./circle')
var Mask = require('./mask')
module.exports = function CircleBounce (data) {
return function render (time) {
var mask = Mask(renderInner(data.radius, time))
var outer = renderOuter(data.radius, time, data.fill, mask.id)
var options = Size({x: data.radius * 2, y: data.radius * 2})
return svg('svg', options, [
mask.vtree,
outer
])
}
}
function renderInner (radius, time) {
var coefficient = 0.95 * curve(time < 0.5 ? time : 1 - time)
return Circle({
radius: radius * coefficient,
center: radius
})
}
function renderOuter (radius, time, fill, mask) {
var coefficent = curve(time < 0.5 ? 1 - time : time)
return Circle({
id: 'circle-bounce-circle',
radius: radius * coefficent,
center: radius,
fill: fill,
mask: mask
})
}
function curve (value) {
return bezier(.10, 0.45, .9, .45).get(value)
}
| Multiply inner circle coefficient by .95 to ensure a stroke remains | Multiply inner circle coefficient by .95 to ensure a stroke remains
| JavaScript | mit | bendrucker/circle-bounce |
c6eb2c136ed61fc0ac5e38a1c2e16872a7f99822 | index.js | index.js | const onepass = require("onepass")({
bundleId: "com.sudolikeaboss.sudolikeaboss"
});
exports.decorateTerm = (Term, { React }) => {
return class extends React.Component {
_onTerminal (term) {
if (this.props && this.props.onTerminal) this.props.onTerminal(term);
term.uninstallKeyboard();
term.keyboard.handlers_ = term.keyboard.handlers_.map(handler => {
if (handler[0] !== "keydown") {
return handler;
}
return [
"keydown",
function(e) {
if (e.metaKey && e.keyCode === 220) {
onepass.password("sudolikeaboss://local")
.then(pass => this.terminal.io.sendString(pass))
.catch(() => {});
}
return this.onKeyDown_(e);
}.bind(term.keyboard)
];
});
term.installKeyboard();
}
render () {
return React.createElement(Term, Object.assign({}, this.props, {
onTerminal: this._onTerminal
}));
}
};
};
| const onepass = require("onepass")({
bundleId: "com.sudolikeaboss.sudolikeaboss"
});
exports.decorateTerm = (Term, { React }) => {
return class extends React.Component {
_onTerminal (term) {
if (this.props && this.props.onTerminal) this.props.onTerminal(term);
term.uninstallKeyboard();
term.keyboard.handlers_ = term.keyboard.handlers_.map(handler => {
if (handler[0] !== "keydown") {
return handler;
}
const fn = handler[1];
return [
"keydown",
function(e) {
if (e.metaKey && e.keyCode === 220) {
onepass.password("sudolikeaboss://local")
.then(pass => this.terminal.io.sendString(pass))
.catch(() => {});
}
return fn(e);
}.bind(term.keyboard)
];
});
term.installKeyboard();
}
render () {
return React.createElement(Term, Object.assign({}, this.props, {
onTerminal: this._onTerminal
}));
}
};
};
| Extend existing keydown handler, instead of overriding it | Extend existing keydown handler, instead of overriding it
| JavaScript | mit | sibartlett/hyperterm-1password |
91b608d905aa602fd9f8d7b0019602b6d077f6ea | src/umd-wrapper.js | src/umd-wrapper.js | (function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore', 'backbone.paginator'], function(Backbone, Underscore, PageableCollection) {
return (root.Hal = factory(root, Backbone, _, PageableCollection));
});
}
else if (typeof exports !== 'undefined') {
var Backbone = require('backbone');
var _ = require('underscore');
var PageableCollection = require('backbone.paginator');
module.exports = factory(root, Backbone, _, PageableCollection);
}
else {
root.Hal = factory(root, root.Backbone, root._, root.PageableCollection);
}
}(this, function(root) {
'use strict';
/**
* @namespace Hal
*/
var Hal = {};
// @include link.js
// @include model.js
// @include collection.js
return Hal;
}));
| (function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore', 'backbone.paginator'], function(Backbone, Underscore, PageableCollection) {
Backbone.PageableCollection = PageableCollection;
return (root.Hal = factory(root, Backbone, _));
});
}
else if (typeof exports !== 'undefined') {
var Backbone = require('backbone');
var _ = require('underscore');
Backbone.PageableCollection = require('backbone.paginator');
module.exports = factory(root, Backbone, _);
}
else {
root.Hal = factory(root, root.Backbone, root._);
}
}(this, function(root, Backbone, _) {
'use strict';
/**
* @namespace Hal
*/
var Hal = {};
// @include link.js
// @include model.js
// @include collection.js
return Hal;
}));
| Fix AMD / UMD problems. | Fix AMD / UMD problems. | JavaScript | mit | gomoob/backbone.hateoas,gomoob/backbone.hateoas,gomoob/backbone.hateoas |
48aeb44374abc3baae4bb098f9e94dea26c91494 | index.js | index.js | #! /usr/bin/env node
var opts = require('optimist').argv
var through = require('through2');
function indexhtmlify(opts) {
var s = through(function onwrite(chunk, enc, cb) {
s.push(chunk)
cb()
}, function onend(cb) {
s.push('</script>\n')
s.push('</html>\n')
cb()
})
s.push('<!DOCTYPE html>\n')
s.push('<html>\n')
s.push('<head>\n')
s.push('<title>---</title>\n')
s.push('<meta content="width=device-width, initial-scale=1.0, ' +
'maximum-scale=1.0, user-scalable=0" name="viewport" />\n')
s.push('<meta charset=utf-8></head>\n')
if (opts.style) {
s.push('<style>\n')
s.push(require('fs').readFileSync(opts.style, 'utf8'))
s.push('</style>\n')
}
s.push('<body></body>\n')
s.push('<script language=javascript>\n')
return s
}
module.exports = indexhtmlify
if (require.main === module) {
if(process.stdin.isTTY) {
console.error('USAGE: browserify client.js | indexhtmlify ' +
'--style style.css > index.html')
process.exit(1)
}
process.stdin
.pipe(indexhtmlify(opts))
.pipe(process.stdout)
}
| #! /usr/bin/env node
var opts = require('optimist').argv
var through = require('through2');
function indexhtmlify(opts) {
opts = opts || {}
var s = through(function onwrite(chunk, enc, cb) {
s.push(chunk)
cb()
}, function onend(cb) {
s.push('</script>\n')
s.push('</html>\n')
cb()
})
s.push('<!DOCTYPE html>\n')
s.push('<html>\n')
s.push('<head>\n')
s.push('<title>' + (opts.title || '---') + '</title>\n')
s.push('<meta content="width=device-width, initial-scale=1.0, ' +
'maximum-scale=1.0, user-scalable=0" name="viewport" />\n')
s.push('<meta charset=utf-8></head>\n')
if (opts.style) {
s.push('<style>\n')
s.push(require('fs').readFileSync(opts.style, 'utf8'))
s.push('</style>\n')
}
s.push('<body></body>\n')
s.push('<script language=javascript>\n')
return s
}
module.exports = indexhtmlify
if (require.main === module) {
if(process.stdin.isTTY) {
console.error('USAGE: browserify client.js | indexhtmlify ' +
'--style style.css > index.html')
process.exit(1)
}
process.stdin
.pipe(indexhtmlify(opts))
.pipe(process.stdout)
}
| Allow passing in a title | Allow passing in a title
| JavaScript | mit | dominictarr/indexhtmlify |
cd460dadc9bd85f4dc7356b20abf7cb3e3401dd0 | index.js | index.js | const Automerge = require('automerge')
function applyCodeMirrorChangeToAutomerge(state, findList, change, cm) {
const startPos = cm.indexFromPos(change.from)
if (change.to.line === change.from.line && change.to.ch === change.from.ch) {
// nothing was removed.
} else {
// delete.removed contains an array of removed lines as strings, so this adds
// all the lengths. Later change.removed.length - 1 is added for the \n-chars
// (-1 because the linebreak on the last line won't get deleted)
let delLen = 0
for (let rm = 0; rm < change.removed.length; rm++) {
delLen += change.removed[rm].length
}
delLen += change.removed.length - 1
state = Automerge.changeset(state, 'Delete', doc => {
findList(doc).splice(startPos, delLen)
})
}
if (change.text) {
state = Automerge.changeset(state, 'Insert', doc => {
findList(doc).splice(startPos, 0, ...change.text.join('\n').split(''))
})
}
if (change.next) {
state = applyCodeMirrorChangeToAutomerge(state, change.next, cm)
}
return state
}
module.exports = {
applyCodeMirrorChangeToAutomerge,
}
| const Automerge = require('automerge')
function applyCodeMirrorChangeToAutomerge(state, findList, change, cm) {
const startPos = cm.indexFromPos(change.from)
if (change.to.line === change.from.line && change.to.ch === change.from.ch) {
// nothing was removed.
} else {
// delete.removed contains an array of removed lines as strings.
// each removed line does not include the \n, so we add +1
// Finally remove 1 because the last \n won't be deleted
let delLen =
change.removed.reduce((sum, remove) => sum + remove.length + 1, 0) - 1
state = Automerge.changeset(state, 'Delete', doc => {
findList(doc).splice(startPos, delLen)
})
}
if (change.text) {
state = Automerge.changeset(state, 'Insert', doc => {
findList(doc).splice(startPos, 0, ...change.text.join('\n').split(''))
})
}
if (change.next) {
state = applyCodeMirrorChangeToAutomerge(state, change.next, cm)
}
return state
}
module.exports = {
applyCodeMirrorChangeToAutomerge,
}
| Use Array.reduce to compute how much to delete | Use Array.reduce to compute how much to delete
| JavaScript | mit | aslakhellesoy/automerge-codemirror,aslakhellesoy/automerge-codemirror |
5b5e156f3581cce8ecca166198e4a2d758eb576e | websites/submit.vefverdlaun.is/src/App.js | websites/submit.vefverdlaun.is/src/App.js | import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
)
}
}
export default App
| import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<p className="App-intro">
This project will be the form to submit projects to the Icelandic Web
Awards.
</p>
</div>
)
}
}
export default App
| Add some text to try out ci setup | Add some text to try out ci setup
| JavaScript | mit | svef/www,svef/www |
065ba9eda7d93f2bb956ac74166b241af83c6202 | modules/core/content/services/url-helper.js | modules/core/content/services/url-helper.js | // DecentCMS (c) 2015 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';
function UrlHelper(scope) {
this.scope = scope;
}
UrlHelper.prototype.feature = 'content';
UrlHelper.prototype.service = 'url-helper';
UrlHelper.prototype.scope = 'shell';
UrlHelper.prototype.getUrl = function getUrl(id) {
var middlewares = this.scope.getServices('middleware')
.sort(function(m1, m2) {
return m1.routePriority - m2.routePriority;});
for (var i = 0; i < middlewares.length; i++) {
var middleware = middlewares[i];
if (middleware.getUrl) {
var url = middleware.getUrl(id);
if (url) return url;
}
}
return '/';
};
module.exports = UrlHelper; | // DecentCMS (c) 2015 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';
function UrlHelper(scope) {
this.scope = scope;
}
UrlHelper.feature = 'content';
UrlHelper.service = 'url-helper';
UrlHelper.scope = 'shell';
UrlHelper.prototype.getUrl = function getUrl(id) {
var middlewares = this.scope.getServices('middleware')
.sort(function(m1, m2) {
return m1.routePriority - m2.routePriority;});
for (var i = 0; i < middlewares.length; i++) {
var middleware = middlewares[i];
if (middleware.getUrl) {
var url = middleware.getUrl(id);
if (url) return url;
}
}
return '/';
};
module.exports = UrlHelper; | Define UrlHelper meta-data on the class instead of the prototype. | Define UrlHelper meta-data on the class instead of the prototype.
| JavaScript | mit | DecentCMS/DecentCMS |
6cae911047d15eef3bb48c39a448f8b66f54ee49 | tests/trafficSpec.js | tests/trafficSpec.js | describe('traffic', function() {
beforeEach(function() {
window.matrix.settings = {
profileId: ''
};
subject = window.matrix.traffic;
});
it('has initial points', function() {
expect(subject.points).to.eq(720);
});
it('has empty counts', function() {
expect(subject.counts).to.eql([]);
});
it('has interval of 2 minutes', function() {
expect(subject.interval).to.eq(120000);
});
});
| describe('traffic', function() {
beforeEach(function() {
window.matrix.settings = {
profileId: ''
};
subject = window.matrix.traffic;
});
it('has initial points', function() {
expect(subject.points).to.eq(720);
});
it('has empty counts', function() {
expect(subject.counts).to.eql([]);
});
it('has interval of 2 minutes', function() {
expect(subject.interval).to.eq(120000);
});
describe('#endpoint', function() {
it('returns the path to the servers realtime endpoint', function() {
expect(subject.endpoint()).to.eql('/realtime?ids=ga:&metrics=rt:activeUsers&max-results=10');
});
context('with profileId', function() {
beforeEach(function() {
window.matrix.settings = {
profileId: 'Test'
};
});
it('returns correct profile Id in the endpoint path', function() {
expect(subject.endpoint()).to.eql('/realtime?ids=ga:Test&metrics=rt:activeUsers&max-results=10');
});
});
});
});
| Add test for the endpoint method | Add test for the endpoint method
| JavaScript | mit | codeforamerica/city-analytics-dashboard,codeforamerica/city-analytics-dashboard,codeforamerica/city-analytics-dashboard |
e25ee1f46a21bcee96821e459617090a5bb922e5 | spec/arethusa.core/key_capture_spec.js | spec/arethusa.core/key_capture_spec.js | "use strict";
describe('keyCapture', function() {
beforeEach(module('arethusa.core'));
describe('onKeyPressed', function() {
it('calls the given callback', inject(function(keyCapture) {
var event = {
keyCode: 27,
target: { tagname: '' }
};
var callbackCalled = false;
var callback = function() { callbackCalled = true; };
keyCapture.onKeyPressed('esc', callback);
keyCapture.keyup(event);
expect(callbackCalled).toBe(true);
}));
});
});
| "use strict";
describe('keyCapture', function() {
beforeEach(module('arethusa.core'));
var keyCapture;
beforeEach(inject(function(_keyCapture_) {
keyCapture = _keyCapture_;
}));
var Event = function(key, shift) {
this.keyCode = key;
this.shiftKey = shift;
this.target = { tagname: '' };
};
describe('onKeyPressed', function() {
it('calls the given callback', function() {
// 27 is esc
var event = new Event(27);
var callbackCalled = false;
var callback = function() { callbackCalled = true; };
keyCapture.onKeyPressed('esc', callback);
keyCapture.keyup(event);
expect(callbackCalled).toBe(true);
});
it('handles shifted keys', function() {
// 74 is j
var eventWithShift = new Event(74, true);
var eventWithoutShift = new Event(74);
var e1callbackCalled = 0;
var e2callbackCalled = 0;
var e1callback = function() { e1callbackCalled++; };
var e2callback = function() { e2callbackCalled++; };
keyCapture.onKeyPressed('J', e1callback);
keyCapture.onKeyPressed('j', e2callback);
keyCapture.keyup(eventWithShift);
expect(e1callbackCalled).toEqual(1);
expect(e2callbackCalled).toEqual(0);
keyCapture.keyup(eventWithoutShift);
expect(e1callbackCalled).toEqual(1);
expect(e2callbackCalled).toEqual(1);
});
});
});
| Add spec for new keyCapture modifier handling | Add spec for new keyCapture modifier handling
| JavaScript | mit | alpheios-project/arethusa,Masoumeh/arethusa,Masoumeh/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa |
d4edd2fba11ee073a65807f347ca9857a1663572 | spec/javascripts/helpers/SpecHelper.js | spec/javascripts/helpers/SpecHelper.js | require.config({
paths:{
jquery: "vendor/assets/javascripts/jquery/jquery-1.7.2.min",
jsmin: "vendor/assets/javascripts/jsmin",
polyfills: "vendor/assets/javascripts/polyfills",
lib: 'public/assets/javascripts/lib',
handlebars: 'vendor/assets/javascripts/handlebars',
underscore: 'vendor/assets/javascripts/underscore',
jplugs: "vendor/assets/javascripts/jquery/plugins",
pointer: "vendor/assets/javascripts/pointer",
touchwipe: "vendor/assets/javascripts/jquery.touchwipe.1.1.1",
s_code: "vendor/assets/javascripts/omniture/s_code"
}
});
| require.config({
paths:{
jquery: "vendor/assets/javascripts/jquery/jquery-1.7.2.min",
jsmin: "vendor/assets/javascripts/jsmin",
lib: 'public/assets/javascripts/lib',
handlebars: 'vendor/assets/javascripts/handlebars',
underscore: 'vendor/assets/javascripts/underscore',
jplugs: "vendor/assets/javascripts/jquery/plugins",
pointer: "vendor/assets/javascripts/pointer",
touchwipe: "vendor/assets/javascripts/jquery.touchwipe.1.1.1",
s_code: "vendor/assets/javascripts/omniture/s_code"
}
});
| Remove polyfills from the specHelper temporarily (as it fixes a weird bug) | Remove polyfills from the specHelper temporarily (as it fixes a weird bug)
| JavaScript | mit | Lostmyname/rizzo,lonelyplanet/rizzo,Lostmyname/rizzo,lonelyplanet/rizzo,lonelyplanet/rizzo,Lostmyname/rizzo,Lostmyname/rizzo,lonelyplanet/rizzo,lonelyplanet/rizzo,Lostmyname/rizzo |
0c313cf2f04bc5f769f1fa1e4ba9dc31da615861 | packages/components/hooks/useBlackFriday.js | packages/components/hooks/useBlackFriday.js | import { useEffect, useState } from 'react';
import { isBlackFridayPeriod } from 'proton-shared/lib/helpers/blackfriday';
const EVERY_TEN_MINUTES = 10 * 60 * 1000;
const useBlackFriday = () => {
const [blackFriday, setBlackFriday] = useState(isBlackFridayPeriod());
useEffect(() => {
const intervalID = setInterval(() => {
setBlackFriday(isBlackFridayPeriod());
}, EVERY_TEN_MINUTES);
return () => {
clearInterval(intervalID);
};
}, []);
return blackFriday;
};
export default useBlackFriday;
| import { useEffect, useState } from 'react';
import { isBlackFridayPeriod } from 'proton-shared/lib/helpers/blackfriday';
const EVERY_MINUTE = 60 * 1000;
const useBlackFriday = () => {
const [blackFriday, setBlackFriday] = useState(isBlackFridayPeriod());
useEffect(() => {
const intervalID = setInterval(() => {
setBlackFriday(isBlackFridayPeriod());
}, EVERY_MINUTE);
return () => {
clearInterval(intervalID);
};
}, []);
return blackFriday;
};
export default useBlackFriday;
| Check BF condition every minute | Check BF condition every minute
| JavaScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient |
65cdcae6172ce01bcc8be4e31252f9740816438d | index.js | index.js | var isPatched = false;
if (isPatched) return console.log('already patched');
function addColor(string, name) {
var colors = {
green: ['\x1B[32m', '\x1B[39m'],
red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'],
yellow: ['\x1B[33m', '\x1B[39m']
}
return colors[name][0] + string + colors[name][1];
}
function getColorName(methodName) {
switch (methodName) {
case 'error': return 'red';
case 'warn': return 'yellow';
default: return 'green';
}
}
['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) {
var baseConsoleMethod = console[method];
var slice = Array.prototype.slice;
var color = getColorName(method);
var messageType = method.toUpperCase();
var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout';
console[method] = function() {
var date = (new Date()).toISOString();
var args = slice.call(arguments);
if (process[output].isTTY)
messageType = addColor(messageType, color);
process[output].write('[' + date + '] ' + messageType + ' ');
return baseConsoleMethod.apply(console, args);
}
});
isPatched = true;
| var isPatched = false;
var slice = Array.prototype.slice;
if (isPatched) return console.log('already patched');
function addColor(string, name) {
var colors = {
green: ['\x1B[32m', '\x1B[39m'],
red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'],
yellow: ['\x1B[33m', '\x1B[39m']
}
return colors[name][0] + string + colors[name][1];
}
function getColorName(methodName) {
switch (methodName) {
case 'error': return 'red';
case 'warn': return 'yellow';
default: return 'green';
}
}
['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) {
var baseConsoleMethod = console[method];
var color = getColorName(method);
var messageType = method.toUpperCase();
var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout';
console[method] = function() {
var date = (new Date()).toISOString();
var args = slice.call(arguments);
if (process[output].isTTY)
messageType = addColor(messageType, color);
process[output].write('[' + date + '] ' + messageType + ' ');
return baseConsoleMethod.apply(console, args);
}
});
isPatched = true;
| Move slice variable assignment out of loop | Move slice variable assignment out of loop
| JavaScript | mit | coachme/console-time |
022e9339a27d89511811bff56e417e069d21610e | index.js | index.js | var fs = require('fs');
var path = require('path');
var sass = require('node-sass');
module.exports = function dmpSass ($, document, done) {
sass.render({
file: 'assets/css/style.scss',
outputStyle: 'compressed',
sourceMap: false,
success: function (result) {
var cache = require('documark-cache')(document);
var file = cache.fileWriteStream('sass-cache.css');
file.end(result.css);
$.root().append('<link rel="stylesheet" type="text/css" href="' + cache.filePath('sass-cache.css') + '">');
},
error: function (error) {
console.log(error.message);
}
});
done();
};
| var fs = require('fs');
var path = require('path');
var sass = require('node-sass');
var cacheHelper = require('documark-cache');
module.exports = function dmpSass ($, document, done) {
sass.render({
file: 'assets/css/style.scss',
outputStyle: 'compressed',
sourceMap: false,
success: function (result) {
var cache = cacheHelper(document);
var file = cache.fileWriteStream('sass-cache.css');
var container = $.('head');
if ( !container.length ) {
container = $.root();
}
file.end(result.css);
container.append('<link rel="stylesheet" type="text/css" href="' + cache.filePath('sass-cache.css') + '">');
done();
},
error: function (error) {
done(error.message);
}
});
};
| Move documark-cache dependency to top of the document. Check for head container | Move documark-cache dependency to top of the document. Check for head container
| JavaScript | mit | jeroenkruis/dmp-sass |
34cd265eb9284effdffb6b6314ea4632e80fbd86 | index.js | index.js |
var postcss = require('postcss'),
colors = require('color');
module.exports = postcss.plugin('postcss-lowvision', function () {
return function (css) {
css.walkDecls('color', function (decl) {
var color = decl.value
var rgb = colors.rgb(color);
decl.value = rgb;
decl.cloneAfter({ prop: 'text-shadow',
value: '0 0 5px rgba(0,0,0,0.5)' });
});
};
});
|
var postcss = require('postcss'),
color = require('color');
module.exports = postcss.plugin('postcss-lowvision', function () {
return function (css) {
css.walkDecls('color', function (decl) {
var val = decl.value
var rgb = color(val);
rgb.rgb();
decl.value = rgb;
decl.cloneAfter({ prop: 'text-shadow',
value: '0 0 5px rgba(0,0,0,0.5)' });
});
};
});
| Test to see if colors package works | Test to see if colors package works
| JavaScript | mit | keukenrolletje/postcss-lowvision |
56415d857b49a427736679050a0b59cddbbfb65f | index.js | index.js | 'use strict'
const driver = require('node-phantom-simple')
function genPromiseFunc(originalFunc) {
return function () {
const _args = Array.prototype.slice.call(arguments)
const _this = this
return new Promise(function (resolve, reject) {
_args.push(function () {
const _args2 = Array.prototype.slice.call(arguments)
const err = _args2.shift()
if (err) {
reject(err)
} else {
const _arg3 = _args2.map(function (arg) {
return promisifyAll(arg)
})
resolve.apply(null, _arg3)
}
})
originalFunc.apply(_this, _args)
})
}
}
function promisifyAll(target) {
if (typeof target !== 'object' || Array.isArray(target)) {
return target
}
const promisifiedTarget = {}
for (let targetPropName of Object.keys(target)) {
if (typeof target[targetPropName] !== 'function') {
promisifiedTarget[targetPropName] = target[targetPropName]
continue
}
promisifiedTarget[targetPropName] = genPromiseFunc(target[targetPropName])
}
return promisifiedTarget
}
return promisifyAll(driver)
| 'use strict'
const driver = require('node-phantom-simple')
function genPromiseFunc(originalFunc) {
return function () {
const _args = Array.prototype.slice.call(arguments)
const _this = this
return new Promise(function (resolve, reject) {
_args.push(function () {
const _args2 = Array.prototype.slice.call(arguments)
const err = _args2.shift()
if (err) {
reject(err)
} else {
const _arg3 = _args2.map(function (arg) {
return promisifyAll(arg)
})
resolve.apply(null, _arg3)
}
})
originalFunc.apply(_this, _args)
})
}
}
function promisifyAll(target) {
if (typeof target !== 'object' || Array.isArray(target)) {
return target
}
const promisifiedTarget = {}
for (let targetPropName of Object.keys(target)) {
if (typeof target[targetPropName] !== 'function') {
promisifiedTarget[targetPropName] = target[targetPropName]
continue
}
promisifiedTarget[targetPropName] = genPromiseFunc(target[targetPropName])
}
return promisifiedTarget
}
module.exports = promisifyAll(driver)
| Use module.exports instead of return | Use module.exports instead of return
| JavaScript | mit | foray1010/node-phantom-promise |
f7a134a8ebe7fa255932ceb9aba9bb8197dbdfac | index.js | index.js | var fs = require('fs'),
path = require('path');
// Load all stated versions into the module exports
module.exports.version = {};
['2.0.0', '2.0.1', '2.0.2', '2.1.0', '2.1.1', 'latest'].map(function(version) {
module.exports.version[version] = JSON.parse(
fs.readFileSync(
path.join(__dirname, version, 'reference.json'), 'utf8'));
});
| var fs = require('fs'),
path = require('path');
// Load all stated versions into the module exports
module.exports.version = {};
['2.0.0', '2.0.1', '2.0.2', '2.1.0', '2.1.1', 'latest'].map(function(version) {
module.exports.version[version] = JSON.parse(
fs.readFileSync(
path.join(__dirname, version, 'reference.json'), 'utf8'));
if (version === 'latest') {
module.exports.version[version].datasources = JSON.parse(
fs.readFileSync(
path.join(__dirname, version, 'datasources.json'), 'utf8')).datasources;
}
});
| Include datasources key in latest reference. | Include datasources key in latest reference.
| JavaScript | unlicense | mapycz/mapnik-reference,CartoDB/mapnik-reference,mapnik/mapnik-reference,mapnik/mapnik-reference,mojodna/mapnik-reference,florianf/mapnik-reference,mapycz/mapnik-reference,florianf/mapnik-reference,gravitystorm/mapnik-reference,mojodna/mapnik-reference,gravitystorm/mapnik-reference,CartoDB/mapnik-reference,mapnik/mapnik-reference |
5239a5418abaac18e3a15cf1f0581f361f54449e | index.js | index.js | "use strict";
// Return the panorama ID
var getPanoID = function(string) {
let value = decodeURIComponent(string).match("^https:\/\/.*\!1s(.*)\!2e.*$");
if (value === null) {
throw "URL incorrect";
}
value = "F:" + value[1];
return value;
};
// Return Embed URL to use on iframe
var getEmbed = function(string) {
let id = getPanoID(string);
let embedURL = "https://www.google.com/maps/embed/v1/streetview?pano=" + id + "&key=YOUR_APIKEY";
return embedURL;
};
// Method main
var main = function(url, options) {
try {
options = options || {};
if (typeof options !== "object") {
throw "Expected an object";
}
return options.embed === true ? getEmbed(url) : getPanoID(url);
} catch (error) {
return error;
}
};
module.exports = main; | "use strict";
// Return the panorama ID
var getPanoID = function(string) {
let value = decodeURIComponent(string).match("^https:\/\/.*\!1s(.*)\!2e.*$");
if (value === null) {
throw "Incorrect URL";
}
return "F:" + value[1];
};
// Return Embed URL to use on iframe
var getEmbed = function(string) {
let id = getPanoID(string);
let embedURL = "https://www.google.com/maps/embed/v1/streetview?pano=" + id + "&key=YOUR_APIKEY";
return embedURL;
};
// Method main
var main = function(url, options) {
try {
options = options || {};
if (typeof options !== "object") {
throw "Expected an object";
}
return options.embed ? getEmbed(url) : getPanoID(url);
} catch (error) {
return error;
}
};
module.exports = main; | Fix typo and remove some illogical code | Fix typo and remove some illogical code
| JavaScript | mit | dorianneto/get-streetview-panorama-id |
2c534a16c1bfabb72ba01f40f8a50ab941df15fe | index.js | index.js | /*
* This is a very basic webserver and HTTP Client.
* In production, you may want to use something like Express.js
* or Botkit to host a webserver and manage API calls
*/
const {TOKEN, PORT} = process.env,
triage = require('./triage'),
qs = require('querystring'),
axios = require('axios'),
http = require('http');
// Handle any request to this server and parse the POST
function handleRequest(req, res){
let body = "";
req.on('data', data => body += data);
req.on('end', () => handleCommand(qs.parse(body)));
res.end('');
}
// Get channel history, build triage report, and respond with results
function handleCommand(payload) {
let {channel_id, response_url} = payload;
// load channel history
let params = qs.stringify({ count: 1000, token: TOKEN, channel: channel_id });
let getHistory = axios.post('https://slack.com/api/channels.history', params);
// build the triage report
let buildReport = result => Promise.resolve( triage(payload, result.data.messages) );
// post back to channel
let postResults = results => axios.post(response_url, results);
// execute
getHistory.then(buildReport).then(postResults);
}
// start server
http.createServer(handleRequest).listen(PORT, () => console.log(`server started on ${PORT}`));
| /*
* This is a very basic webserver and HTTP Client.
* In production, you may want to use something like Express.js
* or Botkit to host a webserver and manage API calls
*/
const {TOKEN, PORT} = process.env,
triage = require('./triage'),
qs = require('querystring'),
axios = require('axios'),
http = require('http');
// Handle any request to this server and parse the POST
function handleRequest(req, res){
let body = "";
req.on('data', data => body += data);
req.on('end', () => handleCommand(qs.parse(body)));
res.end('');
}
// Get channel history, build triage report, and respond with results
function handleCommand(payload) {
let {channel_id, response_url} = payload;
// load channel history
let params = qs.stringify({ count: 1000, token: TOKEN, channel: channel_id });
let getHistory = axios.post('https://slack.com/api/channels.history', params);
// build the triage report
let buildReport = result => Promise.resolve( triage(payload, result.data.messages || []) );
// post back to channel
let postResults = results => axios.post(response_url, results);
// execute
getHistory.then(buildReport).then(postResults).catch(console.error);
}
// start server
http.createServer(handleRequest).listen(PORT, () => console.log(`server started on ${PORT}`));
| Handle rejected promise, handle zero message case. | Handle rejected promise, handle zero message case.
| JavaScript | mit | Ihamblen/slacktriage |
24093d73f2b3b7518f7447d9261f0bf896f13526 | index.js | index.js | /* eslint-env node */
'use strict';
module.exports = {
name: 'ember-cli-chart',
included: function included(app) {
this._super.included(app);
app.import(app.bowerDirectory + '/chartjs/dist/Chart.js');
}
};
| /* eslint-env node */
'use strict';
module.exports = {
name: 'ember-cli-chart',
included: function(app, parentAddon) {
this._super.included.apply(this, arguments);
var target = (parentAddon || app);
if (target.app) {
target = target.app;
}
var bowerDir = target.bowerDirectory;
app.import(bowerDir + '/chartjs/dist/Chart.js');
}
};
| Allow usage in nested addons | Allow usage in nested addons | JavaScript | mit | aomra015/ember-cli-chart,aomran/ember-cli-chart,aomran/ember-cli-chart,aomra015/ember-cli-chart |
662aaae249f1411499aaf21b02c6527ceec1cca4 | app/js/arethusa.conf_editor/directives/plugin_conf.js | app/js/arethusa.conf_editor/directives/plugin_conf.js | "use strict";
angular.module('arethusa.confEditor').directive('pluginConf', function() {
return {
restrict: 'AE',
scope: true,
link: function(scope, element, attrs) {
var name = scope.$eval(attrs.name);
scope.template = 'templates/configs/' + name + '.html';
},
templateUrl: 'templates/plugin_conf.html'
};
});
| "use strict";
angular.module('arethusa.confEditor').directive('pluginConf', function() {
return {
restrict: 'AE',
scope: true,
link: function(scope, element, attrs) {
var name = scope.$eval(attrs.name);
// Right now paths to such configuration are hardcoded to a specific
// folder. This will be much more dynamic in the future.
scope.template = 'templates/configs/' + name + '.html';
},
templateUrl: 'templates/plugin_conf.html'
};
});
| Add comment to plugin conf | Add comment to plugin conf
| JavaScript | mit | fbaumgardt/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa |
93f0d993dbfc7bbbd88c452c5aace505b73c761f | index.js | index.js | 'use strict';
module.exports = function(){
};
| 'use strict';
var fs = require('fs');
var stream = require('stream');
var readline = require('readline');
var moment = require('moment');
function readFileContent(filename, callback){
var lines = [];
var instream = fs.createReadStream(filename);
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;
var rl = readline.createInterface({
input: instream,
output: outstream,
terminal: false
});
rl.on('line', function(line){
lines.push(formatLine(line));
});
rl.on('close', function(){
callback(null, lines);
});
}
function formatLine(line) {
// Remove empty lines
if(!line || !line.length) {
return;
}
var lineParts = line.split(': ');
return messageDetails(lineParts);
}
function messageDetails(parts){
var date = formatDate(parts[0]);
var details = {
date: date
};
if(parts[2]){
details.sender = parts[1];
// remove timestamp and sender info
parts.splice(0, 2);
details.message = parts.join(': ');
return details;
}
details.message = parts[1];
details.announcement = true;
return details;
}
function formatDate(timestamp){
if(timestamp.length !== 17){
throw new Error('Timestamp is of the wrong length:', timestamp);
}
return moment(timestamp, 'DD/MM/YY HH:mm:ss').format();
}
module.exports = function(filename){
return readFileContent.apply(this, arguments);
};
| Add initial file-reading and line formatting | Add initial file-reading and line formatting
| JavaScript | mit | matiassingers/whatsapp-log-parser |
d42fcb9add392e3cca86600b494af6bb7c51468d | index.js | index.js | var forIn = require('for-in'),
xobj = require('xhr'),
XhrError = require('xhrerror');
function noop() { }
function xhr(options, callback, errback) {
var req = xobj();
if(Object.prototype.toString.call(options) == '[object String]') {
options = { url: options };
}
req.open(options.method || 'GET', options.url, true);
if(options.credentials) {
req.withCredentials = true;
}
forIn(options.headers || {}, function (value, key) {
req.setRequestHeader(key, value);
});
req.onreadystatechange = function() {
if(req.readyState != 4) return;
if([
200,
304,
0
].indexOf(req.status) === -1) {
(errback || noop)(new XhrError('Server responded with a status of ' + req.status, req.status));
} else {
(callback || noop)(req.responseText);
}
};
req.send(options.data || void 0);
}
module.exports = xhr;
| var forIn = require('for-in'),
xobj = require('xhr'),
XhrError = require('xhrerror');
function noop() { }
function xhr(options, callback, errback) {
var req = xobj();
if(Object.prototype.toString.call(options) == '[object String]') {
options = { url: options };
}
req.open(options.method || 'GET', options.url, true);
if(options.credentials) {
req.withCredentials = true;
}
forIn(options.headers || {}, function (value, key) {
req.setRequestHeader(key, value);
});
req.onreadystatechange = function() {
if(req.readyState != 4) return;
if([
200,
304,
0
].indexOf(req.status) === -1) {
(errback || noop)(new XhrError('Server responded with a status of ' + req.status, req.status));
} else {
(callback || noop)(req);
}
};
req.send(options.data || void 0);
}
module.exports = xhr;
| Send the req to the callback. | Send the req to the callback.
| JavaScript | mit | matthewp/xhr,npmcomponent/matthewp-xhr |
e5d46a0a24acd994ccd5c2f59c89f8c7c69485c6 | example/src/pages/MeshPage.js | example/src/pages/MeshPage.js | import React, {Component, PropTypes} from 'react';
import {Akkad, Scene, shapes, cameras, lights, systems} from "akkad";
const googleStorageEndpoint = `http://storage.googleapis.com/akkad-assets-1/`;
const {ArcRotateCamera} = cameras;
const {HemisphericLight} = lights;
const {Mesh, Position, Rotate} = systems;
class MeshPage extends Component {
render() {
return (
<div>
<h2>
Mesh Example
</h2>
<Akkad>
<Scene>
<ArcRotateCamera
initialPosition={[0, 0, 100]}
target={[0, 0, 0]}
/>
<HemisphericLight />
<Mesh
path={googleStorageEndpoint}
fileName={'skull.babylon'}
>
<Position vector={[0, 0, 0]}/>
<Rotate
axis={[0, 1.2, 0]}
amount={60}
space="LOCAL"
/>
</Mesh>
</Scene>
</Akkad>
</div>
);
}
}
export default MeshPage;
| import React, {Component, PropTypes} from 'react';
import {Akkad, Scene, shapes, cameras, lights, systems} from "akkad";
const googleStorageEndpoint = `https://storage.googleapis.com/akkad-assets-1/`;
const {ArcRotateCamera} = cameras;
const {HemisphericLight} = lights;
const {Mesh, Position, Rotate} = systems;
class MeshPage extends Component {
render() {
return (
<div>
<h2>
Mesh Example
</h2>
<Akkad>
<Scene>
<ArcRotateCamera
initialPosition={[0, 0, 100]}
target={[0, 0, 0]}
/>
<HemisphericLight />
<Mesh
path={googleStorageEndpoint}
fileName={'skull.babylon'}
>
<Position vector={[0, 0, 0]}/>
<Rotate
axis={[0, 1.2, 0]}
amount={60}
space="LOCAL"
/>
</Mesh>
</Scene>
</Akkad>
</div>
);
}
}
export default MeshPage;
| Change google storage endpoint to us https | Change google storage endpoint to us https
| JavaScript | mit | brochington/Akkad,cgrinker/Akkad,brochington/Akkad,cgrinker/Akkad |
3a18004c4d66395faf0559e37c68d02370f5e1b5 | index.js | index.js | var mozjpeg = require('mozjpeg')
var dcp = require('duplex-child-process')
/**
* @param {Object} options
* @param {Number} opts.quality the 1 to 100. Docs suggest 5 to 95 is actual useable range.
* @param {String} opts.args raw `mozjpeg` args for the connoisseur. See: https://github.com/mozilla/mozjpeg/blob/master/usage.txt#L70
*/
module.exports = function (opts) {
opts = opts || {}
// Force the quality flag to be specified, because: https://github.com/mozilla/mozjpeg/issues/181
opts.quality = opts.quality || 75
var args = []
if (opts.quality) args.push('-quality', opts.quality)
if (opts.args) args.push(opts.args.split[' '])
var foo = dcp.spawn(mozjpeg, args)
return foo
}
| var mozjpeg = require('mozjpeg')
var dcp = require('duplex-child-process')
/**
* @param {Object} options
* @param {Number} opts.quality the 1 to 100. Docs suggest 5 to 95 is actual useable range.
* @param {String} opts.args raw `mozjpeg` args for the connoisseur. See: https://github.com/mozilla/mozjpeg/blob/master/usage.txt#L70
*/
module.exports = function (opts) {
opts = opts || {}
// Force the quality flag to be specified, because: https://github.com/mozilla/mozjpeg/issues/181
opts.quality = opts.quality || 75
var args = []
if (opts.quality) args.push('-quality', opts.quality)
if (opts.args) {
args = args.concat(opts.args.split(' '))
}
return dcp.spawn(mozjpeg, args)
}
| Fix args option not functioning | Fix args option not functioning | JavaScript | isc | tableflip/mozjpeg-stream |
e374134bd7ff60faeaa561ee984f2d23802d486e | index.js | index.js | var Promise = require('bluebird')
var request = require('got')
var extend = require('xtend')
var BASE_URL = 'http://www.broadbandmap.gov/broadbandmap/broadband/jun2014/'
module.exports = function broadbandMap (lat, long, options) {
options = extend({
types: ['wireline', 'wireless']
}, options || {})
var promises = []
options.types.forEach(function (type) {
promises.push(buildRequest(lat, long, type))
})
return Promise.all(promises)
.spread(function (res1, res2) {
var results = []
if (res1 && res1.body) results.push(JSON.parse(res1.body).Results)
if (res2 && res2.body) results.push(JSON.parse(res2.body).Results)
return results
})
.catch(function (err) {
throw err
})
}
function buildRequest (lat, long, type) {
return request.get(BASE_URL + type + '?latitude=' +
lat + '&longitude=' + long + '&format=json')
}
| var Promise = require('bluebird')
var request = require('got')
var extend = require('xtend')
var BASE_URL = 'http://www.broadbandmap.gov/broadbandmap/broadband/jun2014/'
module.exports = function broadbandMap (lat, long, options) {
options = extend({
types: ['wireline', 'wireless']
}, options || {})
return Promise.map(options.type, buildRequest)
.spread(function (res1, res2) {
var results = []
if (res1 && res1.body) results.push(JSON.parse(res1.body).Results)
if (res2 && res2.body) results.push(JSON.parse(res2.body).Results)
return results
})
.catch(function (err) {
throw err
})
function buildRequest (type) {
return request.get(BASE_URL + type + '?latitude=' +
lat + '&longitude=' + long + '&format=json')
}
}
| Use promise.map to build requests | Use promise.map to build requests
Requires moving buildRequest into inner fn scope
| JavaScript | mit | bsiddiqui/broadband-map |
954762c783fa53ab6772f2ff08a63b7dc018b396 | index.js | index.js | /*!
* data-driven
* Copyright(c) 2013 Fluent Software Solutions Ltd <info@fluentsoftware.co.uk>
* MIT Licensed
*/
module.exports = function(data, fn) {
var mochaIt = it
data.forEach(function(testData) {
try {
it = function(title, f) {
for (var key in testData) {
title = title.replace('{'+key+'}',testData[key])
}
var testFn = f.length < 2 ?
function() {
f(testData)
} :
function(done) {
f(testData,done)
}
mochaIt(title, testFn)
}
fn()
} finally {
it = mochaIt
}
})
} | /*!
* data-driven
* Copyright(c) 2013 Fluent Software Solutions Ltd <info@fluentsoftware.co.uk>
* MIT Licensed
*/
module.exports = function(data, fn) {
var mochaIt = it
var mochaBefore = before
data.forEach(function(testData) {
try {
it = function(title, f) {
for (var key in testData) {
title = title.replace('{'+key+'}',testData[key])
}
if (f !== undefined) {
var testFn = f.length < 2 ?
function() {
f(testData)
} :
function(done) {
f(testData,done)
}
}
mochaIt(title, testFn)
}
before = function(f) {
var testFn = f.length < 2 ?
function() {
f(testData)
} :
function(done) {
f(testData,done)
}
mochaBefore(testFn)
}
fn()
} finally {
it = mochaIt
before = mochaBefore
}
})
}
| Add support for pending, undefined it() tests and for data-driving Mocha's before() | Add support for pending, undefined it() tests and for data-driving Mocha's before()
| JavaScript | mit | danbehar/data-driven,fluentsoftware/data-driven |
a16fe50dad78d42b10fe9fd6af24a3b63754afa3 | index.js | index.js | 'use strict';
function DefaultRegistry(){
this._tasks = {};
}
DefaultRegistry.prototype.get = function get(name){
return this._tasks[name];
};
DefaultRegistry.prototype.set = function set(name, fn){
this._tasks[name] = fn;
};
DefaultRegistry.prototype.tasks = function tasks(){
return Object.keys(this._tasks).map(this.get, this);
};
module.exports = DefaultRegistry;
| 'use strict';
function DefaultRegistry(){
this._tasks = {};
}
DefaultRegistry.prototype.get = function get(name){
return this._tasks[name];
};
DefaultRegistry.prototype.set = function set(name, fn){
this._tasks[name] = fn;
};
DefaultRegistry.prototype.tasks = function tasks(){
var self = this;
return Object.keys(this._tasks).reduce(function(tasks, name){
tasks[name] = self.get(name);
return tasks;
}, {});
};
module.exports = DefaultRegistry;
| Make `.tasks` return an object instead of array | Breaking: Make `.tasks` return an object instead of array
| JavaScript | mit | phated/undertaker-registry,gulpjs/undertaker-registry |
8decbaffecdfa2528f6dafaeb3dcde940a208c61 | index.js | index.js | /**
* Turnpike.JS
*
* A lightweight and politely opinionated MVC framework for Node.js. Turnpike can be used as a traditional
* framework, with code generation and rapid deployment, or invoked as a library for more obscure use cases.
*
* Within the framework, some elements will be documented as "plumbing". If you are using Turnpike as a rapid
* deployment framework, then these should be treated as the internal workings of the Turnpike "black box".
* You shouldn't need or want to use or call any of the plumbing yourself.
* If you are using Turnpike as a library, you will probably need use use a good deal of the plumbing directly.
* If you do this, that's fine, but be aware that continuing development of the Turnpike framework may radically
* alter the plumbing interfaces at any time, even between minor versions and revisions.
*
* Other elements of the framework are documented as "porcelain". These are the entry points to the framework we
* expect any app relying on Turnpike to use. In general, after the 0.1.0 release, we will aim to maintain the
* existing plumbing interfaces with few to no changes without a bump in the major version number.
*/
var turnpike = {};
//Porcelain interfaces:
turnpike.EndpointController = require("./lib/EndpointController");
//Plumbing interfaces:
turnpike.ModelPool = require("./lib/ModelPool");
module.exports.turnpike = turnpike;
| /**
* Turnpike.JS
*
* A lightweight and politely opinionated MVC framework for Node.js. Turnpike can be used as a traditional
* framework, with code generation and rapid deployment, or invoked as a library for more obscure use cases.
*
* Within the framework, some elements will be documented as "plumbing". If you are using Turnpike as a rapid
* deployment framework, then these should be treated as the internal workings of the Turnpike "black box".
* You shouldn't need or want to use or call any of the plumbing yourself.
* If you are using Turnpike as a library, you will probably need use use a good deal of the plumbing directly.
* If you do this, that's fine, but be aware that continuing development of the Turnpike framework may radically
* alter the plumbing interfaces at any time, even between minor versions and revisions.
*
* Other elements of the framework are documented as "porcelain". These are the entry points to the framework we
* expect any app relying on Turnpike to use. In general, after the 0.1.0 release, we will aim to maintain the
* existing plumbing interfaces with few to no changes without a bump in the major version number.
*/
var turnpike = {};
//Porcelain interfaces:
turnpike.EndpointController = require("./lib/EndpointController");
turnpike.drive = require("./lib/Drive");
//Plumbing interfaces:
turnpike.ModelPool = require("./lib/ModelPool");
turnpike.Connection = require("./lib/Connection");
module.exports = turnpike;
| Declare a few more entry points | Declare a few more entry points
| JavaScript | mit | jay-depot/turnpike,jay-depot/turnpike |
cca531597c989497759bdcf3bbd6cd8da0a0a4ef | index.js | index.js | var es = require('event-stream');
var coffee = require('coffee-script');
var gutil = require('gulp-util');
var formatError = require('./lib/formatError');
var Buffer = require('buffer').Buffer;
module.exports = function(opt){
function modifyFile(file, cb){
if (file.isNull()) return cb(null, file); // pass along
if (file.isStream()) return cb(new Error("gulp-coffee: Streaming not supported"));
var str = file.contents.toString('utf8');
try {
file.contents = new Buffer(coffee.compile(str, opt));
} catch (err) {
var newError = formatError(file, err);
return cb(newError);
}
file.path = gutil.replaceExtension(file.path, ".js");
cb(null, file);
}
return es.map(modifyFile);
}; | var es = require('event-stream');
var coffee = require('coffee-script');
var gutil = require('gulp-util');
var formatError = require('./lib/formatError');
var Buffer = require('buffer').Buffer;
module.exports = function(opt){
function modifyFile(file){
if (file.isNull()) return this.emit('data', file); // pass along
if (file.isStream()) return this.emit('error', new Error("gulp-coffee: Streaming not supported"));
var str = file.contents.toString('utf8');
try {
file.contents = new Buffer(coffee.compile(str, opt));
} catch (err) {
var newError = formatError(file, err);
return this.emit('error', newError);
}
file.path = gutil.replaceExtension(file.path, ".js");
this.emit('data', file);
}
return es.through(modifyFile);
};
| Use es.through instead of es.map | Use es.through instead of es.map
See https://github.com/gulpjs/gulp/issues/75#issuecomment-31581317
Partial results for continue-on-error behaviour. | JavaScript | mit | steveluscher/gulp-coffee,develar/gulp-coffee,t3chnoboy/gulp-coffee-es6,doublerebel/gulp-iced-coffee,contra/gulp-coffee,coffee-void/gulp-coffee,jrolfs/gulp-coffee,leny/gulp-coffee,stevelacy/gulp-coffee,dereke/gulp-pogo,mattparlane/gulp-coffee,halhenke/gulp-coffee,typicode/gulp-coffee,wearefractal/gulp-coffee |
836cdee104ab82d2d1eebebf403ae415563a20f2 | src/yunity/materialConfig.js | src/yunity/materialConfig.js | export default function materialConfig($mdThemingProvider) {
'ngInject';
$mdThemingProvider.theme('default')
.primaryPalette('pink')
.accentPalette('orange');
} | export default function materialConfig($mdThemingProvider) {
'ngInject';
$mdThemingProvider.theme('default')
.primaryPalette('brown')
.accentPalette('orange');
} | Change primary palette to brown | Change primary palette to brown
| JavaScript | agpl-3.0 | yunity/yunity-webapp-mobile,yunity/yunity-webapp-mobile,yunity/yunity-webapp-mobile |
60aabaa0d9c071939b7960557f122224d4e5231b | config.js | config.js | 'use strict';
/**
* Global config settings.
* (C) 2015 Diego Lafuente.
*/
// requires
var Log = require('log');
// globals
exports.logLevel = 'info';
var log = new Log(exports.logLevel);
exports.limit = 100;
exports.expressPort = 8080;
exports.packagesCollection = 'packages';
exports.mongoConnection = 'mongodb://localhost/quality?autoReconnect=true&connectTimeoutMS=5000';
exports.testMongoConnection = 'mongodb://localhost/qualitytest?autoReconnect=true&connectTimeoutMS=5000';
try {
var localConfig = require("./local-config.js");
for (var key in localConfig) {
exports[key] = localConfig[key];
}
} catch(exception) {
log.notice("local-config.js not found");
} | 'use strict';
/**
* Global config settings.
* (C) 2015 Diego Lafuente.
*/
// requires
var Log = require('log');
// globals
exports.logLevel = 'info';
var log = new Log(exports.logLevel);
exports.limit = 100;
exports.expressPort = 8080;
exports.packagesCollection = 'packages';
exports.mongoConnection = 'mongodb://localhost/quality?autoReconnect=true&connectTimeoutMS=5000';
exports.testMongoConnection = 'mongodb://localhost/qualitytest?autoReconnect=true&connectTimeoutMS=5000';
exports.githubToken = '';
try {
var localConfig = require("./local-config.js");
for (var key in localConfig) {
exports[key] = localConfig[key];
}
} catch(exception) {
log.notice("local-config.js not found");
}
| Add an empty githubToken to avoid request auth crash | Add an empty githubToken to avoid request auth crash
| JavaScript | mit | alexfernandez/package-quality,alexfernandez/package-quality,alexfernandez/package-quality |
84562c0e47351abb6a2db7d58e58b5820af15131 | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'emberfire-utils'
};
| /* jshint node: true */
'use strict';
var Funnel = require('broccoli-funnel');
var featuresToExclude = [];
function filterFeatures(addonConfig) {
addonConfig.exclude.forEach((exclude) => {
if (exclude === 'firebase-util') {
featuresToExclude.push('**/firebase-util.js');
featuresToExclude.push('**/has-limited.js');
}
});
}
module.exports = {
name: 'emberfire-utils',
included: function(app) {
this._super.included.apply(this, arguments);
var addonConfig = this.app.options[this.name];
if (addonConfig) {
filterFeatures(addonConfig);
}
},
treeForApp: function() {
var tree = this._super.treeForApp.apply(this, arguments);
return new Funnel(tree, { exclude: featuresToExclude });
},
treeForAddon: function() {
var tree = this._super.treeForAddon.apply(this, arguments);
return new Funnel(tree, { exclude: featuresToExclude });
},
};
| Add base code for tree-shaking | Add base code for tree-shaking
| JavaScript | mit | rmmmp/emberfire-utils,rmmmp/emberfire-utils |
e0fc535bba6b9e08548a43ef47b2d692ec0a8119 | index.js | index.js | var fs = require( "fs" );
var path = require( "path" );
var slash = require( "slash" );
var through = require( "through2" );
module.exports = function( jadeFile, options ) {
var scriptTags = "";
options.root = options.root || process.cwd();
var write = function( file, encoding, callback ) {
if( file.path != "undefined" ) {
scriptTags = scriptTags + "\n" + "script(src=\"" + slash( path.relative( options.root, file.path ) ) + "\")";
}
this.push( file );
callback();
};
var flush = function( callback ) {
fs.writeFile( jadeFile, scriptTags, callback );
};
return through.obj( write, flush );
};
| var fs = require( "fs" );
var path = require( "path" );
var slash = require( "slash" );
var through = require( "through2" );
module.exports = function( jadeFile, options ) {
var scriptTags = "";
options.root = options.root || process.cwd();
var write = function( file, encoding, callback ) {
if( file.path != "undefined" ) {
scriptTags = scriptTags + "script(src=\"" + slash( path.relative( options.root, file.path ) ) + "\")" + "\n";
}
this.push( file );
callback();
};
var flush = function( callback ) {
fs.writeFile( jadeFile, scriptTags, callback );
};
return through.obj( write, flush );
};
| Put newline at end of output | Put newline at end of output
| JavaScript | mit | oliversalzburg/gulp-pug-script,oliversalzburg/gulp-jade-script |
8bb53eb34850bc0ff0cc7aab1a3bacd39b0a6acc | index.js | index.js | 'use strict';
var buttons = require('sdk/ui/button/action');
buttons.ActionButton({
id: 'elasticmarks-sidebar-button',
label: 'Open Elastic Bookmarks Sidebar',
icon: {
'16': './bookmark-16.png',
'32': './bookmark-32.png',
'64': './bookmark-64.png'
},
onClick: handleClick
});
function handleClick() {
sidebar.show();
}
var sidebar = require('sdk/ui/sidebar').Sidebar({
id: 'elasticmarks-sidebar',
title: 'Elastic Bookmarks Sidebar',
url: './sidebar.html',
onAttach: function (worker) {
worker.port.on('bmquery', function(query, queryId) {
let { search } = require('sdk/places/bookmarks');
search(
{ query: query }
).on('end', function (results) {
worker.port.emit('queryResults', results, queryId);
});
});
}
});
| 'use strict';
var buttons = require('sdk/ui/button/action');
buttons.ActionButton({
id: 'elasticmarks-sidebar-button',
label: 'Open Elastic Bookmarks Sidebar',
icon: {
'16': './bookmark-16.png',
'32': './bookmark-32.png',
'64': './bookmark-64.png'
},
onClick: handleClick
});
function handleClick() {
sidebar.show();
}
var sidebar = require('sdk/ui/sidebar').Sidebar({
id: 'elasticmarks-sidebar',
title: 'Elastic Bookmarks Sidebar',
url: './sidebar.html',
onAttach: function (worker) {
worker.port.on('bmquery', function(query, queryId) {
let { search } = require('sdk/places/bookmarks');
search(
{ query: query }
).on('end', function (bookmarks) {
const fixedBookmarks = bookmarks.map(bookmark => {bookmark.tags = [...bookmark.tags]; return bookmark;});
worker.port.emit('queryResults', fixedBookmarks, queryId);
});
});
}
});
| Make tags accessible in sidebar | Make tags accessible in sidebar
The tags as provided by the query are a Set element.
The sidebar js does not understand Set elements, so
we convert the set to an array.
This is prework for issue #4
| JavaScript | agpl-3.0 | micgro42/firefox-addon-elasticmarks,micgro42/firefox-addon-elasticmarks |
d06d593a348d01a633b7ac23babfbe0f96e563ad | index.js | index.js | var path = require('path');
var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');
module.exports = function(source, map) {
this.cacheable && this.cacheable();
this.addDependency(this.resourcePath);
var callback = this.async();
// Pass on query parameters as an options object to the DtsCreator. This lets
// you change the default options of the DtsCreator and e.g. use a different
// output folder.
var options = loaderUtils.getOptions(this) || {};
var context = options.context || this.context || this.rootContext;
var emitFile = !options.noEmit;
// Make sure to not modify options object directly
var creatorOptions = JSON.parse(JSON.stringify(options));
delete creatorOptions.noEmit;
var creator = new DtsCreator(creatorOptions);
// creator.create(..., source) tells the module to operate on the
// source variable. Check API for more details.
creator.create(this.resourcePath, source).then(content => {
if (emitFile) {
// Emit the created content as well
this.emitFile(path.relative(context, content.outputFilePath), content.contents || [''], map);
}
content.writeFile().then(_ => {
callback(null, source, map);
});
});
};
| var path = require('path');
var DtsCreator = require('typed-css-modules');
var loaderUtils = require('loader-utils');
module.exports = function(source, map) {
this.cacheable && this.cacheable();
this.addDependency(this.resourcePath);
var callback = this.async();
// Pass on query parameters as an options object to the DtsCreator. This lets
// you change the default options of the DtsCreator and e.g. use a different
// output folder.
var options = loaderUtils.getOptions(this) || {};
var context = options.context || this.context || this.rootContext;
var emitFile = !options.noEmit;
// Make sure to not modify options object directly
var creatorOptions = Object.assign({}, options);
delete creatorOptions.noEmit;
var creator = new DtsCreator(creatorOptions);
// creator.create(..., source) tells the module to operate on the
// source variable. Check API for more details.
creator.create(this.resourcePath, source).then(content => {
if (emitFile) {
// Emit the created content as well
this.emitFile(path.relative(context, content.outputFilePath), content.contents || [''], map);
}
content.writeFile().then(_ => {
callback(null, source, map);
});
});
};
| Use Object.assign for better performance | Use Object.assign for better performance | JavaScript | mit | olegstepura/typed-css-modules-loader |
7e4d2ccc6a1ecfabcdd70ec73a3d49a1fc835721 | index.js | index.js | var build = require('./build');
var clean = require('./clean');
var copy = require('./copy');
var karma = require('./default-karma.conf');
var lint = require('./lint');
var requirejs = require('./requirejs');
var resolve = require('./resolve');
var test = require('./test');
var teamCity = require('./teamCity');
var typescript = require('./typescript');
module.exports = {
build: build,
clean: clean,
copy: copy,
karma: karma,
lint: lint,
requirejs: requirejs,
resolve: resolve,
test: test,
teamCity: teamCity,
typescript: typescript,
};
| var build = require('./build');
var clean = require('./clean');
var compile = require('./compile');
var copy = require('./copy');
var karma = require('./default-karma.conf');
var lint = require('./lint');
var requirejs = require('./requirejs');
var resolve = require('./resolve');
var teamCity = require('./teamCity');
var test = require('./test');
var typescript = require('./typescript');
module.exports = {
build: build,
clean: clean,
compile: compile,
copy: copy,
karma: karma,
lint: lint,
requirejs: requirejs,
resolve: resolve,
teamCity: teamCity,
test: test,
typescript: typescript,
};
| Add compile and rearrange (alphabetical) | Add compile and rearrange (alphabetical)
| JavaScript | mit | RenovoSolutions/Gulp-Typescript-Utilities,SonofNun15/Gulp-Typescript-Utilities |
5eaee47df9738da4fe488289e2b3220d9585f0ca | index.js | index.js | const Assert = require('assert');
const FS = require('fs');
const Winston = require('winston');
const Factory = require('./lib/factory');
var exceptionLogger;
function isString(str) {
return typeof str === 'string';
}
module.exports = function (namespace) {
var level;
Assert(namespace && isString(namespace), 'must provide namespace');
level = process.env.LOG_LEVEL || 'info'; // eslint-disable-line no-process-env
return Factory(namespace, level, !exceptionLogger);
};
module.exports.writeExceptions = function (path) {
Assert(path && isString(path), 'must provide a file path');
// TODO use FS.accessSync(path, FS.F_OK | FS.W_OK), node > 4.0
FS.appendFileSync(path, ''); // eslint-disable-line no-sync
exceptionLogger = new Winston.Logger({
transports: [
new Winston.transports.File({
exitOnError: true,
filename: path,
handleExceptions: true,
humanReadableUnhandledException: true
})
]
});
};
| const Assert = require('assert');
const FS = require('fs');
const Winston = require('winston');
const Factory = require('./lib/factory');
var exceptionLogger;
function isString(str) {
return typeof str === 'string';
}
module.exports = function (namespace) {
var level;
Assert(namespace && isString(namespace), 'must provide namespace');
level = process.env.LOG_LEVEL || 'info'; // eslint-disable-line no-process-env
return Factory(namespace, level, !exceptionLogger);
};
module.exports.writeExceptions = function (path, exitOnError) {
Assert(path && isString(path), 'must provide a file path');
// TODO use FS.accessSync(path, FS.F_OK | FS.W_OK), node > 4.0
FS.appendFileSync(path, ''); // eslint-disable-line no-sync
exceptionLogger = new Winston.Logger({
transports: [
new Winston.transports.File({
exitOnError: exitOnError,
filename: path,
handleExceptions: true,
humanReadableUnhandledException: true
})
]
});
};
| Add exitOnError as optional parameter | Add exitOnError as optional parameter
| JavaScript | mit | onmodulus/logger |
063113769c777c480732856fb66d575856a3b1b4 | app/assets/javascripts/admin/analytics.js | app/assets/javascripts/admin/analytics.js | $(document).ready(function() {
$("#date_range").daterangepicker({ format: 'YYYY-MM-DD' });
$("#date_range").on('apply.daterangepicker', function(ev, picker){
Chartkick.eachChart( function(chart) {
var path, search;
[path, search] = chart.dataSource.split('?')
var params = new URLSearchParams(search);
params.set('date_start', picker.startDate.format('YYYY-MM-DD'));
params.set('date_end', picker.endDate.format('YYYY-MM-DD'));
chart.dataSource = path + '?' + params.toString();
chart.refreshData();
});
});
});
| $(document).ready(function() {
$("#date_range").daterangepicker({
locale: { format: 'YYYY-MM-DD' }
});
$("#date_range").on('apply.daterangepicker', function(ev, picker){
Chartkick.eachChart( function(chart) {
var path, search;
[path, search] = chart.dataSource.split('?')
var params = new URLSearchParams(search);
params.set('date_start', picker.startDate.format('YYYY-MM-DD'));
params.set('date_end', picker.endDate.format('YYYY-MM-DD'));
chart.dataSource = path + '?' + params.toString();
chart.refreshData();
});
});
});
| Fix date ranrge picker format | Fix date ranrge picker format
| JavaScript | agpl-3.0 | EFForg/action-center-platform,EFForg/action-center-platform,EFForg/action-center-platform,EFForg/action-center-platform |
d219f427858f0bf97e2ae13564113e49659acb5b | index.js | index.js | 'use strict'
const port = 5000
var server = require('./server')
server.listen(port, () => console.log('Server is up on port %d.', port))
| 'use strict'
let ENV
try { // look for local environment variable file first
ENV = require('./env')
} catch (LocalEnvFileNotFound) {
ENV = process.env
}
const PORT = ENV.PORT || 5000
let server = require('./server')
server.listen(PORT, () => console.log('Server is up on port %d.', PORT))
| Use port specified in environment for server | Use port specified in environment for server
| JavaScript | mit | mooniker/captran |
24f59d9b90e634932e801870ade69e2fa6cd9a84 | index.js | index.js | 'use strict';
var catchErrors = require('./lib/catchErrors');
var log = require('./lib/log');
var transportConsole = require('./lib/transports/console');
var transportFile = require('./lib/transports/file');
var transportRemote = require('./lib/transports/remote');
var transportMainConsole = require('./lib/transports/mainConsole');
var transportRendererConsole = require('./lib/transports/rendererConsole');
var utils = require('./lib/utils');
module.exports = {
catchErrors: function callCatchErrors(options) {
var opts = Object.assign({}, {
log: module.exports.error,
showDialog: process.type === 'browser'
}, options || {});
catchErrors(opts);
},
hooks: [],
isDev: utils.isDev(),
levels: ['error', 'warn', 'info', 'verbose', 'debug', 'silly'],
variables: {
processType: process.type
}
};
module.exports.transports = {
console: transportConsole(module.exports),
file: transportFile(module.exports),
remote: transportRemote(module.exports),
mainConsole: transportMainConsole(module.exports),
rendererConsole: transportRendererConsole(module.exports)
};
module.exports.levels.forEach(function (level) {
module.exports[level] = log.bind(null, module.exports, level);
});
module.exports.default = module.exports;
| 'use strict';
var catchErrors = require('./lib/catchErrors');
var log = require('./lib/log');
var transportConsole = require('./lib/transports/console');
var transportFile = require('./lib/transports/file');
var transportRemote = require('./lib/transports/remote');
var transportMainConsole = require('./lib/transports/mainConsole');
var transportRendererConsole = require('./lib/transports/rendererConsole');
var utils = require('./lib/utils');
module.exports = {
catchErrors: function callCatchErrors(options) {
var opts = Object.assign({}, {
log: module.exports.error,
showDialog: process.type === 'browser'
}, options || {});
catchErrors(opts);
},
hooks: [],
isDev: utils.isDev(),
levels: ['error', 'warn', 'info', 'verbose', 'debug', 'silly'],
variables: {
processType: process.type
}
};
module.exports.transports = {
console: transportConsole(module.exports),
file: transportFile(module.exports),
remote: transportRemote(module.exports),
mainConsole: transportMainConsole(module.exports),
rendererConsole: transportRendererConsole(module.exports)
};
module.exports.levels.forEach(function (level) {
module.exports[level] = log.bind(null, module.exports, level);
});
module.exports.log = log.bind(null, module.exports, 'info');
module.exports.default = module.exports;
| Add log function for compatibility with Console API | Add log function for compatibility with Console API
| JavaScript | mit | megahertz/electron-log,megahertz/electron-log,megahertz/electron-log |
2dfb621099b647dd5b513fef9abc02256dcd74ec | index.js | index.js | var ls = require('ls');
var fs = require('fs');
exports.generate = function(dir) {
if(dir === undefined || dir === null) {
dir = __dirname;
}
fs.mkdir(dir);
var decks = ls(__dirname + "/decks/*.js");
for(var i = 0, len = decks.length; i < len; i++) {
var json = require(decks[i].full).generate();
var out = JSON.stringify(json, null, 2);
var filename = json.name.replace(" ", "_").replace("[^a-zA-Z0-9]", "");
fs.writeFile(dir + "/" + filename + ".json", out, function(err) {
if(err) {
return console.log(err);
}
console.log(filename + " was saved!");
});
}
}
if(module.parent == null) {
exports.generate();
}
| var ls = require('ls');
var fs = require('fs');
exports.generate = function(dir) {
if(dir === undefined || dir === null) {
dir = __dirname;
}
fs.mkdir(dir, 0777, function(err) {
if(err && err.code != 'EEXIST') {
return console.error(err);
}
var decks = ls(__dirname + "/decks/*.js");
for(var i = 0, len = decks.length; i < len; i++) {
var json = require(decks[i].full).generate();
var out = JSON.stringify(json, null, 2);
var filename = json.name.replace(" ", "_").replace("[^a-zA-Z0-9]", "");
fs.writeFile(dir + "/" + filename + ".json", out, function(err) {
if(err) {
return console.log(err);
}
console.log(filename + " was saved!");
});
}
});
}
if(module.parent == null) {
exports.generate();
}
| Handle mkdir error when directory exists | Handle mkdir error when directory exists
| JavaScript | mit | DataDecks/DataDecks-Data |
14edb196096b9263a5e119a69a83d729dc0607f2 | api/signup/index.js | api/signup/index.js | var async = require( 'async' );
var Validation = require( './validation' );
var Data = require( './data' );
var Output = require( './output' );
var utils = require( '../utils' );
var validationError = require( '../utils/error_messages' ).validationError;
exports.userSignup = function ( req, res ) {
async.waterfall( [
function ( callback ) {
req.checkBody( 'email', "Must be an email address" ).isEmail();
req.checkBody( 'password', "Field is required" ).notEmpty();
var errors = req.validationErrors();
if ( errors ) {
return callback( errors );
}
return callback( null, req.body );
},
function ( requestBody, callback ) {
Data.createUser( req.body.email, req.body.password, callback );
},
function ( newUserData, callback ) {
Output.forSignup( newUserData, callback );
}
], function ( err, outputData ) {
if ( err ) {
return utils.handleRouteError( err, res );
}
return res.json( outputData, 201 );
} );
};
| var async = require( 'async' );
var Data = require( './data' );
var Output = require( './output' );
var utils = require( '../utils' );
exports.userSignup = function ( req, res ) {
async.waterfall( [
function ( callback ) {
req.checkBody( 'email', "Must be an email address" ).isEmail();
req.checkBody( 'password', "Field is required" ).notEmpty();
var errors = req.validationErrors();
if ( errors ) {
return callback( errors );
}
return callback( null, req.body );
},
function ( requestBody, callback ) {
Data.createUser( req.body.email, req.body.password, callback );
},
function ( newUserData, callback ) {
Output.forSignup( newUserData, callback );
}
], function ( err, outputData ) {
if ( err ) {
return utils.handleRouteError( err, res );
}
return res.json( outputData, 201 );
} );
};
| Clean out old validation stuff from Signup | Clean out old validation stuff from Signup
| JavaScript | mit | projectweekend/Node-Backend-Seed |
09920accba7a74d481e57b6389af6c45b3307375 | index.js | index.js | var rollbar = require("rollbar");
module.exports = {
install: function(Vue, options) {
Vue.rollbar = rollbar.init(options);
}
};
| var Rollbar = require("rollbar");
module.exports = {
install: function(Vue, options) {
Vue.rollbar = new Rollbar(options);
}
};
| Use new Rollbar initialization method | Use new Rollbar initialization method
| JavaScript | mit | Zevran/vue-rollbar,Zevran/vue-rollbar |
03a39b08a64b898717a46405c92d67b285dae98f | index.js | index.js | var fs = require('fs');
var postcss = require('postcss');
var autoprefixer = require('autoprefixer');
var app = 'src/app.css';
var dist = 'dist/build.css';
var css = fs.readFileSync(app);
postcss([autoprefixer])
.process(css, {
from: app,
to: dist
})
.then(function(res) {
fs.writeFileSync(dist, res.css);
});
| var fs = require('fs');
var postcss = require('postcss');
var autoprefixer = require('autoprefixer');
var app = 'src/app.css';
var dist = 'dist/build.css';
var css = fs.readFileSync(app);
var processors = [
autoprefixer({
browsers: ['> 1%', 'last 2 versions'],
cascade: false
})
];
postcss(processors)
.process(css, {
from: app,
to: dist
})
.then(function(res) {
fs.writeFileSync(dist, res.css);
});
| Store processors into array. Pass through options to Autoprefixer. | Store processors into array. Pass through options to Autoprefixer.
| JavaScript | mit | cahamilton/postcss-test |
8ef4d85fd4fcc1a90841730fd01b3dd95354bd9c | index.js | index.js | module.exports = {
parser: 'babel-eslint',
extends: 'airbnb',
globals: {
describe: true,
it: true,
},
};
| module.exports = {
parser: 'babel-eslint',
extends: 'airbnb',
globals: {
before: true,
beforeEach: true,
after: true,
afterEach: true,
describe: true,
it: true,
},
};
| Allow some more test functions. | Allow some more test functions.
| JavaScript | mit | crewmeister/eslint-config-crewmeister |
fb3cfeda6e6f3dcb7c72df8ae750005067b7ed94 | test/docco_test.js | test/docco_test.js | "use strict"
var grunt = require('grunt');
var rr = require("rimraf");
exports.docco = {
tests: function(test) {
var css = grunt.file.read("docs/docco.css");
var html = grunt.file.read("docs/docco.html");
test.expect(2);
test.equal(css.length, 7207, "Should create CSS.");
test.equal(html.length, 1017, "Should create HTML.");
test.done();
rr('docs', function(){});
}
};
| "use strict";
var grunt = require('grunt');
var rr = require("rimraf");
exports.docco = {
tearDown: function (callback) {
rr('docs', function(){});
callback();
},
tests: function(test) {
var css = grunt.file.read("docs/docco.css");
var html = grunt.file.read("docs/docco.html");
test.expect(2);
test.ok(css.length > 0, "Should create CSS.");
test.ok(html.length > 0, "Should create HTML.");
test.done();
}
};
| Change of assertion to not depend on exact file length. Removal of docs moved to tearDown, to call it on test failure. | Change of assertion to not depend on exact file length. Removal of docs moved to tearDown, to call it on test failure.
| JavaScript | mit | DavidSouther/grunt-docco,neocotic/grunt-docco,joseph-jja/grunt-docco-dir,joseph-jja/grunt-docco-dir |
1a54820bbac1c3fff9f68ecee7b979cb9679bbc8 | index.js | index.js | var importcss = require('rework-npm')
, rework = require('rework')
, variables = require('rework-vars')
, path = require('path')
, read = require('fs').readFileSync
module.exports = function (opts, cb) {
opts = opts || {}
var css = rework(read(opts.entry, 'utf8'))
css.use(importcss(path.dirname(opts.entry)))
if (opts.variables) {
css.use(variables(opts.variables))
}
if (opts.transform) {
opts.transform(css.toString(), cb)
} else {
cb(null, css.toString())
}
}
| var importcss = require('rework-npm')
, rework = require('rework')
, variables = require('rework-vars')
, path = require('path')
, read = require('fs').readFileSync
module.exports = function (opts, cb) {
opts = opts || {}
var css = rework(read(opts.entry, 'utf8'))
css.use(importcss(path.dirname(opts.entry)))
if (opts.variables) {
css.use(variables(opts.variables))
}
// utilize any custom rework plugins provided
if (opts.plugins) {
opts.plugins.forEach(function (plugin) {
css.use(plugin)
})
}
if (opts.transform) {
opts.transform(css.toString(), cb)
} else {
cb(null, css.toString())
}
}
| Add opts.plugins for specifying additional rework plugins | Add opts.plugins for specifying additional rework plugins | JavaScript | mit | atomify/atomify-css |
5904b6e737d32dd743a2c323c56e105ab5a710b6 | gulpfile.babel.js | gulpfile.babel.js | 'use strict';
import gulp from 'gulp';
import ignite from 'gulp-ignite';
import browserify from 'gulp-ignite-browserify';
import babelify from 'babelify';
import inject from 'gulp-inject';
import uglify from 'uglify-js';
const ASSET_PATH = './src/Bonfire.JavascriptLoader/Assets';
const INJECT_PATH = './src/Bonfire.JavascriptLoader/Core';
const buildTask = {
name: 'build',
fn() {
return gulp.src(INJECT_PATH + '/JavascriptLoaderHtmlHelper.cs')
.pipe(inject(gulp.src(`${ASSET_PATH}/loader.js`), {
starttag: '/*INJECT:JS*/',
endtag: '/*ENDINJECT*/',
transform: (filepath, file) => {
return `"${uglify.minify(file.contents.toString('utf8'), { fromString: true }).code.slice(1)}"`;
}
}))
.pipe(gulp.dest(INJECT_PATH));
}
}
const tasks = [
browserify,
buildTask,
];
const options = {
browserify: {
src: './src/Bonfire.JavascriptLoader.Demo/Assets/main.js',
dest: './src/Bonfire.JavascriptLoader.Demo/Content/js',
options: {
transform: [babelify],
},
watchFiles: [
'./src/Bonfire.JavascriptLoader.Demo/Assets/*',
],
},
};
ignite.start(tasks, options);
| 'use strict';
import gulp from 'gulp';
import ignite from 'gulp-ignite';
import browserify from 'gulp-ignite-browserify';
import babelify from 'babelify';
import inject from 'gulp-inject';
import uglify from 'uglify-js';
import yargs from 'yargs';
const ASSET_PATH = './src/Bonfire.JavascriptLoader/Assets';
const INJECT_PATH = './src/Bonfire.JavascriptLoader/Core';
const buildTask = {
name: 'build',
fn() {
return gulp.src(INJECT_PATH + '/JavascriptLoaderHtmlHelper.cs')
.pipe(inject(gulp.src(`${ASSET_PATH}/loader.js`), {
starttag: '/*INJECT:JS*/',
endtag: '/*ENDINJECT*/',
transform: (filepath, file) => {
return `"${uglify.minify(file.contents.toString('utf8'), { fromString: true }).code.slice(1)}"`;
}
}))
.pipe(gulp.dest(INJECT_PATH));
}
}
const tasks = [
browserify,
buildTask,
];
const filename = yargs.argv.filename || yargs.argv.f || 'main.js';
const options = {
browserify: {
src: `./src/Bonfire.JavascriptLoader.Demo/Assets/${filename}`,
dest: './src/Bonfire.JavascriptLoader.Demo/Content/js',
filename: filename,
options: {
transform: [babelify],
},
watchFiles: [
'./src/Bonfire.JavascriptLoader.Demo/Assets/*',
],
},
};
ignite.start(tasks, options);
| Add ability to build other js files | Add ability to build other js files
| JavaScript | mit | buildabonfire/Bonfire.JavascriptLoader,buildabonfire/Bonfire.JavascriptLoader,buildabonfire/Bonfire.JavascriptLoader |
e8dffdae918fd10fdc547b80a10c5fb09e8fe188 | app/scripts/map-data.js | app/scripts/map-data.js | (function(window, undefined) {
var data = window.data = window.data || { };
var map = data.map = data.map || { };
map['Germany'] = [52.5, 13.4];
map['France'] = [48.9, 2.4];
})(window); | (function(window, undefined) {
var data = window.data = window.data || { };
var map = data.map = data.map || { };
map['Germany'] = [52.5, 13.4];
map['France'] = [48.9, 2.4];
map['Spain'] = [40.4, -3.7];
map['Russia'] = [55.7, 37.6];
map['Italy'] = [41.9, 12.5];
map['Ukraine'] = [50.5, 30.5];
map['Sweden'] = [59.3, 18.0];
map['Norway'] = [60.0, 10.8];
map['Estonia'] = [59.4, 24.7];
})(window); | Add remaining capitals for FPO dataset | Add remaining capitals for FPO dataset
| JavaScript | apache-2.0 | SF-Housing-Visualization/mids-sf-housing-visualization,SF-Housing-Visualization/mids-sf-housing-visualization |
5190e1409985f4c1e1268772fd378e8a275c128e | index.js | index.js | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-sinon',
options: {
nodeAssets: {
'sinon': {
import: [{ path: 'pkg/sinon.js', type: 'test' }]
}
}
},
included: function (app) {
this._super.included.apply(this, arguments);
app.import('vendor/shims/sinon.js', { type: 'test' });
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-sinon',
options: {
nodeAssets: {
'sinon': {
import: [{ path: 'pkg/sinon.js', type: 'test' }]
}
}
},
included: function(app) {
this._super.included.apply(this, arguments);
while (typeof app.import !== 'function' && app.app) {
app = app.app;
}
app.import('vendor/shims/sinon.js', { type: 'test' });
}
};
| Add support for being a nested dependency | Add support for being a nested dependency
| JavaScript | mit | csantero/ember-sinon,csantero/ember-sinon |
2b5ca9641957a664b772d8d146273abd0fcf286b | index.js | index.js | const loaderUtils = require('loader-utils');
const path = require('path');
const deepMerge = require('./lib/deep-merge');
module.exports = function(source) {
const HEADER = '/**** Start Merge Loader ****/';
const FOOTER = '/**** End Merge Loader ****/';
const callback = this.async();
const options = loaderUtils.getOptions(this);
const thisLoader = this;
const overridePath = path.resolve(__dirname,
`test/cases/lib/${options.override}`);
this.cacheable && this.cacheable();
this.loadModule(overridePath,
function(err, overrideSource, sourceMap, module) {
if (err) { return callback(err); }
const override = overrideSource
.replace(/^ ?module.exports ?= ?/i, '')
.replace(/\;/g, '');
const mergedModule = deepMerge(JSON.parse(source), JSON.parse(override));
callback(null, mergedModule);
});
};
| const loaderUtils = require('loader-utils');
const path = require('path');
const deepMerge = require('./lib/deep-merge');
module.exports = function(source) {
const callback = this.async();
const options = loaderUtils.getOptions(this);
const overridePath = path.resolve(__dirname,
`test/cases/lib/${options.override}`);
this.cacheable && this.cacheable();
this.loadModule(overridePath,
function(err, overrideSource, sourceMap, module) {
if (err) { return callback(err); }
const override = overrideSource
.replace(/^ ?module.exports ?= ?/i, '')
.replace(/\;/g, '');
const mergedModule = deepMerge(JSON.parse(source), JSON.parse(override));
callback(null, mergedModule);
});
};
| Remove unnecessary variables in loader | Remove unnecessary variables in loader
| JavaScript | mit | bitfyre/config-merge-loader |
c22b100cbd55f6bb4e4097f2def34839f5d70780 | packages/generator-react-server/generators/app/templates/test.js | packages/generator-react-server/generators/app/templates/test.js | import cp from 'child_process';
import http from 'http';
import test from 'ava';
let rs;
test.before('start the server', async () => {
rs = cp.spawn('npm', ['start']);
rs.stderr.on('data', data => console.error(data.toString()));
await sleep(10000);
});
test('server is running', async t => {
t.is(200, await getResponseCode('/'));
});
test.after.always('shut down the server', async () => {
rs.kill('SIGHUP');
});
// gets the response code for an http request
function getResponseCode(url) {
return new Promise((resolve, reject) => {
const req = http.get({
hostname: 'localhost',
port: 3000,
path: url,
}, res => {
resolve(res.statusCode);
});
req.on('error', e => reject(e));
});
}
function sleep(time) {
return new Promise(resolve => {
setTimeout(resolve, time);
});
}
| import cp from 'child_process';
import http from 'http';
import test from 'ava';
let rs;
test.before('start the server', async () => {
rs = cp.spawn('npm', ['start']);
rs.stderr.on('data', data => console.error(data.toString()));
await sleep(15000);
});
test('server is running', async t => {
t.is(200, await getResponseCode('/'));
});
test.after.always('shut down the server', async () => {
rs.kill('SIGHUP');
});
// gets the response code for an http request
function getResponseCode(url) {
return new Promise((resolve, reject) => {
const req = http.get({
hostname: 'localhost',
port: 3000,
path: url,
}, res => {
resolve(res.statusCode);
});
req.on('error', e => reject(e));
});
}
function sleep(time) {
return new Promise(resolve => {
setTimeout(resolve, time);
});
}
| Increase wait time for server start to 15s | Increase wait time for server start to 15s
| JavaScript | apache-2.0 | emecell/react-server,lidawang/react-server,redfin/react-server,lidawang/react-server,emecell/react-server,redfin/react-server |
33ab3db66a6f37f0e8c8f48a19035464fea358c1 | index.js | index.js | import { Kefir as K } from "kefir";
const NEVER = K.never();
const ZERO = K.constant(0);
const ADD1 = (x) => x + 1;
const SUBTRACT1 = (x) => x - 1;
const ALWAYS = (x) => () => x;
const delay = (n, s) => s.slidingWindow(n + 1, 2).map(([i, _]) => i);
function galvo({ advance = NEVER, recede = NEVER, index = ZERO } = {}, slides) {
const length = slides.length;
const nextT = advance.map(() => ADD1);
const previousT = recede.map(() => SUBTRACT1);
const indexT = index.map(ALWAYS);
const transformations = K.merge([
nextT,
previousT,
indexT
]);
const currentIndex =
transformations
.scan((i, transform) => transform(i), 0)
.map((i) => (i + length) % length);
const current = currentIndex.map((i) => slides[i]);
const previousIndex = delay(1, currentIndex);
const previous = delay(1, current);
return {
current,
currentIndex,
previous,
previousIndex
}
}
module.exports = galvo;
| import { Kefir as K } from "kefir";
const NEVER = K.never();
const ZERO = K.constant(0);
const ADD1 = (x) => x + 1;
const SUBTRACT1 = (x) => x - 1;
const ALWAYS = (x) => () => x;
const delay = (n, s) => s.slidingWindow(n + 1, 2).map(([i, _]) => i);
function galvo({ advance = NEVER, recede = NEVER, index = ZERO } = {}, collection) {
const length = collection.length;
const nextT = advance.map(() => ADD1);
const previousT = recede.map(() => SUBTRACT1);
const indexT = index.map(ALWAYS);
const transformations = K.merge([
nextT,
previousT,
indexT
]);
const currentIndex =
transformations
.scan((i, transform) => transform(i), 0)
.map((i) => (i + length) % length);
const current = currentIndex.map((i) => collection[i]);
const previousIndex = delay(1, currentIndex);
const previous = delay(1, current);
return {
current,
currentIndex,
previous,
previousIndex
}
}
module.exports = galvo;
| Change slides variable to collection | Change slides variable to collection
| JavaScript | mit | standard-library/galvo |
266931cf123010a232981421b96c6d7381f9fe57 | index.js | index.js | 'use strict';
var ejs = require('ejs');
var fs = require('fs');
exports.name = 'ejs';
exports.outputFormat = 'xml';
exports.compile = ejs.compile;
exports.compileClient = function (source, options) {
options = options || {};
options.client = true;
return exports.compile(source, options).toString();
};
exports.compileFile = function (path, options) {
options = options || {};
options.filename = options.filename || path;
return exports.compile(fs.readFileSync(path, 'utf8'), options);
};
| 'use strict';
var ejs = require('ejs');
var fs = require('fs');
exports.name = 'ejs';
exports.outputFormat = 'html';
exports.compile = ejs.compile;
exports.compileClient = function (source, options) {
options = options || {};
options.client = true;
return exports.compile(source, options).toString();
};
exports.compileFile = function (path, options) {
options = options || {};
options.filename = options.filename || path;
return exports.compile(fs.readFileSync(path, 'utf8'), options);
};
| Use `'html'` as output format | Use `'html'` as output format
Per jstransformers/jstransformer#3.
| JavaScript | mit | jstransformers/jstransformer-ejs,jstransformers/jstransformer-ejs |
aba731a6b68d09a065e2b97c4eff2d51a86195e1 | index.js | index.js | const express = require('express');
const helmet = require('helmet');
const winston = require('winston');
const bodyParser = require('body-parser');
const env = require('./src/env');
var server = express();
var router = require('./src/router');
var PORT = env.PORT || 8000;
server.use(bodyParser.urlencoded({ extended: false }));
server.use(helmet());
server.use('/', router);
function _get() {
return server;
}
function run(fn) {
fn = fn || function _defaultStart() {
winston.info('Listening at ' + PORT);
};
return server.listen(PORT, fn);
}
if (require.main === module) {
run();
}
module.exports = {
_get: _get,
run: run
};
| const express = require('express');
const helmet = require('helmet');
const winston = require('winston');
const bodyParser = require('body-parser');
const env = require('./src/env');
var server = express();
var router = require('./src/router');
var PORT = env.PORT || 8000;
server.use(bodyParser.json());
server.use(helmet());
server.use('/', router);
function _get() {
return server;
}
function run(fn) {
fn = fn || function _defaultStart() {
winston.info('Listening at ' + PORT);
};
return server.listen(PORT, fn);
}
if (require.main === module) {
run();
}
module.exports = {
_get: _get,
run: run
};
| Switch to use JSON payload parser | fix: Switch to use JSON payload parser
| JavaScript | mit | NSAppsTeam/nickel-bot |
4dec8ace74bc153a67cd32b1e5be026bfbf852be | index.js | index.js | /**
* A lightweight promise-based Reddit API wrapper.
* @module reddit-api
*/
exports = module.exports = Reddit;
function Reddit() {
this.baseApiUrl = 'http://www.reddit.com';
return this;
};
/**
* Logs in a Reddit user.
*
* @param {string} username
* @param {string} password
*/
Reddit.prototype.login = function(username, password) {
};
/**
* Logs out a Reddit user.
*/
Reddit.prototype.logout = function() {
};
/**
* Retrieves the comments associated with a URL.
*
* @param {string} url
*/
Reddit.prototype.getComments = function(url) {
};
/**
* Posts a comment on a Reddit "thing".
*
* @param {string} parentId - The
* {@link http://www.reddit.com/dev/api#fullnames fullname} of a parent
* "thing".
* @param {string} text - The comment body.
* @link http://www.reddit.com/dev/api#POST_api_comment
*/
Reddit.prototype.comment = function(parentId, text) {
};
| /**
* A lightweight promise-based Reddit API wrapper.
* @module reddit-api
*/
exports = module.exports = Reddit;
function Reddit() {
this._baseApiUrl = 'http://www.reddit.com';
return this;
};
/**
* Logs in a Reddit user.
*
* @param {string} username
* @param {string} password
*/
Reddit.prototype.login = function(username, password) {
};
/**
* Logs out a Reddit user.
*/
Reddit.prototype.logout = function() {
};
/**
* Retrieves the comments associated with a URL.
*
* @param {string} url
*/
Reddit.prototype.getComments = function(url) {
};
/**
* Posts a comment on a Reddit "thing".
*
* @param {string} parentId - The
* {@link http://www.reddit.com/dev/api#fullnames fullname} of a parent
* "thing".
* @param {string} text - The comment body.
* @link http://www.reddit.com/dev/api#POST_api_comment
*/
Reddit.prototype.comment = function(parentId, text) {
};
| Use underscore for private properties | Use underscore for private properties
| JavaScript | mit | imiric/reddit-api |
5a58033f8cc97ac0d07b220ac73c8ae76a34d5c3 | index.js | index.js | /*!
* Mongoose findOrCreate Plugin
* Copyright(c) 2012 Nicholas Penree <nick@penree.com>
* MIT Licensed
*/
function findOrCreatePlugin(schema, options) {
schema.statics.findOrCreate = function findOrCreate(conditions, doc, options, callback) {
if (arguments.length < 4) {
if (typeof options === 'function') {
// Scenario: findOrCreate(conditions, doc, callback)
callback = options;
options = {};
} else if (typeof doc === 'function') {
// Scenario: findOrCreate(conditions, callback);
callback = doc;
doc = {};
options = {};
}
}
var self = this;
this.findOne(conditions, function(err, result) {
if(err || result) {
if(options && options.upsert && !err) {
self.update(conditions, doc, function(err, count){
self.findOne(conditions, function(err, result) {
callback(err, result, false);
});
})
} else {
callback(err, result, false)
}
} else {
for (var key in conditions) {
doc[key] = conditions[key];
}
var obj = new self(conditions)
obj.save(function(err) {
callback(err, obj, true);
});
}
})
}
}
/**
* Expose `findOrCreatePlugin`.
*/
module.exports = findOrCreatePlugin; | /*!
* Mongoose findOrCreate Plugin
* Copyright(c) 2012 Nicholas Penree <nick@penree.com>
* MIT Licensed
*/
function findOrCreatePlugin(schema, options) {
schema.statics.findOrCreate = function findOrCreate(conditions, doc, options, callback) {
if (arguments.length < 4) {
if (typeof options === 'function') {
// Scenario: findOrCreate(conditions, doc, callback)
callback = options;
options = {};
} else if (typeof doc === 'function') {
// Scenario: findOrCreate(conditions, callback);
callback = doc;
doc = {};
options = {};
}
}
var self = this;
this.findOne(conditions, function(err, result) {
if(err || result) {
if(options && options.upsert && !err) {
self.update(conditions, doc, function(err, count){
self.findOne(conditions, function(err, result) {
callback(err, result, false);
});
})
} else {
callback(err, result, false)
}
} else {
for (var key in conditions) {
doc[key] = conditions[key];
}
var obj = new self(doc)
obj.save(function(err) {
callback(err, obj, true);
});
}
})
}
}
/**
* Expose `findOrCreatePlugin`.
*/
module.exports = findOrCreatePlugin; | Use doc instead of conditions | Use doc instead of conditions | JavaScript | mit | yura415/mongoose-findorcreate |
3bc450b26c681b10efc3144e1e83cd97f703aa3b | app/models/users.js | app/models/users.js | 'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema({
name: String,
username: String,
password: String,
date: Date
});
module.exports = mongoose.model('User', User);
| 'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema({
name: String,
username: String,
password: String,
date: Date,
friends: Array
});
module.exports = mongoose.model('User', User);
| Add friends column to store info | Add friends column to store info
| JavaScript | mit | mirabalj/graphriend,mirabalj/graphriend |
bb95b8a1375f5bd395e6cb9d3db40b7b427d12b7 | production/defaults/collective.js | production/defaults/collective.js | var CELOS_USER = "celos";
var CELOS_DEFAULT_OOZIE = "http://oozie002.ny7.collective-media.net:11000/oozie";
var CELOS_DEFAULT_HDFS = "hdfs://nameservice1";
var NAME_NODE = CELOS_DEFAULT_HDFS;
var JOB_TRACKER = "admin1.ny7.collective-media.net:8032";
var HIVE_METASTORE = "thrift://hive002.ny7.collective-media.net:9083";
var OUTPUT_ROOT = NAME_NODE + "/output";
var CELOS_DEFAULT_OOZIE_PROPERTIES = {
"user.name": CELOS_USER,
"jobTracker" : JOB_TRACKER,
"nameNode" : CELOS_DEFAULT_HDFS,
"hiveMetastore": HIVE_METASTORE,
"hiveDefaults": NAME_NODE + "/deploy/TheOneWorkflow/hive/hive-site.xml",
"oozie.use.system.libpath": "true",
"outputRoot": OUTPUT_ROOT
};
| var CELOS_USER = "celos";
var CELOS_DEFAULT_OOZIE = "http://oozie002.ny7.collective-media.net:11000/oozie";
var CELOS_DEFAULT_HDFS = "hdfs://nameservice1";
var NAME_NODE = CELOS_DEFAULT_HDFS;
var JOB_TRACKER = "admin1.ny7.collective-media.net:8032";
var HIVE_METASTORE = "thrift://hive002.ny7.collective-media.net:9083";
var ETL002 = "etl002.ny7.collective-media.net";
var OUTPUT_ROOT = NAME_NODE + "/output";
var CELOS_DEFAULT_OOZIE_PROPERTIES = {
"user.name": CELOS_USER,
"jobTracker" : JOB_TRACKER,
"nameNode" : CELOS_DEFAULT_HDFS,
"hiveMetastore": HIVE_METASTORE,
"hiveDefaults": NAME_NODE + "/deploy/TheOneWorkflow/hive/hive-site.xml",
"oozie.use.system.libpath": "true",
"outputRoot": OUTPUT_ROOT,
"etl002": ETL002
};
| Add etl002 FQDN to Celos Oozie default properties. | Add etl002 FQDN to Celos Oozie default properties.
| JavaScript | apache-2.0 | collectivemedia/celos,collectivemedia/celos,collectivemedia/celos |
f086077dd8eee8503192c13f646e9d63231e0174 | app/routes/index.js | app/routes/index.js | import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import Analytics from 'ember-osf/mixins/analytics';
/**
* @module ember-preprints
* @submodule routes
*/
/**
* Loads all disciplines and preprint providers to the index page
* @class Index Route Handler
*/
export default Ember.Route.extend(Analytics, ResetScrollMixin, {
// store: Ember.inject.service(),
theme: Ember.inject.service(),
model() {
return Ember.RSVP.hash({
taxonomies: this.get('theme.provider')
.then(provider => provider
.query('taxonomies', {
filter: {
parents: 'null'
},
page: {
size: 20
}
})
),
brandedProviders: this
.store
.findAll('preprint-provider', { reload: true })
.then(result => result
.filter(item => item.id !== 'osf')
)
});
},
actions: {
search(q) {
let route = 'discover';
if (this.get('theme.isSubRoute'))
route = `provider.${route}`;
this.transitionTo(route, { queryParams: { q: q } });
}
}
});
| import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import Analytics from 'ember-osf/mixins/analytics';
/**
* @module ember-preprints
* @submodule routes
*/
/**
* Loads all disciplines and preprint providers to the index page
* @class Index Route Handler
*/
export default Ember.Route.extend(Analytics, ResetScrollMixin, {
// store: Ember.inject.service(),
theme: Ember.inject.service(),
model() {
return Ember.RSVP.hash({
taxonomies: this.get('theme.provider')
.then(provider => provider
.query('highlightedTaxonomies', {
page: {
size: 20
}
})
),
brandedProviders: this
.store
.findAll('preprint-provider', { reload: true })
.then(result => result
.filter(item => item.id !== 'osf')
)
});
},
actions: {
search(q) {
let route = 'discover';
if (this.get('theme.isSubRoute'))
route = `provider.${route}`;
this.transitionTo(route, { queryParams: { q: q } });
}
}
});
| Use highlighted taxonomies instead of top level taxonomies | Use highlighted taxonomies instead of top level taxonomies
| JavaScript | apache-2.0 | laurenrevere/ember-preprints,baylee-d/ember-preprints,baylee-d/ember-preprints,laurenrevere/ember-preprints,CenterForOpenScience/ember-preprints,CenterForOpenScience/ember-preprints |
08b84474bedcc17f810289364b91011ebd6219ec | public/javascripts/application.js | public/javascripts/application.js | $(document).ready(function() {
$('.add_child').click(function() {
var assoc = $(this).attr('data-association');
var content = $('#' + assoc + '_fields_template').html();
var regexp = new RegExp('new_' + assoc, 'g')
var new_id = new Date().getTime();
$(this).parent().before(content.replace(regexp, new_id));
});
$('.remove_child').live('click', function() {
var hidden_field = $(this).prev('input[type=hidden]')[0];
if(hidden_field) {
hidden_field.value = '1';
}
$(this).parents('.fields').hide();
return false;
});
}); | $(document).ready(function() {
$('.add_child').click(function() {
var assoc = $(this).attr('data-association');
var content = $('#' + assoc + '_fields_template').html();
var regexp = new RegExp('new_' + assoc, 'g')
var new_id = new Date().getTime();
$(this).parent().before(content.replace(regexp, new_id));
return false;
});
$('.remove_child').live('click', function() {
var hidden_field = $(this).prev('input[type=hidden]')[0];
if(hidden_field) {
hidden_field.value = '1';
}
$(this).parents('.fields').hide();
return false;
});
}); | Add a missing return false at the end of a jquery event | Add a missing return false at the end of a jquery event
| JavaScript | mit | timriley/complex-form-examples,timriley/complex-form-examples |
c333a80c898397ff2905a67cf2b28b1833157841 | public/modules/common/readMode.js | public/modules/common/readMode.js | 'use strict';
angular.module('theLawFactory')
.directive('readMode', ['$location', function($location) {
return {
restrict: 'A',
controller: function($scope) {
$scope.read = $location.search()['read'] === '1';
$scope.readmode = function () {
$("#sidebar").addClass('readmode');
if ($scope.mod === 'amendements') {
$location.replace();
$location.search('read', '1');
}
$scope.read = true;
};
$scope.viewmode = function () {
$("#sidebar").removeClass('readmode');
if ($scope.mod === 'amendements') {
$location.replace();
$location.search('read', null);
}
$scope.read = false;
};
if ($scope.read) {
$scope.readmode();
}
}
}
}]);
| 'use strict';
angular.module('theLawFactory')
.directive('readMode', ['$location', function($location) {
return {
restrict: 'A',
controller: function($rootScope, $scope) {
$rootScope.read = $location.search()['read'] === '1';
$rootScope.readmode = function () {
$("#sidebar").addClass('readmode');
if ($scope.mod === 'amendements') {
$location.replace();
$location.search('read', '1');
}
$rootScope.read = true;
};
$rootScope.viewmode = function () {
$("#sidebar").removeClass('readmode');
if ($scope.mod === 'amendements') {
$location.replace();
$location.search('read', null);
}
$rootScope.read = false;
};
if ($rootScope.read) {
$rootScope.readmode();
}
}
}
}]);
| Move readmode to root scope | Move readmode to root scope
Prevents incorrect angular scope inheritance behaviour (calling $scope.readmode()
would set the "read" variable on the calling scope, not in the readMode controller
scope).
| JavaScript | agpl-3.0 | regardscitoyens/the-law-factory,regardscitoyens/the-law-factory,regardscitoyens/the-law-factory |
0716c83e8ec9bbd3b7359d962c95ecb1b43e00e4 | application/src/main/resources/assets/js/app/controller.js | application/src/main/resources/assets/js/app/controller.js | define([
'backbone',
'marionette'
], function(Backbone, Marionette) {
var Controller = Marionette.Controller.extend({
initialize: function(options) {
this.app = options.app;
this.addressBar = new Backbone.Router();
},
navigateHome: function() {
this.addressBar.navigate('/');
console.log('controller: navigateHome');
},
navigateAbout: function() {
this.addressBar.navigate('/about');
console.log('controller: navigateAbout');
}
});
return Controller;
});
| define([
'backbone',
'marionette'
], function(Backbone, Marionette) {
var Controller = Marionette.Controller.extend({
initialize: function(options) {
this.app = options.app;
},
navigateHome: function() {
Backbone.history.navigate('/');
console.log('controller: navigateHome');
},
navigateAbout: function() {
Backbone.history.navigate('/about');
console.log('controller: navigateAbout');
}
});
return Controller;
});
| Call Backbone.history directly (instead of through a dummy router) | Call Backbone.history directly (instead of through a dummy router)
| JavaScript | apache-2.0 | tumbarumba/dropwizard-marionette,tumbarumba/dropwizard-marionette,tumbarumba/dropwizard-marionette |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.