commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
06dba54a9bd08e27756dceebd214841986de9d1a
grunt.js
grunt.js
module.exports = function (grunt) { grunt.initConfig({ meta: { banner: '// ' + grunt.file.read('src/loStorage.js').split("\n")[0] }, min: { dist: { src: ['<banner>', 'src/loStorage.js'], dest: 'src/loStorage.min.js' } }, jasmine: { all: ['spec/index.html'] }, watch: { test: { files: ['src/loStorage.js', 'spec/*'], tasks: 'test' } } }); grunt.loadNpmTasks('grunt-jasmine-task'); grunt.registerTask('test', 'jasmine'); grunt.registerTask('release', 'test min'); grunt.registerTask('default', 'release'); };
module.exports = function (grunt) { grunt.initConfig({ meta: { banner: '// ' + grunt.file.read('src/loStorage.js').split("\n")[0] }, min: { dist: { src: ['<banner>', 'src/loStorage.js'], dest: 'src/loStorage.min.js' } }, jasmine: { all: ['spec/index.html'] }, watch: { test: { files: ['src/loStorage.js', 'spec/*'], tasks: 'test' }, min: { files: ['src/loStorage.js'], tasks: 'min' } } }); grunt.loadNpmTasks('grunt-jasmine-task'); grunt.registerTask('test', 'jasmine'); grunt.registerTask('release', 'test min'); grunt.registerTask('default', 'release'); };
Add min task to watch
Add min task to watch
JavaScript
mit
js-coder/loStorage.js,js-coder/loStorage.js,florian/loStorage.js,florian/loStorage.js,joshprice/loStorage.js,npmcomponent/js-coder-loStorage.js
--- +++ @@ -21,6 +21,11 @@ test: { files: ['src/loStorage.js', 'spec/*'], tasks: 'test' + }, + + min: { + files: ['src/loStorage.js'], + tasks: 'min' } }
c945aa9f72df97c2244d108d7cb0a4a778d6e2f1
vendor/assets/javascripts/_element.js
vendor/assets/javascripts/_element.js
this.Element && function (ElementPrototype) { ElementPrototype.matches = ElementPrototype.matches || ElementPrototype.matchesSelector || ElementPrototype.mozMatchesSelector || ElementPrototype.msMatchesSelector || ElementPrototype.webkitMatchesSelector || function (selector) { var node = this, nodes = (node.parentNode || node.document).querySelectorAll(selector), i = -1; while (nodes[++i] && nodes[i] != node); return !!nodes[i]; } } (Element.prototype); this.Element && function (ElementPrototype) { ElementPrototype.closest = function (selector) { var node = this; while (node) { if (node == document) return undefined; if (node.matches(selector)) return node; node = node.parentNode; } } } (Element.prototype);
/*jshint bitwise: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, quotmark: double, undef: true, unused: vars, strict: true, trailing: true, maxdepth: 3, devel: true, asi: true */ /*global HTMLElement: true */ // // ELEMENT // // Closest // Usage: element.closest(selector) this.Element && function (ElementPrototype) { ElementPrototype.closest = function (selector) { var node = this; while (node) { if (node == document) return undefined; if (node.matches(selector)) return node; node = node.parentNode; } } } (Element.prototype); // Matches // Usage: element.matches(selector) this.Element && function (ElementPrototype) { ElementPrototype.matches = ElementPrototype.matches || ElementPrototype.matchesSelector || ElementPrototype.mozMatchesSelector || ElementPrototype.msMatchesSelector || ElementPrototype.webkitMatchesSelector || function (selector) { var node = this, nodes = (node.parentNode || node.document).querySelectorAll(selector), i = -1; while (nodes[++i] && nodes[i] != node); return !!nodes[i]; } } (Element.prototype);
Add jshint options and comments.
Add jshint options and comments.
JavaScript
mit
smockle/black-coffee
--- +++ @@ -1,3 +1,26 @@ +/*jshint bitwise: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, quotmark: double, undef: true, unused: vars, strict: true, trailing: true, maxdepth: 3, devel: true, asi: true */ +/*global HTMLElement: true */ + +// +// ELEMENT +// + +// Closest +// Usage: element.closest(selector) +this.Element && function (ElementPrototype) { + ElementPrototype.closest = + function (selector) { + var node = this; + while (node) { + if (node == document) return undefined; + if (node.matches(selector)) return node; + node = node.parentNode; + } + } +} (Element.prototype); + +// Matches +// Usage: element.matches(selector) this.Element && function (ElementPrototype) { ElementPrototype.matches = ElementPrototype.matches || ElementPrototype.matchesSelector || @@ -10,15 +33,3 @@ return !!nodes[i]; } } (Element.prototype); - -this.Element && function (ElementPrototype) { - ElementPrototype.closest = - function (selector) { - var node = this; - while (node) { - if (node == document) return undefined; - if (node.matches(selector)) return node; - node = node.parentNode; - } - } -} (Element.prototype);
0dd0ec941fcc80c20a522ed409fd98b49b40e3a6
src/app/utilities/api-clients/collections.js
src/app/utilities/api-clients/collections.js
import http from '../http'; export default class collections { static get(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response; }) } static getAll() { return http.get(`/zebedee/collections`) .then(response => { return response; }) } static create(body) { return http.post(`/zebedee/collection`, body) .then(response => { return response; }) } static approve(collectionID) { return http.post(`/zebedee/approve/${collectionID}`); } static delete(collectionID) { return http.delete(`/zebedee/collection/${collectionID}`); } static update(collectionID, body) { body.id = collectionID; return http.put(`/zebedee/collection/${collectionID}`, body); } static deletePage(collectionID, pageURI) { return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`); } static cancelDelete(collectionID, pageURI) { return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`); } }
import http from '../http'; export default class collections { static get(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response; }) } static getAll() { return http.get(`/zebedee/collections`) .then(response => { return response; }) } static create(body) { return http.post(`/zebedee/collection`, body) .then(response => { return response; }) } static approve(collectionID) { return http.post(`/zebedee/approve/${collectionID}`); } static delete(collectionID) { return http.delete(`/zebedee/collection/${collectionID}`); } static update(collectionID, body) { body.id = collectionID; return http.put(`/zebedee/collection/${collectionID}`, body); } static deletePage(collectionID, pageURI) { return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`); } static cancelDelete(collectionID, pageURI) { return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`); } static async checkContentIsInCollection(pageURI) { return http.get(`/zebedee/checkcollectionsforuri?uri=${pageURI}`) } }
Add method to check is content is in another collection
Add method to check is content is in another collection
JavaScript
mit
ONSdigital/florence,ONSdigital/florence,ONSdigital/florence,ONSdigital/florence
--- +++ @@ -44,4 +44,8 @@ return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`); } + static async checkContentIsInCollection(pageURI) { + return http.get(`/zebedee/checkcollectionsforuri?uri=${pageURI}`) + } + }
c56370a3518f967a6f4afed8bcc84c17500ee0b3
assets/js/googlesitekit-settings.js
assets/js/googlesitekit-settings.js
/** * Settings component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import { HashRouter } from 'react-router-dom'; /** * WordPress dependencies */ import domReady from '@wordpress/dom-ready'; import { render } from '@wordpress/element'; /** * Internal dependencies */ import './components/legacy-notifications'; import Root from './components/Root'; import SettingsApp from './components/settings/SettingsApp'; import './modules'; // Initialize the app once the DOM is ready. domReady( () => { const renderTarget = document.getElementById( 'googlesitekit-settings-wrapper' ); if ( renderTarget ) { render( <Root dataAPIContext="Settings"> <HashRouter> <SettingsApp /> </HashRouter> </Root>, renderTarget ); } } );
/** * Settings component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import { HashRouter } from 'react-router-dom'; /** * WordPress dependencies */ import domReady from '@wordpress/dom-ready'; import { render } from '@wordpress/element'; /** * Internal dependencies */ import './components/legacy-notifications'; import Root from './components/Root'; import SettingsApp from './components/settings/SettingsApp'; // Initialize the app once the DOM is ready. domReady( () => { const renderTarget = document.getElementById( 'googlesitekit-settings-wrapper' ); if ( renderTarget ) { render( <Root dataAPIContext="Settings"> <HashRouter> <SettingsApp /> </HashRouter> </Root>, renderTarget ); } } );
Remove import ref so builds.
Remove import ref so builds.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
--- +++ @@ -33,7 +33,6 @@ import './components/legacy-notifications'; import Root from './components/Root'; import SettingsApp from './components/settings/SettingsApp'; -import './modules'; // Initialize the app once the DOM is ready. domReady( () => {
9c2095a5ac8baab688a6a063ebf879ec5768ccb1
app/setup/initializers/origin.js
app/setup/initializers/origin.js
import config from 'config'; export const originMiddleware = async (ctx, next) => { ctx.response.set('Access-Control-Allow-Origin', config.origin); ctx.response.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); ctx.response.set('Access-Control-Allow-Headers', [ 'Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'X-Authentication-Token', 'Access-Control-Request-Method', 'Authorization', ].join(', ')); ctx.response.set('Access-Control-Expose-Headers', 'Date, X-Freefeed-Server'); await next(); };
import config from 'config'; export const originMiddleware = async (ctx, next) => { ctx.response.set('Access-Control-Allow-Origin', config.origin); ctx.response.set('Access-Control-Allow-Methods', 'GET,PUT,POST,PATCH,DELETE,OPTIONS'); ctx.response.set('Access-Control-Allow-Headers', [ 'Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'X-Authentication-Token', 'Access-Control-Request-Method', 'Authorization', ].join(', ')); ctx.response.set('Access-Control-Expose-Headers', 'Date, X-Freefeed-Server'); await next(); };
Add PATCH to Access-Control-Allow-Methods header
Add PATCH to Access-Control-Allow-Methods header
JavaScript
mit
FreeFeed/freefeed-server,FreeFeed/freefeed-server
--- +++ @@ -3,7 +3,7 @@ export const originMiddleware = async (ctx, next) => { ctx.response.set('Access-Control-Allow-Origin', config.origin); - ctx.response.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); + ctx.response.set('Access-Control-Allow-Methods', 'GET,PUT,POST,PATCH,DELETE,OPTIONS'); ctx.response.set('Access-Control-Allow-Headers', [ 'Origin', 'X-Requested-With',
0427b16a7ca1a2f1f5811794d798952787ffc6ea
blueprints/ivy-redactor/index.js
blueprints/ivy-redactor/index.js
/* jshint node:true */ module.exports = { afterInstall: function() { return this.addBowerPackageToProject('polyfills-pkg'); }, normalizeEntityName: function() { } };
/* jshint node:true */ module.exports = { normalizeEntityName: function() { } };
Stop requiring a polyfill that we don't need
Stop requiring a polyfill that we don't need
JavaScript
mit
IvyApp/ivy-redactor,IvyApp/ivy-redactor
--- +++ @@ -1,10 +1,6 @@ /* jshint node:true */ module.exports = { - afterInstall: function() { - return this.addBowerPackageToProject('polyfills-pkg'); - }, - normalizeEntityName: function() { } };
e331915acffec129dd38f2d6b797cbe55a39b07f
source/boot/version.js
source/boot/version.js
/* Each Enyo-provided library will annotate this structure with its own version info. Why? In general, Enyo and its libraries are versioned and released together, but libraries may be versioned separately in the future. Also, since libraries are checked out and updated individually, a project may be using "mismatched" libraries at any given time (e.g., the last stable release of Enyo, but an unreleased checkout from the master branch of layout). Enyo uses semantic versioning. Official releases have version numbers of the form "X.y.z". Prereleases are indicated by a suffix of the form "-pre.N" where N is incremented for each prerelease. Between releases, version numbers include an additional "-dev" suffix. */ enyo.version = { enyo: "2.3.0-pre.5-dev" };
/* Each Enyo-provided library will annotate this structure with its own version info. Why? In general, Enyo and its libraries are versioned and released together, but libraries may be versioned separately in the future. Also, since libraries are checked out and updated individually, a project may be using "mismatched" libraries at any given time (e.g., the last stable release of Enyo, but an unreleased checkout from the master branch of layout). Enyo uses semantic versioning. Official releases have version numbers of the form "X.y.z". Prereleases are indicated by a suffix of the form "-pre.N" where N is incremented for each prerelease. Between releases, version numbers include an additional "-dev" suffix. */ enyo.version = { enyo: "2.3.0-pre.5" };
Remove -dev suffix for pilot-5 release.
Remove -dev suffix for pilot-5 release.
JavaScript
apache-2.0
bright-sparks/enyo,enyojs/enyo,mcanthony/enyo,kustomzone/enyo,beni55/enyo,wikieswan/enyo,PKRoma/enyo,soapdog/enyo,beni55/enyo,enyojs/enyo,kustomzone/enyo,bright-sparks/enyo,zefsolutions/enyo,zefsolutions/enyo,PKRoma/enyo,mcanthony/enyo,wikieswan/enyo,soapdog/enyo
--- +++ @@ -15,5 +15,5 @@ */ enyo.version = { - enyo: "2.3.0-pre.5-dev" + enyo: "2.3.0-pre.5" };
1af89b716f562b046bb1673725ee2cb6b660a82d
spec/writeFile.spec.js
spec/writeFile.spec.js
var path = require('path'), fs = require('fs'), crypto = require('crypto'); describe("writeFile functionality", function() { var _this = this; require('./harness.js')(_this); it("creates a directory", function(done) { var fname = "testDir"; var resolved = path.resolve(_this.tempdir, fname); crypto.pseudoRandomBytes(128 * 1024, function(err, data) { if (err) throw err; _this.wd.writeFile(fname, data, function(err) { expect(err).toBe(null); fs.readFile(resolved, function(err, rdata) { if (err) throw err; expect(rdata.toString()).toBe(data.toString()); done(); }); }); }); }); });
var path = require('path'), fs = require('fs'), crypto = require('crypto'); describe("writeFile functionality", function() { var _this = this; require('./harness.js')(_this); it("writes data to a file that doesn't exist", function(done) { var fname = "testDir"; var resolved = path.resolve(_this.tempdir, fname); crypto.pseudoRandomBytes(128 * 1024, function(err, data) { if (err) throw err; _this.wd.writeFile(fname, data, function(err) { expect(err).toBe(null); fs.readFile(resolved, function(err, rdata) { if (err) throw err; expect(rdata.toString()).toBe(data.toString()); done(); }); }); }); }); });
Fix name of writeFile test
Fix name of writeFile test
JavaScript
bsd-2-clause
terribleplan/WorkingDirectory
--- +++ @@ -5,7 +5,7 @@ describe("writeFile functionality", function() { var _this = this; require('./harness.js')(_this); - it("creates a directory", function(done) { + it("writes data to a file that doesn't exist", function(done) { var fname = "testDir"; var resolved = path.resolve(_this.tempdir, fname); crypto.pseudoRandomBytes(128 * 1024, function(err, data) {
1ab1f0a5ee5726f1c917ce6c40e4df03eb647589
sentiment/index.js
sentiment/index.js
// Include The 'require.async' Module require("require.async")(require); /** * Tokenizes an input string. * * @param {String} Input * * @return {Array} */ function tokenize (input) { return input .replace(/[^a-zA-Z ]+/g, "") .replace("/ {2,}/", " ") .toLowerCase() .split(" "); } /** * Performs sentiment analysis on the provided input "term". * * @param {String} Input term * * @return {Object} */ module.exports = function (term, callback) { // Include the AFINN Dictionary JSON asynchronously require.async("./AFINN.json", function(afinn) { // Split line term to letters only words array var words = tokenize(term || ""); var score = 0; var rate; var i = 0; function calculate(word) { // Get the word rate from the AFINN dictionary rate = afinn[word]; if (rate) { // Add current word rate to the final calculated sentiment score score += rate; } // Defer next turn execution (Etheration) setImmediate(function() { // Use callback for completion if (i === (words.length - 1)) { callback(null, score); } else { // Invoke next turn calculate(words[++i]); } }); } // Start calculating calculate(i); }); };
// Include The 'require.async' Module require("require.async")(require); /** * Tokenizes an input string. * * @param {String} Input * * @return {Array} */ function tokenize (input) { return input .replace(/[^a-zA-Z ]+/g, "") .replace("/ {2,}/", " ") .toLowerCase() .split(" "); } /** * Performs sentiment analysis on the provided input "term". * * @param {String} Input term * * @return {Object} */ module.exports = function (term, callback) { // Include the AFINN Dictionary JSON asynchronously require.async("./AFINN.json", function(afinn) { // Split line term to letters only words array var words = tokenize(term || ""); var score = 0; var rate; var i = 0; function calculate(word) { // Get the word rate from the AFINN dictionary rate = afinn[word]; if (rate) { // Add current word rate to the final calculated sentiment score score += rate; } // Defer next turn execution (Etheration) setImmediate(function() { // Use callback for completion if (i === (words.length - 1)) { callback(null, score); } else { // Invoke next turn calculate(words[++i]); } }); } // Start calculating calculate(words[i]); }); };
Fix bug in sentiment calculation
Fix bug in sentiment calculation Signed-off-by: Itai Koren <7a3f8a9ea5df78694ad87e4c8117b31e1b103a24@gmail.com>
JavaScript
mit
itkoren/Lets-Node-ex-8
--- +++ @@ -56,6 +56,6 @@ } // Start calculating - calculate(i); + calculate(words[i]); }); };
1ec5cc77997e6cc254b1891c2efdc1839f63625e
client/src/actions.js
client/src/actions.js
import { createAction } from 'redux-actions'; export const REQUEST_LOGIN = "REQUEST_LOGIN"; export const SUCCESS_LOGIN = "SUCCESS_LOGIN"; export const FAILURE_LOGIN = "FAILURE_LOGIN"; export const REQUEST_SUBMIT_SONG = "REQUEST_SUBMIT_SONG"; export const SUCCESS_SUBMIT_SONG = "SUCCESS_SUBMIT_SONG"; export const FAILURE_SUBMIT_SONG = "FAILURE_SUBMIT_SONG"; export const INPUT_QUERY = "INPUT_QUERY"; export const REQUEST_SEARCH = "REQUEST_SEARCH"; export const SUCCESS_SEARCH = "SUCCESS_SEARCH"; export const FAILURE_SEARCH = "FAILURE_SEARCH"; export const ADDED_SONG = "ADDED_SONG"; export const RequestLogin = createAction(REQUEST_LOGIN); export const SuccessLogin = createAction(SUCCESS_LOGIN); export const FailureLogin = createAction(FAILURE_LOGIN); export const RequestSubmitSong = createAction(REQUEST_SUBMIT_SONG); export const SuccessSubmitSong = createAction(SUCCESS_SUBMIT_SONG); export const FailureSubmitSong = createAction(FAILURE_SUBMIT_SONG); export const InputQuery = createAction(INPUT_QUERY); export const RequestSearch = createAction(REQUEST_SEARCH); export const SuccessSearch = createAction(SUCCESS_SEARCH); export const FailureSearch = createAction(FAILURE_SEARCH); export const AddedSong = createAction(ADDED_SONG);
import { createAction } from 'redux-actions'; export createActions( "REQUEST_LOGIN", "SUCCESS_LOGIN", "FAILURE_LOGIN", "REQUEST_SUBMIT_SONG", "SUCCESS_SUBMIT_SONG", "FAILURE_SUBMIT_SONG", "INPUT_QUERY", "REQUEST_SEARCH", "SUCCESS_SEARCH", "FAILURE_SEARCH", "ADDED_SONG", "PLAYED_SONG" );
Use createActions to create actioncreator
Use createActions to create actioncreator
JavaScript
mit
ygkn/DJ-YAGICHAN-SYSTEM,ygkn/DJ-YAGICHAN-SYSTEM
--- +++ @@ -1,25 +1,16 @@ import { createAction } from 'redux-actions'; -export const REQUEST_LOGIN = "REQUEST_LOGIN"; -export const SUCCESS_LOGIN = "SUCCESS_LOGIN"; -export const FAILURE_LOGIN = "FAILURE_LOGIN"; -export const REQUEST_SUBMIT_SONG = "REQUEST_SUBMIT_SONG"; -export const SUCCESS_SUBMIT_SONG = "SUCCESS_SUBMIT_SONG"; -export const FAILURE_SUBMIT_SONG = "FAILURE_SUBMIT_SONG"; -export const INPUT_QUERY = "INPUT_QUERY"; -export const REQUEST_SEARCH = "REQUEST_SEARCH"; -export const SUCCESS_SEARCH = "SUCCESS_SEARCH"; -export const FAILURE_SEARCH = "FAILURE_SEARCH"; -export const ADDED_SONG = "ADDED_SONG"; - -export const RequestLogin = createAction(REQUEST_LOGIN); -export const SuccessLogin = createAction(SUCCESS_LOGIN); -export const FailureLogin = createAction(FAILURE_LOGIN); -export const RequestSubmitSong = createAction(REQUEST_SUBMIT_SONG); -export const SuccessSubmitSong = createAction(SUCCESS_SUBMIT_SONG); -export const FailureSubmitSong = createAction(FAILURE_SUBMIT_SONG); -export const InputQuery = createAction(INPUT_QUERY); -export const RequestSearch = createAction(REQUEST_SEARCH); -export const SuccessSearch = createAction(SUCCESS_SEARCH); -export const FailureSearch = createAction(FAILURE_SEARCH); -export const AddedSong = createAction(ADDED_SONG); +export createActions( + "REQUEST_LOGIN", + "SUCCESS_LOGIN", + "FAILURE_LOGIN", + "REQUEST_SUBMIT_SONG", + "SUCCESS_SUBMIT_SONG", + "FAILURE_SUBMIT_SONG", + "INPUT_QUERY", + "REQUEST_SEARCH", + "SUCCESS_SEARCH", + "FAILURE_SEARCH", + "ADDED_SONG", + "PLAYED_SONG" +);
146601a2d4ebe4f9549146907c9c1fb757cf3405
src/kit/ui/_IsolatedInlineNodeComponent.js
src/kit/ui/_IsolatedInlineNodeComponent.js
import { IsolatedInlineNodeComponent as SubstanceIsolatedInlineNodeComponent } from 'substance' /* This is overriding Substance.IsolatedInlineNodeComponent to support Models. */ export default class IsolatedInlineNodeComponentNew extends SubstanceIsolatedInlineNodeComponent { // overriding AbstractIsolatedNodeComponent.didMount() because it uses deprecated EditorSession.onRender() didMount () { let appState = this.context.appState appState.addObserver(['selection'], this._onSelectionChanged, this, { stage: 'render' }) } // overriding AbstractIsolatedNodeComponent.dispose() because it uses EditorSession.off() in a way which has been deprecated dispose () { this.context.appState.off(this) } }
import { IsolatedInlineNodeComponent as SubstanceIsolatedInlineNodeComponent } from 'substance' /* This is overriding Substance.IsolatedInlineNodeComponent to support Models. */ export default class IsolatedInlineNodeComponentNew extends SubstanceIsolatedInlineNodeComponent { // overriding AbstractIsolatedNodeComponent.didMount() because it uses deprecated EditorSession.onRender() didMount () { let appState = this.context.appState appState.addObserver(['selection'], this._onSelectionChanged, this, { stage: 'render' }) } // overriding AbstractIsolatedNodeComponent.dispose() because it uses EditorSession.off() in a way which has been deprecated dispose () { this.context.appState.off(this) } render ($$) { let el = super.render($$) // HACK: substnace IsoloatedInlineNodeComponent does not listen on click, but IMO this should be the case. // TODO instead of this HACK fix the implementation in Substance Land if (!this.isDisabled()) { el.on('click', this.onClick) } return el } }
Add a click hook to IsolatedInlineNodeComponent.
Add a click hook to IsolatedInlineNodeComponent.
JavaScript
mit
substance/texture,substance/texture
--- +++ @@ -14,4 +14,14 @@ dispose () { this.context.appState.off(this) } + + render ($$) { + let el = super.render($$) + // HACK: substnace IsoloatedInlineNodeComponent does not listen on click, but IMO this should be the case. + // TODO instead of this HACK fix the implementation in Substance Land + if (!this.isDisabled()) { + el.on('click', this.onClick) + } + return el + } }
7f641cdf7fa3c1507c50e4bad02ec6ee2f9a13d7
problems/kata/001-todo-backend/001/todo.js
problems/kata/001-todo-backend/001/todo.js
var nano = require('nano')('http://localhost:5984'); var db = nano.db.use('todo'); var todo = {}; module.exports = todo;
var nano = require('nano')('http://localhost:5984'); var db = nano.db.use('todo'); var todo = {}; todo.getAll = function() { var results = []; db.view('todos', 'all_todos', function(err, body) { for (var row of body.rows) { results.push(row.value); } return results; }); }; module.exports = todo;
Copy get all logic into a getAll function.
Copy get all logic into a getAll function.
JavaScript
mit
PurityControl/uchi-komi-js
--- +++ @@ -3,4 +3,14 @@ var todo = {}; +todo.getAll = function() { + var results = []; + db.view('todos', 'all_todos', function(err, body) { + for (var row of body.rows) { + results.push(row.value); + } + return results; + }); +}; + module.exports = todo;
7e33179406372482e0cfba1f14b5959883ae7fa3
backend/index.js
backend/index.js
"use strict"; var debug = require('debug')('server'); var express = require('express'); var path = require('path'); var routes = require('./routes/index'); var app = express(); app.use('/', routes); app.set('view engine', 'jade'); app.set('views', path.join(__dirname, 'views')); var server = app.listen(process.env.PORT || 3000, function () { var host = server.address().address; var port = server.address().port; debug('listening at http://%s:%s', host, port); });
"use strict"; var debug = require('debug')('server'); var express = require('express'); var io = require('socket.io')(); var path = require('path'); var routes = require('./routes/index'); var app = express(); app.use('/', routes); app.set('view engine', 'jade'); app.set('views', path.join(__dirname, 'views')); var server = app.listen(process.env.PORT || 3000, function () { var host = server.address().address; var port = server.address().port; debug('listening at http://%s:%s', host, port); }); io.attach(server); io.on('connection', function (socket) { debug('+1 socket connection'); io.emit('test', { message: 'Hey, everyone! +1 connection' }); socket.on('test', function (data) { debug('received: %s', data); }); socket.on('disconnect', function () { debug('-1 socket connection'); }); });
Integrate socket.io to the backend.
Integrate socket.io to the backend. with dummy lines.
JavaScript
mit
team-kke/erichika
--- +++ @@ -2,6 +2,7 @@ var debug = require('debug')('server'); var express = require('express'); +var io = require('socket.io')(); var path = require('path'); var routes = require('./routes/index'); @@ -19,3 +20,16 @@ debug('listening at http://%s:%s', host, port); }); + +io.attach(server); + +io.on('connection', function (socket) { + debug('+1 socket connection'); + io.emit('test', { message: 'Hey, everyone! +1 connection' }); + socket.on('test', function (data) { + debug('received: %s', data); + }); + socket.on('disconnect', function () { + debug('-1 socket connection'); + }); +});
2c2517cef0f4b3183b8bbeabc72ff754a82178fc
web_external/js/init.js
web_external/js/init.js
/*global isic:true*/ var isic = isic || {}; _.extend(isic, { models: {}, collections: {}, views: {}, router: new Backbone.Router(), events: _.clone(Backbone.Events) }); girder.router.enabled(false);
/*global isic:true*/ var isic = isic || {}; _.extend(isic, { models: {}, collections: {}, views: {}, router: new Backbone.Router(), events: girder.events }); girder.router.enabled(false);
Make isic.events an alias for girder.events
Make isic.events an alias for girder.events Make isic.events an alias for girder.events instead of a separate object. For one, this ensures that triggering the 'g:appload.before' and 'g:appload.after' events in main.js reach plugins that observe those events on girder.events, such as the google_analytics plugin.
JavaScript
apache-2.0
ImageMarkup/isic-archive,ImageMarkup/isic-archive,ImageMarkup/isic-archive,ImageMarkup/isic-archive
--- +++ @@ -7,7 +7,7 @@ collections: {}, views: {}, router: new Backbone.Router(), - events: _.clone(Backbone.Events) + events: girder.events }); girder.router.enabled(false);
ddcc84a84d3eced473e57c46c5f667424b4386fa
test/integration/test-remote.js
test/integration/test-remote.js
const Test = require('./include/runner'); const setUp = (context) => { return context.gitP(context.root).init(); }; describe('remote', () => { let context; let REMOTE_URL = 'https://github.com/steveukx/git-js.git'; beforeEach(() => setUp(context = Test.createContext())); it('adds and removes named remotes', async () => { const {gitP, root} = context; await gitP(root).addRemote('remote-name', REMOTE_URL); expect(await gitP(root).getRemotes(true)).toEqual([ { name: 'remote-name', refs: { fetch: REMOTE_URL, push: REMOTE_URL }}, ]); await gitP(root).removeRemote('remote-name'); expect(await gitP(root).getRemotes(true)).toEqual([]); }); })
const Test = require('./include/runner'); const setUp = (context) => { return context.gitP(context.root).init(); }; describe('remote', () => { let context; let REMOTE_URL_ROOT = 'https://github.com/steveukx'; let REMOTE_URL = `${ REMOTE_URL_ROOT }/git-js.git`; beforeEach(() => setUp(context = Test.createContext())); it('adds and removes named remotes', async () => { const {gitP, root} = context; await gitP(root).addRemote('remote-name', REMOTE_URL); expect(await gitP(root).getRemotes(true)).toEqual([ {name: 'remote-name', refs: {fetch: REMOTE_URL, push: REMOTE_URL}}, ]); await gitP(root).removeRemote('remote-name'); expect(await gitP(root).getRemotes(true)).toEqual([]); }); it('allows setting the remote url', async () => { const {gitP, root} = context; const git = gitP(root); let repoName = 'origin'; let initialRemoteRepo = `${REMOTE_URL_ROOT}/initial.git`; let updatedRemoteRepo = `${REMOTE_URL_ROOT}/updated.git`; await git.addRemote(repoName, initialRemoteRepo); expect(await git.getRemotes(true)).toEqual([ {name: repoName, refs: {fetch: initialRemoteRepo, push: initialRemoteRepo}}, ]); await git.remote(['set-url', repoName, updatedRemoteRepo]); expect(await git.getRemotes(true)).toEqual([ {name: repoName, refs: {fetch: updatedRemoteRepo, push: updatedRemoteRepo}}, ]); }); })
Add test for using `addRemote` and `remote(['set-url', ...])'`
Add test for using `addRemote` and `remote(['set-url', ...])'` Ref: #452
JavaScript
mit
steveukx/git-js,steveukx/git-js
--- +++ @@ -7,7 +7,8 @@ describe('remote', () => { let context; - let REMOTE_URL = 'https://github.com/steveukx/git-js.git'; + let REMOTE_URL_ROOT = 'https://github.com/steveukx'; + let REMOTE_URL = `${ REMOTE_URL_ROOT }/git-js.git`; beforeEach(() => setUp(context = Test.createContext())); @@ -16,11 +17,31 @@ await gitP(root).addRemote('remote-name', REMOTE_URL); expect(await gitP(root).getRemotes(true)).toEqual([ - { name: 'remote-name', refs: { fetch: REMOTE_URL, push: REMOTE_URL }}, + {name: 'remote-name', refs: {fetch: REMOTE_URL, push: REMOTE_URL}}, ]); await gitP(root).removeRemote('remote-name'); expect(await gitP(root).getRemotes(true)).toEqual([]); }); + it('allows setting the remote url', async () => { + const {gitP, root} = context; + const git = gitP(root); + + let repoName = 'origin'; + let initialRemoteRepo = `${REMOTE_URL_ROOT}/initial.git`; + let updatedRemoteRepo = `${REMOTE_URL_ROOT}/updated.git`; + + await git.addRemote(repoName, initialRemoteRepo); + expect(await git.getRemotes(true)).toEqual([ + {name: repoName, refs: {fetch: initialRemoteRepo, push: initialRemoteRepo}}, + ]); + + await git.remote(['set-url', repoName, updatedRemoteRepo]); + expect(await git.getRemotes(true)).toEqual([ + {name: repoName, refs: {fetch: updatedRemoteRepo, push: updatedRemoteRepo}}, + ]); + + }); + })
ce70133b029a387bc4af082e44d85ac0b77bc698
config/Definitions.js
config/Definitions.js
module.exports = { Env: process.env.NODE_ENV || 'development', Permissions: { viewPage: 'viewPage' }, boxWidth: 55, boxHeight: 30, Difficulties: { 1: { name: 'Very Easy', percent: 10 }, 2: { name: 'Easy', percent: 15 }, 3: { name: 'Medium', percent: 20 }, 4: { name: 'Hard', percent: 30 }, 5: { name: 'Nightmare', percent: 60 }, 6: { name: 'Impossibruuu!!', percent: 90 } } };
module.exports = { Env: process.env.NODE_ENV || 'development', Permissions: { viewPage: 'viewPage' }, boxWidth: 40, boxHeight: 35, Difficulties: { 1: { name: 'Very Easy', percent: 10 }, 2: { name: 'Easy', percent: 15 }, 3: { name: 'Medium', percent: 20 }, 4: { name: 'Hard', percent: 30 }, 5: { name: 'Nightmare', percent: 60 }, 6: { name: 'Impossibruuu!!', percent: 90 } } };
Adjust dimensions of grid to be squarer
Adjust dimensions of grid to be squarer
JavaScript
mit
EnzoMartin/Minesweeper-React,EnzoMartin/Minesweeper-React
--- +++ @@ -3,8 +3,8 @@ Permissions: { viewPage: 'viewPage' }, - boxWidth: 55, - boxHeight: 30, + boxWidth: 40, + boxHeight: 35, Difficulties: { 1: { name: 'Very Easy',
5f6c2a23b524f1b6465e3335956b2d62e9c6f42b
index.js
index.js
(function() { 'use strict'; var ripper = require('./Rip'), encoder = require('./Encode'), ui = require('bull-ui/app')({ redis: { host: 'localhost', port: '6379' } }), Queue = require('bull'); ui.listen(1337, function() { console.log('bull-ui started listening on port', this.address().port); }); var ripQ = Queue('disc ripping'); var encodeQ = Queue('video encoding'); encodeQ.add({ type: './HandBrakeCLI', options: '-Z "High Profile" -O -q 21 --main-feature --min-duration 2000 -i /mnt/temp/RIP -o', destination: '/mnt/temp' }); ripQ.add({ destination: '/mnt/temp' }); encodeQ.process(function(job) { return encoder.encode(job); }); ripQ.process(function(job) { return ripper.rip(job); }); }());
(function() { 'use strict'; var ripper = require('./Rip'), fs = require('fs'), encoder = require('./Encode'), ui = require('bull-ui/app')({ redis: { host: 'localhost', port: '6379' } }), Queue = require('bull'); ui.listen(1337, function() { console.log('bull-ui started listening on port', this.address().port); }); var ripQ = Queue('disc ripping'); var encodeQ = Queue('video encoding'); encodeQ.add({ type: './HandBrakeCLI', options: '-Z "High Profile" -O -q 21 --main-feature --min-duration 2000 -i /mnt/temp/RIP -o', destination: '/mnt/temp' }); ripQ.add({ destination: '/mnt/temp' }); encodeQ.process(function(job) { return encoder.encode(job); }); if(fs.existsSync('/dev/sr0')) { //if a DVD device exists, then we can process the Ripping queue ripQ.process(function(job) { return ripper.rip(job); }); } }());
Check for DVD device for ripping queue processing
Check for DVD device for ripping queue processing
JavaScript
mit
aztechian/ncoder,aztechian/ncoder
--- +++ @@ -2,6 +2,7 @@ 'use strict'; var ripper = require('./Rip'), + fs = require('fs'), encoder = require('./Encode'), ui = require('bull-ui/app')({ redis: { @@ -32,7 +33,11 @@ return encoder.encode(job); }); - ripQ.process(function(job) { - return ripper.rip(job); - }); + if(fs.existsSync('/dev/sr0')) { + //if a DVD device exists, then we can process the Ripping queue + ripQ.process(function(job) { + return ripper.rip(job); + }); + } + }());
3086a6cb835bc47ca26c357178612f01b6f4ade8
src/server/webapp.js
src/server/webapp.js
'use strict'; const path = require('path'); const express = require('express'); const bodyParser = require('body-parser'); const routes = require('./controllers/routes'); let app = express(); // Configure view engine and views directory app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // Configure middleware app.use(bodyParser.urlencoded({ extended: false })); // Static file serving happens everywhere but in production if (process.env.NODE_ENV !== 'production') { let staticPath = path.join(__dirname, '..', '..', 'public'); app.use('/static', express.static(staticPath)); } // Mount application routes routes(app); // Export Express webapp instance module.exports = app;
'use strict'; const path = require('path'); const express = require('express'); const bodyParser = require('body-parser'); const routes = require('./controllers/routes'); let app = express(); // Configure view engine and views directory app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); app.set('x-powered-by', false); // Configure middleware app.use(bodyParser.urlencoded({ extended: false })); // Static file serving happens everywhere but in production if (process.env.NODE_ENV !== 'production') { let staticPath = path.join(__dirname, '..', '..', 'public'); app.use('/static', express.static(staticPath)); } // Mount application routes routes(app); // Export Express webapp instance module.exports = app;
Remove the 'X-Powered-By: Express' HTTP response header
Remove the 'X-Powered-By: Express' HTTP response header Fixes #2
JavaScript
mit
kwhinnery/todomvc-plusplus,kwhinnery/todomvc-plusplus
--- +++ @@ -10,6 +10,7 @@ // Configure view engine and views directory app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); +app.set('x-powered-by', false); // Configure middleware app.use(bodyParser.urlencoded({ extended: false }));
350cfb9149d7137d54cc53dee10d6d367ab24bfb
test/imagenames.js
test/imagenames.js
var test = require('tape') var names = require('../lib/imageref.js') test('litmus', function (t) { t.plan(2) t.looseEqual( names(['1', '']), ['atom-h'] ) t.looseEqual( names(['1', 'gc']), ['bond-left', 'bond-right', 'atom-h'] ) })
var test = require('tape') var names = require('../lib/imagenames.js') test('litmus', function (t) { t.plan(2) t.looseEqual( names(['1', '']), ['atom-h'] ) t.looseEqual( names(['1', 'gc']), ['bond-left', 'bond-right', 'atom-h'] ) })
Fix last minute name chang bug.
Fix last minute name chang bug.
JavaScript
isc
figlief/jsatomix
--- +++ @@ -1,5 +1,5 @@ var test = require('tape') -var names = require('../lib/imageref.js') +var names = require('../lib/imagenames.js') test('litmus', function (t) { t.plan(2)
80ce4c3203bff1e5848360d91a507778ea86edc3
index.js
index.js
var postcss = require('postcss'); module.exports = postcss.plugin('postcss-prefixer-font-face', function (opts) { opts = opts || {}; var prefix = opts.prefix || ''; var usedFonts = []; return function (css, result) { /* Font Faces */ css.walkAtRules(/font-face$/, function (font) { font.walkDecls(/font-family/, function (decl) { var fontName = decl.value.replace(/['"]+/g, ''); usedFonts.push(fontName); decl.value = '\''+String(prefix+fontName)+'\''; }); }); css.walkDecls(/font-family/, function (decl) { var fontName = decl.value.replace(/['"]+/g, ''); if (usedFonts.indexOf(fontName) > -1) { decl.value = '\''+String(prefix+fontName)+'\''; } }); }; });
var postcss = require('postcss'); module.exports = postcss.plugin('postcss-prefixer-font-face', function (opts) { opts = opts || {}; var prefix = opts.prefix || ''; var usedFonts = []; return function (css, result) { /* Font Faces */ css.walkAtRules(/font-face$/, function (font) { font.walkDecls(/font-family/, function (decl) { var fontName = decl.value.replace(/['"]+/g, ''); usedFonts.push(fontName); decl.value = String(prefix + fontName); }); }); css.walkDecls(/font-family/, function (decl) { var fontNames = decl.value.replace(/['"]+/g, '').split(','); for (var i = 0; i < fontNames.length; i++) { var fontName = fontNames[i].trim(); if (usedFonts.indexOf(fontName) > -1) { fontNames[i] = String(prefix + fontName); } } decl.value = fontNames.join(','); }); }; });
Support prefix if multiple font families are used
Support prefix if multiple font families are used
JavaScript
bsd-2-clause
koala-framework/postcss-prefixer-font-face
--- +++ @@ -14,15 +14,19 @@ font.walkDecls(/font-family/, function (decl) { var fontName = decl.value.replace(/['"]+/g, ''); usedFonts.push(fontName); - decl.value = '\''+String(prefix+fontName)+'\''; + decl.value = String(prefix + fontName); }); }); css.walkDecls(/font-family/, function (decl) { - var fontName = decl.value.replace(/['"]+/g, ''); - if (usedFonts.indexOf(fontName) > -1) { - decl.value = '\''+String(prefix+fontName)+'\''; + var fontNames = decl.value.replace(/['"]+/g, '').split(','); + for (var i = 0; i < fontNames.length; i++) { + var fontName = fontNames[i].trim(); + if (usedFonts.indexOf(fontName) > -1) { + fontNames[i] = String(prefix + fontName); + } } + decl.value = fontNames.join(','); }); }; });
d117690efaadd5db838818cbe43a1dbaa63ca885
index.js
index.js
'use strict'; var async = require("async"); function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } module.exports = function seeder(seedObject, mongoose, logger, cb) { if(!cb) { cb = logger; logger = console.log; } var ObjectId = mongoose.Types.ObjectId; async.each(Object.keys(seedObject), function(mongoModel, cb) { var documents = seedObject[mongoModel]; var mongoModelName = capitalize(mongoModel); var Model = mongoose.model(mongoModelName); async.each(Object.keys(documents), function(_id, cb) { // Fake an upsert call, to keep the hooks Model.findById(_id, function(err, mongoDocument) { if(err) { return cb(err); } if(!mongoDocument) { mongoDocument = new Model({_id: new ObjectId(_id)}); } var document = documents[_id]; for(var key in document) { mongoDocument[key] = document[key]; mongoDocument.markModified(key); } logger(mongoModelName, _id); mongoDocument.save(cb); }); }, cb); }, cb); };
'use strict'; var async = require("async"); function capitalize(string) { return string.charAt(0).toUpperCase() + string.slice(1); } module.exports = function seeder(seedObject, mongoose, logger, cb) { if(!cb) { cb = logger; logger = console.log; } var ObjectId = mongoose.Types.ObjectId; async.each(Object.keys(seedObject), function(mongoModel, cb) { var documents = seedObject[mongoModel]; var mongoModelName = capitalize(mongoModel); var Model = mongoose.model(mongoModelName); async.each(Object.keys(documents), function(_id, cb) { var document = documents[_id]; if(document._id) { _id = document._id; } // Fake an upsert call, to keep the hooks Model.findById(_id, function(err, mongoDocument) { if(err) { return cb(err); } if(!mongoDocument) { mongoDocument = new Model({_id: new ObjectId(_id)}); } for(var key in document) { mongoDocument[key] = document[key]; mongoDocument.markModified(key); } logger(mongoModelName, _id); mongoDocument.save(cb); }); }, cb); }, cb); };
Add managing of _id field
Add managing of _id field
JavaScript
mit
AnyFetch/seeder.js
--- +++ @@ -20,6 +20,12 @@ var Model = mongoose.model(mongoModelName); async.each(Object.keys(documents), function(_id, cb) { + var document = documents[_id]; + + if(document._id) { + _id = document._id; + } + // Fake an upsert call, to keep the hooks Model.findById(_id, function(err, mongoDocument) { if(err) { @@ -29,7 +35,6 @@ mongoDocument = new Model({_id: new ObjectId(_id)}); } - var document = documents[_id]; for(var key in document) { mongoDocument[key] = document[key]; mongoDocument.markModified(key);
b98db4ad0e627c6a5326e8cabfde1e71e4bfdf2e
test/plexacious.js
test/plexacious.js
const { expect } = require('chai'); const Plexacious = require('../lib/Plexacious'); const config = { "hostname": process.env.PLEX_SERVER_HOST, "port": process.env.PLEX_SERVER_PORT, "https": process.env.PLEX_SERVER_HTTPS, "token": process.env.PLEX_AUTH_TOKEN }; const plex = new Plexacious(config); describe('Plexacious:', () => { describe('Event attaching:', () => { it('should instantiate with no events', () => { expect(plex.events()).to.deep.equal({}); expect(typeof plex.events('test')).to.equal('undefined'); }); it('should attach a callback to an event', () => { plex.on('test', () => {}); expect(Object.keys(plex.events()).length).to.equal(1); expect(typeof plex.events('test')).to.equal('function'); }); }); describe('Recently Added:', () => { }); });
const { expect } = require('chai'); const Plexacious = require('../lib/Plexacious'); const env = require('node-env-file'); env('./.env'); const config = { "hostname": process.env.PLEX_SERVER_HOST, "port": process.env.PLEX_SERVER_PORT, "https": process.env.PLEX_SERVER_HTTPS, "token": process.env.PLEX_AUTH_TOKEN }; const plex = new Plexacious(config); describe('Plexacious:', () => { describe('Event attaching:', () => { it('should instantiate with no events', () => { expect(plex.eventFunctions()).to.deep.equal({}); expect(typeof plex.eventFunctions('test')).to.equal('undefined'); }); it('should attach a callback to an event', () => { plex.on('test', () => {}); expect(Object.keys(plex.eventFunctions()).length).to.equal(1); expect(typeof plex.eventFunctions('test')).to.equal('function'); }); }); describe('Recently Added:', () => { }); });
Fix events() call to match renamed function eventFunctions()
Fix events() call to match renamed function eventFunctions()
JavaScript
isc
ketsugi/plexacious
--- +++ @@ -1,5 +1,7 @@ const { expect } = require('chai'); const Plexacious = require('../lib/Plexacious'); +const env = require('node-env-file'); +env('./.env'); const config = { "hostname": process.env.PLEX_SERVER_HOST, "port": process.env.PLEX_SERVER_PORT, @@ -12,14 +14,14 @@ describe('Plexacious:', () => { describe('Event attaching:', () => { it('should instantiate with no events', () => { - expect(plex.events()).to.deep.equal({}); - expect(typeof plex.events('test')).to.equal('undefined'); + expect(plex.eventFunctions()).to.deep.equal({}); + expect(typeof plex.eventFunctions('test')).to.equal('undefined'); }); it('should attach a callback to an event', () => { plex.on('test', () => {}); - expect(Object.keys(plex.events()).length).to.equal(1); - expect(typeof plex.events('test')).to.equal('function'); + expect(Object.keys(plex.eventFunctions()).length).to.equal(1); + expect(typeof plex.eventFunctions('test')).to.equal('function'); }); });
203add406fbf5e23976bb32cac99bf004ba5eb4d
src/filter.js
src/filter.js
function hide_covers() { // Remove covers $(".mix_element div.cover").remove() // Add class so cards can be restyled $(".mix_card.half_card").addClass("ext-coverless_card") // Remove covers on track page $("#cover_art").remove() // Remove covers in the sidebar of a track page $(".card.sidebar_mix .cover").remove() $(".card.sidebar_mix").addClass("ext-coverless_card") // Remove covers in "suggested collections" $(".suggested_collection .covers").remove() $(".suggested_collection").addClass("ext-coverless_card") } function filter() { chrome.storage.local.get("state", function(result) { if(result["state"] == "on") { hide_covers() } }); } // Make sure that when we navigate the site (which doesn't refresh the page), the filter is still run var observer = new MutationObserver(filter) observer.observe(document.getElementById("main"), {childList: true, subtree: true}) filter();
function hide_covers() { // Remove covers $(".mix_element div.cover").remove() // Add class so cards can be restyled $(".mix_card.half_card").addClass("ext-coverless_card") // Remove covers on track page $("#cover_art").remove() // Remove covers in the sidebar of a track page $(".card.sidebar_mix .cover").remove() $(".card.sidebar_mix").addClass("ext-coverless_card") // Remove covers in "suggested collections" $(".suggested_collection .covers").remove() $(".suggested_collection").addClass("ext-coverless_card") // Remove mini covers ("Because you liked ____") // Replace with 8tracks icon $(".card img.mini-cover") .replaceWith("<span class='avatar'><span class='i-logo'></span></span>") } function filter() { chrome.storage.local.get("state", function(result) { if(result["state"] == "on") { hide_covers() } }); } // Make sure that when we navigate the site (which doesn't refresh the page), the filter is still run var observer = new MutationObserver(filter) observer.observe(document.getElementById("main"), {childList: true, subtree: true}) filter();
Replace mini covers with 8tracks icon
Replace mini covers with 8tracks icon
JavaScript
mit
pbhavsar/8tracks-Filter
--- +++ @@ -13,6 +13,11 @@ // Remove covers in "suggested collections" $(".suggested_collection .covers").remove() $(".suggested_collection").addClass("ext-coverless_card") + + // Remove mini covers ("Because you liked ____") + // Replace with 8tracks icon + $(".card img.mini-cover") + .replaceWith("<span class='avatar'><span class='i-logo'></span></span>") } function filter() {
877e9a521fe131978cd63b0af669c01746fe1d8c
index.js
index.js
var cookie = require('cookie'); var _cookies = cookie.parse((typeof document !== 'undefined') ? document.cookie : ''); for (var key in _cookies) { try { _cookies[key] = JSON.parse(_cookies[key]); } catch(e) { // Not serialized object } } function load(name) { return _cookies[name]; } function save(name, val, opt) { _cookies[name] = val; // Cookies only work in the browser if (typeof document === 'undefined') return; document.cookie = cookie.serialize(name, val, opt); } var reactCookie = { load: load, save: save }; if (typeof module !== 'undefined') { module.exports = reactCookie } if (typeof window !== 'undefined') { window['reactCookie'] = reactCookie; }
var cookie = require('cookie'); var _cookies = cookie.parse((typeof document !== 'undefined') ? document.cookie : ''); for (var key in _cookies) { try { _cookies[key] = JSON.parse(_cookies[key]); } catch(e) { // Not serialized object } } function load(name) { return _cookies[name]; } function save(name, val, opt) { _cookies[name] = val; // Cookies only work in the browser if (typeof document === 'undefined') return; // allow you to work with cookies as objects. if (typeof val === 'object') val = JSON.stringify(val); document.cookie = cookie.serialize(name, val, opt); } var reactCookie = { load: load, save: save }; if (typeof module !== 'undefined') { module.exports = reactCookie } if (typeof window !== 'undefined') { window['reactCookie'] = reactCookie; }
Fix cookie not being parsed on load.
Fix cookie not being parsed on load. If you have to stringify your object before saving, and you add that, to the `_cookies` cache, then you'll return that on `load` after setting it with `save`. While if the value is already set, the script correctly parses the cookie values and what you load is returned as an object. This oneliner takes care of that for you.
JavaScript
mit
ChrisCinelli/react-cookie-async,reactivestack/cookies,xpepermint/react-cookie,eXon/react-cookie,reactivestack/cookies,reactivestack/cookies
--- +++ @@ -16,10 +16,13 @@ function save(name, val, opt) { _cookies[name] = val; - + // Cookies only work in the browser if (typeof document === 'undefined') return; + // allow you to work with cookies as objects. + if (typeof val === 'object') val = JSON.stringify(val); + document.cookie = cookie.serialize(name, val, opt); }
d982c14d41f9a36e34471c19bc3cf277a64685ee
index.js
index.js
#!/usr/bin/env node 'use strict'; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; process.argv.splice(0, 2); if (process.argv.length > 0) { // Attempt to parse the date let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (parsedDate != "Invalid Date") { // Date could be parsed, parse the date to git date format let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); // Actually modify the dates let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit"; exec(command, (err, stdout, stderr) => { if (err) { console.log("fatal: Could not change the previous commit"); } else { console.log("\nModified previous commit:\n\tAUTHOR_DATE " + chalk.grey(dateString) + "\n\tCOMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n\t" + chalk.bgWhite.black(command) + "\n"); } }); } else { console.log("fatal: Could not parse \"" + date + "\" into a valid date"); } } else { console.log("fatal: No date string given"); }
#!/usr/bin/env node "use strict"; const moment = require("moment"); const sugar = require("sugar"); const chalk = require("chalk"); const exec = require("child_process").exec; process.argv.splice(0, 2); if (process.argv.length > 0) { // Attempt to parse the date let date = process.argv.join(" "); let parsedDate = new sugar.Date.create(date); if (parsedDate != "Invalid Date") { // Date could be parsed, parse the date to git date format let dateString = moment(parsedDate).format("ddd MMM DD HH:mm:ss YYYY ZZ"); // Actually modify the dates let command = "GIT_COMMITTER_DATE=\"" + dateString + "\" git commit --amend --date=\"" + dateString + "\" --no-edit"; exec(command, (err, stdout, stderr) => { if (err) { console.log("fatal: Could not change the previous commit"); } else { console.log("\nModified previous commit:\n\tAUTHOR_DATE " + chalk.grey(dateString) + "\n\tCOMMITTER_DATE " + chalk.grey(dateString) + "\n\nCommand executed:\n\t" + chalk.bgWhite.black(command) + "\n"); } }); } else { console.log("fatal: Could not parse \"" + date + "\" into a valid date"); } } else { console.log("fatal: No date string given"); }
Use double quotes on "use strict"
Use double quotes on "use strict"
JavaScript
mit
sam3d/git-date
--- +++ @@ -1,6 +1,6 @@ #!/usr/bin/env node -'use strict'; +"use strict"; const moment = require("moment"); const sugar = require("sugar");
79bf07a15de57912c2f6a0306e028fb3e99fa31e
index.js
index.js
var child_process = require('child_process'); var byline = require('./byline'); exports.handler = function(event, context) { var proc = child_process.spawn('./main', [JSON.stringify(event)], { stdio: [process.stdin, 'pipe', 'pipe'] }); proc.stdout.on('data', function(line){ var msg = JSON.parse(line); context.succeed(msg); }) proc.stderr.on('data', function(line){ var msg = new Error(line) context.fail(msg); }) proc.on('exit', function(code){ console.error('exit blabla: %s', code) context.fail("No results") }) }
var child_process = require('child_process'); exports.handler = function(event, context) { var proc = child_process.spawn('./main', [JSON.stringify(event)], { stdio: [process.stdin, 'pipe', 'pipe'] }); proc.stdout.on('data', function(line){ var msg = JSON.parse(line); context.succeed(msg); }) proc.stderr.on('data', function(line){ var msg = new Error(line) context.fail(msg); }) proc.on('exit', function(code){ console.error('exit blabla: %s', code) context.fail("No results") }) }
Remove unused dependency from JS wrapper
Remove unused dependency from JS wrapper
JavaScript
mit
ArjenSchwarz/igor,ArjenSchwarz/igor
--- +++ @@ -1,5 +1,4 @@ var child_process = require('child_process'); -var byline = require('./byline'); exports.handler = function(event, context) { var proc = child_process.spawn('./main', [JSON.stringify(event)], { stdio: [process.stdin, 'pipe', 'pipe'] });
f232636afd0a7ab9cb148f7b87aac551a866f3ec
index.js
index.js
'use strict'; class Mutex { constructor() { // Item at index 0 is the caller with the lock: // [ <has the lock>, <waiting>, <waiting>, <waiting> ... ] this.queue = []; } acquire({ timeout = 60000 } = {}) { const queue = this.queue; return new Promise((resolve, reject) => { setTimeout(() => { const index = queue.indexOf(resolve); if (index > 0) { // Still waiting in the queue queue.splice(index, 1); reject('Queue timeout'); } }, timeout); if (queue.push(resolve) === 1) { // Queue was empty, resolve the promise immediately. Caller is kept in the queue and // blocks it until it caller calls release() resolve({ release: function release() { queue.shift(); if (queue.length > 0) { queue[0]({ release }); // give the lock to the next in line by resolving the promise } }}); } }); } } module.exports = Mutex;
'use strict'; class Mutex { constructor() { // Item at index 0 is the caller with the lock: // [ <has the lock>, <waiting>, <waiting>, <waiting> ... ] this.queue = []; } acquire({ timeout = false } = {}) { const queue = this.queue; return new Promise((resolve, reject) => { if (timeout !== false) { setTimeout(() => { const index = queue.indexOf(resolve); if (index > 0) { // Still waiting in the queue queue.splice(index, 1); reject('Queue timeout'); } }, timeout); } if (queue.push(resolve) === 1) { // Queue was empty, resolve this promise immediately. Caller is kept in the queue until // it calls release() resolve({ release: function release() { queue.shift(); if (queue.length > 0) { queue[0]({ release }); // give the lock to the next in line by resolving the promise } } }); } }); } } module.exports = Mutex;
Make timeout disabled by default
Make timeout disabled by default
JavaScript
mit
ilkkao/snap-mutex
--- +++ @@ -7,29 +7,33 @@ this.queue = []; } - acquire({ timeout = 60000 } = {}) { + acquire({ timeout = false } = {}) { const queue = this.queue; return new Promise((resolve, reject) => { - setTimeout(() => { - const index = queue.indexOf(resolve); + if (timeout !== false) { + setTimeout(() => { + const index = queue.indexOf(resolve); - if (index > 0) { // Still waiting in the queue - queue.splice(index, 1); - reject('Queue timeout'); - } - }, timeout); + if (index > 0) { // Still waiting in the queue + queue.splice(index, 1); + reject('Queue timeout'); + } + }, timeout); + } if (queue.push(resolve) === 1) { - // Queue was empty, resolve the promise immediately. Caller is kept in the queue and - // blocks it until it caller calls release() - resolve({ release: function release() { - queue.shift(); + // Queue was empty, resolve this promise immediately. Caller is kept in the queue until + // it calls release() + resolve({ + release: function release() { + queue.shift(); - if (queue.length > 0) { - queue[0]({ release }); // give the lock to the next in line by resolving the promise + if (queue.length > 0) { + queue[0]({ release }); // give the lock to the next in line by resolving the promise + } } - }}); + }); } }); }
b758446bae6fc066626d04f207c3e668d2a38fd4
index.js
index.js
'use strict'; var express = require('express'); var path = require('path'); var bodyParser = require('body-parser'); var api = require('./nestor/api'); var app = express(); app.use(bodyParser.json()); var router = express.Router(); router.route('/') .get(function (req, res) { api.rtm.start(); }); app.use('/', router); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function () { console.log('Nestor listening on port ' + server.address().port); });
'use strict'; var express = require('express'); var path = require('path'); var bodyParser = require('body-parser'); var api = require('./nestor/api'); var app = express(); app.use(bodyParser.json()); var router = express.Router(); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function () { api.rtm.start(); console.log('Nestor listening on port ' + server.address().port); });
Connect to RTM right away
Connect to RTM right away
JavaScript
mit
maxdeviant/nestor
--- +++ @@ -12,16 +12,10 @@ var router = express.Router(); -router.route('/') - .get(function (req, res) { - - api.rtm.start(); - }); - -app.use('/', router); - app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function () { + api.rtm.start(); + console.log('Nestor listening on port ' + server.address().port); });
e5e3e797753c954d1da82bf29adaf2d6bfacf945
index.js
index.js
'use strict'; var fs = require('fs'); function reset() { exports.out = []; exports.xmlEmitter = null; exports.opts = {}; } reset(); /** * Load a formatter * @param {String} formatterPath * @return */ function loadFormatter(formatterPath) { return require('./lib/' + formatterPath + '_emitter'); } /** * Write out a XML file for the encountered results */ exports.reporter = function (results, data, opts) { console.log(arguments); console.log('\n\n\n\n'); opts = opts || {}; opts.format = opts.format || 'checkstyle'; opts.filePath = opts.filePath || 'jshint.xml'; exports.opts = opts; exports.xmlEmitter = loadFormatter(opts.format); exports.out.push(exports.xmlEmitter.formatContent(results)); }; exports.writeFile = function () { var outStream = fs.createWriteStream(exports.opts.filePath); outStream.write(exports.xmlEmitter.getHeader()); outStream.write(exports.out.join('\n')); outStream.write(exports.xmlEmitter.getFooter()); reset(); };
'use strict'; var fs = require('fs'); function reset() { exports.out = []; exports.xmlEmitter = null; exports.opts = {}; } reset(); /** * Load a formatter * @param {String} formatterPath * @return */ function loadFormatter(formatterPath) { return require('./lib/' + formatterPath + '_emitter'); } /** * Write out a XML file for the encountered results * @param {Array} results * @param {Array} data * @param {Object} opts */ exports.reporter = function (results) { exports.out.push(results); }; exports.writeFile = function (opts) { opts = opts || {}; opts.filePath = opts.filePath || 'jshint.xml'; opts.format = opts.format || 'checkstyle'; exports.xmlEmitter = loadFormatter(opts.format); return function () { if (!exports.out.length) { reset(); return; } var outStream = fs.createWriteStream(opts.filePath); outStream.write(exports.xmlEmitter.getHeader()); exports.out.forEach(function (item) { outStream.write(exports.xmlEmitter.formatContent(item)); }); outStream.write(exports.out.join('\n')); outStream.write(exports.xmlEmitter.getFooter()); reset(); }; };
Restructure things to handle all-ok cases
Restructure things to handle all-ok cases
JavaScript
mit
cleydsonjr/gulp-jshint-xml-file-reporter,lourenzo/gulp-jshint-xml-file-reporter
--- +++ @@ -19,22 +19,31 @@ /** * Write out a XML file for the encountered results + * @param {Array} results + * @param {Array} data + * @param {Object} opts */ -exports.reporter = function (results, data, opts) { - console.log(arguments); - console.log('\n\n\n\n'); - opts = opts || {}; - opts.format = opts.format || 'checkstyle'; - opts.filePath = opts.filePath || 'jshint.xml'; - exports.opts = opts; - exports.xmlEmitter = loadFormatter(opts.format); - exports.out.push(exports.xmlEmitter.formatContent(results)); +exports.reporter = function (results) { + exports.out.push(results); }; -exports.writeFile = function () { - var outStream = fs.createWriteStream(exports.opts.filePath); - outStream.write(exports.xmlEmitter.getHeader()); - outStream.write(exports.out.join('\n')); - outStream.write(exports.xmlEmitter.getFooter()); - reset(); +exports.writeFile = function (opts) { + opts = opts || {}; + opts.filePath = opts.filePath || 'jshint.xml'; + opts.format = opts.format || 'checkstyle'; + exports.xmlEmitter = loadFormatter(opts.format); + return function () { + if (!exports.out.length) { + reset(); + return; + } + var outStream = fs.createWriteStream(opts.filePath); + outStream.write(exports.xmlEmitter.getHeader()); + exports.out.forEach(function (item) { + outStream.write(exports.xmlEmitter.formatContent(item)); + }); + outStream.write(exports.out.join('\n')); + outStream.write(exports.xmlEmitter.getFooter()); + reset(); + }; };
63978e0a545bb6945964fe0b5c964ccb52a67624
index.js
index.js
'use strict'; var minimatch = require('minimatch'); var anymatch = function(criteria, string, returnIndex, startIndex, endIndex) { if (!Array.isArray(criteria)) { criteria = [criteria]; } if (arguments.length === 1) { return anymatch.bind(null, criteria); } if (startIndex == null) { startIndex = 0; } var matchIndex = -1; function testCriteria (criterion, index) { var result; switch (toString.call(criterion)) { case '[object String]': result = string === criterion || minimatch(string, criterion); break; case '[object RegExp]': result = criterion.test(string); break; case '[object Function]': result = criterion(string); break; default: result = false; } if (result) { matchIndex = index + startIndex; } return result; } var matched = criteria.slice(startIndex, endIndex).some(testCriteria); return returnIndex === true ? matchIndex : matched; }; module.exports = anymatch;
'use strict'; var minimatch = require('minimatch'); var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) { if (!Array.isArray(criteria)) { criteria = [criteria]; } var string = Array.isArray(value) ? value[0] : value; if (arguments.length === 1) { return anymatch.bind(null, criteria); } if (startIndex == null) { startIndex = 0; } var matchIndex = -1; function testCriteria (criterion, index) { var result; switch (toString.call(criterion)) { case '[object String]': result = string === criterion || minimatch(string, criterion); break; case '[object RegExp]': result = criterion.test(string); break; case '[object Function]': result = criterion.apply(null, Array.isArray(value) ? value : [value]); break; default: result = false; } if (result) { matchIndex = index + startIndex; } return result; } var matched = criteria.slice(startIndex, endIndex).some(testCriteria); return returnIndex === true ? matchIndex : matched; }; module.exports = anymatch;
Allow passing extra args to function matchers
Allow passing extra args to function matchers
JavaScript
isc
es128/anymatch,floatdrop/anymatch
--- +++ @@ -2,8 +2,9 @@ var minimatch = require('minimatch'); -var anymatch = function(criteria, string, returnIndex, startIndex, endIndex) { +var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) { if (!Array.isArray(criteria)) { criteria = [criteria]; } + var string = Array.isArray(value) ? value[0] : value; if (arguments.length === 1) { return anymatch.bind(null, criteria); } if (startIndex == null) { startIndex = 0; } var matchIndex = -1; @@ -17,7 +18,7 @@ result = criterion.test(string); break; case '[object Function]': - result = criterion(string); + result = criterion.apply(null, Array.isArray(value) ? value : [value]); break; default: result = false;
f788366f2d9c21eb208bd53575210ed8da881b1b
index.js
index.js
/** * Dispatcher prototype */ var dispatcher = Dispatcher.prototype; /** * Exports */ module.exports = Dispatcher; /** * Dispatcher * * @return {Object} * @api public */ function Dispatcher() { if (!(this instanceof Dispatcher)) return new Dispatcher; this.callbacks = []; }; /** * Register a new store. * * dispatcher.register('update_course', callbackFunction); * * @param {String} action * @param {Function} callback * @api public */ dispatcher.register = function(action, callback) { this.callbacks.push({ action: action, callback: callback }); }; /** * Dispatch event to stores. * * dispatcher.dispatch('update_course', {id: 123, title: 'Tobi'}); * * @param {String} action * @param {Object | Object[]} data * @return {Function[]} * @api public */ dispatcher.dispatch = function(action, data) { this.getCallbacks(action) .map(function(callback) { return callback.call(callback, data); }); }; /** * Return registered callbacks. * * @param {String} action * @return {Function[]} * @api private */ dispatcher.getCallbacks = function(action) { return this.callbacks .filter(function(callback) { return callback.action === action; }) .map(function(callback) { return callback.callback; }); };
/** * Exports */ module.exports = Dispatcher; /** * Dispatcher prototype */ var dispatcher = Dispatcher.prototype; /** * Dispatcher * * @return {Object} * @api public */ function Dispatcher() { if (!(this instanceof Dispatcher)) return new Dispatcher; this.callbacks = []; }; /** * Register a new store. * * dispatcher.register('update_course', callbackFunction); * * @param {String} action * @param {Function} callback * @api public */ dispatcher.register = function(action, callback) { this.callbacks.push({ action: action, callback: callback }); }; /** * Dispatch event to stores. * * dispatcher.dispatch('update_course', {id: 123, title: 'Tobi'}); * * @param {String} action * @param {Object | Object[]} data * @return {Function[]} * @api public */ dispatcher.dispatch = function(action, data) { this.getCallbacks(action) .forEach(function(callback) { callback.call(callback, data); }); }; /** * Return registered callbacks. * * @param {String} action * @return {Function[]} * @api private */ dispatcher.getCallbacks = function(action) { return this.callbacks .filter(function(callback) { return callback.action === action; }) .map(function(callback) { return callback.callback; }); };
Remove last reference to array returns
Remove last reference to array returns
JavaScript
mit
vebin/barracks,yoshuawuyts/barracks,yoshuawuyts/barracks
--- +++ @@ -1,14 +1,14 @@ +/** + * Exports + */ + +module.exports = Dispatcher; + /** * Dispatcher prototype */ var dispatcher = Dispatcher.prototype; - -/** - * Exports - */ - -module.exports = Dispatcher; /** * Dispatcher @@ -52,8 +52,8 @@ dispatcher.dispatch = function(action, data) { this.getCallbacks(action) - .map(function(callback) { - return callback.call(callback, data); + .forEach(function(callback) { + callback.call(callback, data); }); };
f188b3030f519a90708a57b0b840ec7516d6c53b
index.js
index.js
var util = require('util'); GeometryBounds = function(bounds) { this.xKey = "x"; this.yKey = "y"; this.bounds = []; if(!bounds || !bounds[0]) return; this.xKey = Object.keys(bounds[0])[0]; this.yKey = Object.keys(bounds[0])[1]; for(var b1 in bounds) { var constructedBound = []; var bound = bounds[b1]; for(var b2 in bound) { var constructedPoint = []; var point = bound[b2]; constructedPoint.push(parseFloat(point[this.xKey])); constructedPoint.push(parseFloat(point[this.yKey])); } } } GeometryBounds.prototype.contains = function contains(dot) { if(dot == null || !(this.xKey in dot) || !(this.yKey in dot)) { return false; } var x = parseFloat(dot[this.xKey]); var y = parseFloat(dot[this.yKey]); for(var index in this.bounds) { if(testInPolygon(this.bounds[index], x, y)) return true; } return false; } function testInPolygon(bound, x, y) { var c = false; for(i = 0, j = 1; i < bound.length; i++) { } } exports.GeometryBounds = GeometryBounds;
var util = require('util'); GeometryBounds = function(bounds) { this.xKey = "x"; this.yKey = "y"; this.bounds = []; if(!bounds || !bounds[0] || !bounds[0][0]) return; this.xKey = Object.keys(bounds[0][0])[0]; this.yKey = Object.keys(bounds[0][0])[1]; for(var b1 in bounds) { var constructedBound = []; var bound = bounds[b1]; for(var b2 in bound) { var constructedPoint = []; var point = bound[b2]; constructedPoint.push(parseFloat(point[this.xKey])); constructedPoint.push(parseFloat(point[this.yKey])); } } } GeometryBounds.prototype.contains = function contains(dot) { if(dot == null || !(this.xKey in dot) || !(this.yKey in dot)) { return false; } var x = parseFloat(dot[this.xKey]); var y = parseFloat(dot[this.yKey]); console.log(this.bounds); for(var index in this.bounds) { if(testInPolygon(this.bounds[index], x, y)) return true; } return false; } function testInPolygon(bound, x, y) { var c = false; console.log(bound); for(i = 0, j = bound.length - 1; i < bound.length; j = i++) { console.log(util.format("i = %d, j = %d", i, j)); } } exports.GeometryBounds = GeometryBounds;
Fix in defining keys for x,y
Fix in defining keys for x,y
JavaScript
mit
alandarev/node-geometry
--- +++ @@ -5,10 +5,10 @@ this.yKey = "y"; this.bounds = []; - if(!bounds || !bounds[0]) return; + if(!bounds || !bounds[0] || !bounds[0][0]) return; - this.xKey = Object.keys(bounds[0])[0]; - this.yKey = Object.keys(bounds[0])[1]; + this.xKey = Object.keys(bounds[0][0])[0]; + this.yKey = Object.keys(bounds[0][0])[1]; for(var b1 in bounds) { var constructedBound = []; @@ -32,6 +32,7 @@ var x = parseFloat(dot[this.xKey]); var y = parseFloat(dot[this.yKey]); + console.log(this.bounds); for(var index in this.bounds) { if(testInPolygon(this.bounds[index], x, y)) return true; @@ -42,7 +43,9 @@ function testInPolygon(bound, x, y) { var c = false; - for(i = 0, j = 1; i < bound.length; i++) { + console.log(bound); + for(i = 0, j = bound.length - 1; i < bound.length; j = i++) { + console.log(util.format("i = %d, j = %d", i, j)); } }
572907e88cc2acf6ad7482f8cee43cce03385d39
library/CM/FormField/Text.js
library/CM/FormField/Text.js
/** * @class CM_FormField_Text * @extends CM_FormField_Abstract */ var CM_FormField_Text = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Text', /** @type Boolean */ _skipTriggerChange: false, events: { 'blur input': function() { this.trigger('blur'); }, 'focus input': function() { this.trigger('focus'); } }, /** * @param {String} value */ setValue: function(value) { this._skipTriggerChange = true; this.$('input').val(value); this._skipTriggerChange = false; }, setFocus: function() { this.$('input').focus(); }, enableTriggerChange: function() { var self = this; var $input = this.$('input'); var valueLast = $input.val(); var callback = function() { var value = this.value; if (value != valueLast) { valueLast = value; if (!self._skipTriggerChange) { self.trigger('change'); } } }; // `propertychange` and `keyup` needed for IE9 $input.on('input propertychange keyup', callback); } });
/** * @class CM_FormField_Text * @extends CM_FormField_Abstract */ var CM_FormField_Text = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Text', /** @type Boolean */ _skipTriggerChange: false, events: { 'blur input': function() { this.trigger('blur'); }, 'focus input': function() { this.trigger('focus'); } }, /** * @param {String} value */ setValue: function(value) { this._skipTriggerChange = true; this.$('input').val(value); this._skipTriggerChange = false; }, setFocus: function() { this.$('input').focus(); }, /** * @return {Boolean} */ hasFocus: function() { return this.$('input').is(':focus'); }, enableTriggerChange: function() { var self = this; var $input = this.$('input'); var valueLast = $input.val(); var callback = function() { var value = this.value; if (value != valueLast) { valueLast = value; if (!self._skipTriggerChange) { self.trigger('change'); } } }; // `propertychange` and `keyup` needed for IE9 $input.on('input propertychange keyup', callback); } });
Add hasFocus() for text formField
Add hasFocus() for text formField
JavaScript
mit
vogdb/cm,fvovan/CM,tomaszdurka/CM,zazabe/cm,fauvel/CM,cargomedia/CM,mariansollmann/CM,mariansollmann/CM,njam/CM,vogdb/cm,christopheschwyzer/CM,fvovan/CM,fauvel/CM,tomaszdurka/CM,cargomedia/CM,alexispeter/CM,fvovan/CM,alexispeter/CM,zazabe/cm,fauvel/CM,fvovan/CM,cargomedia/CM,njam/CM,tomaszdurka/CM,mariansollmann/CM,vogdb/cm,mariansollmann/CM,cargomedia/CM,njam/CM,njam/CM,christopheschwyzer/CM,christopheschwyzer/CM,vogdb/cm,zazabe/cm,njam/CM,fauvel/CM,alexispeter/CM,tomaszdurka/CM,tomaszdurka/CM,vogdb/cm,christopheschwyzer/CM,fauvel/CM,alexispeter/CM,zazabe/cm
--- +++ @@ -30,6 +30,13 @@ this.$('input').focus(); }, + /** + * @return {Boolean} + */ + hasFocus: function() { + return this.$('input').is(':focus'); + }, + enableTriggerChange: function() { var self = this; var $input = this.$('input');
ff3e075eba9f87013879c889a8d70e119be04e13
lib/stack/Builder.js
lib/stack/Builder.js
/** * Builder.js * * @author: Harish Anchu <harishanchu@gmail.com> * @copyright Copyright (c) 2015-2016, QuorraJS. * @license See LICENSE.txt */ var StackedHttpKernel = require('./StackedHttpKernel'); function Builder() { /** * Stores middleware classes * * @type {Array} * @protected */ this.__specs = []; } Builder.prototype.push = function(spec) { if (typeof spec != 'function') { throw new Error("Spec error"); } this.__specs.push(spec); return this; }; Builder.prototype.resolve = function(app) { var next = app; var middlewares = [app]; var key; var spec; for(key = this.__specs.length -1; key >= 0; key--) { spec = this.__specs[key]; next = new spec(app, next); middlewares.unshift(next); } return new StackedHttpKernel(next, middlewares); }; module.exports = Builder;
/** * Builder.js * * @author: Harish Anchu <harishanchu@gmail.com> * @copyright Copyright (c) 2015-2016, QuorraJS. * @license See LICENSE.txt */ var StackedHttpKernel = require('./StackedHttpKernel'); function Builder() { /** * Stores middleware classes * * @type {Array} * @protected */ this.__specs = []; } Builder.prototype.push = function(spec) { if (typeof spec != 'function') { throw new Error("Spec error"); } this.__specs.push(spec); return this; }; Builder.prototype.resolve = function(app) { var next = app; var key; var spec; for(key = this.__specs.length -1; key >= 0; key--) { spec = this.__specs[key]; next = new spec(app, next); } return new StackedHttpKernel(next); }; module.exports = Builder;
Stop passing middlewares array to stack
Stop passing middlewares array to stack
JavaScript
mit
quorrajs/Positron,quorrajs/Positron
--- +++ @@ -35,7 +35,6 @@ Builder.prototype.resolve = function(app) { var next = app; - var middlewares = [app]; var key; var spec; @@ -43,11 +42,9 @@ spec = this.__specs[key]; next = new spec(app, next); - - middlewares.unshift(next); } - return new StackedHttpKernel(next, middlewares); + return new StackedHttpKernel(next); }; module.exports = Builder;
47d947642b5199ed81c388a51e5381fd0c6347f6
bin/pg-server.js
bin/pg-server.js
#!/usr/bin/env node 'use strict'; /** * Binary to run a pg server. * (C) 2015 Alex Fernández. */ // requires var stdio = require('stdio'); var server = require('../lib/server.js'); var packageJson = require(__dirname + '/../package.json'); // constants var PORT = 5433; // init var options = stdio.getopt({ version: {key: 'v', description: 'Display version and quit'}, port: {key: 'p', args: 1, description: 'Port to connect to', default: PORT}, host: {key: 'h', args: 1, description: 'Host to connect to'}, quiet: {description: 'Do not log any messages'}, debug: {description: 'Show debug messages'}, }); if (options.version) { console.log('Loadtest version: %s', packageJson.version); process.exit(0); } if (options.args && options.args.length > 0) { console.error('Too many arguments: %s', options.args); options.printHelp(); process.exit(1); } server.start(options, function(error) { if (error) { return console.error('Could not start server on port %s: %s', options.port, error); } console.log('Pooled PostgreSQL server started on port %s', options.port); });
#!/usr/bin/env node 'use strict'; /** * Binary to run a pg server. * (C) 2015 Alex Fernández. */ // requires var Log = require('log'); var stdio = require('stdio'); var server = require('../lib/server.js'); var packageJson = require(__dirname + '/../package.json'); // globals var log = new Log('info'); // constants var PORT = 5433; // init var options = stdio.getopt({ version: {key: 'v', description: 'Display version and quit'}, port: {key: 'p', args: 1, description: 'Port to connect to', default: PORT}, host: {key: 'h', args: 1, description: 'Host to connect to'}, quiet: {key: 'q', description: 'Do not log any messages'}, debug: {key: 'd', description: 'Show debug messages'}, }); if (options.version) { console.log('Loadtest version: %s', packageJson.version); process.exit(0); } if (options.args && options.args.length > 0) { console.error('Too many arguments: %s', options.args); options.printHelp(); process.exit(1); } server.start(options, function(error) { if (error) { return console.error('Could not start server on port %s: %s', options.port, error); } log.info('Pooled PostgreSQL server started on port %s', options.port); });
Debug and quiet have short keys.
Debug and quiet have short keys.
JavaScript
mit
alexfernandez/pooled-pg
--- +++ @@ -7,11 +7,14 @@ */ // requires +var Log = require('log'); var stdio = require('stdio'); var server = require('../lib/server.js'); var packageJson = require(__dirname + '/../package.json'); - +// globals +var log = new Log('info'); + // constants var PORT = 5433; @@ -20,8 +23,8 @@ version: {key: 'v', description: 'Display version and quit'}, port: {key: 'p', args: 1, description: 'Port to connect to', default: PORT}, host: {key: 'h', args: 1, description: 'Host to connect to'}, - quiet: {description: 'Do not log any messages'}, - debug: {description: 'Show debug messages'}, + quiet: {key: 'q', description: 'Do not log any messages'}, + debug: {key: 'd', description: 'Show debug messages'}, }); if (options.version) { @@ -40,6 +43,6 @@ { return console.error('Could not start server on port %s: %s', options.port, error); } - console.log('Pooled PostgreSQL server started on port %s', options.port); + log.info('Pooled PostgreSQL server started on port %s', options.port); });
1142407be4e1884fc79188680f2b8649f19d887f
test/unit/unit.js
test/unit/unit.js
'use strict'; require.config({ baseUrl: '../lib', paths: { 'test': '..', 'forge': 'forge.min' }, shim: { sinon: { exports: 'sinon', } } }); // add function.bind polyfill if (!Function.prototype.bind) { Function.prototype.bind = function(oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, FNOP = function() {}, fBound = function() { return fToBind.apply(this instanceof FNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; FNOP.prototype = this.prototype; fBound.prototype = new FNOP(); return fBound; }; } mocha.setup('bdd'); require(['test/unit/browserbox-test', 'test/unit/browserbox-imap-test'], function() { (window.mochaPhantomJS || window.mocha).run(); });
'use strict'; require.config({ baseUrl: '../lib', paths: { 'test': '..', 'forge': 'forge.min' } }); // add function.bind polyfill if (!Function.prototype.bind) { Function.prototype.bind = function(oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, FNOP = function() {}, fBound = function() { return fToBind.apply(this instanceof FNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; FNOP.prototype = this.prototype; fBound.prototype = new FNOP(); return fBound; }; } mocha.setup('bdd'); require(['test/unit/browserbox-test', 'test/unit/browserbox-imap-test'], function() { (window.mochaPhantomJS || window.mocha).run(); });
Remove useless sinon require shim
Remove useless sinon require shim
JavaScript
mit
dopry/browserbox,emailjs/emailjs-imap-client,nifgraup/browserbox,ltgorm/emailjs-imap-client,dopry/browserbox,emailjs/emailjs-imap-client,whiteout-io/browserbox,ltgorm/emailjs-imap-client
--- +++ @@ -5,11 +5,6 @@ paths: { 'test': '..', 'forge': 'forge.min' - }, - shim: { - sinon: { - exports: 'sinon', - } } });
6e5a575e2bab2ce9b1cb83182a791fe8d1995558
test/utils-test.js
test/utils-test.js
describe('getFolders()', function() { it('should return the correct list of folders', function() { var objects = [ { Key: '/' }, { Key: 'test/' }, { Key: 'test/test/' }, { Key: 'test/a/b' }, { Key: 'test' }, ]; chai.expect(dodgercms.utils.getFolders(objects)).to.have.members(['/', 'test/', 'test/test/', 'test/a/']); }); it('should return the root folder if the array is empty', function() { var objects = []; chai.expect(dodgercms.utils.getFolders(objects)).to.have.members(['/']); }); }); describe('newFolder()', function() { before(function(done) { sinon .stub(dodgercms.s3, 'putObject') .yields(null, 'index'); done(); }); after(function(done) { dodgercms.s3.putObject.restore(); done(); }); it('should match the given key', function(done) { dodgercms.utils.newFolder('index', 'dataBucket','siteBucket', function(err, key) { if (err) { return done(err); } chai.assert(key === 'index'); done(); }); }); });
describe('getFolders()', function() { it('should return the correct list of folders', function() { var objects = [ { Key: '/' }, { Key: 'test/' }, { Key: 'test/test/' }, { Key: 'test/a/b' }, { Key: 'test' }, ]; chai.expect(dodgercms.utils.getFolders(objects)).to.have.members(['/', 'test/', 'test/test/', 'test/a/']); }); it('should return the root folder if the array is empty', function() { var objects = []; chai.expect(dodgercms.utils.getFolders(objects)).to.have.members(['/']); }); }); describe('newFolder()', function() { before(function(done) { sinon .stub(dodgercms.s3, 'putObject') .yields(null, 'index'); done(); }); after(function(done) { dodgercms.s3.putObject.restore(); done(); }); it('should match the given key', function(done) { dodgercms.utils.newFolder('index', 'dataBucket','siteBucket', function(err, key) { if (err) { return done(err); } chai.assert(key === 'index'); done(); }); }); }); describe('isFolder()', function() { it('should return true for root', function() { chai.assert(dodgercms.utils.isFolder('/')); }); it('should return true for folder', function() { chai.assert(dodgercms.utils.isFolder('/folder/')); }); it('should return true for nested folder', function() { chai.assert(dodgercms.utils.isFolder('/folder/test/folder/')); }); });
Add test cases for the utils
Add test cases for the utils
JavaScript
mit
ChrisZieba/dodgercms,ChrisZieba/dodgercms,etopian/dodgercms,etopian/dodgercms
--- +++ @@ -39,3 +39,15 @@ }); }); }); + +describe('isFolder()', function() { + it('should return true for root', function() { + chai.assert(dodgercms.utils.isFolder('/')); + }); + it('should return true for folder', function() { + chai.assert(dodgercms.utils.isFolder('/folder/')); + }); + it('should return true for nested folder', function() { + chai.assert(dodgercms.utils.isFolder('/folder/test/folder/')); + }); +});
c638b15fe519f33b2bfda4ae1269d77d4dba0cae
packages/test-in-browser/package.js
packages/test-in-browser/package.js
Package.describe({ summary: "Run tests interactively in the browser", version: '1.0.5-pre.2' }); Package.on_use(function (api) { // XXX this should go away, and there should be a clean interface // that tinytest and the driver both implement? api.use('tinytest'); api.use('bootstrap'); api.use('underscore'); api.use('session'); api.use('reload'); api.use(['blaze', 'templating', 'spacebars', 'ddp', 'tracker'], 'client'); api.add_files('diff_match_patch_uncompressed.js', 'client'); api.add_files('diff_match_patch_uncompressed.js', 'client'); api.add_files([ 'driver.css', 'driver.html', 'driver.js' ], "client"); api.use('autoupdate', 'server', {weak: true}); api.use('random', 'server'); api.add_files('autoupdate.js', 'server'); });
Package.describe({ summary: "Run tests interactively in the browser", version: '1.0.5-pre.2' }); Package.on_use(function (api) { // XXX this should go away, and there should be a clean interface // that tinytest and the driver both implement? api.use('tinytest'); api.use('bootstrap@1.0.1'); api.use('underscore'); api.use('session'); api.use('reload'); api.use(['blaze', 'templating', 'spacebars', 'ddp', 'tracker'], 'client'); api.add_files('diff_match_patch_uncompressed.js', 'client'); api.add_files('diff_match_patch_uncompressed.js', 'client'); api.add_files([ 'driver.css', 'driver.html', 'driver.js' ], "client"); api.use('autoupdate', 'server', {weak: true}); api.use('random', 'server'); api.add_files('autoupdate.js', 'server'); });
Add version constraing to bootstrap use
Add version constraing to bootstrap use
JavaScript
mit
akintoey/meteor,ndarilek/meteor,Puena/meteor,ljack/meteor,Profab/meteor,ashwathgovind/meteor,DCKT/meteor,nuvipannu/meteor,shrop/meteor,DAB0mB/meteor,deanius/meteor,Paulyoufu/meteor-1,AnthonyAstige/meteor,jirengu/meteor,Ken-Liu/meteor,sdeveloper/meteor,AnjirHossain/meteor,emmerge/meteor,TechplexEngineer/meteor,yanisIk/meteor,judsonbsilva/meteor,codingang/meteor,newswim/meteor,HugoRLopes/meteor,chasertech/meteor,eluck/meteor,Puena/meteor,Theviajerock/meteor,pandeysoni/meteor,jrudio/meteor,yonas/meteor-freebsd,framewr/meteor,planet-training/meteor,LWHTarena/meteor,colinligertwood/meteor,whip112/meteor,skarekrow/meteor,alexbeletsky/meteor,lpinto93/meteor,Eynaliyev/meteor,aldeed/meteor,kencheung/meteor,lieuwex/meteor,dandv/meteor,benjamn/meteor,colinligertwood/meteor,shrop/meteor,chmac/meteor,kidaa/meteor,rozzzly/meteor,Hansoft/meteor,paul-barry-kenzan/meteor,sunny-g/meteor,shadedprofit/meteor,deanius/meteor,katopz/meteor,mirstan/meteor,daslicht/meteor,dev-bobsong/meteor,l0rd0fwar/meteor,calvintychan/meteor,yyx990803/meteor,wmkcc/meteor,calvintychan/meteor,fashionsun/meteor,katopz/meteor,allanalexandre/meteor,HugoRLopes/meteor,servel333/meteor,TribeMedia/meteor,Eynaliyev/meteor,kengchau/meteor,SeanOceanHu/meteor,modulexcite/meteor,justintung/meteor,shmiko/meteor,yanisIk/meteor,mubassirhayat/meteor,SeanOceanHu/meteor,mubassirhayat/meteor,jrudio/meteor,benjamn/meteor,tdamsma/meteor,luohuazju/meteor,akintoey/meteor,dev-bobsong/meteor,cbonami/meteor,Eynaliyev/meteor,wmkcc/meteor,michielvanoeffelen/meteor,chmac/meteor,youprofit/meteor,evilemon/meteor,lieuwex/meteor,queso/meteor,yinhe007/meteor,akintoey/meteor,yanisIk/meteor,luohuazju/meteor,Jeremy017/meteor,meonkeys/meteor,shrop/meteor,skarekrow/meteor,hristaki/meteor,kencheung/meteor,ericterpstra/meteor,sdeveloper/meteor,DAB0mB/meteor,yanisIk/meteor,cog-64/meteor,cog-64/meteor,udhayam/meteor,sitexa/meteor,Quicksteve/meteor,cog-64/meteor,cbonami/meteor,fashionsun/meteor,joannekoong/meteor,somallg/meteor,planet-training/meteor,namho102/meteor,iman-mafi/meteor,iman-mafi/meteor,youprofit/meteor,tdamsma/meteor,stevenliuit/meteor,iman-mafi/meteor,codedogfish/meteor,pjump/meteor,oceanzou123/meteor,iman-mafi/meteor,msavin/meteor,whip112/meteor,mirstan/meteor,johnthepink/meteor,paul-barry-kenzan/meteor,neotim/meteor,lorensr/meteor,johnthepink/meteor,oceanzou123/meteor,JesseQin/meteor,lawrenceAIO/meteor,neotim/meteor,ljack/meteor,henrypan/meteor,ljack/meteor,Puena/meteor,karlito40/meteor,IveWong/meteor,yonglehou/meteor,justintung/meteor,sitexa/meteor,HugoRLopes/meteor,Prithvi-A/meteor,alexbeletsky/meteor,ndarilek/meteor,ljack/meteor,framewr/meteor,pjump/meteor,aramk/meteor,emmerge/meteor,sclausen/meteor,justintung/meteor,baiyunping333/meteor,codingang/meteor,cherbst/meteor,ndarilek/meteor,sitexa/meteor,eluck/meteor,chasertech/meteor,jg3526/meteor,bhargav175/meteor,devgrok/meteor,ericterpstra/meteor,codingang/meteor,evilemon/meteor,Jeremy017/meteor,alphanso/meteor,Quicksteve/meteor,lieuwex/meteor,vacjaliu/meteor,AnjirHossain/meteor,alphanso/meteor,yalexx/meteor,ndarilek/meteor,pandeysoni/meteor,Puena/meteor,karlito40/meteor,chengxiaole/meteor,evilemon/meteor,shrop/meteor,pandeysoni/meteor,lieuwex/meteor,Urigo/meteor,dboyliao/meteor,juansgaitan/meteor,qscripter/meteor,msavin/meteor,lassombra/meteor,kengchau/meteor,michielvanoeffelen/meteor,eluck/meteor,benstoltz/meteor,Jeremy017/meteor,nuvipannu/meteor,meonkeys/meteor,Urigo/meteor,servel333/meteor,kidaa/meteor,mauricionr/meteor,sdeveloper/meteor,Jeremy017/meteor,alexbeletsky/meteor,rozzzly/meteor,Profab/meteor,AnjirHossain/meteor,lawrenceAIO/meteor,sunny-g/meteor,l0rd0fwar/meteor,Urigo/meteor,somallg/meteor,meonkeys/meteor,newswim/meteor,Eynaliyev/meteor,chinasb/meteor,benstoltz/meteor,mjmasn/meteor,namho102/meteor,sunny-g/meteor,l0rd0fwar/meteor,newswim/meteor,yalexx/meteor,ashwathgovind/meteor,Prithvi-A/meteor,servel333/meteor,johnthepink/meteor,ericterpstra/meteor,meonkeys/meteor,neotim/meteor,meteor-velocity/meteor,LWHTarena/meteor,Theviajerock/meteor,jeblister/meteor,Jeremy017/meteor,benstoltz/meteor,yanisIk/meteor,planet-training/meteor,sdeveloper/meteor,modulexcite/meteor,yonas/meteor-freebsd,alexbeletsky/meteor,Prithvi-A/meteor,DAB0mB/meteor,somallg/meteor,Ken-Liu/meteor,saisai/meteor,shmiko/meteor,Urigo/meteor,brdtrpp/meteor,msavin/meteor,guazipi/meteor,newswim/meteor,arunoda/meteor,PatrickMcGuinness/meteor,yinhe007/meteor,allanalexandre/meteor,HugoRLopes/meteor,h200863057/meteor,alexbeletsky/meteor,ndarilek/meteor,udhayam/meteor,D1no/meteor,tdamsma/meteor,guazipi/meteor,Paulyoufu/meteor-1,namho102/meteor,kidaa/meteor,williambr/meteor,yonglehou/meteor,vjau/meteor,sitexa/meteor,papimomi/meteor,chiefninew/meteor,paul-barry-kenzan/meteor,jenalgit/meteor,yonas/meteor-freebsd,rabbyalone/meteor,aleclarson/meteor,vjau/meteor,hristaki/meteor,cherbst/meteor,4commerce-technologies-AG/meteor,steedos/meteor,jeblister/meteor,lorensr/meteor,elkingtonmcb/meteor,williambr/meteor,jdivy/meteor,brdtrpp/meteor,lorensr/meteor,Prithvi-A/meteor,emmerge/meteor,akintoey/meteor,DAB0mB/meteor,dboyliao/meteor,LWHTarena/meteor,daltonrenaldo/meteor,juansgaitan/meteor,dboyliao/meteor,daltonrenaldo/meteor,joannekoong/meteor,4commerce-technologies-AG/meteor,dfischer/meteor,IveWong/meteor,h200863057/meteor,michielvanoeffelen/meteor,saisai/meteor,lassombra/meteor,benjamn/meteor,pjump/meteor,henrypan/meteor,Puena/meteor,benstoltz/meteor,wmkcc/meteor,AlexR1712/meteor,EduShareOntario/meteor,meteor-velocity/meteor,servel333/meteor,fashionsun/meteor,whip112/meteor,ndarilek/meteor,modulexcite/meteor,tdamsma/meteor,h200863057/meteor,shmiko/meteor,jirengu/meteor,joannekoong/meteor,AnthonyAstige/meteor,newswim/meteor,lawrenceAIO/meteor,lawrenceAIO/meteor,namho102/meteor,yalexx/meteor,AnthonyAstige/meteor,devgrok/meteor,newswim/meteor,dandv/meteor,deanius/meteor,lassombra/meteor,DCKT/meteor,dfischer/meteor,Jonekee/meteor,baysao/meteor,GrimDerp/meteor,arunoda/meteor,SeanOceanHu/meteor,akintoey/meteor,arunoda/meteor,eluck/meteor,imanmafi/meteor,vacjaliu/meteor,jirengu/meteor,oceanzou123/meteor,judsonbsilva/meteor,esteedqueen/meteor,fashionsun/meteor,brdtrpp/meteor,chengxiaole/meteor,zdd910/meteor,skarekrow/meteor,Jeremy017/meteor,ljack/meteor,somallg/meteor,Eynaliyev/meteor,benjamn/meteor,rozzzly/meteor,queso/meteor,Theviajerock/meteor,brdtrpp/meteor,Jeremy017/meteor,codingang/meteor,hristaki/meteor,namho102/meteor,shadedprofit/meteor,IveWong/meteor,shadedprofit/meteor,cherbst/meteor,vacjaliu/meteor,lpinto93/meteor,neotim/meteor,mjmasn/meteor,Ken-Liu/meteor,h200863057/meteor,calvintychan/meteor,Quicksteve/meteor,yanisIk/meteor,chengxiaole/meteor,vjau/meteor,saisai/meteor,benstoltz/meteor,aldeed/meteor,saisai/meteor,karlito40/meteor,joannekoong/meteor,chmac/meteor,guazipi/meteor,aldeed/meteor,l0rd0fwar/meteor,DCKT/meteor,elkingtonmcb/meteor,deanius/meteor,iman-mafi/meteor,daslicht/meteor,vacjaliu/meteor,skarekrow/meteor,cog-64/meteor,AnthonyAstige/meteor,jdivy/meteor,queso/meteor,baiyunping333/meteor,mjmasn/meteor,allanalexandre/meteor,papimomi/meteor,Eynaliyev/meteor,sclausen/meteor,kengchau/meteor,chmac/meteor,saisai/meteor,shmiko/meteor,yonglehou/meteor,pjump/meteor,h200863057/meteor,karlito40/meteor,colinligertwood/meteor,EduShareOntario/meteor,jg3526/meteor,shmiko/meteor,joannekoong/meteor,jg3526/meteor,Quicksteve/meteor,EduShareOntario/meteor,TribeMedia/meteor,PatrickMcGuinness/meteor,mirstan/meteor,framewr/meteor,jagi/meteor,chengxiaole/meteor,pjump/meteor,mubassirhayat/meteor,hristaki/meteor,jrudio/meteor,wmkcc/meteor,GrimDerp/meteor,D1no/meteor,daslicht/meteor,zdd910/meteor,baysao/meteor,fashionsun/meteor,daltonrenaldo/meteor,jenalgit/meteor,servel333/meteor,jirengu/meteor,4commerce-technologies-AG/meteor,SeanOceanHu/meteor,Urigo/meteor,johnthepink/meteor,benstoltz/meteor,jg3526/meteor,wmkcc/meteor,Ken-Liu/meteor,codedogfish/meteor,jeblister/meteor,arunoda/meteor,lieuwex/meteor,AlexR1712/meteor,kidaa/meteor,Prithvi-A/meteor,yonas/meteor-freebsd,sunny-g/meteor,pandeysoni/meteor,jg3526/meteor,brdtrpp/meteor,cog-64/meteor,AlexR1712/meteor,mauricionr/meteor,luohuazju/meteor,calvintychan/meteor,emmerge/meteor,AnthonyAstige/meteor,yonas/meteor-freebsd,mubassirhayat/meteor,jagi/meteor,imanmafi/meteor,dev-bobsong/meteor,mauricionr/meteor,ljack/meteor,pandeysoni/meteor,GrimDerp/meteor,guazipi/meteor,yalexx/meteor,ashwathgovind/meteor,youprofit/meteor,lassombra/meteor,yiliaofan/meteor,sitexa/meteor,steedos/meteor,elkingtonmcb/meteor,shmiko/meteor,lassombra/meteor,Jonekee/meteor,yanisIk/meteor,henrypan/meteor,brettle/meteor,GrimDerp/meteor,elkingtonmcb/meteor,karlito40/meteor,namho102/meteor,baysao/meteor,jagi/meteor,devgrok/meteor,4commerce-technologies-AG/meteor,brdtrpp/meteor,yonas/meteor-freebsd,whip112/meteor,kengchau/meteor,l0rd0fwar/meteor,codingang/meteor,karlito40/meteor,cog-64/meteor,lawrenceAIO/meteor,steedos/meteor,michielvanoeffelen/meteor,EduShareOntario/meteor,justintung/meteor,planet-training/meteor,meteor-velocity/meteor,dfischer/meteor,alphanso/meteor,aleclarson/meteor,juansgaitan/meteor,codedogfish/meteor,AnjirHossain/meteor,katopz/meteor,Paulyoufu/meteor-1,paul-barry-kenzan/meteor,rabbyalone/meteor,cbonami/meteor,bhargav175/meteor,brdtrpp/meteor,DAB0mB/meteor,yonas/meteor-freebsd,qscripter/meteor,shadedprofit/meteor,brettle/meteor,mjmasn/meteor,JesseQin/meteor,lpinto93/meteor,Prithvi-A/meteor,jg3526/meteor,kencheung/meteor,ashwathgovind/meteor,somallg/meteor,evilemon/meteor,jdivy/meteor,jagi/meteor,juansgaitan/meteor,esteedqueen/meteor,dboyliao/meteor,katopz/meteor,dfischer/meteor,dandv/meteor,vacjaliu/meteor,chengxiaole/meteor,DCKT/meteor,Profab/meteor,chiefninew/meteor,shadedprofit/meteor,williambr/meteor,esteedqueen/meteor,chmac/meteor,LWHTarena/meteor,4commerce-technologies-AG/meteor,saisai/meteor,juansgaitan/meteor,Profab/meteor,ericterpstra/meteor,karlito40/meteor,sclausen/meteor,bhargav175/meteor,jenalgit/meteor,Jonekee/meteor,chmac/meteor,dboyliao/meteor,HugoRLopes/meteor,Profab/meteor,esteedqueen/meteor,cog-64/meteor,jagi/meteor,yyx990803/meteor,Theviajerock/meteor,kidaa/meteor,alphanso/meteor,jirengu/meteor,Quicksteve/meteor,somallg/meteor,evilemon/meteor,benjamn/meteor,somallg/meteor,TribeMedia/meteor,kengchau/meteor,arunoda/meteor,yanisIk/meteor,vjau/meteor,yalexx/meteor,jenalgit/meteor,nuvipannu/meteor,deanius/meteor,Theviajerock/meteor,stevenliuit/meteor,luohuazju/meteor,steedos/meteor,sdeveloper/meteor,lieuwex/meteor,aramk/meteor,stevenliuit/meteor,imanmafi/meteor,chiefninew/meteor,PatrickMcGuinness/meteor,meonkeys/meteor,pandeysoni/meteor,oceanzou123/meteor,yinhe007/meteor,TribeMedia/meteor,wmkcc/meteor,kencheung/meteor,chasertech/meteor,queso/meteor,kencheung/meteor,devgrok/meteor,katopz/meteor,chinasb/meteor,colinligertwood/meteor,sclausen/meteor,jg3526/meteor,zdd910/meteor,rabbyalone/meteor,yinhe007/meteor,chiefninew/meteor,yiliaofan/meteor,shadedprofit/meteor,qscripter/meteor,AlexR1712/meteor,whip112/meteor,jrudio/meteor,brettle/meteor,daltonrenaldo/meteor,steedos/meteor,fashionsun/meteor,SeanOceanHu/meteor,steedos/meteor,aramk/meteor,alexbeletsky/meteor,sclausen/meteor,esteedqueen/meteor,DAB0mB/meteor,mauricionr/meteor,D1no/meteor,modulexcite/meteor,Theviajerock/meteor,sclausen/meteor,aldeed/meteor,l0rd0fwar/meteor,skarekrow/meteor,baiyunping333/meteor,Paulyoufu/meteor-1,msavin/meteor,meonkeys/meteor,yyx990803/meteor,modulexcite/meteor,paul-barry-kenzan/meteor,rabbyalone/meteor,shmiko/meteor,benstoltz/meteor,TechplexEngineer/meteor,meteor-velocity/meteor,PatrickMcGuinness/meteor,hristaki/meteor,nuvipannu/meteor,emmerge/meteor,bhargav175/meteor,aramk/meteor,dev-bobsong/meteor,imanmafi/meteor,baiyunping333/meteor,chasertech/meteor,dandv/meteor,stevenliuit/meteor,sclausen/meteor,4commerce-technologies-AG/meteor,yiliaofan/meteor,yonglehou/meteor,papimomi/meteor,AnjirHossain/meteor,alexbeletsky/meteor,whip112/meteor,codingang/meteor,lorensr/meteor,justintung/meteor,sitexa/meteor,sunny-g/meteor,colinligertwood/meteor,mjmasn/meteor,sunny-g/meteor,GrimDerp/meteor,mjmasn/meteor,Hansoft/meteor,AnjirHossain/meteor,juansgaitan/meteor,justintung/meteor,framewr/meteor,youprofit/meteor,yonglehou/meteor,williambr/meteor,SeanOceanHu/meteor,dandv/meteor,jdivy/meteor,saisai/meteor,Hansoft/meteor,dandv/meteor,chinasb/meteor,yinhe007/meteor,cherbst/meteor,mauricionr/meteor,johnthepink/meteor,codedogfish/meteor,vjau/meteor,yinhe007/meteor,tdamsma/meteor,sdeveloper/meteor,allanalexandre/meteor,yiliaofan/meteor,lawrenceAIO/meteor,yiliaofan/meteor,ericterpstra/meteor,elkingtonmcb/meteor,rabbyalone/meteor,Eynaliyev/meteor,PatrickMcGuinness/meteor,paul-barry-kenzan/meteor,cherbst/meteor,dboyliao/meteor,queso/meteor,calvintychan/meteor,oceanzou123/meteor,williambr/meteor,planet-training/meteor,jeblister/meteor,Hansoft/meteor,judsonbsilva/meteor,l0rd0fwar/meteor,allanalexandre/meteor,henrypan/meteor,tdamsma/meteor,joannekoong/meteor,GrimDerp/meteor,codedogfish/meteor,newswim/meteor,yiliaofan/meteor,cherbst/meteor,h200863057/meteor,michielvanoeffelen/meteor,neotim/meteor,baysao/meteor,planet-training/meteor,steedos/meteor,michielvanoeffelen/meteor,jdivy/meteor,udhayam/meteor,kencheung/meteor,aldeed/meteor,zdd910/meteor,lawrenceAIO/meteor,cherbst/meteor,mauricionr/meteor,D1no/meteor,4commerce-technologies-AG/meteor,JesseQin/meteor,planet-training/meteor,bhargav175/meteor,devgrok/meteor,Quicksteve/meteor,daltonrenaldo/meteor,lassombra/meteor,udhayam/meteor,fashionsun/meteor,papimomi/meteor,namho102/meteor,Hansoft/meteor,ericterpstra/meteor,modulexcite/meteor,youprofit/meteor,eluck/meteor,lpinto93/meteor,akintoey/meteor,daltonrenaldo/meteor,Jonekee/meteor,Urigo/meteor,dev-bobsong/meteor,framewr/meteor,sdeveloper/meteor,jenalgit/meteor,johnthepink/meteor,neotim/meteor,wmkcc/meteor,tdamsma/meteor,D1no/meteor,elkingtonmcb/meteor,brdtrpp/meteor,baiyunping333/meteor,LWHTarena/meteor,nuvipannu/meteor,kidaa/meteor,juansgaitan/meteor,SeanOceanHu/meteor,mirstan/meteor,shrop/meteor,JesseQin/meteor,oceanzou123/meteor,yonglehou/meteor,queso/meteor,TechplexEngineer/meteor,skarekrow/meteor,jeblister/meteor,Profab/meteor,guazipi/meteor,imanmafi/meteor,Jonekee/meteor,mauricionr/meteor,akintoey/meteor,imanmafi/meteor,nuvipannu/meteor,chinasb/meteor,ericterpstra/meteor,dev-bobsong/meteor,guazipi/meteor,Puena/meteor,nuvipannu/meteor,daslicht/meteor,luohuazju/meteor,dfischer/meteor,ljack/meteor,johnthepink/meteor,shrop/meteor,meteor-velocity/meteor,ashwathgovind/meteor,esteedqueen/meteor,sunny-g/meteor,qscripter/meteor,lassombra/meteor,sitexa/meteor,lpinto93/meteor,katopz/meteor,papimomi/meteor,Eynaliyev/meteor,vacjaliu/meteor,allanalexandre/meteor,SeanOceanHu/meteor,stevenliuit/meteor,yalexx/meteor,msavin/meteor,chiefninew/meteor,Quicksteve/meteor,vjau/meteor,mirstan/meteor,ashwathgovind/meteor,meonkeys/meteor,chmac/meteor,AnthonyAstige/meteor,JesseQin/meteor,yalexx/meteor,hristaki/meteor,ndarilek/meteor,AlexR1712/meteor,ashwathgovind/meteor,TribeMedia/meteor,kengchau/meteor,chiefninew/meteor,TechplexEngineer/meteor,alphanso/meteor,HugoRLopes/meteor,colinligertwood/meteor,emmerge/meteor,jenalgit/meteor,calvintychan/meteor,codedogfish/meteor,skarekrow/meteor,lieuwex/meteor,lorensr/meteor,lpinto93/meteor,brettle/meteor,IveWong/meteor,meteor-velocity/meteor,eluck/meteor,yonglehou/meteor,Jonekee/meteor,henrypan/meteor,henrypan/meteor,baysao/meteor,TechplexEngineer/meteor,codingang/meteor,evilemon/meteor,yyx990803/meteor,baiyunping333/meteor,D1no/meteor,pandeysoni/meteor,Theviajerock/meteor,rozzzly/meteor,somallg/meteor,Profab/meteor,mjmasn/meteor,Paulyoufu/meteor-1,katopz/meteor,mirstan/meteor,dfischer/meteor,rozzzly/meteor,LWHTarena/meteor,aramk/meteor,jenalgit/meteor,eluck/meteor,judsonbsilva/meteor,zdd910/meteor,chiefninew/meteor,aleclarson/meteor,AnthonyAstige/meteor,qscripter/meteor,mubassirhayat/meteor,D1no/meteor,pjump/meteor,qscripter/meteor,hristaki/meteor,dboyliao/meteor,youprofit/meteor,yinhe007/meteor,mubassirhayat/meteor,mubassirhayat/meteor,papimomi/meteor,williambr/meteor,esteedqueen/meteor,aramk/meteor,Paulyoufu/meteor-1,cbonami/meteor,baiyunping333/meteor,TribeMedia/meteor,kengchau/meteor,brettle/meteor,yiliaofan/meteor,IveWong/meteor,jrudio/meteor,williambr/meteor,codedogfish/meteor,michielvanoeffelen/meteor,brettle/meteor,cbonami/meteor,baysao/meteor,stevenliuit/meteor,chengxiaole/meteor,modulexcite/meteor,jirengu/meteor,chiefninew/meteor,PatrickMcGuinness/meteor,vjau/meteor,mubassirhayat/meteor,udhayam/meteor,AnthonyAstige/meteor,DAB0mB/meteor,daltonrenaldo/meteor,henrypan/meteor,imanmafi/meteor,IveWong/meteor,Prithvi-A/meteor,lpinto93/meteor,HugoRLopes/meteor,jagi/meteor,servel333/meteor,eluck/meteor,bhargav175/meteor,Jonekee/meteor,AlexR1712/meteor,deanius/meteor,jrudio/meteor,udhayam/meteor,LWHTarena/meteor,ndarilek/meteor,judsonbsilva/meteor,papimomi/meteor,jeblister/meteor,bhargav175/meteor,paul-barry-kenzan/meteor,karlito40/meteor,colinligertwood/meteor,jdivy/meteor,lorensr/meteor,rabbyalone/meteor,zdd910/meteor,allanalexandre/meteor,benjamn/meteor,chasertech/meteor,cbonami/meteor,alphanso/meteor,h200863057/meteor,Paulyoufu/meteor-1,TribeMedia/meteor,chengxiaole/meteor,aramk/meteor,queso/meteor,neotim/meteor,DCKT/meteor,jdivy/meteor,yyx990803/meteor,Ken-Liu/meteor,Puena/meteor,Hansoft/meteor,qscripter/meteor,arunoda/meteor,servel333/meteor,stevenliuit/meteor,baysao/meteor,ljack/meteor,whip112/meteor,framewr/meteor,dboyliao/meteor,PatrickMcGuinness/meteor,vacjaliu/meteor,daslicht/meteor,kidaa/meteor,GrimDerp/meteor,deanius/meteor,DCKT/meteor,devgrok/meteor,luohuazju/meteor,IveWong/meteor,daltonrenaldo/meteor,arunoda/meteor,rabbyalone/meteor,TechplexEngineer/meteor,chinasb/meteor,devgrok/meteor,elkingtonmcb/meteor,framewr/meteor,pjump/meteor,dandv/meteor,tdamsma/meteor,aldeed/meteor,chasertech/meteor,JesseQin/meteor,aldeed/meteor,EduShareOntario/meteor,judsonbsilva/meteor,jirengu/meteor,calvintychan/meteor,lorensr/meteor,mirstan/meteor,youprofit/meteor,iman-mafi/meteor,evilemon/meteor,servel333/meteor,benjamn/meteor,luohuazju/meteor,EduShareOntario/meteor,chinasb/meteor,allanalexandre/meteor,shrop/meteor,D1no/meteor,HugoRLopes/meteor,msavin/meteor,judsonbsilva/meteor,AlexR1712/meteor,AnjirHossain/meteor,Hansoft/meteor,jagi/meteor,alphanso/meteor,Urigo/meteor,dfischer/meteor,daslicht/meteor,daslicht/meteor,yyx990803/meteor,shadedprofit/meteor,msavin/meteor,Ken-Liu/meteor,chasertech/meteor,TechplexEngineer/meteor,emmerge/meteor,Ken-Liu/meteor,justintung/meteor,cbonami/meteor,JesseQin/meteor,chinasb/meteor,guazipi/meteor,jeblister/meteor,iman-mafi/meteor,EduShareOntario/meteor,yyx990803/meteor,kencheung/meteor,planet-training/meteor,udhayam/meteor,dev-bobsong/meteor,sunny-g/meteor,joannekoong/meteor,zdd910/meteor,rozzzly/meteor,oceanzou123/meteor,rozzzly/meteor,DCKT/meteor,brettle/meteor,alexbeletsky/meteor,meteor-velocity/meteor
--- +++ @@ -7,7 +7,7 @@ // XXX this should go away, and there should be a clean interface // that tinytest and the driver both implement? api.use('tinytest'); - api.use('bootstrap'); + api.use('bootstrap@1.0.1'); api.use('underscore'); api.use('session');
ed79ebfb2f092f386a2b6798ebbbd21dd2f68fbb
client/src/components/Header/Header.js
client/src/components/Header/Header.js
import React from 'react'; import { NavLink } from 'react-router-dom'; import './style.css'; const Header = props => { const { isAdmin, loggedIn } = props; return ( <div> <div className="navbar"> <div className="navbar-brand"> <NavLink to="/"> <img src="http://via.placeholder.com/185x80" alt="Logo" /> </NavLink> <NavLink activeClassName="selected" className="navbar-item" to="/jobs" > Explore Jobs </NavLink> {isAdmin && ( <NavLink activeClassName="selected" className="navbar-item" to="/admin" > Admin Panel </NavLink> )} {!loggedIn && ( <NavLink activeClassName="selected" className="navbar-item" to="/login" > Log in </NavLink> )} {!loggedIn && ( <NavLink activeClassName="selected" className="navbar-item" to="/join" > Join </NavLink> )} </div> </div> </div> ); }; export default Header;
import React from 'react'; import { NavLink } from 'react-router-dom'; import './style.css'; const Header = props => { const { isAdmin, loggedIn } = props; return ( <div> <div className="navbar"> <div className="navbar-brand"> <NavLink to="/"> <img src="http://via.placeholder.com/185x80" alt="Logo" /> </NavLink> <NavLink activeClassName="selected" className="navbar-item" to="/jobs" > Explore Jobs </NavLink> {isAdmin && ( <NavLink activeClassName="selected" className="navbar-item" to="/admin" > Admin Panel </NavLink> )} {!loggedIn && ( <NavLink activeClassName="selected" className="navbar-item" to="/login" > Log in </NavLink> )} {!loggedIn && ( <NavLink activeClassName="selected" className="navbar-item" to="/join" > Join </NavLink> )} {loggedIn && ( <NavLink activeClassName="selected" className="navbar-item" to="/bookmarks" > My saved jobs </NavLink> )} </div> </div> </div> ); }; export default Header;
Add navbar link to /bookmarks
Add navbar link to /bookmarks
JavaScript
mit
jenovs/bears-team-14,jenovs/bears-team-14
--- +++ @@ -46,6 +46,15 @@ Join </NavLink> )} + {loggedIn && ( + <NavLink + activeClassName="selected" + className="navbar-item" + to="/bookmarks" + > + My saved jobs + </NavLink> + )} </div> </div> </div>
4dc707df767bd7d4ace82747a9b478a29b7eda2e
config/log4js.js
config/log4js.js
var log4js = require('log4js'); log4js.configure({ appenders: [ { 'type': 'file', 'filename': 'logs/mymap.log', 'category': ['mymap', 'console'], 'maxLogSize': 5242880, 'backups': 10 }, { type: 'console' } ], replaceConsole: true }); exports.getLogger = function() { return log4js.getLogger('mymap'); }
var log4js = require('log4js'), fs = require('fs'); configure(); exports.getLogger = function() { return log4js.getLogger('mymap'); } function configure() { if(!fs.existsSync('logs')) { fs.mkdirSync('logs'); } log4js.configure({ appenders: [ { 'type': 'file', 'filename': 'logs/mymap.log', 'category': ['mymap', 'console'], 'maxLogSize': 5242880, 'backups': 10 }, { type: 'console' } ], replaceConsole: true }); }
Create logs dir if necessary
Create logs dir if necessary
JavaScript
mit
k4v1cs/mymap
--- +++ @@ -1,21 +1,30 @@ -var log4js = require('log4js'); +var log4js = require('log4js'), + fs = require('fs'); -log4js.configure({ - appenders: [ - { - 'type': 'file', - 'filename': 'logs/mymap.log', - 'category': ['mymap', 'console'], - 'maxLogSize': 5242880, - 'backups': 10 - }, - { - type: 'console' - } - ], - replaceConsole: true -}); +configure(); exports.getLogger = function() { return log4js.getLogger('mymap'); } + +function configure() { + if(!fs.existsSync('logs')) { + fs.mkdirSync('logs'); + } + + log4js.configure({ + appenders: [ + { + 'type': 'file', + 'filename': 'logs/mymap.log', + 'category': ['mymap', 'console'], + 'maxLogSize': 5242880, + 'backups': 10 + }, + { + type: 'console' + } + ], + replaceConsole: true + }); +}
cf1b6a0f7df449b834d1fecca64a774a6f768593
DataAccess/Meets.js
DataAccess/Meets.js
const MySql = require("./MySql.js"); class Meet{ constructor(obj){ Object.keys(obj).forEach(k=>this[k]=obj[k]); } asMarkdown(){ return `*${this.post_title}* ${this.meet_start_time}\n_${this.guid}_`; } } Meet.fromObjArray = function(objArray){ return objArray.map(o=>new Meet(o)); }; function getAllMeets(){ return MySql.query(`SELECT * FROM wp_posts WHERE post_type = 'meet'`) .then(results=>Meet.fromObjArray(results.results)); } function getUpcomingMeets(){ return MySql.query(` SELECT meta_value AS meet_start_time, wp_posts.* FROM wp_postmeta LEFT JOIN wp_posts ON post_id=ID WHERE meta_key = 'meet_start_time' AND CAST(meta_value AS DATE) > CURDATE() `).then(results=>Meet.fromObjArray(results.results)); } module.exports = {getAllMeets,getUpcomingMeets};
const MySql = require("./MySql.js"); const entities = require("entities"); class Meet{ constructor(obj){ Object.keys(obj).forEach(k=>this[k]=entities.decodeHTML(obj[k])); } asMarkdown(){ return `*${this.post_title}* ${this.meet_start_time}\n${this.guid}`; } } Meet.fromObjArray = function(objArray){ return objArray.map(o=>new Meet(o)); }; function getAllMeets(){ return MySql.query(`SELECT * FROM wp_posts WHERE post_type = 'meet'`) .then(results=>Meet.fromObjArray(results.results)); } function getUpcomingMeets(){ return MySql.query(` SELECT CAST(meta_value AS DATE) AS meet_start_time, wp_posts.* FROM wp_postmeta LEFT JOIN wp_posts ON post_id=ID WHERE meta_key = 'meet_start_time' AND CAST(meta_value AS DATE) > CURDATE() `).then(results=>Meet.fromObjArray(results.results)); } module.exports = {getAllMeets,getUpcomingMeets};
FIX broken markdown and entities
FIX broken markdown and entities
JavaScript
mit
severnbronies/Sail
--- +++ @@ -1,12 +1,13 @@ const MySql = require("./MySql.js"); +const entities = require("entities"); class Meet{ constructor(obj){ - Object.keys(obj).forEach(k=>this[k]=obj[k]); + Object.keys(obj).forEach(k=>this[k]=entities.decodeHTML(obj[k])); } asMarkdown(){ - return `*${this.post_title}* ${this.meet_start_time}\n_${this.guid}_`; + return `*${this.post_title}* ${this.meet_start_time}\n${this.guid}`; } } @@ -21,7 +22,7 @@ function getUpcomingMeets(){ return MySql.query(` - SELECT meta_value AS meet_start_time, wp_posts.* + SELECT CAST(meta_value AS DATE) AS meet_start_time, wp_posts.* FROM wp_postmeta LEFT JOIN wp_posts ON post_id=ID WHERE meta_key = 'meet_start_time' AND CAST(meta_value AS DATE) > CURDATE() `).then(results=>Meet.fromObjArray(results.results));
703714a2b5d527aa87cd996cbc07c9f3fab3a55d
emcee.js
emcee.js
module.exports = exports = MC function MC () { this._loading = 0 this.models = {} } var modelLoaders = {} MC.model = function (name, loader) { modelLoaders[name] = loader return MC } MC.prototype.load = function (name) { if (!modelLoaders[name]) { throw new Error('Unknown model: ' + name) } if (this.error) return var a = new Array(arguments.length) for (var i = 1; i < arguments.length; i ++) { a[i-1] = arguments[i] } a[i-1] = next.bind(this) this._loading ++ modelLoaders[name].apply(this, a) function next (er, data) { if (this.error) return this.error = er this.models[name] = data this._loading -- if (er || this._loading === 0) { this.ondone(this.error, this.models) } } } MC.prototype.end = function (cb) { this.ondone = cb if (this._loading === 0) this.ondone(this.error, this.models) }
module.exports = exports = MC function MC () { this.loading = 0 this.models = {} this.ondone = function () {} } var modelLoaders = {} MC.model = function (name, loader) { if (MC.prototype.hasOwnProperty(name) || name === 'loading' || name === 'ondone' || name === 'error' || name === 'models') { throw new Error('invalid model name: ' + name) } modelLoaders[name] = loader return MC } MC.prototype.load = function (name) { if (!modelLoaders[name]) { throw new Error('Unknown model: ' + name) } if (this.error) return var a = new Array(arguments.length) for (var i = 1; i < arguments.length; i ++) { a[i-1] = arguments[i] } a[i-1] = next.bind(this) this.loading ++ modelLoaders[name].apply(this, a) function next (er, data) { if (this.error) return this.error = er this[name] = this.models[name] = data this.loading -- if ((er || this.loading === 0) && this.ondone) { this.ondone(this.error, this.models) } } } MC.prototype.end = function (cb) { this.ondone = cb if (this.loading === 0 || this.error) { this.ondone(this.error, this.models) } }
Put the model results right on the MC object
Put the model results right on the MC object
JavaScript
isc
isaacs/emcee
--- +++ @@ -1,12 +1,20 @@ module.exports = exports = MC function MC () { - this._loading = 0 + this.loading = 0 this.models = {} + this.ondone = function () {} } var modelLoaders = {} MC.model = function (name, loader) { + if (MC.prototype.hasOwnProperty(name) || + name === 'loading' || + name === 'ondone' || + name === 'error' || + name === 'models') { + throw new Error('invalid model name: ' + name) + } modelLoaders[name] = loader return MC } @@ -21,15 +29,15 @@ a[i-1] = arguments[i] } a[i-1] = next.bind(this) - this._loading ++ + this.loading ++ modelLoaders[name].apply(this, a) function next (er, data) { if (this.error) return this.error = er - this.models[name] = data + this[name] = this.models[name] = data - this._loading -- - if (er || this._loading === 0) { + this.loading -- + if ((er || this.loading === 0) && this.ondone) { this.ondone(this.error, this.models) } } @@ -37,5 +45,7 @@ MC.prototype.end = function (cb) { this.ondone = cb - if (this._loading === 0) this.ondone(this.error, this.models) + if (this.loading === 0 || this.error) { + this.ondone(this.error, this.models) + } }
c2d0f37353c6ea1daf5f10c149d01c6e667c3524
fetch.js
fetch.js
const fs = require('fs'); const path = require('path'); const exec = require('child_process').exec; // this is from the env of npm, not node const nodePath = process.env.NODE; const version = process.versions.v8; const tmpfile = path.join(__dirname, version+'.flags.json'); if (!fs.existsSync(tmpfile)) { exec('"'+nodePath+'" --v8-options', function (execErr, result) { var flags; if (execErr) { throw new Error(execErr); } else { flags = result.match(/\s\s--(\w+)/gm).map(function (match) { return match.substring(2); }); fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' }, function (writeErr) { if (writeErr) { throw new Error(writeErr); } else { console.log('flags for v8 '+version+' cached.'); } } ); } }); } module.exports = require.bind(null, tmpfile);
const fs = require('fs'); const path = require('path'); const exec = require('child_process').exec; const nodePath = process.execPath; const version = process.versions.v8; const tmpfile = path.join(__dirname, version+'.flags.json'); if (!fs.existsSync(tmpfile)) { exec('"'+nodePath+'" --v8-options', function (execErr, result) { var flags; if (execErr) { throw new Error(execErr); } else { flags = result.match(/\s\s--(\w+)/gm).map(function (match) { return match.substring(2); }); fs.writeFile(tmpfile, JSON.stringify(flags), { encoding:'utf8' }, function (writeErr) { if (writeErr) { throw new Error(writeErr); } else { console.log('flags for v8 '+version+' cached.'); } } ); } }); } module.exports = require.bind(null, tmpfile);
Use process.execPath to find node executable on Windows
Fix: Use process.execPath to find node executable on Windows
JavaScript
mit
js-cli/js-v8flags,tkellen/js-v8flags
--- +++ @@ -2,8 +2,7 @@ const path = require('path'); const exec = require('child_process').exec; -// this is from the env of npm, not node -const nodePath = process.env.NODE; +const nodePath = process.execPath; const version = process.versions.v8; const tmpfile = path.join(__dirname, version+'.flags.json');
d6484cd7f2cb24f7c0596f363c983c6c2a71057a
tools/scripts/property-regex.js
tools/scripts/property-regex.js
const { assemble, writeFile, unicodeVersion } = require('./utils.js'); const properties = [ 'ASCII', 'Alphabetic', 'Any', 'Default_Ignorable_Code_Point', 'Lowercase', 'Noncharacter_Code_Point', 'Uppercase', 'White_Space' ]; const result = []; for (const property of properties) { const codePoints = require(`${unicodeVersion}/Binary_Property/${property}/code-points.js`); result.push(assemble({ name: property, codePoints })); } writeFile('properties.js', result);
const { assemble, writeFile, unicodeVersion } = require('./utils.js'); // This intentially includes only the binary properties required by UTS 18 Level 1 RL1.2 for Unicode // regex support, minus `Assigned` which has special handling since it is the inverse of Unicode // category `Unassigned` (`Cn`). To include all binary properties, change this to: // `const properties = require(`${unicodeVersion}`).Binary_Property;` const properties = [ 'ASCII', 'Alphabetic', 'Any', 'Default_Ignorable_Code_Point', 'Lowercase', 'Noncharacter_Code_Point', 'Uppercase', 'White_Space' ]; const result = []; for (const property of properties) { const codePoints = require(`${unicodeVersion}/Binary_Property/${property}/code-points.js`); result.push(assemble({ name: property, codePoints })); } writeFile('properties.js', result);
Add comment about level 1 Unicode properties
Add comment about level 1 Unicode properties
JavaScript
mit
GerHobbelt/xregexp,slevithan/xregexp,slevithan/xregexp,slevithan/XRegExp,slevithan/xregexp,GerHobbelt/xregexp,GerHobbelt/xregexp,slevithan/XRegExp
--- +++ @@ -4,6 +4,10 @@ unicodeVersion } = require('./utils.js'); +// This intentially includes only the binary properties required by UTS 18 Level 1 RL1.2 for Unicode +// regex support, minus `Assigned` which has special handling since it is the inverse of Unicode +// category `Unassigned` (`Cn`). To include all binary properties, change this to: +// `const properties = require(`${unicodeVersion}`).Binary_Property;` const properties = [ 'ASCII', 'Alphabetic',
16f58e1d165b0d683fd44535ac6e8f6cb12fdd8c
popit-hosting/app.js
popit-hosting/app.js
/** * Module dependencies. */ var express = require('express'), expressHogan = require('express-hogan.js'), mongoose = require('mongoose'), nodemailer = require('nodemailer'); // Connect to the default database mongoose.connect('mongodb://localhost/all'); var app = module.exports = express.createServer(); // Configuration app.configure(function(){ app.set('views', __dirname + '/views'); app.register('.txt', expressHogan); app.register('.html', expressHogan); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); app.use(express.logger({ format: ':method :status :url' })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); app.nodemailer_transport = nodemailer.createTransport("Sendmail"); // Routes require('./routes').route(app); app.listen(3000); console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
/** * Module dependencies. */ var express = require('express'), expressHogan = require('express-hogan.js'), mongoose = require('mongoose'), nodemailer = require('nodemailer'); // Connect to the default database mongoose.connect('mongodb://localhost/all'); var app = module.exports = express.createServer(); // Configuration app.configure(function(){ app.use(express.logger('dev')); app.set('views', __dirname + '/views'); app.register('.txt', expressHogan); app.register('.html', expressHogan); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); app.nodemailer_transport = nodemailer.createTransport("Sendmail"); // Routes require('./routes').route(app); app.listen(3000); console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
Add logging to all requests (needed to be at start of configure, perhaps a template rendering issue?)
Add logging to all requests (needed to be at start of configure, perhaps a template rendering issue?)
JavaScript
agpl-3.0
maxogden/popit,mysociety/popit,mysociety/popit,openstate/popit,mysociety/popit,openstate/popit,maxogden/popit,mysociety/popit,mysociety/popit,Sinar/popit,openstate/popit,Sinar/popit,Sinar/popit,Sinar/popit,openstate/popit
--- +++ @@ -17,6 +17,7 @@ // Configuration app.configure(function(){ + app.use(express.logger('dev')); app.set('views', __dirname + '/views'); app.register('.txt', expressHogan); app.register('.html', expressHogan); @@ -28,7 +29,6 @@ app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); - app.use(express.logger({ format: ':method :status :url' })); }); app.configure('production', function(){
a8514306b93f1311c6052cfe6440e84a1da1cca2
scripts/generators.js
scripts/generators.js
var pagination = require('hexo-pagination'); var _ = require('lodash'); hexo.extend.generator.register('category', function(locals){ var config = this.config; var categories = locals.data.categories; if (config.category_generator) { var perPage = config.category_generator.per_page; } else { var perPage = 10; } var paginationDir = config.pagination_dir || 'page'; var result = []; _.each(categories, function(data, title) { _.each(data, function(data, lang) { result = result.concat( pagination(lang + '/' + data.slug, getCategoryByName(locals.categories, data.category).posts, { perPage: perPage, layout: ['category', 'archive', 'index'], format: paginationDir + '/%d/', data: { lang: lang, title: data.name, category: data.category } }) ); }); }); return result; }); function getCategoryByName(categories, name) { return categories.toArray().filter(function(category){ return category.name == name; })[0]; }
var pagination = require('hexo-pagination'); var _ = require('lodash'); hexo.extend.generator.register('category', function(locals){ var config = this.config; var categories = locals.data.categories; if (config.category_generator) { var perPage = config.category_generator.per_page; } else { var perPage = 10; } var paginationDir = config.pagination_dir || 'page'; var result = []; _.each(categories, function(category, title) { _.each(category, function(data, lang) { result = result.concat( pagination(lang + '/' + data.slug, getCategoryByName(locals.categories, data.category).posts, { perPage: perPage, layout: ['category', 'archive', 'index'], format: paginationDir + '/%d/', data: { lang: lang, title: data.name, category: data.category, alternates: getAlternateLangs(category, lang) } }) ); }); }); return result; }); function getCategoryByName(categories, name) { return categories.toArray().filter(function(category){ return category.name == name; })[0]; } function getAlternateLangs(category, currentLang) { var result = []; _.each(category, function(data, lang) { if (currentLang != lang) { result.push({ lang: lang, path: lang + '/' + data.slug }); } }); return result; }
Add alternate language categories in generator
Add alternate language categories in generator This will populate the `alternates` variable that will be available to use in the layout files. The current language is not included for obvious reasons. Built from a10e346a1e29ca8ed1cb71666f8bf7b7d2fd8239.
JavaScript
mit
ahaasler/hexo-theme-colos,ahaasler/hexo-theme-colos
--- +++ @@ -12,8 +12,8 @@ var paginationDir = config.pagination_dir || 'page'; var result = []; - _.each(categories, function(data, title) { - _.each(data, function(data, lang) { + _.each(categories, function(category, title) { + _.each(category, function(data, lang) { result = result.concat( pagination(lang + '/' + data.slug, getCategoryByName(locals.categories, data.category).posts, { perPage: perPage, @@ -22,7 +22,8 @@ data: { lang: lang, title: data.name, - category: data.category + category: data.category, + alternates: getAlternateLangs(category, lang) } }) ); @@ -37,3 +38,16 @@ return category.name == name; })[0]; } + +function getAlternateLangs(category, currentLang) { + var result = []; + _.each(category, function(data, lang) { + if (currentLang != lang) { + result.push({ + lang: lang, + path: lang + '/' + data.slug + }); + } + }); + return result; +}
03bd8cd920c7d2d26e93da9e690cef5a01b710bf
core/util/DefaultKeystoneConfiguration.js
core/util/DefaultKeystoneConfiguration.js
/** * DefaultKeystoneConfiguration contains the default settings for keystone. * @class DefaultKeystoneConfiguration * @param {Theme} theme * @constructor * */ module.exports = function DefaultKeystoneConfiguration(theme) { return { 'name': process.env.DOMAIN || 'Estore', 'brand': process.env.DOMAIN || 'Estore', 'auto update': process.env.KEYSTONE_AUTO_UPDATE || true, 'session': true, 'session store': 'mongo', 'auth': true, 'cookie secret': process.env.COOKIE_SECRET, 'view engine': 'html', 'views': theme.getTemplatePath(), 'static': theme.getStaticPath(), 'emails': theme.getEmailPath(), 'port': process.env.PORT || 3000, 'mongo': process.env.MONGO_URI, }; };
/** * DefaultKeystoneConfiguration contains the default settings for keystone. * @class DefaultKeystoneConfiguration * @param {Theme} theme * @constructor * */ module.exports = function DefaultKeystoneConfiguration(theme) { return { 'name': process.env.DOMAIN || 'Estore', 'brand': process.env.DOMAIN || 'Estore', 'auto update': (process.env.KEYSTONE_AUTO_UPDATE === true) ? true : false, 'session': true, 'session store': 'mongo', 'auth': true, 'cookie secret': process.env.COOKIE_SECRET, 'view engine': 'html', 'views': theme.getTemplatePath(), 'static': theme.getStaticPath(), 'emails': theme.getEmailPath(), 'port': process.env.PORT || 3000, 'mongo': process.env.MONGO_URI, }; };
Use an explicit check for auto update override.
Use an explicit check for auto update override.
JavaScript
mit
stunjiturner/estorejs,stunjiturner/estorejs,quenktechnologies/estorejs
--- +++ @@ -6,12 +6,11 @@ * */ module.exports = function DefaultKeystoneConfiguration(theme) { - return { 'name': process.env.DOMAIN || 'Estore', 'brand': process.env.DOMAIN || 'Estore', - 'auto update': process.env.KEYSTONE_AUTO_UPDATE || true, + 'auto update': (process.env.KEYSTONE_AUTO_UPDATE === true) ? true : false, 'session': true, 'session store': 'mongo', 'auth': true,
70b429733a5a9be44be5d21fb2703b27068552b4
test-helpers/init.js
test-helpers/init.js
// First require your DOM emulation file (see below) require('./emulateDom.js'); import db_config from '../knexfile'; let exec_env = process.env.DB_ENV || 'test'; global.$dbConfig = db_config[exec_env]; process.env.NODE_ENV = 'test';
global.Promise = require('bluebird') global.Promise.onPossiblyUnhandledRejection((e) => { throw e; }); global.Promise.config({ // Enable warnings. warnings: false, // Enable long stack traces. longStackTraces: true, // Enable cancellation. cancellation: true }); // First require your DOM emulation file (see below) require('./emulateDom.js'); import db_config from '../knexfile'; let exec_env = process.env.DB_ENV || 'test'; global.$dbConfig = db_config[exec_env]; process.env.NODE_ENV = 'test';
Use bluebird for debuggable promises in tests
Use bluebird for debuggable promises in tests
JavaScript
agpl-3.0
Lokiedu/libertysoil-site,Lokiedu/libertysoil-site
--- +++ @@ -1,3 +1,15 @@ +global.Promise = require('bluebird') +global.Promise.onPossiblyUnhandledRejection((e) => { throw e; }); + +global.Promise.config({ + // Enable warnings. + warnings: false, + // Enable long stack traces. + longStackTraces: true, + // Enable cancellation. + cancellation: true +}); + // First require your DOM emulation file (see below) require('./emulateDom.js');
66921fdcec7506f3f86ee34ff9619e1978f7c41d
gevents.js
gevents.js
'use strict'; var request = require('request'); var opts = { uri: 'https://api.github.com' + '/users/' + parseParams(process.argv[2]) + '/events', json: true, method: 'GET', headers: { 'User-Agent': 'nodejs script' } } request(opts, function (err, res, body) { if (err) throw new Error(err); var format = '[%s]: %s %s %s %s'; for (var i = 0; i < body.length; i++) { /* * TODO return something like this as JSON * for caller consumption (useful for servers). */ console.log(format , body[i].created_at , body[i].type , body[i].actor.login , body[i].repo.name); } }); function parseParams(params) { if (! params) { console.log('Usage: nodejs gevents.js <user-name>'); process.exit(0); } return params; }
'use strict'; var request = require('request'); var opts = { uri: 'https://api.github.com' + '/users/' + parseParams(process.argv[2]) + '/events', json: true, method: 'GET', headers: { 'User-Agent': 'nodejs script' } } request(opts, function (err, res, body) { if (err) throw new Error(err); var format = '[%s]: %s %s %s %s'; for (var i = 0; i < body.length; i++) { /* * TODO return something like this as JSON * for caller consumption (useful for servers). */ console.log(format , body[i].created_at , body[i].type , body[i].actor.login , body[i].repo.name); } }); /* * Verify param is present, and just return it. * TODO * Check for multiple params, and check validity * as well as presence. */ function parseParams(params) { if (! params) { console.log('Usage: nodejs gevents.js <user-name>'); process.exit(0); } return params; }
Add explanatory and TODO notes
Add explanatory and TODO notes
JavaScript
mit
jm-janzen/scripts,jm-janzen/scripts,jm-janzen/scripts
--- +++ @@ -29,6 +29,12 @@ } }); +/* + * Verify param is present, and just return it. + * TODO + * Check for multiple params, and check validity + * as well as presence. + */ function parseParams(params) { if (! params) { console.log('Usage: nodejs gevents.js <user-name>');
1528ba519169e493fac28c21d6c483187d24bc36
test/markup/index.js
test/markup/index.js
'use strict'; var _ = require('lodash'); var bluebird = require('bluebird'); var fs = bluebird.promisifyAll(require('fs')); var glob = require('glob'); var hljs = require('../../build'); var path = require('path'); var utility = require('../utility'); function testLanguage(language) { describe(language, function() { var filePath = utility.buildPath('markup', language, '*.expect.txt'), filenames = glob.sync(filePath); _.each(filenames, function(filename) { var testName = path.basename(filename, '.expect.txt'), sourceName = filename.replace(/\.expect/, ''); it(`should markup ${testName}`, function(done) { var sourceFile = fs.readFileAsync(sourceName, 'utf-8'), expectedFile = fs.readFileAsync(filename, 'utf-8'); bluebird.join(sourceFile, expectedFile, function(source, expected) { var actual = hljs.highlight(language, source).value; actual.trim().should.equal(expected.trim()); done(); }); }); }); }); } describe('hljs.highlight()', function() { var languages = fs.readdirSync(utility.buildPath('markup')); _.each(languages, testLanguage, this); });
'use strict'; var _ = require('lodash'); var bluebird = require('bluebird'); var fs = bluebird.promisifyAll(require('fs')); var glob = require('glob'); var hljs = require('../../build'); var path = require('path'); var utility = require('../utility'); function testLanguage(language) { describe(language, function() { var filePath = utility.buildPath('markup', language, '*.expect.txt'), filenames = glob.sync(filePath); _.each(filenames, function(filename) { var testName = path.basename(filename, '.expect.txt'), sourceName = filename.replace(/\.expect/, ''); it(`should markup ${testName}`, function(done) { var sourceFile = fs.readFileAsync(sourceName, 'utf-8'), expectedFile = fs.readFileAsync(filename, 'utf-8'); bluebird.join(sourceFile, expectedFile, function(source, expected) { var actual = hljs.highlight(language, source).value; actual.trim().should.equal(expected.trim()); done(); }); }); }); }); } describe('hljs.highlight()', function() { var markupPath = utility.buildPath('markup'); return fs.readdirAsync(markupPath).each(testLanguage); });
Change synchronous readdir to a promise
Change synchronous readdir to a promise
JavaScript
bsd-3-clause
bluepichu/highlight.js,carlokok/highlight.js,aurusov/highlight.js,highlightjs/highlight.js,MakeNowJust/highlight.js,palmin/highlight.js,teambition/highlight.js,palmin/highlight.js,Sannis/highlight.js,sourrust/highlight.js,isagalaev/highlight.js,tenbits/highlight.js,Sannis/highlight.js,highlightjs/highlight.js,sourrust/highlight.js,isagalaev/highlight.js,palmin/highlight.js,teambition/highlight.js,teambition/highlight.js,sourrust/highlight.js,lead-auth/highlight.js,tenbits/highlight.js,highlightjs/highlight.js,highlightjs/highlight.js,MakeNowJust/highlight.js,dbkaplun/highlight.js,dbkaplun/highlight.js,aurusov/highlight.js,tenbits/highlight.js,StanislawSwierc/highlight.js,dbkaplun/highlight.js,StanislawSwierc/highlight.js,Sannis/highlight.js,MakeNowJust/highlight.js,bluepichu/highlight.js,carlokok/highlight.js,bluepichu/highlight.js,carlokok/highlight.js,aurusov/highlight.js,carlokok/highlight.js
--- +++ @@ -33,7 +33,7 @@ } describe('hljs.highlight()', function() { - var languages = fs.readdirSync(utility.buildPath('markup')); + var markupPath = utility.buildPath('markup'); - _.each(languages, testLanguage, this); + return fs.readdirAsync(markupPath).each(testLanguage); });
34d660f07f603b9017fe2dcd88518c0a5c175503
test/onerror-test.js
test/onerror-test.js
var assert = buster.referee.assert; buster.testCase("Call onerror", { setUp: function () { $ = {}; $.post = this.spy(); initErrorHandler("/error", "localhost"); }, "exception within the system": function () { window.onerror('error message', 'http://localhost/test.js', 11); assert.isTrue($.post.called); }, "error within the system": function (done) { setTimeout(function() { // throw some real-life exception not_defined.not_defined(); }, 10); setTimeout(function() { assert.isTrue($.post.called); done(); }, 100); }, "error outside the system": function() { window.onerror('error message', 'http://example.com/test.js', 11); assert.isFalse($.post.called); }, "error from unknown source": function() { window.onerror('error message', 'http://localhost/foo', 11); assert.isFalse($.post.called); } });
var assert = buster.referee.assert; var hostname = location.hostname; buster.testCase("Call onerror", { setUp: function () { $ = {}; $.post = this.spy(); initErrorHandler("/error", hostname); }, "exception within the system": function () { window.onerror('error message', 'http://' + hostname + '/test.js', 11); assert.isTrue($.post.called); }, "error within the system": function (done) { setTimeout(function() { // throw some real-life exception not_defined.not_defined(); }, 10); setTimeout(function() { assert.isTrue($.post.called); done(); }, 100); }, "error outside the system": function() { window.onerror('error message', 'http://example.com/test.js', 11); assert.isFalse($.post.called); }, "error from unknown source": function() { window.onerror('error message', 'http://' + hostname + '/foo', 11); assert.isFalse($.post.called); } });
Make the tests work for remote test clients.
Make the tests work for remote test clients.
JavaScript
mit
lucho-yankov/window.onerror
--- +++ @@ -1,4 +1,5 @@ var assert = buster.referee.assert; +var hostname = location.hostname; buster.testCase("Call onerror", { @@ -6,11 +7,11 @@ $ = {}; $.post = this.spy(); - initErrorHandler("/error", "localhost"); + initErrorHandler("/error", hostname); }, "exception within the system": function () { - window.onerror('error message', 'http://localhost/test.js', 11); + window.onerror('error message', 'http://' + hostname + '/test.js', 11); assert.isTrue($.post.called); }, @@ -33,7 +34,7 @@ }, "error from unknown source": function() { - window.onerror('error message', 'http://localhost/foo', 11); + window.onerror('error message', 'http://' + hostname + '/foo', 11); assert.isFalse($.post.called); } });
2b7213f17e1b6206329bbc02693053b04e52669a
this.js
this.js
console.log(this) //contexto global console.log(this === window) //true var developer = { name : 'Erik', lastName : 'Ochoa', isAdult : true, completeName: function(){ return this.name + this.lastName } } console.log(developer.name) // Erik console.log(developer.lastName) // Ochoa console.log(developer.isAdult) // true //We call a function that is stored as a property of an object becoming a method console.log(developer.completeName()) // ErikOchoa
console.log(this) //contexto global console.log(this === window) //true var developer = { name : 'Erik', lastName : 'Ochoa', isAdult : true, get completeName() { return this.name + this.lastName } } console.log(developer.name) // Erik console.log(developer.lastName) // Ochoa console.log(developer.isAdult) // true console.log(developer.completeName) // ErikOchoa
Use getter to call completeName as a property
Use getter to call completeName as a property
JavaScript
mit
Elyager/this-in-depth,Elyager/this-in-depth
--- +++ @@ -6,7 +6,7 @@ name : 'Erik', lastName : 'Ochoa', isAdult : true, - completeName: function(){ + get completeName() { return this.name + this.lastName } } @@ -14,7 +14,6 @@ console.log(developer.name) // Erik console.log(developer.lastName) // Ochoa console.log(developer.isAdult) // true -//We call a function that is stored as a property of an object becoming a method -console.log(developer.completeName()) // ErikOchoa +console.log(developer.completeName) // ErikOchoa
3a04f4e532a7dbba3d560866e9e93b305ae3bf17
test/prerequisite.js
test/prerequisite.js
describe('Prerequisites', () => { describe('Call the same resource with both http client and iframe', () => { it('http headers should be less or equal than iframe ones', () => { browser.url('/'); browser.leftClick('.httpCall'); browser.waitForExist('.detail_headers'); browser.waitForExist('.detail_body'); const httpHeadersCount = Object.keys(browser.elements('.detail_headers').value).length; const httpBodyCount = Object.keys(browser.elements('.detail_body').value).length; browser.leftClick('.iframeCall'); browser.waitForExist('.detail_headers'); browser.waitForExist('.detail_body'); const iframeHeadersCount = Object.keys(browser.elements('.detail_headers').value).length; const iframeBodyCount = Object.keys(browser.elements('.detail_body').value).length; expect(iframeHeadersCount).toBeGreaterThanOrEqual(httpHeadersCount); expect(iframeBodyCount).toBeGreaterThanOrEqual(httpBodyCount); }); }) });
describe('Prerequisites', () => { describe('Call the same resource with both http client and iframe', () => { it('http headers should be less or equal than iframe ones', () => { browser.url('/'); browser.leftClick('.httpCall'); browser.waitForExist('.detail_headers'); browser.waitForExist('.detail_body'); const httpHeadersCount = Object.keys(browser.elements('.detail_headers').value).length; const httpBodyCount = Object.keys(browser.elements('.detail_body').value).length; browser.refresh(); browser.leftClick('.iframeCall'); browser.waitForExist('.detail_headers'); browser.waitForExist('.detail_body'); const iframeHeadersCount = Object.keys(browser.elements('.detail_headers').value).length; const iframeBodyCount = Object.keys(browser.elements('.detail_body').value).length; expect(iframeHeadersCount).toBeGreaterThanOrEqual(httpHeadersCount); expect(iframeBodyCount).toBeGreaterThanOrEqual(httpBodyCount); }); }) });
Refresh the page between a test and another
Refresh the page between a test and another
JavaScript
mit
apiaryio/apiary-console-seed,apiaryio/apiary-console-seed,apiaryio/console-proxy,apiaryio/console-proxy
--- +++ @@ -9,6 +9,7 @@ const httpHeadersCount = Object.keys(browser.elements('.detail_headers').value).length; const httpBodyCount = Object.keys(browser.elements('.detail_body').value).length; + browser.refresh(); browser.leftClick('.iframeCall'); browser.waitForExist('.detail_headers'); browser.waitForExist('.detail_body');
c907f340b2ac40a6d4af218f2d68df5fde5cc57d
test/test-builder.js
test/test-builder.js
const Alfred = require('../index'); const Builder = Alfred.Builder; const bot = new Alfred(); bot.login('username', 'password') .then(() => bot.send('servernotifyregister', { 'event': 'server' })) .then(() => bot.send('servernotifyregister', { 'event': 'textprivate' })) .then(() => console.log('Connected with clid', bot.get('clid'))) .catch(console.error); bot.use(Alfred.User); bot.on('cliententerview', data => console.log(data.user.get('name'), 'connected', '[db:' + data.user.get('dbid') + ']')); bot.on('clientleftview', data => console.log(data.user.get('name'), 'disconnected')); bot.on('textmessage', data => { let msg = "" + data.msg; console.log(JSON.stringify(data)); if (msg.startsWith("!exit")) { bot.disconnect(); console.log("disconnected"); } if (msg.startsWith("!kickserver")) { data.user.serverKick(Builder.underline("Bye from the server!")); } if (msg.startsWith("!kickchannel")) { data.user.channelKick(Builder.italic("bye have great day!")); } });
const Alfred = require('../index'); const Builder = Alfred.Builder; const bot = new Alfred(); bot.login('username', 'password') .then(() => bot.send('servernotifyregister', { 'event': 'server' })) .then(() => bot.send('servernotifyregister', { 'event': 'textprivate' })) .then(() => console.log('Connected with clid', bot.get('clid'))) .catch(console.error); bot.use(Alfred.User); bot.on('cliententerview', data => console.log(data.user.get('name'), 'connected', '[db:' + data.user.get('dbid') + ']')); bot.on('clientleftview', data => console.log(data.user.get('name'), 'disconnected')); bot.on('textmessage', data => { let msg = "" + data.msg; console.log(JSON.stringify(data)); if (msg.startsWith("!exit")) { bot.disconnect(); console.log("disconnected"); } if (msg.startsWith("!kickserver")) { data.user.serverKick(Builder.underline("Bye from the server!")); } if (msg.startsWith("!kickchannel")) { data.user.channelKick(Builder.italic("bye have great day!")); } });
Add new line at the end of test files
Add new line at the end of test files
JavaScript
mit
schroffl/alfred-teamspeak
df378b792ed24f04915783f803cc3355b69e6129
APE_Server/APScripts/framework/cmd_event.js
APE_Server/APScripts/framework/cmd_event.js
/* * Command to handle APS events */ Ape.registerCmd("event", true, function(params, info) { if(params.multi){ var recipient = Ape.getChannelByPubid(params.pipe); }else{ var recipient = Ape.getUserByPubid(params.pipe); } if(recipient){ if(!!params.sync){ info.sendResponse("SYNC", { data: params.data, event: params.event, chanid: params.pipe }); } delete params.sync; recipient.sendEvent(params, {from: info.user.pipe}); } return 1; });
/* * Command to handle APS events */ Ape.registerCmd("event", true, function(params, info) { if(params.multi){ var recipient = Ape.getChannelByPubid(params.pipe); }else{ var recipient = Ape.getUserByPubid(params.pipe); } if(recipient){ if(!!params.sync){ info.sendResponse("SYNC", { data: params.data, event: params.event, chanid: params.pipe }); } delete params.sync; recipient.sendEvent(params, {from: info.user.pipe}); return 1; } return ["425", "UNKNOWN_RECIPIENT"]; });
Send error 425 if the recipient of an event is not found
Send error 425 if the recipient of an event is not found
JavaScript
mit
ptejada/ApePubSub,ptejada/ApePubSub
--- +++ @@ -22,7 +22,10 @@ delete params.sync; recipient.sendEvent(params, {from: info.user.pipe}); + + return 1; } - return 1; + return ["425", "UNKNOWN_RECIPIENT"]; + });
35b55bec4912c6f14351422bc6e6c6fecfd5bfe5
server/auth/index.js
server/auth/index.js
const logger = require('../logging'); const passport = require('passport'); const { setupOIDC } = require('./oidc'); const getUserById = require('../models/user.accessors').getUserById; require('./providers/ow4.js'); module.exports = async (app) => { passport.serializeUser((user, done) => { logger.silly('Serializing user', { userId: user.id }); done(null, user.id); }); passport.deserializeUser((id, done) => { logger.silly('Deserializing user', { userId: id }); done(null, () => getUserById(id)); }); app.use(passport.initialize()); app.use(passport.session()); app.get('/login', passport.authenticate('oauth2', { successReturnToOrRedirect: '/' })); app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); }); app.get('/auth', passport.authenticate('oauth2', { callback: true }), (req, res) => { res.redirect('/'); }); if (process.env.SDF_OIDC && process.env.SDF_OIDC.toLowerCase() === 'true') { const success = await setupOIDC(); if (success) { app.get('/openid-login', passport.authenticate('oidc')); app.get('/openid-auth', passport.authenticate('oidc', { successRedirect: '/', failureRedirect: '/openid-login' })); } return app; } return app; };
const logger = require('../logging'); const passport = require('passport'); const { setupOIDC } = require('./oidc'); const getUserById = require('../models/user.accessors').getUserById; require('./providers/ow4.js'); module.exports = async (app) => { await setupOIDC(); passport.serializeUser((user, done) => { logger.silly('Serializing user', { userId: user.id }); done(null, user.id); }); passport.deserializeUser((id, done) => { logger.silly('Deserializing user', { userId: id }); done(null, () => getUserById(id)); }); app.use(passport.initialize()); app.use(passport.session()); app.get('/login', passport.authenticate('oidc')); app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); }); app.get('/auth', passport.authenticate('oidc', { successRedirect: '/', failureRedirect: '/openid-login' })); return app; };
Make OIDC be default auth mechanism
Make OIDC be default auth mechanism
JavaScript
mit
dotkom/super-duper-fiesta,dotkom/super-duper-fiesta,dotkom/super-duper-fiesta
--- +++ @@ -7,6 +7,8 @@ require('./providers/ow4.js'); module.exports = async (app) => { + await setupOIDC(); + passport.serializeUser((user, done) => { logger.silly('Serializing user', { userId: user.id }); done(null, user.id); @@ -18,21 +20,11 @@ }); app.use(passport.initialize()); app.use(passport.session()); - app.get('/login', passport.authenticate('oauth2', { successReturnToOrRedirect: '/' })); + app.get('/login', passport.authenticate('oidc')); app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); }); - app.get('/auth', passport.authenticate('oauth2', { callback: true }), (req, res) => { - res.redirect('/'); - }); - if (process.env.SDF_OIDC && process.env.SDF_OIDC.toLowerCase() === 'true') { - const success = await setupOIDC(); - if (success) { - app.get('/openid-login', passport.authenticate('oidc')); - app.get('/openid-auth', passport.authenticate('oidc', { successRedirect: '/', failureRedirect: '/openid-login' })); - } - return app; - } + app.get('/auth', passport.authenticate('oidc', { successRedirect: '/', failureRedirect: '/openid-login' })); return app; };
5e44054ad4223d32b53c2312ecd5798b0e114548
main.js
main.js
exports.AgGridAurelia = require('./lib/agGridAurelia').AgGridAurelia; exports.AgGridColumn = require('./lib/agGridColumn').AgGridColumn; exports.AgCellTemplate = require('./lib/agTemplate').AgCellTemplate; exports.AgEditorTemplate = require('./lib/agTemplate').AgEditorTemplate; exports.AgFilterTemplate = require('./lib/agTemplate').AgFilterTemplate; exports.AureliaCellRendererComponent = require('./lib/aureliaCellRendererComponent').AureliaCellRendererComponent; exports.AureliaComponentFactory = require('./lib/aureliaComponentFactory').AureliaComponentFactory; exports.AureliaFrameworkFactory = require('./lib/aureliaFrameworkFactory').AureliaFrameworkFactory; exports.BaseAureliaEditor = require('./lib/editorViewModels').BaseAureliaEditor; function configure(config) { config.globalResources( './lib/agGridAurelia', './lib/agGridColumn', './lib/agTemplate' ); } exports.configure = configure;
exports.AgGridAurelia = require('./lib/agGridAurelia').AgGridAurelia; exports.AgGridColumn = require('./lib/agGridColumn').AgGridColumn; exports.AgCellTemplate = require('./lib/agTemplate').AgCellTemplate; exports.AgEditorTemplate = require('./lib/agTemplate').AgEditorTemplate; exports.AgFullWidthRowTemplate = require('./lib/agTemplate').AgFullWidthRowTemplate; exports.AgFilterTemplate = require('./lib/agTemplate').AgFilterTemplate; exports.AureliaCellRendererComponent = require('./lib/aureliaCellRendererComponent').AureliaCellRendererComponent; exports.AureliaComponentFactory = require('./lib/aureliaComponentFactory').AureliaComponentFactory; exports.AureliaFrameworkFactory = require('./lib/aureliaFrameworkFactory').AureliaFrameworkFactory; exports.BaseAureliaEditor = require('./lib/editorViewModels').BaseAureliaEditor; function configure(config) { config.globalResources( './lib/agGridAurelia', './lib/agGridColumn', './lib/agTemplate' ); } exports.configure = configure;
Add FullWidth row template to exports
Add FullWidth row template to exports
JavaScript
mit
ceolter/ag-grid,ceolter/angular-grid,ceolter/angular-grid,ceolter/ag-grid
--- +++ @@ -3,6 +3,7 @@ exports.AgGridColumn = require('./lib/agGridColumn').AgGridColumn; exports.AgCellTemplate = require('./lib/agTemplate').AgCellTemplate; exports.AgEditorTemplate = require('./lib/agTemplate').AgEditorTemplate; +exports.AgFullWidthRowTemplate = require('./lib/agTemplate').AgFullWidthRowTemplate; exports.AgFilterTemplate = require('./lib/agTemplate').AgFilterTemplate; exports.AureliaCellRendererComponent = require('./lib/aureliaCellRendererComponent').AureliaCellRendererComponent; exports.AureliaComponentFactory = require('./lib/aureliaComponentFactory').AureliaComponentFactory;
272e86c5f7e2d661fff0914abd612f5aef4ee6b1
demo/Progress.js
demo/Progress.js
import React, {Component} from 'react'; import Style from 'styled-components'; class Progress extends Component { state = {progress: 0}; componentDidMount() { this.props.emitter.on(({progress}) => { if (this.state.progress !== progress) { this.setState({progress: progress}); } }); } Bar = Style.div` position:absolute; left: 0; top: 0; height: 2px; background-color: #337ab7; transition: all 0.4s ease-in-out; `; render() { return <this.Bar style={{width: `${this.state.progress}%`}} />; } } export default Progress;
import React, {Component} from 'react'; import Style from 'styled-components'; class Progress extends Component { state = {progress: 0}; componentDidMount() { this.props.emitter.on(({progress}) => { if (this.state.progress !== progress) { this.setState({progress: progress}); } }); } Bar = Style.div` position:absolute; left: 0; top: 0; height: 2px; background-color: #337ab7; `; render() { return <this.Bar style={{width: `${this.state.progress}%`}} />; } } export default Progress;
Remove css transition from progress bar
Remove css transition from progress bar
JavaScript
mit
chitchu/react-mosaic,chitchu/react-mosaic
--- +++ @@ -17,7 +17,6 @@ top: 0; height: 2px; background-color: #337ab7; - transition: all 0.4s ease-in-out; `; render() { return <this.Bar style={{width: `${this.state.progress}%`}} />;
bdbeb4706abdf570ac5a926a2ed156a67909fac6
template/_copyright.js
template/_copyright.js
/* * Raven.js @VERSION * https://github.com/getsentry/raven-js * * Includes TraceKit * https://github.com/getsentry/TraceKit * * Copyright 2013 Matt Robenolt and other contributors * Released under the BSD license * https://github.com/getsentry/raven-js/blob/master/LICENSE * */ /*! Raven.js @VERSION | github.com/getsentry/raven-js */
/*! Raven.js @VERSION | github.com/getsentry/raven-js */ /* * Includes TraceKit * https://github.com/getsentry/TraceKit * * Copyright 2013 Matt Robenolt and other contributors * Released under the BSD license * https://github.com/getsentry/raven-js/blob/master/LICENSE * */
Build the copyright header slightly less dumb
Build the copyright header slightly less dumb
JavaScript
bsd-2-clause
grelas/raven-js,Mappy/raven-js,malandrew/raven-js,chrisirhc/raven-js,eaglesjava/raven-js,vladikoff/raven-js,malandrew/raven-js,iodine/raven-js,janmisek/raven-js,chrisirhc/raven-js,housinghq/main-raven-js,housinghq/main-raven-js,getsentry/raven-js,iodine/raven-js,samgiles/raven-js,PureBilling/raven-js,vladikoff/raven-js,danse/raven-js,benoitg/raven-js,clara-labs/raven-js,hussfelt/raven-js,samgiles/raven-js,benoitg/raven-js,getsentry/raven-js,getsentry/raven-js,housinghq/main-raven-js,janmisek/raven-js,hussfelt/raven-js,grelas/raven-js,clara-labs/raven-js,getsentry/raven-js,danse/raven-js,PureBilling/raven-js,Mappy/raven-js,Mappy/raven-js,eaglesjava/raven-js
--- +++ @@ -1,7 +1,6 @@ +/*! Raven.js @VERSION | github.com/getsentry/raven-js */ + /* - * Raven.js @VERSION - * https://github.com/getsentry/raven-js - * * Includes TraceKit * https://github.com/getsentry/TraceKit * @@ -10,5 +9,3 @@ * https://github.com/getsentry/raven-js/blob/master/LICENSE * */ - -/*! Raven.js @VERSION | github.com/getsentry/raven-js */
632cdba5fab5df66cbbc98bb7168c13e9b5eb81b
packages/mjml-spacer/src/index.js
packages/mjml-spacer/src/index.js
import { MJMLElement } from 'mjml-core' import React, { Component } from 'react' const tagName = 'mj-spacer' const parentTag = ['mj-column', 'mj-hero-content'] const selfClosingTag = true const defaultMJMLDefinition = { attributes: { 'align': null, 'container-background-color': null, 'height': '20px', 'padding-bottom': null, 'padding-left': null, 'padding-right': null, 'padding-top': null, 'vertical-align': null } } @MJMLElement class Spacer extends Component { styles = this.getStyles() getStyles () { const { mjAttribute, defaultUnit } = this.props return { div: { fontSize: '1px', lineHeight: defaultUnit(mjAttribute('height')) } } } render () { return ( <div dangerouslySetInnerHTML={{ __html: '&nbsp;' }} style={this.styles.div} /> ) } } Spacer.tagName = tagName Spacer.parentTag = parentTag Spacer.selfClosingTag = selfClosingTag Spacer.defaultMJMLDefinition = defaultMJMLDefinition export default Spacer
import { MJMLElement } from 'mjml-core' import React, { Component } from 'react' const tagName = 'mj-spacer' const parentTag = ['mj-column', 'mj-hero-content'] const selfClosingTag = true const defaultMJMLDefinition = { attributes: { 'align': null, 'container-background-color': null, 'height': '20px', 'padding-bottom': null, 'padding-left': null, 'padding-right': null, 'padding-top': null, 'vertical-align': null } } @MJMLElement class Spacer extends Component { styles = this.getStyles() getStyles () { const { mjAttribute, defaultUnit } = this.props return { div: { fontSize: '1px', lineHeight: defaultUnit(mjAttribute('height')), whiteSpace: 'nowrap' } } } render () { return ( <div dangerouslySetInnerHTML={{ __html: '&nbsp;' }} style={this.styles.div} /> ) } } Spacer.tagName = tagName Spacer.parentTag = parentTag Spacer.selfClosingTag = selfClosingTag Spacer.defaultMJMLDefinition = defaultMJMLDefinition export default Spacer
Fix escaping servers which replace the `&nbsp;` with a space
Fix escaping servers which replace the `&nbsp;` with a space We have seen some servers which replace the non-breaking space character with an actual space. This should ensure that even when there is a space the div actually renders
JavaScript
mit
mjmlio/mjml
--- +++ @@ -28,7 +28,8 @@ return { div: { fontSize: '1px', - lineHeight: defaultUnit(mjAttribute('height')) + lineHeight: defaultUnit(mjAttribute('height')), + whiteSpace: 'nowrap' } } }
f43ddd7cc2e642e267970d9ac33931e1e8ac3821
public/js/app.js
public/js/app.js
"use strict"; var GitHubAPI = function(accessToken, org, repo) { var API_URL = 'https://api.github.com/repos/' + org + '/' + repo; return { getBranch: function(branchName) { return $.get(API_URL + '/branches/' + branchName); }, getTree: function(sha) { return $.get(API_URL + '/git/trees/' + sha + '?recursive=1'); }, }; } var Vidius = function(github) { return { getFileListing: function() { return github.getBranch('master').then(function(data) { return github.getTree(data.commit.sha); }).then(function(data) { return data.tree; }); }, getMarkdownFiles: function() { return this.getFileListing().then(function(files) { return files.filter(function(file) { return file.path.endsWith('.md'); }); }); } }; };
"use strict"; var GitHubAPI = function(accessToken, org, repo) { var API_URL = 'https://api.github.com/repos/' + org + '/' + repo; return { getBranch: function(branchName) { return $.get(API_URL + '/branches/' + branchName); }, getTree: function(sha) { return $.get(API_URL + '/git/trees/' + sha + '?recursive=1'); }, getFileContents: function(path, ref) { return $.get(API_URL + '/contents/' + path + '?ref=' + ref); } }; } var Vidius = function(github) { return { getFileListing: function() { return github.getBranch('master').then(function(data) { return github.getTree(data.commit.sha); }).then(function(data) { return data.tree; }); }, getMarkdownFiles: function() { return this.getFileListing().then(function(files) { return files.filter(function(file) { return file.path.endsWith('.md'); }); }); }, getTextFileContents: function(file) { // TODO don't hardcode the ref return github.getFileContents(file.path, 'master').then(function(contents) { // TODO check type is file and encoding is base64, otherwise fail return atob(contents.content.replace(/\s/g, '')); }); } }; };
Add an API call for file contents
Add an API call for file contents
JavaScript
mit
nhsalpha/vidius,nhsalpha/vidius,nhsalpha/vidius
--- +++ @@ -13,6 +13,9 @@ return $.get(API_URL + '/git/trees/' + sha + '?recursive=1'); }, + getFileContents: function(path, ref) { + return $.get(API_URL + '/contents/' + path + '?ref=' + ref); + } }; } @@ -32,6 +35,14 @@ return file.path.endsWith('.md'); }); }); + }, + + getTextFileContents: function(file) { + // TODO don't hardcode the ref + return github.getFileContents(file.path, 'master').then(function(contents) { + // TODO check type is file and encoding is base64, otherwise fail + return atob(contents.content.replace(/\s/g, '')); + }); } }; };
9cfef29bf4495ee906341e1f3836142801093f9c
tests/lib/storage.js
tests/lib/storage.js
var ready; beforeEach(function() { storage = TEST_STORAGE; storage.clear(function() { ready = true; }); waitsFor(function() { return ready; }, "the storage to be set up for testing", 500); }); afterEach(function() { storage = DEFAULT_STORAGE; });
var ready; beforeEach(function() { ready = false; storage = TEST_STORAGE; storage.clear(function() { ready = true; }); waitsFor(function() { return ready; }, "the storage to be set up for testing", 500); }); afterEach(function() { storage = DEFAULT_STORAGE; });
Set ready var to false before each test so it doesn't run prematurely.
Set ready var to false before each test so it doesn't run prematurely.
JavaScript
mit
AntarcticApps/Tiles,AntarcticApps/Tiles
--- +++ @@ -1,6 +1,7 @@ var ready; beforeEach(function() { + ready = false; storage = TEST_STORAGE; storage.clear(function() {
3d283ba50b964b06e0591114483b2f59e9012d5f
assets/js/googlesitekit/widgets/components/WidgetNull.js
assets/js/googlesitekit/widgets/components/WidgetNull.js
/** * WidgetNull component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; /** * Internal dependencies */ import useWidgetStateEffect from '../hooks/useWidgetStateEffect'; import Null from '../../../components/Null'; // The supported props must match `Null` (except `widgetSlug`). export default function WidgetNull( { widgetSlug } ) { useWidgetStateEffect( widgetSlug, Null ); return <Null />; } WidgetNull.propTypes = { widgetSlug: PropTypes.string.isRequired, ...Null.propTypes, };
/** * WidgetNull component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; /** * Internal dependencies */ import useWidgetStateEffect from '../hooks/useWidgetStateEffect'; import Null from '../../../components/Null'; // The supported props must match `Null` (except `widgetSlug`). export default function WidgetNull( { widgetSlug } ) { useWidgetStateEffect( widgetSlug, Null, null ); return <Null />; } WidgetNull.propTypes = { widgetSlug: PropTypes.string.isRequired, ...Null.propTypes, };
Update fn call for unset to work.
Update fn call for unset to work.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
--- +++ @@ -29,7 +29,7 @@ // The supported props must match `Null` (except `widgetSlug`). export default function WidgetNull( { widgetSlug } ) { - useWidgetStateEffect( widgetSlug, Null ); + useWidgetStateEffect( widgetSlug, Null, null ); return <Null />; }
627f1de997b292bd0069048bdda36b2ba0f144c2
lib/plugins/dataforms.js
lib/plugins/dataforms.js
'use strict'; require('../stanza/dataforms'); module.exports = function (client) { client.disco.addFeature('jabber:x:data'); client.disco.addFeature('urn:xmpp:media-element'); client.disco.addFeature('http://jabber.org/protocol/xdata-validate'); client.on('message', function (msg) { if (msg.form) { client.emit('dataform', msg); } }); };
'use strict'; require('../stanza/dataforms'); module.exports = function (client) { client.disco.addFeature('jabber:x:data'); client.disco.addFeature('urn:xmpp:media-element'); client.disco.addFeature('http://jabber.org/protocol/xdata-validate'); client.disco.addFeature('http://jabber.org/protocol/xdata-layout'); client.on('message', function (msg) { if (msg.form) { client.emit('dataform', msg); } }); };
Add disco feature for forms layout
Add disco feature for forms layout
JavaScript
mit
soapdog/stanza.io,legastero/stanza.io,rogervaas/stanza.io,legastero/stanza.io,otalk/stanza.io,flavionegrao/stanza.io,otalk/stanza.io,soapdog/stanza.io,spunkydunker/stanza.io,firdausramlan/stanza.io,spunkydunker/stanza.io,flavionegrao/stanza.io,rogervaas/stanza.io,glpenghui/stanza.io,Palid/stanza.io,glpenghui/stanza.io,Palid/stanza.io,firdausramlan/stanza.io
--- +++ @@ -7,6 +7,7 @@ client.disco.addFeature('jabber:x:data'); client.disco.addFeature('urn:xmpp:media-element'); client.disco.addFeature('http://jabber.org/protocol/xdata-validate'); + client.disco.addFeature('http://jabber.org/protocol/xdata-layout'); client.on('message', function (msg) { if (msg.form) {
a3e393d43c1752420360f71c319d2d6ea2300712
components/dash-core-components/src/utils/optionTypes.js
components/dash-core-components/src/utils/optionTypes.js
import {type} from 'ramda'; export const sanitizeOptions = options => { if (type(options) === 'Object') { return Object.entries(options).map(([value, label]) => ({ label: String(label), value, })); } if (type(options) === 'Array') { if ( options.length > 0 && ['String', 'Number', 'Bool'].includes(type(options[0])) ) { return options.map(option => ({ label: String(option), value: option, })); } return options; } return options; };
import React from 'react'; import {type} from 'ramda'; export const sanitizeOptions = options => { if (type(options) === 'Object') { return Object.entries(options).map(([value, label]) => ({ label: React.isValidElement(label) ? label : String(label), value, })); } if (type(options) === 'Array') { if ( options.length > 0 && ['String', 'Number', 'Bool'].includes(type(options[0])) ) { return options.map(option => ({ label: String(option), value: option, })); } return options; } return options; };
Fix objects options with component label.
Fix objects options with component label.
JavaScript
mit
plotly/dash,plotly/dash,plotly/dash,plotly/dash,plotly/dash
--- +++ @@ -1,9 +1,10 @@ +import React from 'react'; import {type} from 'ramda'; export const sanitizeOptions = options => { if (type(options) === 'Object') { return Object.entries(options).map(([value, label]) => ({ - label: String(label), + label: React.isValidElement(label) ? label : String(label), value, })); }
1dc21a911253f9485a71963701355a226b8a71e5
test/load-json-spec.js
test/load-json-spec.js
/* global require, describe, it */ import assert from 'assert'; var urlPrefix = 'http://katas.tddbin.com/katas/es6/language/'; var katasUrl = urlPrefix + '__grouped__.json'; var GroupedKata = require('../src/grouped-kata.js'); describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { function onSuccess(groupedKatas) { assert.ok(groupedKatas); done(); } new GroupedKata(katasUrl).load(function() {}, onSuccess); }); describe('on error, call error callback and the error passed', function() { it('invalid JSON', function(done) { function onError(err) { assert.ok(err); done(); } var invalidUrl = urlPrefix; new GroupedKata(invalidUrl).load(onError); }); it('for invalid data', function(done) { function onError(err) { assert.ok(err); done(); } var invalidData = urlPrefix + '__all__.json'; new GroupedKata(invalidData).load(onError); }); }); });
/* global describe, it */ import assert from 'assert'; const urlPrefix = 'http://katas.tddbin.com/katas/es6/language'; const katasUrl = `${urlPrefix}/__grouped__.json`; import GroupedKata from '../src/grouped-kata.js'; describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { function onSuccess(groupedKatas) { assert.ok(groupedKatas); done(); } new GroupedKata(katasUrl).load(() => {}, onSuccess); }); describe('on error, call error callback and the error passed', function() { it('invalid JSON', function(done) { function onError(err) { assert.ok(err); done(); } var invalidUrl = urlPrefix; new GroupedKata(invalidUrl).load(onError); }); it('for invalid data', function(done) { function onError(err) { assert.ok(err); done(); } var invalidData = `${urlPrefix}/__all__.json`; new GroupedKata(invalidData).load(onError); }); }); });
Use ES6 in the tests.
Use ES6 in the tests.
JavaScript
mit
wolframkriesing/es6-react-workshop,wolframkriesing/es6-react-workshop
--- +++ @@ -1,10 +1,10 @@ -/* global require, describe, it */ +/* global describe, it */ import assert from 'assert'; -var urlPrefix = 'http://katas.tddbin.com/katas/es6/language/'; -var katasUrl = urlPrefix + '__grouped__.json'; +const urlPrefix = 'http://katas.tddbin.com/katas/es6/language'; +const katasUrl = `${urlPrefix}/__grouped__.json`; -var GroupedKata = require('../src/grouped-kata.js'); +import GroupedKata from '../src/grouped-kata.js'; describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { @@ -13,7 +13,7 @@ done(); } - new GroupedKata(katasUrl).load(function() {}, onSuccess); + new GroupedKata(katasUrl).load(() => {}, onSuccess); }); describe('on error, call error callback and the error passed', function() { it('invalid JSON', function(done) { @@ -31,7 +31,7 @@ done(); } - var invalidData = urlPrefix + '__all__.json'; + var invalidData = `${urlPrefix}/__all__.json`; new GroupedKata(invalidData).load(onError); }); });
33afa5699718ca8afcf7ffcda01e17af214da5bd
app/router.js
app/router.js
import Ember from 'ember'; import config from './config/environment'; var Router = Ember.Router.extend({ location: config.locationType }); Router.map(function() { this.route('lists', function() { this.route('show', {path: 'list/:id'}); }); this.route('top50'); this.route('movies', {path: '/'}, function() { this.route('show', {path: '/movie/:id'}); }); }); export default Router;
import Ember from 'ember'; import config from './config/environment'; var Router = Ember.Router.extend({ location: config.locationType }); Router.map(function() { this.route('lists', function() { this.route('show', {path: ':id'}); }); this.route('top50'); this.route('movies', {path: '/'}, function() { this.route('show', {path: '/movie/:id'}); }); }); export default Router;
Fix up route for single list
Fix up route for single list
JavaScript
mit
sabarasaba/moviezio-client,sabarasaba/moviezio-client,sabarasaba/moviez.city-client,sabarasaba/moviez.city-client,sabarasaba/moviezio-client,sabarasaba/moviez.city-client,sabarasaba/moviezio-client,sabarasaba/moviezio-client,sabarasaba/moviezio-client,sabarasaba/moviez.city-client,sabarasaba/moviez.city-client,sabarasaba/moviez.city-client
--- +++ @@ -7,7 +7,7 @@ Router.map(function() { this.route('lists', function() { - this.route('show', {path: 'list/:id'}); + this.route('show', {path: ':id'}); }); this.route('top50');
08b0f2604942a6b48eedf05a0f1a7e1573ad4699
main.js
main.js
/* * grunt-util-options * https://github.com/mikaelkaron/grunt-util-process * * Copyright (c) 2013 Mikael Karon * Licensed under the MIT license. */ module.exports = function(grunt) { "use strict"; var _ = grunt.util._; var _property = require("grunt-util-property")(grunt); return function (properties) { var me = this; var name = me.name; var target = me.target; _.each(_.rest(arguments), function (key) { _property.call(properties, key, _.find([ grunt.option([ name, target, key ].join(".")), grunt.option([ name, key ].join(".")), grunt.option(key), properties[key] ], function (value) { return !_.isUndefined(value); })); }); return properties; }; }
/* * grunt-util-options * https://github.com/mikaelkaron/grunt-util-process * * Copyright (c) 2013 Mikael Karon * Licensed under the MIT license. */ module.exports = function(grunt) { "use strict"; var _ = grunt.util._; var _property = require("grunt-util-property")(grunt); return function (properties) { var me = this; var name = me.name; var target = me.target; _.each(_.tail(arguments), function (key) { _property.call(properties, key, _.find([ grunt.option([ name, target, key ].join(".")), grunt.option([ name, key ].join(".")), grunt.option(key), properties[key] ], function (value) { return !_.isUndefined(value); })); }); return properties; }; }
Add support for lodash 4.x (Found in Grunt 1.x) * Changed lodash `rest` usage to tail. * Note this still supports lodash 3.x as tail was an alias for the original rest. Both 3.x and 4.x tail do the same thing.
Add support for lodash 4.x (Found in Grunt 1.x) * Changed lodash `rest` usage to tail. * Note this still supports lodash 3.x as tail was an alias for the original rest. Both 3.x and 4.x tail do the same thing.
JavaScript
mit
mikaelkaron/grunt-util-options
--- +++ @@ -17,7 +17,7 @@ var name = me.name; var target = me.target; - _.each(_.rest(arguments), function (key) { + _.each(_.tail(arguments), function (key) { _property.call(properties, key, _.find([ grunt.option([ name, target, key ].join(".")), grunt.option([ name, key ].join(".")),
fd3e37f287d48df7185f8655dab37894ffafaae6
main.js
main.js
import ExamplePluginComponent from "./components/ExamplePluginComponent"; var PluginHelper = global.MarathonUIPluginAPI.PluginHelper; PluginHelper.registerMe("examplePlugin-0.0.1"); PluginHelper.injectComponent(ExamplePluginComponent, "SIDEBAR_BOTTOM");
import ExamplePluginComponent from "./components/ExamplePluginComponent"; var MarathonUIPluginAPI = global.MarathonUIPluginAPI; var PluginHelper = MarathonUIPluginAPI.PluginHelper; var PluginMountPoints = MarathonUIPluginAPI.PluginMountPoints; PluginHelper.registerMe("examplePlugin-0.0.1"); PluginHelper.injectComponent(ExamplePluginComponent, PluginMountPoints.SIDEBAR_BOTTOM);
Introduce read-only but extensible mount points file
Introduce read-only but extensible mount points file
JavaScript
apache-2.0
mesosphere/marathon-ui-example-plugin
--- +++ @@ -1,7 +1,10 @@ import ExamplePluginComponent from "./components/ExamplePluginComponent"; -var PluginHelper = global.MarathonUIPluginAPI.PluginHelper; +var MarathonUIPluginAPI = global.MarathonUIPluginAPI; +var PluginHelper = MarathonUIPluginAPI.PluginHelper; +var PluginMountPoints = MarathonUIPluginAPI.PluginMountPoints; PluginHelper.registerMe("examplePlugin-0.0.1"); -PluginHelper.injectComponent(ExamplePluginComponent, "SIDEBAR_BOTTOM"); +PluginHelper.injectComponent(ExamplePluginComponent, + PluginMountPoints.SIDEBAR_BOTTOM);
87cb50db1913fccaee9e06f4eef8ab16d8564488
popup.js
popup.js
document.addEventListener('DOMContentLoaded', function () { display('Searching...'); }); function display(msg) { var el = document.body; el.innerHTML = msg; } chrome.runtime.getBackgroundPage(displayMessages); function displayMessages(backgroundPage) { var html = '<ul>'; html += backgroundPage.services.map(function (service) { return '<li class="service">' + service.name + '<span class="host">' + service.host + ':' + service.port + '</span>' '</li>'; }).join(''); html += '</ul>'; display(html); var items = Array.prototype.slice.call(document.getElementsByTagName('li')), uiPage = chrome.extension.getURL("ui.html"); items.forEach(function(li) { li.addEventListener('click', function() { chrome.tabs.create({url: uiPage}); }); }); }
document.addEventListener('DOMContentLoaded', function () { display('Searching...'); }); function display(msg) { var el = document.body; el.innerHTML = msg; } chrome.runtime.getBackgroundPage(displayMessages); function displayMessages(backgroundPage) { var html = '<ul>'; html += backgroundPage.services.map(function (service) { return '<li class="service">' + service.host + '<span class="host">' + service.address + ':' + service.port + '</span>' '</li>'; }).join(''); html += '</ul>'; display(html); var items = Array.prototype.slice.call(document.getElementsByTagName('li')), uiPage = chrome.extension.getURL("ui.html"); items.forEach(function(li) { li.addEventListener('click', function() { chrome.tabs.create({url: uiPage}); }); }); }
Change name to match new service instance object
Change name to match new service instance object
JavaScript
apache-2.0
mediascape/discovery-extension,mediascape/discovery-extension
--- +++ @@ -13,9 +13,9 @@ var html = '<ul>'; html += backgroundPage.services.map(function (service) { return '<li class="service">' - + service.name + + service.host + '<span class="host">' - + service.host + ':' + service.port + + service.address + ':' + service.port + '</span>' '</li>'; }).join('');
06164aff052d6922f1506398dc60a7dde78a9f98
resolve-cache.js
resolve-cache.js
'use strict'; const _ = require('lodash'); const tests = { db: (value) => { const keys = ['query', 'connect', 'begin']; return keys.every((key) => _.has(value, key)); }, }; const ok = require('ok')(tests); const previous = []; module.exports = (obj) => { const result = obj ? previous.find((item) => _.isEqual(item, obj)) : _.last(previous); if (result) { return result; } else { const errors = ok(obj); if (errors.length) { throw new Error(`Configuration is invalid: ${errors.join(', ')}`); } if (obj) { previous.push(obj); } return obj; } };
'use strict'; const _ = require('lodash'); const tests = { db: (value) => { const keys = ['query', 'connect', 'begin']; return keys.every((key) => _.has(value, key)); }, }; const ok = require('ok')(tests); const previous = []; module.exports = (obj) => { let result; if (obj) { result = previous.find((item) => _.isEqual(item, obj)); } if (result) { return result; } else { const errors = ok(obj); if (errors.length) { throw new Error(`Configuration is invalid: ${errors.join(', ')}`); } if (obj) { previous.push(obj); } return obj; } };
Remove ability to get last memoize result by passing falsy argument
Remove ability to get last memoize result by passing falsy argument
JavaScript
mit
thebitmill/midwest-membership-services
--- +++ @@ -15,7 +15,11 @@ const previous = []; module.exports = (obj) => { - const result = obj ? previous.find((item) => _.isEqual(item, obj)) : _.last(previous); + let result; + + if (obj) { + result = previous.find((item) => _.isEqual(item, obj)); + } if (result) { return result;
ba70aba5132157e1ec43264a2cc5257ba0ba880c
src/client/app/states/manage/cms/cms.state.js
src/client/app/states/manage/cms/cms.state.js
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper, navigationHelper) { routerHelper.configureStates(getStates()); navigationHelper.navItems(navItems()); navigationHelper.sidebarItems(sidebarItems()); } function getStates() { return { 'manage.cms': { url: '/cms', redirectTo: 'manage.cms.list', template: '<ui-view></ui-view>' } }; } function navItems() { return {}; } function sidebarItems() { return { 'manage.cms': { type: 'state', state: 'manage.cms', label: 'CMS', order: 10 } }; } })();
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper, navigationHelper) { routerHelper.configureStates(getStates()); navigationHelper.navItems(navItems()); navigationHelper.sidebarItems(sidebarItems()); } function getStates() { return { 'manage.cms': { url: '/cms', redirectTo: 'manage.cms.list', template: '<ui-view></ui-view>' } }; } function navItems() { return {}; } function sidebarItems() { return { 'manage.cms': { type: 'state', state: 'manage.cms', label: 'Pages', order: 10 } }; } })();
Rename CMS label to Pages
Rename CMS label to Pages
JavaScript
apache-2.0
stackus/api,sreekantch/JellyFish,mafernando/api,sonejah21/api,AllenBW/api,stackus/api,projectjellyfish/api,AllenBW/api,mafernando/api,boozallen/projectjellyfish,projectjellyfish/api,boozallen/projectjellyfish,stackus/api,sonejah21/api,AllenBW/api,sreekantch/JellyFish,sonejah21/api,sreekantch/JellyFish,boozallen/projectjellyfish,projectjellyfish/api,mafernando/api,boozallen/projectjellyfish
--- +++ @@ -30,7 +30,7 @@ 'manage.cms': { type: 'state', state: 'manage.cms', - label: 'CMS', + label: 'Pages', order: 10 } };
69454caa8503cb7cfa7366d569ed16cd9bf4caa8
app/configureStore.js
app/configureStore.js
import { createStore, applyMiddleware } from 'redux' import logger from 'redux-logger' import thunk from 'redux-thunk' import oaaChat from './reducers' const configureStore = () => { const store = createStore( oaaChat, applyMiddleware(thunk, logger())) return store } export default configureStore
import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import oaaChat from './reducers' const configureStore = () => { const store = createStore( oaaChat, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), applyMiddleware(thunk)) return store } export default configureStore
Remove redux-logger and setup redux devtools
Remove redux-logger and setup redux devtools
JavaScript
mit
danielzy95/oaa-chat,danielzy95/oaa-chat
--- +++ @@ -1,11 +1,12 @@ import { createStore, applyMiddleware } from 'redux' -import logger from 'redux-logger' import thunk from 'redux-thunk' import oaaChat from './reducers' const configureStore = () => { const store = createStore( - oaaChat, applyMiddleware(thunk, logger())) + oaaChat, + window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), + applyMiddleware(thunk)) return store }
f7d6d3ff62ac6de0022e4b014ac5b04096758d48
src/db/migrations/20161005172637_init_demo.js
src/db/migrations/20161005172637_init_demo.js
export async function up(knex) { await knex.schema.createTable('Resource', (table) => { table.uuid('id').notNullable().primary() table.string('name', 32).notNullable() table.string('mime', 32) table.string('md5') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) await knex.schema.createTable('Content', (table) => { table.increments() table.uuid('resourceId').notNullable().references('Resource.id') table.string('name', 32) table.string('title', 255) table.text('description') table.json('data') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) } export async function down(knex) { await knex.schema.dropTableIfExists('Content') await knex.schema.dropTableIfExists('Resource') }
export async function up(knex) { await knex.schema.createTable('Resource', (table) => { table.uuid('id').notNullable().primary() table.string('name', 32).notNullable() table.string('mime', 32) table.string('md5') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) await knex.schema.createTable('Content', (table) => { table.increments() table.uuid('resourceId').notNullable().references('Resource.id') table.string('name', 32).notNullable() table.string('title', 255) table.text('description') table.json('data') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) } export async function down(knex) { await knex.schema.dropTableIfExists('Content') await knex.schema.dropTableIfExists('Resource') }
Tweak Content name to be not nullable
Tweak Content name to be not nullable
JavaScript
mit
thangntt2/chatbot_api_hapi,vietthang/hapi-boilerplate
--- +++ @@ -12,7 +12,7 @@ await knex.schema.createTable('Content', (table) => { table.increments() table.uuid('resourceId').notNullable().references('Resource.id') - table.string('name', 32) + table.string('name', 32).notNullable() table.string('title', 255) table.text('description') table.json('data')
fcbaeb4705d02858f59c1142f77117e953c4db96
app/libs/locale/available-locales.js
app/libs/locale/available-locales.js
'use strict'; // Load our requirements const glob = require('glob'), path = require('path'), logger = require('../log'); // Build a list of the available locale files in a given directory module.exports = function(dir) { // Variables let available = []; // Run through the installed locales and add to array to be loaded glob.sync(path.join(dir, '/*.json')).forEach((file) => { // Get the shortname for the file let lang = path.basename(file, '.json'); // Add to our object logger.debug('Found the "%s" locale.', lang); available.push(lang); }); return available; };
'use strict'; // Load our requirements const glob = require('glob'), path = require('path'), logger = require(__base + 'libs/log'); // Build a list of the available locale files in a given directory module.exports = function(dir) { // Variables let available = ['en']; // Run through the installed locales and add to array to be loaded glob.sync(path.join(dir, '/*.json')).forEach((file) => { // Get the shortname for the file let lang = path.basename(file, '.json'); // Ignore english if ( lang !== 'en' ) { available.push(lang); } }); return available; };
Update available locales to prioritise english
Update available locales to prioritise english
JavaScript
apache-2.0
transmutejs/core
--- +++ @@ -3,13 +3,13 @@ // Load our requirements const glob = require('glob'), path = require('path'), - logger = require('../log'); + logger = require(__base + 'libs/log'); // Build a list of the available locale files in a given directory module.exports = function(dir) { // Variables - let available = []; + let available = ['en']; // Run through the installed locales and add to array to be loaded glob.sync(path.join(dir, '/*.json')).forEach((file) => { @@ -17,9 +17,8 @@ // Get the shortname for the file let lang = path.basename(file, '.json'); - // Add to our object - logger.debug('Found the "%s" locale.', lang); - available.push(lang); + // Ignore english + if ( lang !== 'en' ) { available.push(lang); } }); return available;
27ea2b2e1951431b0f6bae742d7c3babf5053bc1
jest.config.js
jest.config.js
module.exports = { verbose: !!process.env.VERBOSE, moduleNameMapper: { testHelpers: '<rootDir>/testHelpers/index.js', }, setupTestFrameworkScriptFile: '<rootDir>/testHelpers/setup.js', testResultsProcessor: './node_modules/jest-junit', testPathIgnorePatterns: ['/node_modules/'], testEnvironment: 'node', }
module.exports = { verbose: !!process.env.VERBOSE, moduleNameMapper: { testHelpers: '<rootDir>/testHelpers/index.js', }, setupTestFrameworkScriptFile: '<rootDir>/testHelpers/setup.js', testResultsProcessor: './node_modules/jest-junit', testPathIgnorePatterns: ['/node_modules/'], testEnvironment: 'node', bail: true, }
Configure tests to fail fast
Configure tests to fail fast
JavaScript
mit
tulios/kafkajs,tulios/kafkajs,tulios/kafkajs,tulios/kafkajs
--- +++ @@ -7,4 +7,5 @@ testResultsProcessor: './node_modules/jest-junit', testPathIgnorePatterns: ['/node_modules/'], testEnvironment: 'node', + bail: true, }
fd6dd6bbe2220181202535eb6df9715bf78cf956
js/agency.js
js/agency.js
/*! * Start Bootstrap - Agnecy Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top' }) // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); });
/*! * Start Bootstrap - Agnecy Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top' }) // Event tracking for google analytics // inspired by http://cutroni.com/blog/2012/02/21/advanced-content-tracking-with-google-analytics-part-1/ var timer = 0; var callBackTime = 700; var debugTracker = false; var startTime = new Date().getTime(); var currentItem = ""; function trackLocation() { var currentTime = new Date().getTime(); var timeToScroll = Math.round((currentTime - startTime) / 1000); if(!debugTracker) { ga('send', { 'hitType': 'event', 'eventCategory': 'Navigation', 'eventAction': '#'+currentItem, 'eventValue': timeToScroll }); } else { console.log("You have viewed: #" + currentItem + " (" + timeToScroll + " sec.)"); } // determine current location currentItem = $(".nav li.active > a").text(); // reset duration startTime = currentTime; } $('body').on('activate.bs.scrollspy', function () { // Use a buffer so we don't call track location too often (high speed scroll) if (timer) clearTimeout(timer); timer = setTimeout(trackLocation, callBackTime); }) window.onbeforeunload = function() { trackLocation(); return null; } // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); });
Add event tracking to google analytics
Add event tracking to google analytics
JavaScript
apache-2.0
tibotiber/greeny,tibotiber/greeny,tibotiber/greeny
--- +++ @@ -20,6 +20,41 @@ target: '.navbar-fixed-top' }) +// Event tracking for google analytics +// inspired by http://cutroni.com/blog/2012/02/21/advanced-content-tracking-with-google-analytics-part-1/ +var timer = 0; +var callBackTime = 700; +var debugTracker = false; +var startTime = new Date().getTime(); +var currentItem = ""; +function trackLocation() { + var currentTime = new Date().getTime(); + var timeToScroll = Math.round((currentTime - startTime) / 1000); + if(!debugTracker) { + ga('send', { + 'hitType': 'event', + 'eventCategory': 'Navigation', + 'eventAction': '#'+currentItem, + 'eventValue': timeToScroll + }); + } else { + console.log("You have viewed: #" + currentItem + " (" + timeToScroll + " sec.)"); + } + // determine current location + currentItem = $(".nav li.active > a").text(); + // reset duration + startTime = currentTime; +} +$('body').on('activate.bs.scrollspy', function () { + // Use a buffer so we don't call track location too often (high speed scroll) + if (timer) clearTimeout(timer); + timer = setTimeout(trackLocation, callBackTime); +}) +window.onbeforeunload = function() { + trackLocation(); + return null; +} + // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click();
4fd824256e18f986f2cbd3c54cb1b9019cc1918e
index.js
index.js
var pkg = require(process.cwd() + '/package.json'); var intrepidjsVersion = pkg.version; // Dummy index, only shows intrepidjs-cli version console.log(intrepidjsVersion);
var pkg = require(__dirname + '/package.json'); var intrepidjsVersion = pkg.version; // Dummy index, only shows intrepidjs-cli version console.log(intrepidjsVersion);
Use __dirname instead of process.cwd
Use __dirname instead of process.cwd process.cwd refers to the directory in which file was executed, not the directory in which it lives
JavaScript
mit
wtelecom/intrepidjs-cli
--- +++ @@ -1,4 +1,4 @@ -var pkg = require(process.cwd() + '/package.json'); +var pkg = require(__dirname + '/package.json'); var intrepidjsVersion = pkg.version; // Dummy index, only shows intrepidjs-cli version
2f747d79f542577e5cf60d18b9fbf8eea82070da
index.js
index.js
'use strict'; module.exports = { name: 'Ember CLI ic-ajax', init: function(name) { this.treePaths['vendor'] = 'node_modules'; }, included: function(app) { var options = this.app.options.icAjaxOptions || {enabled: true}; if (options.enabled) { this.app.import('vendor/ic-ajax/dist/named-amd/main.js', { exports: { 'ic-ajax': [ 'default', 'defineFixture', 'lookupFixture', 'raw', 'request', ] } }); } } };
'use strict'; module.exports = { name: 'Ember CLI ic-ajax', init: function(name) { this.treePaths['vendor'] = require.resolve('ic-ajax').replace('ic-ajax/dist/cjs/main.js', ''); }, included: function(app) { var options = this.app.options.icAjaxOptions || {enabled: true}; if (options.enabled) { this.app.import('vendor/ic-ajax/dist/named-amd/main.js', { exports: { 'ic-ajax': [ 'default', 'defineFixture', 'lookupFixture', 'raw', 'request', ] } }); } } };
Revert "Revert "resolve ala node_module resolution algorithim (NPM v3 support);""
Revert "Revert "resolve ala node_module resolution algorithim (NPM v3 support);"" This reverts commit 2aeb7307e81c8052b2fb6021bf4ab10ca433abce.
JavaScript
mit
rwjblue/ember-cli-ic-ajax,tsing80/ember-cli-ic-ajax,stefanpenner/ember-cli-ic-ajax,taras/ember-cli-ic-ajax
--- +++ @@ -4,7 +4,7 @@ name: 'Ember CLI ic-ajax', init: function(name) { - this.treePaths['vendor'] = 'node_modules'; + this.treePaths['vendor'] = require.resolve('ic-ajax').replace('ic-ajax/dist/cjs/main.js', ''); }, included: function(app) {
cb0ebc4c7ca492ed3c1144777643468ef0db054e
index.js
index.js
import postcss from 'postcss'; const postcssFlexibility = postcss.plugin('postcss-flexibility', () => css => { css.walkRules(rule => { const isDisabled = rule.some(({prop, text}) => prop === '-js-display' || text === 'flexibility-disable' || text === '! flexibility-disable' ); if (!isDisabled) { rule.walkDecls('display', decl => { const {value} = decl; if (value === 'flex') { decl.cloneBefore({prop: '-js-display'}); } }); } }); }); export default postcssFlexibility;
import postcss from 'postcss'; const postcssFlexibility = postcss.plugin('postcss-flexibility', () => css => { css.walkRules(rule => { const isDisabled = rule.some(({prop, text = ''}) => prop === '-js-display' || text.endsWith('flexibility-disable') ); if (!isDisabled) { rule.walkDecls('display', decl => { const {value} = decl; if (value === 'flex') { decl.cloneBefore({prop: '-js-display'}); } }); } }); }); export default postcssFlexibility;
Change check to use endsWith for supporting loud comments
Change check to use endsWith for supporting loud comments
JavaScript
mit
7rulnik/postcss-flexibility
--- +++ @@ -2,8 +2,8 @@ const postcssFlexibility = postcss.plugin('postcss-flexibility', () => css => { css.walkRules(rule => { - const isDisabled = rule.some(({prop, text}) => - prop === '-js-display' || text === 'flexibility-disable' || text === '! flexibility-disable' + const isDisabled = rule.some(({prop, text = ''}) => + prop === '-js-display' || text.endsWith('flexibility-disable') ); if (!isDisabled) {
98ded26910a319a9bfb7b9ce5cbece57254bbb31
index.js
index.js
$(document).ready(function() { $("#trcAge").slider({ id: "trcAge" }); $("#trcAge").on("slide", function(slideEvt) { console.log("Age range selected", slideEvt.value); $("#trcAgeSelection").text(slideEvt.value.join(" - ")); }); });
$(document).ready(function() { $("#trcAge").slider({ id: "trcAge" }); $("#trcAge").on("slide", function(slideEvt) { // console.log("Age range selected", slideEvt.value); $("#trcAgeSelection").text(slideEvt.value.join(" - ")); }); });
Undo console log (was a demo of git)
Undo console log (was a demo of git)
JavaScript
agpl-3.0
6System7/cep,6System7/cep
--- +++ @@ -3,7 +3,7 @@ id: "trcAge" }); $("#trcAge").on("slide", function(slideEvt) { - console.log("Age range selected", slideEvt.value); + // console.log("Age range selected", slideEvt.value); $("#trcAgeSelection").text(slideEvt.value.join(" - ")); }); });
933ee47b1f2cf923f4937ebb8297cef49c3390f8
index.js
index.js
#!/usr/bin/env node const express = require('express'); const fileExists = require('file-exists'); const bodyParser = require('body-parser'); const fs = require('fs'); const { port = 8123 } = require('minimist')(process.argv.slice(2)); const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.get('*', (req, res) => { const filePath = req.get('X-Requested-File-Path'); if (!filePath) { return res.status(500).send('Server did not provide file path'); } if (!fileExists(filePath)) { return res.status(500).send('Cannot find such file on the server'); } try { require(filePath)(req, res); // eslint-disable-line global-require } catch (e) { return res.status(500).send(`<pre>${e.stack}</pre>`); } const watcher = fs.watch(filePath, (eventType) => { if (eventType === 'change') { delete require.cache[require.resolve(filePath)]; watcher.close(); } }); return undefined; }); app.listen(port, () => { console.log(`node-direct listening on port ${port}!`); });
#!/usr/bin/env node const express = require('express'); const fileExists = require('file-exists'); const bodyParser = require('body-parser'); const fs = require('fs'); const { port = 8123 } = require('minimist')(process.argv.slice(2)); const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.get('*', (req, res) => { const filePath = req.get('X-Requested-File-Path'); if (!filePath) { return res.status(500).send('Server did not provide file path'); } if (!fileExists(filePath)) { return res.status(404).send('Cannot find such file on the server'); } try { require(filePath)(req, res); // eslint-disable-line global-require } catch (e) { return res.status(500).send(`<pre>${e.stack}</pre>`); } const watcher = fs.watch(filePath, (eventType) => { if (eventType === 'change') { delete require.cache[require.resolve(filePath)]; watcher.close(); } }); return undefined; }); app.listen(port, () => { console.log(`node-direct listening on port ${port}!`); });
Use 404 instead of 500 when a file is not found
fix: Use 404 instead of 500 when a file is not found
JavaScript
mit
finom/node-direct,finom/node-direct
--- +++ @@ -18,7 +18,7 @@ } if (!fileExists(filePath)) { - return res.status(500).send('Cannot find such file on the server'); + return res.status(404).send('Cannot find such file on the server'); } try {
a2172115022e7658573428d9ddf9b094f9c6d1b5
index.js
index.js
module.exports = isPromise; function isPromise(obj) { return obj && typeof obj.then === 'function'; }
module.exports = isPromise; function isPromise(obj) { return obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; }
Make the test a bit more strict
Make the test a bit more strict
JavaScript
mit
floatdrop/is-promise,then/is-promise,then/is-promise
--- +++ @@ -1,5 +1,5 @@ module.exports = isPromise; function isPromise(obj) { - return obj && typeof obj.then === 'function'; + return obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; }
edbc6e8931c9c2777520c0ccf0a3d74b8f75ebf6
index.js
index.js
const Discord = require('discord.js'); const client = new Discord.Client(); const config = require("./config.json"); client.on('ready', () => { console.log("I am ready!"); // client.channels.get('spam').send("Soup is ready!") }); client.on('message', (message) => { if (!message.content.startsWith(config.prefix) || message.author.bot) return; let msg = message.content.slice(config.prefix.length); if (msg.startsWith('ping')) { message.reply('pong'); } if (msg.startsWith('echo')) { if (msg.length > 5) { message.channel.send(msg.slice(5)); } else { message.channel.send("Please provide valid text to echo!"); } } if (msg.startsWith('die')) { message.channel.send("Shutting down..."); client.destroy((err) => { console.log(err); }); } }); client.on('disconnected', () => { console.log("Disconnected!"); process.exit(0); }); client.login(config.token);
const Discord = require('discord.js'); const client = new Discord.Client(); const config = require("./config.json"); client.on('ready', () => { console.log("I am ready!"); }); client.on('message', (message) => { if (!message.content.startsWith(config.prefix) || message.author.bot) return; // Ignore messages not // starting with your prefix let msg = message.content.slice(config.prefix.length); if (msg.startsWith('ping')) { message.reply('pong'); } if (msg.startsWith('echo')) { if (msg.length > 5 && msg[4] === ' ') { // If msg starts with 'echo ' message.channel.send(msg.slice(5)); // Echo the rest of msg. } else { message.channel.send("Please provide valid text to echo!"); } } if (msg.startsWith('die')) { message.channel.send("Shutting down..."); client.destroy((err) => { console.log(err); }); } }); client.on('disconnected', () => { console.log("Disconnected!"); process.exit(0); }); client.login(config.token);
Add some comments and refine echo command
Add some comments and refine echo command
JavaScript
mit
Rafer45/soup
--- +++ @@ -5,11 +5,11 @@ client.on('ready', () => { console.log("I am ready!"); - // client.channels.get('spam').send("Soup is ready!") }); client.on('message', (message) => { - if (!message.content.startsWith(config.prefix) || message.author.bot) return; + if (!message.content.startsWith(config.prefix) || message.author.bot) return; // Ignore messages not + // starting with your prefix let msg = message.content.slice(config.prefix.length); @@ -18,8 +18,8 @@ } if (msg.startsWith('echo')) { - if (msg.length > 5) { - message.channel.send(msg.slice(5)); + if (msg.length > 5 && msg[4] === ' ') { // If msg starts with 'echo ' + message.channel.send(msg.slice(5)); // Echo the rest of msg. } else { message.channel.send("Please provide valid text to echo!"); }
e1e5840e921465d0454213cb455aca4661bcf715
index.js
index.js
var Q = require('q'); /** * Chai-Mugshot Plugin * * @param mugshot - Mugshot instance * @param testRunnerCtx - Context of the test runner where the assertions are * done */ module.exports = function(mugshot, testRunnerCtx) { return function(chai) { var Assertion = chai.Assertion; function composeMessage(message) { var standardMessage = 'expected baseline and screenshot of #{act}'; return { affirmative: standardMessage + ' to ' + message, negative: standardMessage + ' to not ' + message }; } function mugshotProperty(name, message) { var msg = composeMessage(message); Assertion.addProperty(name, function() { var captureItem = this._obj; var deferred = Q.defer(); var _this = this; mugshot.test(captureItem, function(error, result) { if (error) { deferred.reject(error); } else { if (testRunnerCtx !== undefined) { testRunnerCtx.result = result; } try { _this.assert(result.isEqual, msg.affirmative, msg.negative); deferred.resolve(); } catch (error) { deferred.reject(error); } } }); return deferred.promise; }); } mugshotProperty('identical', 'be identical'); } };
/** * Chai-Mugshot Plugin * * @param mugshot - Mugshot instance * @param testRunnerCtx - Context of the test runner where the assertions are * done */ module.exports = function(mugshot, testRunnerCtx) { return function(chai) { var Assertion = chai.Assertion; function composeMessage(message) { var standardMessage = 'expected baseline and screenshot of #{act}'; return { affirmative: standardMessage + ' to ' + message, negative: standardMessage + ' to not ' + message }; } function mugshotProperty(name, message) { var msg = composeMessage(message); Assertion.addProperty(name, function() { var _this = this, captureItem = this._obj, promise, resolve, reject; promise = new Promise(function(res, rej) { resolve = res; reject = rej; }); mugshot.test(captureItem, function(error, result) { if (error) { reject(error); } else { if (testRunnerCtx !== undefined) { testRunnerCtx.result = result; } try { _this.assert(result.isEqual, msg.affirmative, msg.negative); resolve(); } catch (error) { reject(error); } } }); return promise; }); } mugshotProperty('identical', 'be identical'); } };
Replace q with native Promises
Replace q with native Promises
JavaScript
mit
uberVU/chai-mugshot,uberVU/chai-mugshot
--- +++ @@ -1,5 +1,3 @@ -var Q = require('q'); - /** * Chai-Mugshot Plugin * @@ -24,13 +22,18 @@ var msg = composeMessage(message); Assertion.addProperty(name, function() { - var captureItem = this._obj; - var deferred = Q.defer(); - var _this = this; + var _this = this, + captureItem = this._obj, + promise, resolve, reject; + + promise = new Promise(function(res, rej) { + resolve = res; + reject = rej; + }); mugshot.test(captureItem, function(error, result) { if (error) { - deferred.reject(error); + reject(error); } else { if (testRunnerCtx !== undefined) { testRunnerCtx.result = result; @@ -38,14 +41,14 @@ try { _this.assert(result.isEqual, msg.affirmative, msg.negative); - deferred.resolve(); + resolve(); } catch (error) { - deferred.reject(error); + reject(error); } } }); - return deferred.promise; + return promise; }); }
bc3e85aafc3fa1095169153661093d3f012424e2
node_modules/hotCoreStoreRegistry/lib/hotCoreStoreRegistry.js
node_modules/hotCoreStoreRegistry/lib/hotCoreStoreRegistry.js
"use strict"; /*! * Module dependencies. */ var dummy , hotplate = require('hotplate') ; exports.getAllStores = hotplate.cachable( function( done ){ var res = { stores: {}, collections: {}, }; hotplate.hotEvents.emit( 'stores', function( err, results){ results.forEach( function( element ) { element.result.forEach( function( Store ){ try { var store = new Store(); } catch ( e ){ hotplate.log("AN ERROR HAPPENED WHILE INSTANCING A STORE: " ); hotplate.log( e ); hotplate.log( element ); hotplate.log( Store ); } // If the store was created (no exception thrown...) if( store ){ // Add the module to the store registry res.stores[ store.storeName ] = { Store: Store, storeObject: store }; // Add the module to the collection registry if( store.collectionName ){ res.collections[ store.collectionName ] = res.collections[ store.collectionName ] || []; res.collections[ store.collectionName ].push( { Store: Store, storeObject: store } ); } } }); }); done( null, res ); }); });
"use strict"; /*! * Module dependencies. */ var dummy , hotplate = require('hotplate') ; exports.getAllStores = hotplate.cachable( function( done ){ var res = { stores: {}, collections: {}, }; hotplate.hotEvents.emit( 'stores', function( err, results){ results.forEach( function( element ) { Object.keys( element.result ).forEach( function( k ){ var Store = element.result[ k ]; try { var store = new Store(); } catch ( e ){ hotplate.log("AN ERROR HAPPENED WHILE INSTANCING A STORE: " ); hotplate.log( e ); hotplate.log( element ); hotplate.log( Store ); } // If the store was created (no exception thrown...) if( store ){ // Add the module to the store registry res.stores[ store.storeName ] = { Store: Store, storeObject: store }; // Add the module to the collection registry if( store.collectionName ){ res.collections[ store.collectionName ] = res.collections[ store.collectionName ] || []; res.collections[ store.collectionName ].push( { Store: Store, storeObject: store } ); } } }); }); done( null, res ); }); });
Change way in which storeRegistry expects stores to be returned, it's now a hash
Change way in which storeRegistry expects stores to be returned, it's now a hash
JavaScript
mit
shelsonjava/hotplate,mercmobily/hotplate,mercmobily/hotplate,shelsonjava/hotplate
--- +++ @@ -19,7 +19,10 @@ hotplate.hotEvents.emit( 'stores', function( err, results){ results.forEach( function( element ) { - element.result.forEach( function( Store ){ + + Object.keys( element.result ).forEach( function( k ){ + + var Store = element.result[ k ]; try { var store = new Store();
9235990779b1098df387e534656a921107732818
src/mw-menu/directives/mw_menu_top_entries.js
src/mw-menu/directives/mw_menu_top_entries.js
angular.module('mwUI.Menu') .directive('mwMenuTopEntries', function ($rootScope, $timeout) { return { scope: { menu: '=mwMenuTopEntries', right: '=' }, transclude: true, templateUrl: 'uikit/mw-menu/directives/templates/mw_menu_top_entries.html', controller: function ($scope) { var menu = $scope.menu || new mwUI.Menu.MwMenu(); this.getMenu = function () { return menu; }; }, link: function (scope, el, attrs, ctrl) { scope.entries = ctrl.getMenu(); scope.unCollapse = function () { var collapseEl = el.find('.navbar-collapse'); if (collapseEl.hasClass('in')) { collapseEl.collapse('hide'); } }; $rootScope.$on('$locationChangeSuccess', function () { scope.unCollapse(); }); scope.$on('mw-menu:triggerReorder', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); scope.$on('mw-menu:triggerResort', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:resort'); scope.entries.sort(); }); })); scope.entries.on('add remove reset', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); } }; });
angular.module('mwUI.Menu') .directive('mwMenuTopEntries', function ($rootScope, $timeout) { return { scope: { menu: '=mwMenuTopEntries', right: '=' }, transclude: true, templateUrl: 'uikit/mw-menu/directives/templates/mw_menu_top_entries.html', controller: function ($scope) { var menu = $scope.menu || new mwUI.Menu.MwMenu(); this.getMenu = function () { return menu; }; }, link: function (scope, el, attrs, ctrl) { scope.entries = ctrl.getMenu(); scope.$on('mw-menu:triggerReorder', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); scope.$on('mw-menu:triggerResort', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:resort'); scope.entries.sort(); }); })); scope.entries.on('add remove reset', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); } }; });
Move close functionality on location change into mwMenuTopBar
Move close functionality on location change into mwMenuTopBar
JavaScript
apache-2.0
mwaylabs/uikit,mwaylabs/uikit,mwaylabs/uikit
--- +++ @@ -17,17 +17,6 @@ }, link: function (scope, el, attrs, ctrl) { scope.entries = ctrl.getMenu(); - - scope.unCollapse = function () { - var collapseEl = el.find('.navbar-collapse'); - if (collapseEl.hasClass('in')) { - collapseEl.collapse('hide'); - } - }; - - $rootScope.$on('$locationChangeSuccess', function () { - scope.unCollapse(); - }); scope.$on('mw-menu:triggerReorder', _.throttle(function () { $timeout(function () {
b9c96cfc73b6e0adcb7b747c40ac40c74995ea7f
eslint-rules/no-primitive-constructors.js
eslint-rules/no-primitive-constructors.js
/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; module.exports = function(context) { function check(node) { const name = node.callee.name; let msg = null; switch (name) { case 'Boolean': msg = 'To cast a value to a boolean, use double negation: !!value'; break; case 'String': msg = 'To cast a value to a string, concat it with the empty string: \'\' + value'; break; } if (msg) { context.report(node, `Do not use the ${name} constructor. ${msg}`); } } return { CallExpression: check, NewExpression: check, }; };
/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; module.exports = function(context) { function report(node, name, msg) { context.report(node, `Do not use the ${name} constructor. ${msg}`); } function check(node) { const name = node.callee.name; switch (name) { case 'Boolean': report( node, name, 'To cast a value to a boolean, use double negation: !!value' ); break; case 'String': report( node, name, 'To cast a value to a string, concat it with the empty string ' + '(unless it\'s a symbol, which have different semantics): ' + '\'\' + value' ); break; } } return { CallExpression: check, NewExpression: check, }; };
Add caveat about symbols to string error message
Add caveat about symbols to string error message
JavaScript
bsd-3-clause
acdlite/react,apaatsio/react,jorrit/react,krasimir/react,jordanpapaleo/react,mosoft521/react,facebook/react,jameszhan/react,yungsters/react,STRML/react,AlmeroSteyn/react,glenjamin/react,tomocchino/react,Simek/react,trueadm/react,jzmq/react,TheBlasfem/react,silvestrijonathan/react,joecritch/react,yiminghe/react,prometheansacrifice/react,shergin/react,jzmq/react,sekiyaeiji/react,STRML/react,quip/react,wmydz1/react,ArunTesco/react,ArunTesco/react,Simek/react,camsong/react,terminatorheart/react,aickin/react,pyitphyoaung/react,ArunTesco/react,facebook/react,silvestrijonathan/react,yiminghe/react,AlmeroSteyn/react,glenjamin/react,quip/react,cpojer/react,chicoxyzzy/react,kaushik94/react,rickbeerendonk/react,acdlite/react,prometheansacrifice/react,TheBlasfem/react,camsong/react,silvestrijonathan/react,yungsters/react,rricard/react,yungsters/react,flarnie/react,yangshun/react,rickbeerendonk/react,jquense/react,syranide/react,VioletLife/react,anushreesubramani/react,jorrit/react,joecritch/react,jordanpapaleo/react,rickbeerendonk/react,glenjamin/react,roth1002/react,edvinerikson/react,jameszhan/react,wmydz1/react,roth1002/react,jdlehman/react,anushreesubramani/react,yangshun/react,edvinerikson/react,AlmeroSteyn/react,AlmeroSteyn/react,jzmq/react,cpojer/react,chicoxyzzy/react,billfeller/react,AlmeroSteyn/react,apaatsio/react,terminatorheart/react,yiminghe/react,leexiaosi/react,STRML/react,maxschmeling/react,mosoft521/react,roth1002/react,Simek/react,empyrical/react,joecritch/react,shergin/react,kaushik94/react,mhhegazy/react,jdlehman/react,nhunzaker/react,roth1002/react,jzmq/react,mosoft521/react,prometheansacrifice/react,mjackson/react,kaushik94/react,rickbeerendonk/react,cpojer/react,Simek/react,acdlite/react,nhunzaker/react,mhhegazy/react,AlmeroSteyn/react,jquense/react,silvestrijonathan/react,silvestrijonathan/react,yungsters/react,joecritch/react,dilidili/react,kaushik94/react,anushreesubramani/react,chenglou/react,ericyang321/react,mhhegazy/react,jzmq/react,jdlehman/react,tomocchino/react,STRML/react,facebook/react,dilidili/react,yiminghe/react,acdlite/react,aickin/react,TheBlasfem/react,dilidili/react,krasimir/react,jordanpapaleo/react,mjackson/react,TheBlasfem/react,yiminghe/react,aickin/react,ericyang321/react,yungsters/react,brigand/react,jzmq/react,chenglou/react,mhhegazy/react,jameszhan/react,cpojer/react,cpojer/react,mjackson/react,brigand/react,shergin/react,jquense/react,anushreesubramani/react,brigand/react,jordanpapaleo/react,pyitphyoaung/react,pyitphyoaung/react,edvinerikson/react,jdlehman/react,roth1002/react,jorrit/react,kaushik94/react,jdlehman/react,glenjamin/react,tomocchino/react,TheBlasfem/react,pyitphyoaung/react,acdlite/react,maxschmeling/react,jordanpapaleo/react,maxschmeling/react,krasimir/react,rricard/react,AlmeroSteyn/react,mhhegazy/react,kaushik94/react,jzmq/react,billfeller/react,joecritch/react,leexiaosi/react,krasimir/react,STRML/react,prometheansacrifice/react,ericyang321/react,trueadm/react,trueadm/react,aickin/react,shergin/react,Simek/react,ericyang321/react,facebook/react,billfeller/react,maxschmeling/react,pyitphyoaung/react,apaatsio/react,VioletLife/react,camsong/react,terminatorheart/react,anushreesubramani/react,silvestrijonathan/react,jquense/react,tomocchino/react,chenglou/react,yiminghe/react,empyrical/react,chenglou/react,yiminghe/react,yangshun/react,aickin/react,facebook/react,nhunzaker/react,prometheansacrifice/react,maxschmeling/react,glenjamin/react,flarnie/react,rricard/react,joecritch/react,prometheansacrifice/react,quip/react,billfeller/react,edvinerikson/react,syranide/react,STRML/react,yangshun/react,aickin/react,jorrit/react,camsong/react,terminatorheart/react,billfeller/react,dilidili/react,ericyang321/react,maxschmeling/react,facebook/react,trueadm/react,nhunzaker/react,VioletLife/react,jameszhan/react,chicoxyzzy/react,mhhegazy/react,brigand/react,empyrical/react,acdlite/react,anushreesubramani/react,yangshun/react,kaushik94/react,jquense/react,apaatsio/react,dilidili/react,quip/react,tomocchino/react,empyrical/react,jdlehman/react,syranide/react,mosoft521/react,cpojer/react,sekiyaeiji/react,jameszhan/react,krasimir/react,prometheansacrifice/react,roth1002/react,shergin/react,krasimir/react,yangshun/react,jorrit/react,trueadm/react,edvinerikson/react,apaatsio/react,TheBlasfem/react,wmydz1/react,mhhegazy/react,flarnie/react,jordanpapaleo/react,leexiaosi/react,pyitphyoaung/react,anushreesubramani/react,mjackson/react,dilidili/react,Simek/react,tomocchino/react,chicoxyzzy/react,VioletLife/react,quip/react,rricard/react,ericyang321/react,quip/react,mosoft521/react,brigand/react,edvinerikson/react,yungsters/react,jameszhan/react,glenjamin/react,sekiyaeiji/react,brigand/react,apaatsio/react,brigand/react,VioletLife/react,mosoft521/react,flarnie/react,rickbeerendonk/react,mjackson/react,mjackson/react,mosoft521/react,cpojer/react,flipactual/react,empyrical/react,wmydz1/react,trueadm/react,dilidili/react,jquense/react,roth1002/react,edvinerikson/react,chicoxyzzy/react,rickbeerendonk/react,wmydz1/react,Simek/react,flipactual/react,chicoxyzzy/react,apaatsio/react,shergin/react,camsong/react,jameszhan/react,chenglou/react,empyrical/react,yungsters/react,mjackson/react,camsong/react,nhunzaker/react,chenglou/react,wmydz1/react,glenjamin/react,flipactual/react,VioletLife/react,jorrit/react,shergin/react,jorrit/react,silvestrijonathan/react,krasimir/react,ericyang321/react,joecritch/react,wmydz1/react,empyrical/react,chenglou/react,billfeller/react,aickin/react,jdlehman/react,nhunzaker/react,VioletLife/react,yangshun/react,rricard/react,rricard/react,rickbeerendonk/react,maxschmeling/react,flarnie/react,quip/react,camsong/react,terminatorheart/react,chicoxyzzy/react,nhunzaker/react,trueadm/react,acdlite/react,pyitphyoaung/react,STRML/react,flarnie/react,facebook/react,jquense/react,syranide/react,jordanpapaleo/react,billfeller/react,tomocchino/react,terminatorheart/react,flarnie/react
--- +++ @@ -12,19 +12,29 @@ 'use strict'; module.exports = function(context) { + function report(node, name, msg) { + context.report(node, `Do not use the ${name} constructor. ${msg}`); + } + function check(node) { const name = node.callee.name; - let msg = null; switch (name) { case 'Boolean': - msg = 'To cast a value to a boolean, use double negation: !!value'; + report( + node, + name, + 'To cast a value to a boolean, use double negation: !!value' + ); break; case 'String': - msg = 'To cast a value to a string, concat it with the empty string: \'\' + value'; + report( + node, + name, + 'To cast a value to a string, concat it with the empty string ' + + '(unless it\'s a symbol, which have different semantics): ' + + '\'\' + value' + ); break; - } - if (msg) { - context.report(node, `Do not use the ${name} constructor. ${msg}`); } }
8aa85b90cbffc79fdc54ba1aac070d7fb2a8dccb
public/controllers/main.routes.js
public/controllers/main.routes.js
'use strict'; angular.module('StudentApp').config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider.when('/studentPage', { templateUrl: 'views/student/student.list.html', controller: 'StudentController' }).when('/comments/:id', { templateUrl: 'views/comment/comments.list.html', controller: 'CommentsController' }).when('/stockPage', { templateUrl: 'views/Stock/StockManagment.html', controller: 'StockController' }).when('/orderPage', { templateUrl: 'views/Stock/OrderManagment.html', controller: 'OrderController' }).otherwise({ redirectTo: '/' }); $locationProvider.html5Mode(true); }]);
'use strict'; angular.module('StudentApp').config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider.when('/studentPage', { templateUrl: 'views/student/student.list.html', controller: 'StudentController' }).when('/comments/:id', { templateUrl: 'views/comment/comments.list.html', controller: 'CommentsController' }).when('/stockPage', { templateUrl: 'views/Stock/StockManagment.html', controller: 'StockController' }).when('/orderPage', { templateUrl: 'views/Stock/OrderManagment.html', controller: 'OrderController' }).when('/customerPage', { templateUrl: 'views/Customer/Customer.html', controller: 'CustomerController' }).otherwise({ redirectTo: '/' }); $locationProvider.html5Mode(true); }]);
Add relevant Customer section changes to main.router.js
Add relevant Customer section changes to main.router.js
JavaScript
mit
scoobygroup/IWEX,scoobygroup/IWEX
--- +++ @@ -14,6 +14,9 @@ }).when('/orderPage', { templateUrl: 'views/Stock/OrderManagment.html', controller: 'OrderController' + }).when('/customerPage', { + templateUrl: 'views/Customer/Customer.html', + controller: 'CustomerController' }).otherwise({ redirectTo: '/' });
c11d0b3d616fb1d03cdbf0453dcdc5cb39ac122a
lib/node_modules/@stdlib/types/ndarray/ctor/lib/getnd.js
lib/node_modules/@stdlib/types/ndarray/ctor/lib/getnd.js
'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; // FUNCTIONS // /** * Returns an array element. * * @private * @param {...integer} idx - indices * @throws {TypeError} provided indices must be integer valued * @throws {RangeError} index exceeds array dimensions * @returns {*} array element */ function get() { /* eslint-disable no-invalid-this */ var len; var idx; var i; // TODO: support index modes len = arguments.length; idx = this._offset; for ( i = 0; i < len; i++ ) { if ( !isInteger( arguments[ i ] ) ) { throw new TypeError( 'invalid input argument. Indices must be integer valued. Argument: '+i+'. Value: `'+arguments[i]+'`.' ); } idx += this._strides[ i ] * arguments[ i ]; } return this._buffer[ idx ]; } // end FUNCTION get() // EXPORTS // module.exports = get;
'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; var getIndex = require( './get_index.js' ); // FUNCTIONS // /** * Returns an array element. * * @private * @param {...integer} idx - indices * @throws {TypeError} provided indices must be integer valued * @throws {RangeError} index exceeds array dimensions * @returns {*} array element */ function get() { /* eslint-disable no-invalid-this */ var len; var idx; var ind; var i; len = arguments.length; idx = this._offset; for ( i = 0; i < len; i++ ) { if ( !isInteger( arguments[ i ] ) ) { throw new TypeError( 'invalid input argument. Indices must be integer valued. Argument: '+i+'. Value: `'+arguments[i]+'`.' ); } ind = getIndex( arguments[ i ], this._shape[ i ], this._mode ); idx += this._strides[ i ] * ind; } return this._buffer[ idx ]; } // end FUNCTION get() // EXPORTS // module.exports = get;
Add support for an index mode
Add support for an index mode
JavaScript
apache-2.0
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
--- +++ @@ -3,6 +3,7 @@ // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; +var getIndex = require( './get_index.js' ); // FUNCTIONS // @@ -20,9 +21,8 @@ /* eslint-disable no-invalid-this */ var len; var idx; + var ind; var i; - - // TODO: support index modes len = arguments.length; idx = this._offset; @@ -30,7 +30,8 @@ if ( !isInteger( arguments[ i ] ) ) { throw new TypeError( 'invalid input argument. Indices must be integer valued. Argument: '+i+'. Value: `'+arguments[i]+'`.' ); } - idx += this._strides[ i ] * arguments[ i ]; + ind = getIndex( arguments[ i ], this._shape[ i ], this._mode ); + idx += this._strides[ i ] * ind; } return this._buffer[ idx ]; } // end FUNCTION get()
2d1bd23a872645053b8e19bdf8b656b8ca872c4b
index.js
index.js
require('babel/register'); require('dotenv').load(); var startServer = require('./app'); var port = process.env['PORT'] || 3000; startServer(port);
require('babel/register'); if (process.env.NODE_ENV !== 'production') { require('dotenv').load(); } var startServer = require('./app'); var port = process.env.PORT || 3000; startServer(port);
Handle case where dotenv is not included in production.
Handle case where dotenv is not included in production.
JavaScript
mit
keokilee/hitraffic-api,hitraffic/api-server
--- +++ @@ -1,7 +1,10 @@ require('babel/register'); -require('dotenv').load(); + +if (process.env.NODE_ENV !== 'production') { + require('dotenv').load(); +} var startServer = require('./app'); -var port = process.env['PORT'] || 3000; +var port = process.env.PORT || 3000; startServer(port);
3321cc95a521445a1ad1a2f70c057acb583ac71e
solutions.digamma.damas.ui/src/components/layouts/app-page.js
solutions.digamma.damas.ui/src/components/layouts/app-page.js
import Vue from "vue" export default { name: 'AppPage', props: { layout: { type: String, required: true, validator: [].includes.bind(["standard", "empty"]) } }, created() { let component = components[this.layout] if (!Vue.options.components[component.name]) { Vue.component( component.name, component, ); } this.$parent.$emit('update:layout', component); }, render(h) { return this.$slots.default ? this.$slots.default[0] : h(); }, } const components = { "standard": () => import("./layout-standard"), "empty": () => import("./layout-empty") }
import Vue from "vue" export default { name: 'AppPage', props: { layout: { type: String, required: true, validator: [].includes.bind(["standard", "empty"]) } }, created() { let component = components[this.layout] if (!Vue.options.components[component.name]) { Vue.component( component.name, component, ); } if (this.$parent.layout !== component) { this.$parent.$emit('update:layout', component); } }, render(h) { return this.$slots.default ? this.$slots.default[0] : h(); }, } const components = { "standard": () => import("./layout-standard"), "empty": () => import("./layout-empty") }
Add identity gard before firing layout change
Add identity gard before firing layout change
JavaScript
mit
digammas/damas,digammas/damas,digammas/damas,digammas/damas
--- +++ @@ -17,7 +17,9 @@ component, ); } - this.$parent.$emit('update:layout', component); + if (this.$parent.layout !== component) { + this.$parent.$emit('update:layout', component); + } }, render(h) { return this.$slots.default ? this.$slots.default[0] : h();
77174ca4c0e6e663ed9fb1cd5ef74d3ae7ec865c
index.js
index.js
"use strict"; var _ = require("lodash"); var HTTP_STATUS_CODES = require("http").STATUS_CODES; var request = require("request"); var url = require("url"); function LamernewsAPI(root) { this.root = root; return this; } LamernewsAPI.prototype.getNews = function getNews(options, callback) { var defaults = { count: 30, start: 0, type: "latest" }; var signature; if (!callback && typeof options === "function") { callback = options; options = {}; } options = _.defaults(options || {}, defaults); signature = ["getnews", options.type, options.start, options.count]; this.query(signature.join("/"), callback); return this; }; LamernewsAPI.prototype.query = function query(signature, callback) { if (!this.root) { throw new Error("No API root specified"); } request(url.resolve(this.root, signature), function(err, res, body) { var status; if (err) { return callback(err); } status = res.statusCode; if (status !== 200) { err = new Error(HTTP_STATUS_CODES[status]); err.code = status; return callback(err); } try { body = JSON.parse(body); } catch (err) { callback(err); } callback(null, body); }); }; module.exports = LamernewsAPI;
"use strict"; var _ = require("lodash"); var HTTP_STATUS_CODES = require("http").STATUS_CODES; var request = require("request"); var url = require("url"); function LamernewsAPI(root) { this.root = root; return this; } LamernewsAPI.prototype = { getNews: function getNews(options, callback) { var defaults = { count: 30, start: 0, type: "latest" }; var signature; if (!callback && typeof options === "function") { callback = options; options = {}; } options = _.defaults(options || {}, defaults); signature = ["getnews", options.type, options.start, options.count]; this.query(signature.join("/"), callback); return this; }, query: function query(signature, callback) { if (!this.root) { throw new Error("No API root specified"); } request(url.resolve(this.root, signature), function(err, res, body) { var status; if (err) { return callback(err); } status = res.statusCode; if (status !== 200) { err = new Error(HTTP_STATUS_CODES[status]); err.code = status; return callback(err); } try { body = JSON.parse(body); } catch (err) { callback(err); } callback(null, body); }); } }; module.exports = LamernewsAPI;
Refactor method definitions on prototype to be more DRY
Refactor method definitions on prototype to be more DRY
JavaScript
mit
sbruchmann/lamernews-api
--- +++ @@ -10,56 +10,58 @@ return this; } -LamernewsAPI.prototype.getNews = function getNews(options, callback) { - var defaults = { - count: 30, - start: 0, - type: "latest" - }; - var signature; +LamernewsAPI.prototype = { + getNews: function getNews(options, callback) { + var defaults = { + count: 30, + start: 0, + type: "latest" + }; + var signature; - if (!callback && typeof options === "function") { - callback = options; - options = {}; - } - - options = _.defaults(options || {}, defaults); - signature = ["getnews", options.type, options.start, options.count]; - - this.query(signature.join("/"), callback); - - return this; -}; - -LamernewsAPI.prototype.query = function query(signature, callback) { - if (!this.root) { - throw new Error("No API root specified"); - } - - request(url.resolve(this.root, signature), function(err, res, body) { - var status; - - if (err) { - return callback(err); + if (!callback && typeof options === "function") { + callback = options; + options = {}; } - status = res.statusCode; + options = _.defaults(options || {}, defaults); + signature = ["getnews", options.type, options.start, options.count]; - if (status !== 200) { - err = new Error(HTTP_STATUS_CODES[status]); - err.code = status; + this.query(signature.join("/"), callback); - return callback(err); + return this; + }, + + query: function query(signature, callback) { + if (!this.root) { + throw new Error("No API root specified"); } - try { - body = JSON.parse(body); - } catch (err) { - callback(err); - } + request(url.resolve(this.root, signature), function(err, res, body) { + var status; - callback(null, body); - }); + if (err) { + return callback(err); + } + + status = res.statusCode; + + if (status !== 200) { + err = new Error(HTTP_STATUS_CODES[status]); + err.code = status; + + return callback(err); + } + + try { + body = JSON.parse(body); + } catch (err) { + callback(err); + } + + callback(null, body); + }); + } }; module.exports = LamernewsAPI;
5e4c5c4d4ecc1698c5adddb31a2378df0e78ec22
index.js
index.js
/** * espower-source - Power Assert instrumentor from source to source. * * https://github.com/twada/espower-source * * Copyright (c) 2014 Takuto Wada * Licensed under the MIT license. * https://github.com/twada/espower-source/blob/master/MIT-LICENSE.txt */ var espower = require('espower'), esprima = require('esprima'), escodegen = require('escodegen'), merge = require('lodash.merge'), convert = require('convert-source-map'); function espowerSourceToSource(jsCode, filepath, options) { 'use strict'; var jsAst, espowerOptions, modifiedAst, escodegenOutput, code, map; jsAst = esprima.parse(jsCode, {tolerant: true, loc: true, tokens: true, raw: true, source: filepath}); espowerOptions = merge(merge(espower.defaultOptions(), options), { destructive: true, path: filepath }); modifiedAst = espower(jsAst, espowerOptions); escodegenOutput = escodegen.generate(modifiedAst, { sourceMap: true, sourceMapWithCode: true }); code = escodegenOutput.code; // Generated source code map = convert.fromJSON(escodegenOutput.map.toString()); map.sourcemap.sourcesContent = [jsCode]; return code + '\n' + map.toComment() + '\n'; } module.exports = espowerSourceToSource;
/** * espower-source - Power Assert instrumentor from source to source. * * https://github.com/twada/espower-source * * Copyright (c) 2014 Takuto Wada * Licensed under the MIT license. * https://github.com/twada/espower-source/blob/master/MIT-LICENSE.txt */ var espower = require('espower'), esprima = require('esprima'), escodegen = require('escodegen'), merge = require('lodash.merge'), convert = require('convert-source-map'); function espowerSource(jsCode, filepath, options) { 'use strict'; var jsAst, espowerOptions, modifiedAst, escodegenOutput, code, map; jsAst = esprima.parse(jsCode, {tolerant: true, loc: true, tokens: true, raw: true, source: filepath}); espowerOptions = merge(merge(espower.defaultOptions(), options), { destructive: true, path: filepath }); modifiedAst = espower(jsAst, espowerOptions); escodegenOutput = escodegen.generate(modifiedAst, { sourceMap: true, sourceMapWithCode: true }); code = escodegenOutput.code; // Generated source code map = convert.fromJSON(escodegenOutput.map.toString()); map.sourcemap.sourcesContent = [jsCode]; return code + '\n' + map.toComment() + '\n'; } module.exports = espowerSource;
Change exposed function name to espowerSource
Change exposed function name to espowerSource
JavaScript
mit
power-assert-js/espower-source
--- +++ @@ -13,7 +13,7 @@ merge = require('lodash.merge'), convert = require('convert-source-map'); -function espowerSourceToSource(jsCode, filepath, options) { +function espowerSource(jsCode, filepath, options) { 'use strict'; var jsAst, espowerOptions, modifiedAst, escodegenOutput, code, map; @@ -34,4 +34,4 @@ return code + '\n' + map.toComment() + '\n'; } -module.exports = espowerSourceToSource; +module.exports = espowerSource;
2083f66c81315589377d6c2a174d45c5d32ff564
index.js
index.js
'use strict' var window = require('global/window') var Struct = require('observ-struct') var Observ = require('observ') var minimumViewport = require('minimum-viewport') var orientation = require('screen-orientation') var MOBILE_WIDTH = 640 var device = Struct({ mobile: Observ(false), orientation: Observ(null) }) module.exports = device if (window.addEventListener) { window.addEventListener('resize', onResize) onResize() } function onResize () { device.mobile.set(minimumViewport({x: MOBILE_WIDTH})) device.orientation.set(orientation().direction) }
'use strict' var window = require('global/window') var Struct = require('observ-struct') var Observ = require('observ') var minimumViewport = require('minimum-viewport') var orientation = require('screen-orientation') var MOBILE_WIDTH = 840 var device = Struct({ mobile: Observ(false), orientation: Observ(null) }) module.exports = device if (window.addEventListener) { window.addEventListener('resize', onResize) onResize() } function onResize () { device.mobile.set(minimumViewport({x: MOBILE_WIDTH})) device.orientation.set(orientation().direction) }
Update mobile width to 840 px
Update mobile width to 840 px
JavaScript
mit
bendrucker/observ-mobile
--- +++ @@ -6,7 +6,7 @@ var minimumViewport = require('minimum-viewport') var orientation = require('screen-orientation') -var MOBILE_WIDTH = 640 +var MOBILE_WIDTH = 840 var device = Struct({ mobile: Observ(false),
be9edb357e5ec2ae7cf99723018d5decbe154ccf
index.js
index.js
'use strict'; var MarkdownIt = require('markdown-it'); exports.name = 'markdown-it'; exports.outputFormat = 'html'; exports.render = function (str, options) { var md = MarkdownIt(options); return md.render(str); };
'use strict'; var MarkdownIt = require('markdown-it'); exports.name = 'markdown-it'; exports.outputFormat = 'xml'; exports.render = function (str, options) { var md = MarkdownIt(options); return md.render(str); };
Mark output format as XML
Mark output format as XML
JavaScript
mit
jstransformers/jstransformer-markdown-it,jstransformers/jstransformer-markdown-it
--- +++ @@ -3,7 +3,7 @@ var MarkdownIt = require('markdown-it'); exports.name = 'markdown-it'; -exports.outputFormat = 'html'; +exports.outputFormat = 'xml'; exports.render = function (str, options) { var md = MarkdownIt(options); return md.render(str);
24ae87eca54f0baa1a379c21cac17fcc3c70f10c
index.js
index.js
function Fs() {} Fs.prototype = require('fs') var fs = new Fs() , Promise = require('promise') module.exports = exports = fs for (var key in fs) if (!(typeof fs[key] != 'function' || key.match(/Sync$/) || key.match(/^[A-Z]/) || key.match(/^create/) || key.match(/^(un)?watch/) )) fs[key] = Promise.denodeify(fs[key])
var fs = Object.create(require('fs')) var Promise = require('promise') module.exports = exports = fs for (var key in fs) if (!(typeof fs[key] != 'function' || key.match(/Sync$/) || key.match(/^[A-Z]/) || key.match(/^create/) || key.match(/^(un)?watch/) )) fs[key] = Promise.denodeify(fs[key])
Use multiple var statements and `Object.create`
Use multiple var statements and `Object.create`
JavaScript
mit
then/fs
--- +++ @@ -1,7 +1,5 @@ -function Fs() {} -Fs.prototype = require('fs') -var fs = new Fs() - , Promise = require('promise') +var fs = Object.create(require('fs')) +var Promise = require('promise') module.exports = exports = fs for (var key in fs)
3c8494b2151178eb169947e7da0775521e1c2bfd
index.js
index.js
/* eslint-env node */ "use strict"; module.exports = { name: "ember-component-attributes", setupPreprocessorRegistry(type, registry) { registry.add("htmlbars-ast-plugin", { name: "attributes-expression", plugin: require("./lib/attributes-expression-transform"), baseDir: function() { return __dirname; } }); } };
/* eslint-env node */ "use strict"; module.exports = { name: "ember-component-attributes", setupPreprocessorRegistry(type, registry) { registry.add("htmlbars-ast-plugin", { name: "attributes-expression", plugin: require("./lib/attributes-expression-transform"), baseDir: function() { return __dirname; } }); }, included() { this.import('vendor/ember-component-attributes/index.js'); }, treeForVendor(rawVendorTree) { let babelAddon = this.addons.find(addon => addon.name === 'ember-cli-babel'); let transpiledVendorTree = babelAddon.transpileTree(rawVendorTree, { 'ember-cli-babel': { compileModules: false } }); return transpiledVendorTree; }, };
Add `treeForVendor` and `included` hook implementations.
Add `treeForVendor` and `included` hook implementations.
JavaScript
mit
mmun/ember-component-attributes,mmun/ember-component-attributes
--- +++ @@ -12,5 +12,21 @@ return __dirname; } }); - } + }, + + included() { + this.import('vendor/ember-component-attributes/index.js'); + }, + + treeForVendor(rawVendorTree) { + let babelAddon = this.addons.find(addon => addon.name === 'ember-cli-babel'); + + let transpiledVendorTree = babelAddon.transpileTree(rawVendorTree, { + 'ember-cli-babel': { + compileModules: false + } + }); + + return transpiledVendorTree; + }, };
9dcd369bcd7529f8c925d82a73111df72fbdd433
index.js
index.js
/** * @jsx React.DOM */ var React = require('react'); var Pdf = React.createClass({ getInitialState: function() { return {}; }, componentDidMount: function() { var self = this; PDFJS.getDocument(this.props.file).then(function(pdf) { pdf.getPage(self.props.page).then(function(page) { self.setState({pdfPage: page, pdf: pdf}); }); }); }, componentWillReceiveProps: function(newProps) { var self = this; if (newProps.page) { self.state.pdf.getPage(newProps.page).then(function(page) { self.setState({pdfPage: page, pageId: newProps.page}); }); } this.setState({ pdfPage: null }); }, render: function() { var self = this; this.state.pdfPage && setTimeout(function() { var canvas = self.getDOMNode(), context = canvas.getContext('2d'), scale = 1.0, viewport = self.state.pdfPage.getViewport(scale); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; self.state.pdfPage.render(renderContext); }); return this.state.pdfPage ? <canvas></canvas> : <div>Loading pdf..</div>; } }); module.exports = Pdf;
/** * @jsx React.DOM */ var React = require('react'); var Pdf = React.createClass({ getInitialState: function() { return {}; }, componentDidMount: function() { var self = this; PDFJS.getDocument(this.props.file).then(function(pdf) { pdf.getPage(self.props.page).then(function(page) { self.setState({pdfPage: page, pdf: pdf}); }); }); }, componentWillReceiveProps: function(newProps) { var self = this; if (newProps.page) { self.state.pdf.getPage(newProps.page).then(function(page) { self.setState({pdfPage: page, pageId: newProps.page}); }); } this.setState({ pdfPage: null }); }, getDefaultProps: function() { return {page: 1}; }, render: function() { var self = this; this.state.pdfPage && setTimeout(function() { var canvas = self.getDOMNode(), context = canvas.getContext('2d'), scale = 1.0, viewport = self.state.pdfPage.getViewport(scale); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; self.state.pdfPage.render(renderContext); }); return this.state.pdfPage ? <canvas></canvas> : <div>Loading pdf..</div>; } }); module.exports = Pdf;
Add default prop for page
Add default prop for page
JavaScript
mit
nnarhinen/react-pdf,wojtekmaj/react-pdf,BartVanHoutte-ADING/react-pdf,BartVanHoutte-ADING/react-pdf,BartVanHoutte-ADING/react-pdf,suancarloj/react-pdf,peergradeio/react-pdf,wojtekmaj/react-pdf,wojtekmaj/react-pdf,peergradeio/react-pdf,suancarloj/react-pdf,nnarhinen/react-pdf,suancarloj/react-pdf
--- +++ @@ -28,6 +28,9 @@ pdfPage: null }); }, + getDefaultProps: function() { + return {page: 1}; + }, render: function() { var self = this; this.state.pdfPage && setTimeout(function() {
6e8d2a2f6587b964d2ded8149898728686a282bf
public/app/controllers/mvUserListController.js
public/app/controllers/mvUserListController.js
angular.module('app').controller('mvUserListController', function ($scope, mvUser) { $scope.users = mvUser.query(); $scope.sortOptions = [{ value: "username", text: "Sort by username" }, { value: "registrationDate", text: "Sort by registration date" }, { value: "role", text: "Sort by role" }]; $scope.sortOrder = { selected: $scope.sortOptions[0].value }; });
angular.module('app').controller('mvUserListController', function ($scope, mvUser) { $scope.users = mvUser.query(); $scope.sortOptions = [{ value: "username", text: "Sort by username" }, { value: "- registrationDate", text: "Sort by registration date" }, { value: "- role", text: "Sort by role" }]; $scope.sortOrder = { selected: $scope.sortOptions[0].value }; });
Fix ordering on user list page
Fix ordering on user list page
JavaScript
mit
BenjaminBini/dilemme,BenjaminBini/dilemme
--- +++ @@ -5,10 +5,10 @@ value: "username", text: "Sort by username" }, { - value: "registrationDate", + value: "- registrationDate", text: "Sort by registration date" }, { - value: "role", + value: "- role", text: "Sort by role" }];