commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
a6f9255f268d8b17d2820aa0cc32a18cee3f778f
.postcssrc.js
.postcssrc.js
module.exports = { plugins: { '@wearegenki/ui-postcss': {}, }, };
module.exports = { plugins: { '@wearegenki/ui-postcss': {}, }, }; // TODO: Put this in the docs (both ways, depending on array or object type of config): // https://github.com/michael-ciniawsky/postcss-load-config // const { uiPostcssPreset } = require('@wearegenki/ui'); // module.exports = { // plugins: [ // uiPostcssPreset({ // // importPath: ['src'], // mixinsDir: 'src/css/mixins', // // verbose: true, // }), // ], // }; // module.exports = { // plugins: { // '@wearegenki/ui-postcss': { // // importPath: ['src'], // mixinsDir: 'src/css/mixins', // // verbose: true, // }, // }, // };
Add comments about ui-postcss in docs
Add comments about ui-postcss in docs
JavaScript
isc
WeAreGenki/wag-ui
358d2a9b5d2959031fa685045a9f1a07f2d27c78
client.src/shared/views/gistbook-view/views/text/edit/index.js
client.src/shared/views/gistbook-view/views/text/edit/index.js
// // textEditView // Modify text based on a textarea // import ItemView from 'base/item-view'; export default ItemView.extend({ template: 'editTextView', tagName: 'textarea', className: 'gistbook-textarea', // Get the value of the element value() { return this.el.value; } });
// // textEditView // Modify text based on a textarea // import ItemView from 'base/item-view'; export default ItemView.extend({ template: 'editTextView', tagName: 'textarea', className: 'gistbook-textarea', // Get the value of the element, // stripping line breaks from the // start and end value() { return this.el.value.replace(/^\s+|\s+$/g, ''); } });
Remove new lines from text areas on save.
Remove new lines from text areas on save. Resolves #390
JavaScript
mit
jmeas/gistbook,joshbedo/gistbook
5aa339bb60364eb0c43690c907cc391788811a24
src/index.js
src/index.js
/* eslint-disable no-console */ import { createFilter } from 'rollup-pluginutils'; import { resolveSourceMap } from 'source-map-resolve'; import { readFile } from 'fs'; import { promisify } from './utils'; const readFileAsync = promisify(readFile); const resolveSourceMapAsync = promisify(resolveSourceMap); export default function sourcemaps({ include, exclude } = {}) { const filter = createFilter(include, exclude); return { async load(id) { if (!filter(id)) { return null; } let code; try { code = await readFileAsync(id, 'utf8'); } catch (err) { // Failed, let Rollup deal with it return null; } let sourceMap; try { sourceMap = await resolveSourceMapAsync(code, id, readFile); } catch (err) { console.error(`rollup-plugin-sourcemaps: Failed resolving source map from ${id}: ${err}`); return code; } // No source map detected, return code if (sourceMap === null) { return code; } const { map } = sourceMap; return { code, map }; }, }; }
/* eslint-disable no-console */ import { createFilter } from 'rollup-pluginutils'; import { resolve } from 'source-map-resolve'; import { readFile } from 'fs'; import { promisify } from './utils'; const readFileAsync = promisify(readFile); const resolveSourceMapAsync = promisify(resolve); export default function sourcemaps({ include, exclude } = {}) { const filter = createFilter(include, exclude); return { async load(id) { if (!filter(id)) { return null; } let code; try { code = await readFileAsync(id, 'utf8'); } catch (err) { // Failed, let Rollup deal with it return null; } let sourceMap; try { sourceMap = await resolveSourceMapAsync(code, id, readFile); } catch (err) { console.error(`rollup-plugin-sourcemaps: Failed resolving source map from ${id}: ${err}`); return code; } // No source map detected, return code if (sourceMap === null) { return code; } const { map, sourcesContent } = sourceMap; map.sourcesContent = sourcesContent; return { code, map }; }, }; }
Include sourcesContent in source map
Include sourcesContent in source map
JavaScript
mit
maxdavidson/rollup-plugin-sourcemaps,maxdavidson/rollup-plugin-sourcemaps
fbd3bd5365b8dd1b6f4773e22f7b94fe4126acfa
src/index.js
src/index.js
import React from 'react'; import { render } from 'react-dom'; import { Provider } from "react-redux"; import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import App from "./containers/App"; import rootReducer from "./reducers"; import { getTodosIfNeeded } from "./actions"; const createStoreWithMiddleware = applyMiddleware(thunk)(createStore); const store = createStoreWithMiddleware(rootReducer) store.dispatch(getTodosIfNeeded()) render( <Provider store={store}> <App /> </Provider>, document.querySelector('#root') );
import React from 'react'; import { render } from 'react-dom'; import { Provider } from "react-redux"; import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import injectTapEventPlugin from "react-tap-event-plugin"; import App from "./containers/App"; import rootReducer from "./reducers"; import { getTodosIfNeeded } from "./actions"; const createStoreWithMiddleware = applyMiddleware(thunk)(createStore); const store = createStoreWithMiddleware(rootReducer) store.dispatch(getTodosIfNeeded()) injectTapEventPlugin(); render( <Provider store={store}> <App /> </Provider>, document.querySelector('#root') );
Add react tap event plugin
Add react tap event plugin
JavaScript
mit
alice02/go-todoapi,alice02/go-todoapi,alice02/go-todoapi
1481d1905b237c768d45335cc431d567f5676d87
src/index.js
src/index.js
//Get the required shit together const config = require("./config.json"); const Discord = require("discord.js"); const client = new Discord.Client(); const MSS = require("./functions/"); const fs = require("fs"); var command = []; //Login to Discord client.login(config.API.discord); //Include all files in the commands directory fs.readdir("./commands/", function(err, items) { items.forEach(function(item) { var file = item.replace(/['"]+/g, ''); command[file] = require(file); }) }) client.on('ready', function() { console.log("Successfully connected to Discord!"); client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version); }); client.on('message', function(message) { if (!message.content.startsWith(config.MSS.prefix)) return false; let input = message.content.replace (/\n/g, "").split(" "); input[0] = input[0].substring(config.MSS.prefix.length); if (input[0] === "eval" && message.author.id === "190519304972664832") { eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1)); } });
//Get the required shit together const config = require("./config.json"); const Discord = require("discord.js"); const client = new Discord.Client(); const MSS = require("./functions/"); const fs = require("fs"); var command = []; //Login to Discord client.login(config.API.discord); //Include all files in the commands directory fs.readdir("./commands/", function(err, items) { items.forEach(function(item) { var file = item.replace(/['"]+/g, ''); command[file] = require("./commands/" + file); }) }) client.on('ready', function() { console.log("Successfully connected to Discord!"); client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version); }); client.on('message', function(message) { if (!message.content.startsWith(config.MSS.prefix)) return false; let input = message.content.replace (/\n/g, "").split(" "); input[0] = input[0].substring(config.MSS.prefix.length); if (input[0] === "eval" && message.author.id === "190519304972664832") { eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1)); } });
Include from the functions directory
Include from the functions directory
JavaScript
mit
moustacheminer/MSS-Discord,moustacheminer/MSS-Discord,moustacheminer/MSS-Discord
25e28e9795aee56e9d7acdb09b362c30ee7dad15
src/index.js
src/index.js
define([ "text!src/templates/command.html" ], function(commandTemplate) { var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); commands.register({ id: "palette.open", title: "Open Command Palette", shortcuts: [ "mod+shift+p" ], run: function() { return dialogs.list(commands, { template: commandTemplate, filter: function(command) { return command.get("palette") !== false && command.isValidContext(); } }) .then(function(command) { return command.run(); }); } }); });
define([ "text!src/templates/command.html" ], function(commandTemplate) { var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); commands.register({ id: "palette.open", title: "Command Palette: Open", shortcuts: [ "mod+shift+p" ], palette: false, run: function() { return dialogs.list(commands, { template: commandTemplate, filter: function(command) { return command.get("palette") !== false && command.isValidContext(); } }) .then(function(command) { return command.run(); }); } }); });
Change command title and hide from palette
Change command title and hide from palette
JavaScript
apache-2.0
etopian/codebox-package-command-palette,CodeboxIDE/package-command-palette,CodeboxIDE/package-command-palette,etopian/codebox-package-command-palette
453d61337dda06c15130b9783b39ce0e58979c86
src/index.js
src/index.js
import React from "react"; import { render } from "react-dom"; import Root from "./Root"; render( React.createElement(Root), document.getElementById("root") );
import React from "react"; import { render } from "react-dom"; import "./index.css"; import Root from "./Root"; render( React.createElement(Root), document.getElementById("root") );
Fix missing root css import
Fix missing root css import
JavaScript
apache-2.0
nwsapps/flashcards,nwsapps/flashcards
6f8019e821d94975cfab7e62c1557af4254be72e
src/index.js
src/index.js
import React from 'react' import { render } from 'react-dom' import createStore from './createStore' const store = createStore() render( <h1>Hello from React</h1>, document.getElementById('react') )
import React from 'react' import { render } from 'react-dom' import createStore from './createStore' import App from './components/App' const store = createStore() render( <App />, document.getElementById('react') )
Use App component in render
Use App component in render
JavaScript
mit
epicsharp/react-boilerplate,epicsharp/react-boilerplate,RSS-Dev/live-html,RSS-Dev/live-html
61c69d309ad8d80812b3467697ef52ead021249a
src/utils.js
src/utils.js
import pf from 'portfinder'; export function homedir() { return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; } export function wait (time) { return new Promise(resolve => { setTimeout(() => resolve(), time); }); } export function getPort () { return new Promise((resolve, reject) => { pf.getPort((err, port) => { if (err) return reject(err); resolve(port); }); }); }
import fs from 'fs'; import pf from 'portfinder'; export function homedir() { return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; } export function wait (time) { return new Promise(resolve => { setTimeout(() => resolve(), time); }); } export function getPort () { return new Promise((resolve, reject) => { pf.getPort({ host: '127.0.0.1' }, (err, port) => { if (err) return reject(err); resolve(port); }); }); } export function readFile (filename) { return new Promise((resolve, reject) => { fs.readFile(filename, (err, data) => { if (err) return reject(err); resolve(data); }); }); }
Fix getPort and add readFile
Fix getPort and add readFile getPort was considering bind to 0.0.0.0 instead of 127.0.0.1. readFile added to provide a promise-based version of fs.readFile
JavaScript
mit
sqlectron/sqlectron-term
a2136a83a4c7eeb988da2a2c1833fd16d4828632
extensions/roc-plugin-dredd/src/roc/index.js
extensions/roc-plugin-dredd/src/roc/index.js
import { lazyFunctionRequire } from 'roc'; import config from '../config/roc.config.js'; import meta from '../config/roc.config.meta.js'; const lazyRequire = lazyFunctionRequire(require); export default { config, meta, actions: [ { hook: 'server-started', description: 'Run dredd tests', action: lazyRequire('../actions/dredd'), }, ], commands: { development: { dredd: { command: lazyRequire('../commands/dredd'), description: 'Runs dredd in current project', settings: true, }, }, }, hooks: { 'run-dev-command': { description: 'Used to start dev server used for dredd testing', }, }, };
import { lazyFunctionRequire } from 'roc'; import config from '../config/roc.config.js'; import meta from '../config/roc.config.meta.js'; const lazyRequire = lazyFunctionRequire(require); export default { config, meta, actions: [ { hook: 'server-started', description: 'Run dredd tests', action: lazyRequire('../actions/dredd'), }, ], commands: { development: { dredd: { command: lazyRequire('../commands/dredd'), description: 'Runs dredd in current project', }, }, }, hooks: { 'run-dev-command': { description: 'Used to start dev server used for dredd testing', }, }, };
Remove superflous settings option on dredd command
Remove superflous settings option on dredd command
JavaScript
mit
voldern/roc-plugin-dredd
83314d1d646ffa3ec5e668ecdc5ae0bbbabfaad8
app/scripts/collections/section.js
app/scripts/collections/section.js
define([ 'underscore', 'backbone', 'models/section', 'config' ], function (_, Backbone, Section, config) { 'use strict'; var SectionCollection = Backbone.Collection.extend({ model: Section, initialize: function(models, options) { if (options) { this.resume = options.resume; } this.fetched = false; this.listenTo(this, 'reset', function() { this.fetched = true }); }, url: function() { if (this.resume) { return config.domain + '/rez/resumes/' + this.resume.id + '/sections'; } else { return config.domain + '/rez/sections'; } }, parse: function(response, options) { return response.sections; } }); return SectionCollection; });
define([ 'underscore', 'backbone', 'models/section', 'config' ], function (_, Backbone, Section, config) { 'use strict'; var SectionCollection = Backbone.Collection.extend({ model: Section, initialize: function(models, options) { if (options) { this.resume = options.resume; } this.fetched = false; this.listenTo(this, 'reset', function() { this.fetched = true }); }, url: function() { return config.domain + '/rez/sections'; }, parse: function(response, options) { return response.sections; } }); return SectionCollection; });
Fix url to be not nested.
Fix url to be not nested.
JavaScript
mit
jmflannery/jackflannery.me,jmflannery/jackflannery.me,jmflannery/rez-backbone,jmflannery/rez-backbone
7b3f810e466248d77218a3d59bd674386ff9bd97
src/DB/Mongo.js
src/DB/Mongo.js
var path = require('path'); var fs = require('extfs'); var mongoose = require('mongoose'); import { AbstractDB } from './AbstractDB'; import { Core } from '../Core/Core'; export class Mongo extends AbstractDB { constructor(uri, options) { super(uri, options); } /** * Connect to mongodb * * @return {Promise} */ connect() { this._linkMongoose(); return new Promise((resolve, reject) => { mongoose.connect(this.uri, this.options); this.connection = mongoose.connection; this.connection.on('connected', () => { this.isOpen = true; resolve(this.connection) }); this.connection.on('error', reject); }); } /** * Close connection with mongodb */ close() { this.isOpen = false; return this.connection.close(); } /** * If the app has mongoose installed, replace its mongoose module with the mongoose module of rode * * @private */ _linkMongoose() { var mongoosePath = path.join(__rodeBase, 'node_modules', 'mongoose'); var appMongoosePath = path.join(Core.instance.getPath('node_modules'), 'mongoose'); if (fs.existsSync(appMongoosePath)) { fs.removeSync(appMongoosePath); fs.symlinkSync(mongoosePath, appMongoosePath); } } }
var path = require('path'); var fs = require('extfs'); var mongoose = require('mongoose'); import { AbstractDB } from './AbstractDB'; import { Core } from '../Core/Core'; export class Mongo extends AbstractDB { constructor(uri, options) { super(uri, options); } /** * Connect to mongodb * * @return {Promise} */ connect() { this._linkMongoose(); return new Promise((resolve, reject) => { mongoose.connect(this.uri, this.options); this.connection = mongoose.connection; this.connection.on('connected', () => { this.isOpen = true; resolve(this.connection) }); this.connection.on('error', reject); }); } /** * Close connection with mongodb */ close() { this.isOpen = false; return this.connection.close(); } /** * If the app has mongoose installed, replace its mongoose module with the mongoose module of rode * * @private */ _linkMongoose() { var mongoosePath = path.join(__rodeBase, 'node_modules', 'mongoose'); var appMongoosePath = path.join(Core.instance.getPath('node_modules'), 'mongoose'); if (fs.existsSync(mongoosePath) && fs.existsSync(appMongoosePath)) { fs.removeSync(appMongoosePath); fs.symlinkSync(mongoosePath, appMongoosePath); } } }
Fix a bug if mongoose path does not exist
Fix a bug if mongoose path does not exist
JavaScript
mit
marian2js/rode
3221f816bc32adee59d03fd9b5549507384f5b08
test/disk.js
test/disk.js
var Disk = require( '../' ) var BlockDevice = require( 'blockdevice' ) var assert = require( 'assert' ) const DISK_IMAGE = __dirname + '/data/bootcamp-osx-win.bin' describe( 'Disk', function( t ) { var device = null var disk = null it( 'init block device', function() { assert.doesNotThrow( function() { device = new BlockDevice({ path: DISK_IMAGE, mode: 'r', blockSize: 512 }) }) }) it( 'init disk with device', function() { assert.doesNotThrow( function() { disk = new Disk( device ) }) }) it( 'disk.open()', function( next ) { disk.open( function( error ) { next( error ) }) }) it( 'repeat disk.open()', function( next ) { disk.open( function( error ) { next( error ) }) }) it( 'disk.close()', function( next ) { disk.close( function( error ) { next( error ) }) }) })
var Disk = require( '../' ) var BlockDevice = require( 'blockdevice' ) var assert = require( 'assert' ) ;[ 'apple-mac-osx-10.10.3.bin', 'bootcamp-osx-win.bin', 'usb-thumb-exfat.bin', 'usb-thumb-fat.bin' ].forEach( function( filename ) { const DISK_IMAGE = __dirname + '/data/' + filename describe( 'Disk ' + filename, function( t ) { var device = null var disk = null it( 'init block device', function() { assert.doesNotThrow( function() { device = new BlockDevice({ path: DISK_IMAGE, mode: 'r', blockSize: 512 }) }) }) it( 'init disk with device', function() { assert.doesNotThrow( function() { disk = new Disk( device ) }) }) it( 'disk.open()', function( next ) { disk.open( function( error ) { next( error ) }) }) it( 'repeat disk.open()', function( next ) { disk.open( function( error ) { next( error ) }) }) it( 'disk.close()', function( next ) { disk.close( function( error ) { next( error ) }) }) }) })
Update test: Run against all test images
Update test: Run against all test images
JavaScript
mit
jhermsmeier/node-disk
170248b70dfe6b4eb9eb476919c19fb98a2e88c8
examples/jquery/http-request.js
examples/jquery/http-request.js
// jQuery built with "grunt custom:-ajax/script,-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-event,-event/alias,-offset,-wrap,-ready,-deferred,-exports/amd,-sizzle" // https://github.com/jquery/jquery#how-to-build-your-own-jquery var $ = require("./lib/jquery.min.js"); var MARGIN = 12; var page = tabris.create("Page", { title: "XMLHttpRequest", topLevel: true }); var createLabel = function(labelText) { tabris.create("Label", { text: labelText, markupEnabled: true, layoutData: {left: MARGIN, right: MARGIN, top: [page.children().last() || 0, MARGIN]} }).appendTo(page); }; $.getJSON("http://www.telize.com/geoip", function(json) { createLabel("The IP address is: " + json.ip); createLabel("Latitude: " + json.latitude); createLabel("Longitude: " + json.longitude); }); page.open();
// jQuery built with "grunt custom:-ajax/script,-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-event,-event/alias,-offset,-wrap,-ready,-deferred,-exports/amd,-sizzle" // https://github.com/jquery/jquery#how-to-build-your-own-jquery var $ = require("./lib/jquery.min.js"); var MARGIN = 12; var page = tabris.create("Page", { title: "XMLHttpRequest", topLevel: true }); var createTextView = function(text) { tabris.create("TextView", { text: text, markupEnabled: true, layoutData: {left: MARGIN, right: MARGIN, top: [page.children().last() || 0, MARGIN]} }).appendTo(page); }; $.getJSON("http://www.telize.com/geoip", function(json) { createTextView("The IP address is: " + json.ip); createTextView("Latitude: " + json.latitude); createTextView("Longitude: " + json.longitude); }); page.open();
Rename "Label" to "TextView" in jquery example
Rename "Label" to "TextView" in jquery example Done to reflect eclipsesource/tabris-js@ca0f105e82a2d27067c9674ecf71a93af2c7b7bd Change-Id: I1c267e0130809077c1339ba0395da1a7e1c6b281
JavaScript
bsd-3-clause
moham3d/tabris-js,mkostikov/tabris-js,mkostikov/tabris-js,softnep0531/tabrisjs,softnep0531/tabrisjs,pimaxdev/tabris,pimaxdev/tabris,eclipsesource/tabris-js,moham3d/tabris-js,eclipsesource/tabris-js,eclipsesource/tabris-js
69914fdba918b1a8c38d9f8b08879d5d3d213132
test/trie.js
test/trie.js
var Trie = require('../app/trie'); describe('Trie', function() { var trie; beforeEach(function() { trie = new Trie(); }); it('should be an object', function() { expect(trie).to.be.ok; }); it('should have a root', function() { expect(trie.root).to.be.ok; }); it('should have add method', function() { expect(trie.add).to.be.an.instanceof(Function); }); it('should have search method', function() { expect(trie.search).to.be.an.instanceof(Function); }); it('should have find method', function() { expect(trie.find).to.be.an.instanceof(Function); }); it('should add string to trie', function() { expect(trie.add('test')).to.be.undefined; }); it('should correctly find an added string', function() { trie.add('test'); expect(trie.find('test')).to.be.true; }); it('should trim leading/trailing spaces when adding a string', function() { trie.add(' test '); expect(trie.find('test')).to.be.true; }); });
var Trie = require('../app/trie'); describe('Trie', function() { var trie; beforeEach(function() { trie = new Trie(); }); it('should be an object', function() { expect(trie).to.be.ok; }); it('should have a root', function() { expect(trie.root).to.be.ok; }); it('should have add method', function() { expect(trie.add).to.be.an.instanceof(Function); }); it('should have search method', function() { expect(trie.search).to.be.an.instanceof(Function); }); it('should have find method', function() { expect(trie.find).to.be.an.instanceof(Function); }); it('should add string without errors', function() { expect(trie.add('test')).to.be.undefined; }); it('should find an added string', function() { trie.add('test'); expect(trie.find('test')).to.be.true; }); it('should trim leading/trailing spaces when adding a string', function() { trie.add(' test '); expect(trie.find('test')).to.be.true; }); });
Reword test for add string and find string
Reword test for add string and find string
JavaScript
mit
mgarbacz/nordrassil,mgarbacz/nordrassil
7749879e6c083bd9c5c4d5fc2244399c3cd5e861
releaf-core/app/assets/javascripts/releaf/include/store_settings.js
releaf-core/app/assets/javascripts/releaf/include/store_settings.js
jQuery(function(){ var body = jQuery('body'); var settings_path = body.data('settings-path'); body.on('settingssave', function( event, key_or_settings, value ) { if (!settings_path) { return; } var settings = key_or_settings; if (typeof settings === "string") { settings = {}; settings[key_or_settings] = value; } jQuery.ajax({ url: settings_path, data: { "settings": settings}, headers: { 'X-CSRF-Token': $('meta[name=csrf-token]').attr('content') }, type: 'POST', dataType: 'json' }); }); });
jQuery(function(){ var body = jQuery('body'); var settings_path = body.data('settings-path'); body.on('settingssave', function( event, key_or_settings, value ) { if (!settings_path) { return; } var settings = key_or_settings; if (typeof settings === "string") { settings = {}; settings[key_or_settings] = value; } LiteAjax.ajax({ url: settings_path, method: 'POST', data: { "settings": settings}, json: true }) }); });
Use vanilla-ujs LiteAjax for user settings sending
Use vanilla-ujs LiteAjax for user settings sending
JavaScript
mit
cubesystems/releaf,cubesystems/releaf,graudeejs/releaf,graudeejs/releaf,cubesystems/releaf,graudeejs/releaf
0fa905726bc545f6809aac20c7a3c8579dadb647
bin/collider-run.js
bin/collider-run.js
#!/usr/bin/env node 'use strict'; var pkg = require('../package.json') var cli = require('commander'); var fs = require('fs'); var path = require('path'); var spawn = require('child_process').spawn; cli .version( pkg.version ) .parse( process.argv ); var cwd = process.cwd(); var colliderFile = path.join( cwd, 'project', '.collider'); // Check if a Collider-file exists in the current working directory before running Gulp. fs.access( colliderFile, fs.F_OK, function(error) { if(error) { console.log('A Collider-file could not be found in this directory.'); } else { spawn('./node_modules/.bin/gulp', ['default'], { stdio: 'inherit' }); } });
#!/usr/bin/env node 'use strict'; var pkg = require('../package.json') var cli = require('commander'); var createError = require('../lib/createError'); var logErrorExit = require('../lib/logErrorExit'); var fs = require('fs'); var path = require('path'); var spawn = require('child_process').spawn; cli .version( pkg.version ) .parse( process.argv ); var cwd = process.cwd(); var colliderFile = path.join( cwd, 'project', '.collider'); // Check if a Collider-file exists in the current working directory before running Gulp. fs.access( colliderFile, fs.F_OK, function(err) { if(err) { var err = createError("a Collider-file couldn't be found. Is this a Collider project?"); logErrorExit( err, true ); } else { spawn('./node_modules/.bin/gulp', ['default'], { stdio: 'inherit' }); } });
Use creatError and logErrorExit to handle errors
Use creatError and logErrorExit to handle errors
JavaScript
mit
simonsinclair/collider-cli
4ccd6bf73b26f9910827bf5bd487bcd30e0b24c0
example/__tests__/example-test.js
example/__tests__/example-test.js
import path from 'path'; import webpack from 'webpack'; import config from '../webpack.config'; describe('example', () => { it('combines loader results into one object', () => new Promise(resolve => { webpack(config, (error, stats) => { const bundlePath = path.resolve( stats.compilation.compiler.outputPath, stats.toJson().assetsByChunkName.main, ); expect(require(bundlePath)).toEqual({ raw: '---\ntitle: Example\n---\n\nSome markdown\n', frontmatter: { title: 'Example' }, content: '<p>Some markdown</p>\n', }); resolve(); }); })); });
import path from 'path'; import webpack from 'webpack'; import config from '../webpack.config'; describe('example', () => { jest.setTimeout(10000); // 10 second timeout it('combines loader results into one object', () => new Promise(resolve => { webpack(config, (error, stats) => { const bundlePath = path.resolve( stats.compilation.compiler.outputPath, stats.toJson().assetsByChunkName.main, ); expect(require(bundlePath)).toEqual({ raw: '---\ntitle: Example\n---\n\nSome markdown\n', frontmatter: { title: 'Example' }, content: '<p>Some markdown</p>\n', }); resolve(); }); })); });
Use a 10-second timeout for the Jest test
Use a 10-second timeout for the Jest test
JavaScript
mit
elliottsj/combine-loader
42e2cac9631969f51352f1c1d04cde129caa0dee
Resources/public/ol6-compat.js
Resources/public/ol6-compat.js
(function () { "use strict"; if (window.ol && ol.source && !ol.source.VectorEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/source/VectorEventType.js ol.source.VectorEventType = { ADDFEATURE: 'addfeature', CHANGEFEATURE: 'changefeature', CLEAR: 'clear', REMOVEFEATURE: 'removefeature' }; } if (window.ol && !ol.ObjectEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/ObjectEventType.js ol.ObjectEventType = { PROPERTYCHANGE: 'propertychange' }; } if (window.ol && ol.interaction && !ol.interaction.ModifyEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/interaction/Modify.js#L64 ol.interaction.ModifyEventType = { MODIFYSTART: 'modifystart', MODIFYEND: 'modifyend' }; } })();
(function () { "use strict"; if (window.ol && ol.source && !ol.source.VectorEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/source/VectorEventType.js ol.source.VectorEventType = { ADDFEATURE: 'addfeature', CHANGEFEATURE: 'changefeature', CLEAR: 'clear', REMOVEFEATURE: 'removefeature' }; } if (window.ol && !ol.ObjectEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/ObjectEventType.js ol.ObjectEventType = { PROPERTYCHANGE: 'propertychange' }; } if (window.ol && ol.interaction && !ol.interaction.ModifyEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/interaction/Modify.js#L64 ol.interaction.ModifyEventType = { MODIFYSTART: 'modifystart', MODIFYEND: 'modifyend' }; } if (window.ol && ol.interaction && !ol.interaction.TranslateEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/interaction/Translate.js#L12 ol.interaction.TranslateEventType = { TRANSLATESTART: 'translatestart', TRANSLATING: 'translating', TRANSLATEEND: 'translateend' }; } })();
Fix "moveFeature" tool initialization errors
Fix "moveFeature" tool initialization errors
JavaScript
mit
mapbender/mapbender-digitizer,mapbender/mapbender-digitizer
83c53032c97e74bff2ba97f1a798ab28cad6f31d
shaders/chunks/normal-perturb.glsl.js
shaders/chunks/normal-perturb.glsl.js
module.exports = /* glsl */ ` #if !defined(USE_TANGENTS) && (defined(USE_NORMAL_MAP) || defined(USE_CLEAR_COAT_NORMAL_MAP)) //http://www.thetenthplanet.de/archives/1180 mat3 cotangentFrame(vec3 N, vec3 p, vec2 uv) { // get edge vectors of the pixel triangle vec3 dp1 = dFdx(p); vec3 dp2 = dFdy(p); vec2 duv1 = dFdx(uv); vec2 duv2 = dFdy(uv); // solve the linear system vec3 dp2perp = cross(dp2, N); vec3 dp1perp = cross(N, dp1); vec3 T = dp2perp * duv1.x + dp1perp * duv2.x; vec3 B = dp2perp * duv1.y + dp1perp * duv2.y; // construct a scale-invariant frame float invmax = 1.0 / sqrt(max(dot(T,T), dot(B,B))); return mat3(normalize(T * invmax), normalize(B * invmax), N); } vec3 perturb(vec3 map, vec3 N, vec3 V, vec2 texcoord) { mat3 TBN = cotangentFrame(N, -V, texcoord); return normalize(TBN * map); } #endif `
module.exports = /* glsl */ ` #if !defined(USE_TANGENTS) && (defined(USE_NORMAL_MAP) || defined(USE_CLEAR_COAT_NORMAL_MAP)) //http://www.thetenthplanet.de/archives/1180 mat3 cotangentFrame(vec3 N, vec3 p, vec2 uv) { // get edge vectors of the pixel triangle highp vec3 dp1 = dFdx(p); highp vec3 dp2 = dFdy(p); highp vec2 duv1 = dFdx(uv); highp vec2 duv2 = dFdy(uv); // solve the linear system vec3 dp2perp = cross(dp2, N); vec3 dp1perp = cross(N, dp1); vec3 T = dp2perp * duv1.x + dp1perp * duv2.x; vec3 B = dp2perp * duv1.y + dp1perp * duv2.y; // construct a scale-invariant frame float invmax = 1.0 / sqrt(max(dot(T,T), dot(B,B))); return mat3(normalize(T * invmax), normalize(B * invmax), N); } vec3 perturb(vec3 map, vec3 N, vec3 V, vec2 texcoord) { mat3 TBN = cotangentFrame(N, -V, texcoord); return normalize(TBN * map); } #endif `
Use highp for derivatives calculations in perturb normal
Use highp for derivatives calculations in perturb normal Fixes #258
JavaScript
mit
pex-gl/pex-renderer,pex-gl/pex-renderer
7783b4bc586b8522cfe5f516c90051133e06fe84
feature-detects/css/animations.js
feature-detects/css/animations.js
/*! { "name": "CSS Animations", "property": "cssanimations", "caniuse": "css-animation", "polyfills": ["transformie", "csssandpaper"], "tags": ["css"], "warnings": ["Android < 4 will pass this test, but can only animate a single property at a time"], "notes": [{ "name" : "Article: 'Dispelling the Android CSS animation myths'", "href": "http://goo.gl/CHVJm" }] } !*/ /* DOC Detects wether or not elements can be animated using CSS */ define(['Modernizr', 'testAllProps'], function( Modernizr, testAllProps ) { Modernizr.addTest('cssanimations', testAllProps('animationName', 'a', true)); });
/*! { "name": "CSS Animations", "property": "cssanimations", "caniuse": "css-animation", "polyfills": ["transformie", "csssandpaper"], "tags": ["css"], "warnings": ["Android < 4 will pass this test, but can only animate a single property at a time"], "notes": [{ "name" : "Article: 'Dispelling the Android CSS animation myths'", "href": "http://goo.gl/OGw5Gm" }] } !*/ /* DOC Detects wether or not elements can be animated using CSS */ define(['Modernizr', 'testAllProps'], function( Modernizr, testAllProps ) { Modernizr.addTest('cssanimations', testAllProps('animationName', 'a', true)); });
Fix broken link in comment
Fix broken link in comment
JavaScript
mit
Modernizr/Modernizr,Modernizr/Modernizr
a8994cdafba3a7f550ea5507530a06a056313dd2
app/assets/javascripts/application.js
app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); finishedLoading(); function startLoading() { loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 5000); } $('a.close').click(function() { var qqq = $(this).closest('.modal'); $(qqq).removeClass('active'); });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); function startLoading() { loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 5000); }
Remove finishedLoading() call, remove a.close on click method - not using, it was there for trying out items purposes
Remove finishedLoading() call, remove a.close on click method - not using, it was there for trying out items purposes
JavaScript
mit
fma2/nyc-high-school-programs,fma2/nyc-high-school-programs
6da644a00f47a7bf6a238ebed701d8b8677316b9
app/assets/javascripts/rating_form.js
app/assets/javascripts/rating_form.js
$(document).ready(function() { $("#progress").on('submit', '.new_rating', function(event) { event.preventDefault(); const $form = $(this), url = $form.attr('action'), method = $form.attr('method'), data = $form.serialize(); $.ajax({ url: url, method: method, data: data, dataType: "json" }) .success(function(response) { $form.closest('.modal')[0].style.display = "none"; // update score $form.closest('.collection-item').find('.current-score').text(response[0].score); // update goal partial $form.closest('.collection-item').find('.rating-partials-container') .prepend('<div class="rating-partial"><p class="confidence_score">Score: ' + response[0].score + '</p><p class="rating_comment">Comment: ' + response[0].comment + '</p></div>'); // update progress bar $('.current-level').text(response[1]); $('.progress-bar').css("width:" + response[2] + "%"); }) .fail(function(error) { console.log(error); }) }); });
$(document).ready(function() { $("#progress").on('submit', '.new_rating', function(event) { event.preventDefault(); const $form = $(this), url = $form.attr('action'), method = $form.attr('method'), data = $form.serialize(); $.ajax({ url: url, method: method, data: data, dataType: "json" }) .success(function(response) { $form.trigger('reset'); $form.closest('.modal')[0].style.display = "none"; // update score $form.closest('.collection-item').find('.current-score').text(response[0].score); // update goal partial $form.closest('.collection-item').find('.rating-partials-container') .prepend('<div class="rating-partial"><p class="confidence_score">Score: ' + response[0].score + '</p><p class="rating_comment">Comment: ' + response[0].comment + '</p></div>'); // update progress bar $('.current-level').text(response[1]); $('.progress-bar').css("width:" + response[2] + "%"); }) .fail(function(error) { console.log(error); }) }); });
Refactor rating jquery to clear rating form on submit
Refactor rating jquery to clear rating form on submit
JavaScript
mit
AliasHendrickson/progress,AliasHendrickson/progress,AliasHendrickson/progress
c6bf12e83cdf792c986b3fc4348a0165fe569e8a
frontend/src/Lists/ListsView.js
frontend/src/Lists/ListsView.js
import React, { Component } from "react"; import styled from "styled-components"; import { Row, RowContent, ColumnContainer } from "../SharedComponents.js"; import Loading from "../loading.js"; import List from "./List.js"; import CreateList from "./CreateList.js"; import Notes from "./Notes.js"; class ListsView extends Component { render() { const { user, lists, loading } = this.props; if (loading) { return <Loading />; } return ( <ColumnContainer> <Row> <RowContent> Du är: {user.nick} </RowContent> </Row> <ListsContainer> {lists.map(list => <List key={list.id} list={list} user={user} />)} <Notes /> {user.isAdmin && <CreateList />} </ListsContainer> </ColumnContainer> ); } } const ListsContainer = styled(Row)` padding-top: 2em; `; export default ListsView;
import React, { Component } from "react"; import styled from "styled-components"; import { Row, RowContent, ColumnContainer } from "../SharedComponents.js"; import Loading from "../loading.js"; import List from "./List.js"; import CreateList from "./CreateList.js"; import Notes from "./Notes.js"; class ListsView extends Component { render() { const { user, lists, loading } = this.props; if (loading) { return <Loading />; } return ( <ColumnContainer> <Row> <RowContent> Du är: {user.nick} </RowContent> </Row> <MainContainer> <ListContainer width={(lists.length - 2) * 20}> {lists.map(list => <List key={list.id} list={list} user={user} />)} </ListContainer> {user.isAdmin && <CreateList />} <Notes /> </MainContainer> </ColumnContainer> ); } } const ListContainer = Row.extend` margin-left: -${props => props.width}em; `; const MainContainer = styled(Row)` padding-top: 2em; `; export default ListsView;
Move lists to the left
Move lists to the left
JavaScript
mit
Tejpbit/talarlista,Tejpbit/talarlista,Tejpbit/talarlista
cf530df7cebd995e5742b4be488fa3c765d267e6
te-append.js
te-append.js
#!/usr/bin/env node 'use strict'; const program = require('commander'); const addLineNumbers = require('add-line-numbers'); const fs = require('fs'); const listAndRun = require('./list-and-run').listAndRun; const path = '/tmp/te'; program.parse(process.argv); const line = '\n' + program.args; fs.appendFileSync(path, line); listAndRun();
#!/usr/bin/env node 'use strict'; const program = require('commander'); const fs = require('fs'); const listAndRun = require('./list-and-run').listAndRun; const path = '/tmp/te'; program.parse(process.argv); const line = program.args; const file = fs.readFileSync(path, 'utf8'); var lines = []; if (file.length) { var lines = file.split('\n'); } lines.push(line); fs.writeFileSync(path, lines.join('\n')); listAndRun();
Make sure append doesn't create an empty line when the first line of code is added
Make sure append doesn't create an empty line when the first line of code is added
JavaScript
mit
gudnm/te
9c21194c68654e2152d70a28cc9261b13a2035a4
lib/api/middlewares/last-updated-time-layergroup.js
lib/api/middlewares/last-updated-time-layergroup.js
'use strict'; module.exports = function setLastUpdatedTimeToLayergroup () { return function setLastUpdatedTimeToLayergroupMiddleware (req, res, next) { const { mapConfigProvider, analysesResults } = res.locals; const layergroup = res.body; mapConfigProvider.createAffectedTables((err, affectedTables) => { if (err) { return next(err); } if (!affectedTables) { return next(); } var lastUpdateTime = affectedTables.getLastUpdatedAt(); lastUpdateTime = getLastUpdatedTime(analysesResults, lastUpdateTime) || lastUpdateTime; // last update for layergroup cache buster layergroup.layergroupid = layergroup.layergroupid + ':' + lastUpdateTime; layergroup.last_updated = new Date(lastUpdateTime).toISOString(); res.locals.cache_buster = lastUpdateTime; next(); }); }; }; function getLastUpdatedTime (analysesResults, lastUpdateTime) { if (!Array.isArray(analysesResults)) { return lastUpdateTime; } return analysesResults.reduce(function (lastUpdateTime, analysis) { return analysis.getNodes().reduce(function (lastNodeUpdatedAtTime, node) { var nodeUpdatedAtDate = node.getUpdatedAt(); var nodeUpdatedTimeAt = (nodeUpdatedAtDate && nodeUpdatedAtDate.getTime()) || 0; return nodeUpdatedTimeAt > lastNodeUpdatedAtTime ? nodeUpdatedTimeAt : lastNodeUpdatedAtTime; }, lastUpdateTime); }, lastUpdateTime); }
'use strict'; module.exports = function setLastUpdatedTimeToLayergroup () { return function setLastUpdatedTimeToLayergroupMiddleware (req, res, next) { const { mapConfigProvider, analysesResults } = res.locals; const layergroup = res.body; mapConfigProvider.createAffectedTables((err, affectedTables) => { if (err) { return next(err); } if (!affectedTables) { res.locals.cache_buster = 0; layergroup.layergroupid = `${layergroup.layergroupid}:${res.locals.cache_buster}`; layergroup.last_updated = new Date(res.locals.cache_buster).toISOString(); return next(); } var lastUpdateTime = affectedTables.getLastUpdatedAt(); lastUpdateTime = getLastUpdatedTime(analysesResults, lastUpdateTime) || lastUpdateTime; // last update for layergroup cache buster layergroup.layergroupid = layergroup.layergroupid + ':' + lastUpdateTime; layergroup.last_updated = new Date(lastUpdateTime).toISOString(); res.locals.cache_buster = lastUpdateTime; next(); }); }; }; function getLastUpdatedTime (analysesResults, lastUpdateTime) { if (!Array.isArray(analysesResults)) { return lastUpdateTime; } return analysesResults.reduce(function (lastUpdateTime, analysis) { return analysis.getNodes().reduce(function (lastNodeUpdatedAtTime, node) { var nodeUpdatedAtDate = node.getUpdatedAt(); var nodeUpdatedTimeAt = (nodeUpdatedAtDate && nodeUpdatedAtDate.getTime()) || 0; return nodeUpdatedTimeAt > lastNodeUpdatedAtTime ? nodeUpdatedTimeAt : lastNodeUpdatedAtTime; }, lastUpdateTime); }, lastUpdateTime); }
Set cache buster equal to 0 when there is no affected tables in the mapconfig
Set cache buster equal to 0 when there is no affected tables in the mapconfig
JavaScript
bsd-3-clause
CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb
79f3d9a6a7ca614dce7fb0444d3799d9d55f198c
assets/js/theme/global/mobile-menu.js
assets/js/theme/global/mobile-menu.js
import $ from 'jquery'; export default function() { const $mobileMenuTrigger = $('[data-mobilemenu]'); const $header = $('.header'); const headerHeight = $('.header').outerHeight(); const $mobileMenu = $('#mobile-menu'); function mobileMenu() { $mobileMenuTrigger.on('click', toggleMobileMenu); } function toggleMobileMenu(e) { e.preventDefault(); calculateMobileMenuOffset(); targetMenuItemID = $mobileMenuTrigger.data('mobilemenu'); $mobileMenuTrigger.toggleClass('is-open').attr('aria-expanded', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); $mobileMenu.toggleClass('is-open').attr('aria-hidden', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); } function calculateMobileMenuOffset() { $mobileMenu.attr('style', (i, attr) => { return attr !== `top:${headerHeight}px` ? `top:${headerHeight}px` : 'top:auto'; }); $header.attr('style', (i, attr) => { return attr === 'height:100%' ? 'height:auto' : 'height:100%'; }); } if ($mobileMenuTrigger.length) { mobileMenu(); } }
import $ from 'jquery'; export default function() { const $mobileMenuTrigger = $('[data-mobilemenu]'); const $header = $('.header'); const headerHeight = $('.header').outerHeight(); const $mobileMenu = $('#mobile-menu'); function mobileMenu() { $mobileMenuTrigger.on('click', toggleMobileMenu); } function toggleMobileMenu(e) { e.preventDefault(); calculateMobileMenuOffset(); $mobileMenuTrigger.toggleClass('is-open').attr('aria-expanded', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); $mobileMenu.toggleClass('is-open').attr('aria-hidden', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); } function calculateMobileMenuOffset() { $mobileMenu.attr('style', (i, attr) => { return attr !== `top:${headerHeight}px` ? `top:${headerHeight}px` : 'top:auto'; }); $header.attr('style', (i, attr) => { return attr === 'height:100%' ? 'height:auto' : 'height:100%'; }); } if ($mobileMenuTrigger.length) { mobileMenu(); } }
Fix mobile hamburger menu contents not appearing
Fix mobile hamburger menu contents not appearing
JavaScript
mit
aaronrodier84/flukerfarms,juancho1/bauhaus,PascalZajac/cornerstone,bigcommerce/stencil,PeteyRev/ud-revamp,aaronrodier84/rouxbrands,bigcommerce/stencil,mcampa/cornerstone,rho1140/cornerstone,ovsokolov/dashconnect-bc,mcampa/cornerstone,PeteyRev/ud-revamp,juancho1/bauhaus,bc-annavu/stencil,aaronrodier84/rouxbrands,mcampa/cornerstone,ovsokolov/dashconnect-bc,bc-annavu/stencil,aaronrodier84/flukerfarms,aaronrodier84/rouxbrands,rho1140/cornerstone,caras-ey/BST,rho1140/cornerstone,caras-ey/BST,bigcommerce/stencil,juancho1/bauhaus,PascalZajac/cornerstone,PeteyRev/ud-revamp,bc-annavu/stencil,caras-ey/BST,aaronrodier84/flukerfarms,ovsokolov/dashconnect-bc,PascalZajac/cornerstone
9557e87a24a1b6d33cef2bce1231f9d9b2a35602
app/components/Auth/Auth.js
app/components/Auth/Auth.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import jwtDecode from 'jwt-decode'; import styles from './styles.scss'; import Login from './Login'; import Signup from './Signup'; import Info from './Info'; import { addUser } from '../../actions/user'; const mapDispatchToProps = dispatch => ({ addUserFromToken: token => dispatch(addUser(jwtDecode(token))), }); class Auth extends Component { state = { isNewUser: false } toggleNewUser = () => { this.setState({ isNewUser: !this.state.isNewUser }); } render() { const { addUserFromToken } = this.props; const { isNewUser } = this.state; return ( <div className={styles.Auth}> <div className={[styles.AuthBox, isNewUser ? '' : styles.OldUser].join(' ')}> { isNewUser ? <Signup switchForm={this.toggleNewUser} addUser={addUserFromToken} /> : <Login switchForm={this.toggleNewUser} addUser={addUserFromToken} /> } <Info message={isNewUser ? 'Take a part in creating better video games!' : 'Welcome back!'} isNewUser={isNewUser} /> </div> </div> ); } } Auth.propTypes = { addUserFromToken: PropTypes.func.isRequired }; export default connect(null, mapDispatchToProps)(Auth);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import jwtDecode from 'jwt-decode'; import styles from './styles.scss'; import Login from './Login'; import Signup from './Signup'; import Info from './Info'; import Controls from '../Controls'; import { addUser } from '../../actions/user'; const mapDispatchToProps = dispatch => ({ addUserFromToken: token => dispatch(addUser(jwtDecode(token))), }); class Auth extends Component { state = { isNewUser: false } toggleNewUser = () => { this.setState({ isNewUser: !this.state.isNewUser }); } render() { const { addUserFromToken } = this.props; const { isNewUser } = this.state; return ( <div className={styles.Auth}> <Controls /> <div className={[styles.AuthBox, isNewUser ? '' : styles.OldUser].join(' ')}> { isNewUser ? <Signup switchForm={this.toggleNewUser} addUser={addUserFromToken} /> : <Login switchForm={this.toggleNewUser} addUser={addUserFromToken} /> } <Info message={isNewUser ? 'Take a part in creating better video games!' : 'Welcome back!'} isNewUser={isNewUser} /> </div> </div> ); } } Auth.propTypes = { addUserFromToken: PropTypes.func.isRequired }; export default connect(null, mapDispatchToProps)(Auth);
Add control buttons to auth
Add control buttons to auth
JavaScript
mit
cdiezmoran/AlphaStage-2.0,cdiezmoran/AlphaStage-2.0
1e1e1e351b3d0a9f4f824e5392de8afea93d5ffe
src/components/posts_index.js
src/components/posts_index.js
import _ from 'lodash'; import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPosts } from '../actions'; class PostsIndex extends React.Component { componentDidMount() { this.props.fetchPosts(); } renderPosts() { return _.map(this.props.posts, (post) => { return ( <li className="list-group-item" key={post.id}> {post.title} </li> ); }); } render() { return ( <div className='posts-index'> <div className='text-xs-right'> <Link className='btn btn-primary' to='/posts/new'> Add a Post </Link> </div> <h3>Posts</h3> <ul className="list-group"> { this.renderPosts() } </ul> </div> ) } } function mapStateToProps(state) { return { posts: state.posts }; } export default connect(mapStateToProps, { fetchPosts: fetchPosts })(PostsIndex);
import _ from 'lodash'; import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPosts } from '../actions'; class PostsIndex extends React.Component { componentDidMount() { this.props.fetchPosts(); } renderPosts() { return _.map(this.props.posts, (post) => { return ( <li className="list-group-item" key={post.id}> <Link to={`/posts/${post.id}`}> {post.title} </Link> </li> ); }); } render() { return ( <div className='posts-index'> <div className='text-xs-right'> <Link className='btn btn-primary' to='/posts/new'> Add a Post </Link> </div> <h3>Posts</h3> <ul className="list-group"> { this.renderPosts() } </ul> </div> ) } } function mapStateToProps(state) { return { posts: state.posts }; } export default connect(mapStateToProps, { fetchPosts: fetchPosts })(PostsIndex);
Add link to link to each page
Add link to link to each page
JavaScript
mit
monsteronfire/redux-learning-blog,monsteronfire/redux-learning-blog
a081e1554614ac92aebe31b0dd514a12484d4ece
app/lib/collections/posts.js
app/lib/collections/posts.js
Posts = new Mongo.Collection('posts'); Posts.allow({ insert: function(userId, doc) { // only allow posting if you are logged in return !! userId; } });
Posts = new Mongo.Collection('posts'); Meteor.methods({ postInsert: function(postAttributes) { check(Meteor.userId(), String); check(postAttributes, { title: String, url: String }); var user = Meteor.user(); var post = _.extend(postAttributes, { userId: user._id, author: user.username, submitted: new Date() }); var postId = Posts.insert(post); return { _id: postId }; } });
Use Meteor.methods to set up post (including user)
Use Meteor.methods to set up post (including user)
JavaScript
mit
drainpip/music-management-system,drainpip/music-management-system
fbae2755bb25ef803cd3508448cb1646868a6618
test/mqtt.js
test/mqtt.js
/** * Testing includes */ var should = require('should'); /** * Unit under test */ var mqtt = require('../lib/mqtt'); describe('mqtt', function() { describe('#createClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); }); describe('#createSecureClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); it('should throw on incorrect args'); }); describe('#createServer', function() { it('should return an MqttServer', function() { var s = mqtt.createServer(); s.should.be.instanceOf(mqtt.MqttServer); }); }); describe('#createSecureServer', function() { it('should return an MqttSecureServer', function() { var s = mqtt.createSecureServer( __dirname + '/helpers/private-key.pem', __dirname + '/helpers/public-cert.pem' ); s.should.be.instanceOf(mqtt.MqttSecureServer); }); }); });
/** * Testing includes */ var should = require('should'); /** * Unit under test */ var mqtt = require('../lib/mqtt'); describe('mqtt', function() { describe('#createClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); }); describe('#createSecureClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); it('should throw on incorrect args'); }); describe('#createServer', function() { it('should return an MqttServer', function() { var s = mqtt.createServer(); s.should.be.instanceOf(mqtt.MqttServer); }); }); describe('#createSecureServer', function() { it('should return an MqttSecureServer', function() { var s = mqtt.createSecureServer( __dirname + '/helpers/private-key.pem', __dirname + '/helpers/public-cert.pem' ); s.should.be.instanceOf(mqtt.MqttSecureServer); }); }); describe('#createConnection', function() { it('should return an MqttConnection', function() { var c = mqtt.createConnection(); c.should.be.instanceOf(mqtt.MqttConnection); }); }); });
Add test for MqttConnection creation
Add test for MqttConnection creation
JavaScript
mit
itavy/MQTT.js,bqevin/MQTT.js,AdySan/MQTT.js,mcanthony/MQTT.js,yunba/MQTT.js,jaambee/MQTT.js,daliworks/MQTT.js,jdiamond/MQTT.js,wesley1001/MQTT.js,authere/MQTT.js,RangerMauve/MQTT.js,1248/MQTT.js
41db6cf165dd083d3b284c961c128db609fcad81
src/extend/getConnectivityMatrix.js
src/extend/getConnectivityMatrix.js
'use strict'; var OCL = require('openchemlib'); module.exports = function getConnectivityMatrix(options={}) { var { sdt, mass } = options; this.ensureHelperArrays(OCL.Molecule.cHelperNeighbours); var nbAtoms=this.getAllAtoms(); var result=new Array(nbAtoms); for (var i=0; i<nbAtoms; i++) { result[i]=new Array(nbAtoms).fill(0); result[i][i]=(mass) ? OCL.Molecule.cRoundedMass[this.getAtomicNo(i)] : 1; } for (var i=0; i<nbAtoms; i++) { for (var j=0; j<this.getAllConnAtoms(i); j++) { result[i][this.getConnAtom(i,j)]=(sdt) ? this.getConnBondOrder(i,j) : 1; } } return result; }
'use strict'; var OCL = require('openchemlib'); module.exports = function getConnectivityMatrix(options) { var options = options || {}; var sdt=options.sdt; var mass=options.mass; this.ensureHelperArrays(OCL.Molecule.cHelperNeighbours); var nbAtoms=this.getAllAtoms(); var result=new Array(nbAtoms); for (var i=0; i<nbAtoms; i++) { result[i]=new Array(nbAtoms).fill(0); result[i][i]=(mass) ? OCL.Molecule.cRoundedMass[this.getAtomicNo(i)] : 1; } for (var i=0; i<nbAtoms; i++) { for (var j=0; j<this.getAllConnAtoms(i); j++) { result[i][this.getConnAtom(i,j)]=(sdt) ? this.getConnBondOrder(i,j) : 1; } } return result; }
Make it compatible with node 4.0
Make it compatible with node 4.0
JavaScript
bsd-3-clause
cheminfo-js/openchemlib-extended
94bc6236e23440d4f3958e601d0ab880b17d09de
public/js/book-app/components/book-app.component.js
public/js/book-app/components/book-app.component.js
;(function() { "use strict"; angular. module("bookApp"). component("bookApp", { template: ` <div class="nav"><a href="new-book">Add new book</a></div> <div class="book-container" ng-repeat="book in $ctrl.books"> <h3>{{book.title}}</h3> <img ng-src="http://theproactiveprogrammer.com/wp-content/uploads/2014/09/js_good_parts.png" alt="" /> <p>{{book.rate}}</p> <p>{{book.author}}</p> <p>{{book.descroption}}</p> </div> `, controller: BookAppController }); BookAppController.$inject = ["$scope"]; function BookAppController($scope) { let vm = this, bookRef = firebase.database().ref("Books"); vm.books = []; bookRef.on("value", function(snapshot) { // vm.users.push(snapshot.val()); snapshot.forEach(function(subSnap) { vm.books.push(subSnap.val()); }); if(!$scope.$$phase) $scope.$apply(); }); } })();
;(function() { "use strict"; angular. module("bookApp"). component("bookApp", { template: ` <div class="nav"><a href="new-book" class="nav-click">Add new book</a></div> <div class="book-container" ng-repeat="book in $ctrl.books"> <h3>{{book.title}}</h3> <img ng-src="http://theproactiveprogrammer.com/wp-content/uploads/2014/09/js_good_parts.png" alt="" /> <p>{{book.rate}}</p> <p>{{book.author}}</p> <p>{{book.descroption}}</p> </div> `, controller: BookAppController }); BookAppController.$inject = ["$scope"]; function BookAppController($scope) { let vm = this, bookRef = firebase.database().ref("Books"); vm.books = []; bookRef.on("value", function(snapshot) { // vm.users.push(snapshot.val()); snapshot.forEach(function(subSnap) { vm.books.push(subSnap.val()); }); if(!$scope.$$phase) $scope.$apply(); }); } })();
Add New Class To Link
Add New Class To Link
JavaScript
mit
fejs-levelup/angular-bookshelf,fejs-levelup/angular-bookshelf
c8b6d8adb8ae1dea1148416acfdfb99502ce281c
app/assets/javascripts/init.js
app/assets/javascripts/init.js
window.atthemovies = { init: function() { var body = document.querySelectorAll("body")[0]; var jsController = body.getAttribute("data-js-controller"); var jsAction = body.getAttribute("data-js-action"); this.pageJS("atthemovies." + jsController + ".init", window); this.pageJS("atthemovies." + jsController + ".init" + jsAction, window); }, pageJS: function(functionName, context) { var namespaces = functionName.split("."); var func = namespaces.pop(); for (var i = 0; i < namespaces.length; i++) { if(context[namespaces[i]]) { context = context[namespaces[i]]; } else { return null; } } if(typeof context[func] === "function") { return context[func].apply(context, null); } else { return null; } } }
window.atthemovies = { init: function() { var body = document.querySelectorAll("body")[0]; var jsController = body.getAttribute("data-js-controller"); var jsAction = body.getAttribute("data-js-action"); this.pageJS("atthemovies." + jsController + ".init", window); this.pageJS("atthemovies." + jsController + ".init" + jsAction, window); }, // pass a string to call a namespaced function that may not exist pageJS: function(functionString, context) { var namespaces = functionString.split("."); var functionName = namespaces.pop(); // recursively loop into existing namespaces, else return harmlessly for (var i = 0; i < namespaces.length; i++) { if(context[namespaces[i]]) { context = context[namespaces[i]]; } else { return null; } } // call the function if it exists in this context, else return harmlessly if(typeof context[functionName] === "function") { return context[functionName].apply(context, null); } else { return null; } } }
Tidy up JS, add commentary
Tidy up JS, add commentary
JavaScript
agpl-3.0
andycroll/atthemovies,andycroll/atthemovies,andycroll/atthemovies,andycroll/atthemovies
d3017cbcd542cc5c310d23c0bd478eae10ceef32
src/modules/ajax/retryAjax.js
src/modules/ajax/retryAjax.js
function doAjax(options, retries, dfr) { $.ajax(options).pipe(function(data) {dfr.resolve(data);}, function(jqXhr) { if (retries > 0) { setTimeout(doAjax, 100, options, retries - 1, dfr); } else { dfr.reject(jqXhr); } }); } export default function retryAjax(options) { var dfr = $.Deferred(); doAjax(options, 10, dfr); return dfr; }
function doAjax(options, retries, dfr) { $.ajax(options).pipe(function(data, textStatus, jqXHR) { dfr.resolve(data, textStatus, jqXHR); }, function(jqXhr, textStatus, errorThrown) { if (retries > 0) { setTimeout(doAjax, 100, options, retries - 1, dfr); } else { dfr.reject(jqXhr, textStatus, errorThrown); } }); } export default function retryAjax(options) { var dfr = $.Deferred(); doAjax(options, 10, dfr); return dfr; }
Return all arguments from AJAX
Return all arguments from AJAX
JavaScript
mit
fallenswordhelper/fallenswordhelper,fallenswordhelper/fallenswordhelper
84c100bbd0fb6749fdcef577690d85beb7aebd34
Gruntfile.js
Gruntfile.js
/* * Copyright 2013, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/node-gh/gh/blob/master/LICENSE.md * * @author Zeno Rocha <zno.rocha@gmail.com> * @author Eduardo Lundgren <zno.rocha@gmail.com> */ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-jsbeautifier'); grunt.initConfig({ jsbeautifier: { files: ['bin/*.js', 'lib/**/*.js', 'test/**/*.js', '*.js'], options: { config: '.jsbeautifyrc' } } }); grunt.registerTask('format', ['jsbeautifier']); };
/* * Copyright 2013, All Rights Reserved. * * Code licensed under the BSD License: * https://github.com/node-gh/gh/blob/master/LICENSE.md * * @author Zeno Rocha <zno.rocha@gmail.com> * @author Eduardo Lundgren <zno.rocha@gmail.com> */ module.exports = function(grunt) { grunt.initConfig({ jsbeautifier: { files: ['bin/*.js', 'lib/**/*.js', 'test/**/*.js', '*.js'], options: { config: '.jsbeautifyrc' } }, jshint: { options: grunt.file.readJSON('.jshintrc'), gruntfile: 'Gruntfile.js', files: { src: [ 'bin/*.js', 'lib/**/*.js' ] }, test: { options: { globals: { describe: true, it: true, beforeEach: true, afterEach: true, before: true, after: true } }, src: 'test/**/*.js' } }, } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-jsbeautifier'); grunt.registerTask('format', ['jsbeautifier']); };
Add jshint as grunt task
Add jshint as grunt task
JavaScript
bsd-3-clause
henvic/gh,TomzxForks/gh,modulexcite/gh,oouyang/gh,oouyang/gh,TomzxForks/gh,tomzx/gh,dustinryerson/gh,modulexcite/gh,henvic/gh,tomzx/gh,dustinryerson/gh
2818b0138520fbb0e9702cddef9e5d121b8f5ad1
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ pkg : grunt.file.readJSON( 'package.json' ), env: { casper: { BASEURL: "http://www.google.com", PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:./node_modules/.bin", PHANTOMJS_EXECUTABLE: "node_modules/casperjs/node_modules/.bin/phantomjs" } }, casperjs: { options: { includes: ['includes/include1.js'], test: true }, files: ['tests/**/*.js'] } }); // casperJS Frontend tests grunt.loadNpmTasks( 'grunt-casperjs' ); grunt.loadNpmTasks( 'grunt-env' ); // grunt for Frontend testing grunt.registerTask('default', [ 'env:casper', 'casperjs']); };
module.exports = function(grunt) { grunt.initConfig({ pkg : grunt.file.readJSON( 'package.json' ), env: { casper: { BASEURL: "http://www.google.com", PHANTOMJS_EXECUTABLE: "node_modules/casperjs/node_modules/.bin/phantomjs" } }, casperjs: { options: { includes: ['includes/include1.js'], test: true }, files: ['tests/**/*.js'] } }); // casperJS Frontend tests grunt.loadNpmTasks( 'grunt-casperjs' ); grunt.loadNpmTasks( 'grunt-env' ); grunt.registerTask('extendPATH', 'Add the npm bin dir to PATH', function() { var pathDelimiter = ':'; var extPath = 'node_modules/.bin'; var pathArray = process.env.PATH.split( pathDelimiter ); pathArray.unshift( extPath ); process.env.PATH = pathArray.join( pathDelimiter ); grunt.log.writeln('Extending PATH to be ' + process.env.PATH); }); // grunt for Frontend testing grunt.registerTask('default', [ 'env:casper', 'extendPATH', 'casperjs']); };
Extend the PATH env var instead of replacing it
Extend the PATH env var instead of replacing it
JavaScript
mit
smlgbl/grunt-casperjs-extra
b68b04de0eec208ca389f93b271a52b3db5b8ed7
Tester/src/Tester.js
Tester/src/Tester.js
/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */ "use strict"; import {spawn} from 'child_process'; const EXPOSE_TEST_SCRIPT = './scripts/analyse'; class Tester { constructor(file) { this.file = file; this.out = ""; } build(done) { let env = process.env; env.EXPOSE_EXPECTED_PC = this.file.expectPaths; let prc = spawn(EXPOSE_TEST_SCRIPT, [this.file.path], { env: env }); prc.stdout.setEncoding('utf8'); prc.stderr.setEncoding('utf8'); prc.stdout.on('data', data => this.out += data.toString()); prc.stderr.on('data', data => this.out += data.toString()); prc.on('close', code => done(code)); } } export default Tester;
/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */ "use strict"; import {spawn} from 'child_process'; const EXPOSE_TEST_SCRIPT = './scripts/analyse'; class Tester { constructor(file) { this.file = file; this.out = ""; } build(done) { let env = process.env; env.EXPOSE_EXPECTED_PC = this.file.expectPaths; let prc = spawn(EXPOSE_TEST_SCRIPT, [this.file.path], { env: env }); prc.stdout.setEncoding('utf8'); prc.stderr.setEncoding('utf8'); prc.stdout.on('data', data => this.out += data.toString()); prc.stderr.on('data', data => this.out += data.toString()); const SECOND = 1000; const TIME_WARNING = 30; let longRunningMessage = setTimeout(() => console.log(`\rTEST WARNING: Test case ${this.file.path} is taking an excessive amount of time to complete (over ${TIME_WARNING}s)`), TIME_WARNING * SECOND); prc.on('close', code => { clearTimeout(longRunningMessage); done(code) }); } } export default Tester;
Print warnings when tests are taking ages so we can see which ones it is
Print warnings when tests are taking ages so we can see which ones it is
JavaScript
mit
ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE,ExpoSEJS/ExpoSE
af38d84173285c9ee1203a4cb468a068ae15e2d7
src/scripts/content/visualstudio.js
src/scripts/content/visualstudio.js
/*jslint indent: 2, plusplus: true */ /*global $: false, document: false, togglbutton: false, createTag:false, window: false, MutationObserver: false */ 'use strict'; // Individual Work Item & Backlog page togglbutton.render('.witform-layout-content-container:not(.toggl)', {observe: true}, function () { var link, description = $('.work-item-form-id span').innerText + ' ' + $('.work-item-form-title input').value, project = $('.menu-item.l1-navigation-text.drop-visible .text').textContent.trim(), container = $('.work-item-form-header-controls-container'), vs_activeClassContent = $('.hub-list .menu-item.currently-selected').textContent.trim(); link = togglbutton.createTimerLink({ className: 'visual-studio-online', description: description, projectName: project }); if (vs_activeClassContent === "Work Items*" || vs_activeClassContent === "Backlogs") { container.appendChild(link); } });
/*jslint indent: 2, plusplus: true */ /*global $: false, document: false, togglbutton: false, createTag:false, window: false, MutationObserver: false */ 'use strict'; // Individual Work Item & Backlog page togglbutton.render('.witform-layout-content-container:not(.toggl)', {observe: true}, function () { var link, description = $('.work-item-form-id span').innerText + ' ' + $('.work-item-form-title input').value, project = $('.tfs-selector span').innerText, container = $('.work-item-form-header-controls-container'), vs_activeClassContent = $('.commandbar.header-bottom > .commandbar-item > .displayed').innerText; link = togglbutton.createTimerLink({ className: 'visual-studio-online', description: description, projectName: project }); if (vs_activeClassContent === "Work Items" || vs_activeClassContent === "Backlogs") { container.appendChild(link); } });
Change VSTS integration for markup change
Change VSTS integration for markup change
JavaScript
bsd-3-clause
glensc/toggl-button,glensc/toggl-button,glensc/toggl-button
d4ca275b1229942dca73b4c4ed27a50f893dd6c9
src/touch-action.js
src/touch-action.js
(function() { function selector(v) { return '[touch-action="' + v + '"]'; } function rule(v) { return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }'; } var attrib2css = [ { rule: 'none', selectors: [ 'none', 'user' ] }, 'pan-x', 'pan-y', { rule: 'pan-x pan-y', selectors: [ 'scroll', 'pan-x pan-y', 'pan-y pan-x' ] } ]; var styles = ''; attrib2css.forEach(function(r) { if (String(r) === r) { styles += selector(r) + rule(r); } else { styles += r.selectors.map(selector) + rule(r.rule); } }); var el = document.createElement('style'); el.textContent = styles; document.head.appendChild(el); })();
(function() { function selector(v) { return '[touch-action="' + v + '"]'; } function rule(v) { return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }'; } var attrib2css = [ { rule: 'none', selectors: [ 'none', 'user' ] }, 'pan-x', 'pan-y', { rule: 'pan-x pan-y', selectors: [ 'scroll', 'pan-x pan-y', 'pan-y pan-x' ] } ]; var styles = ''; attrib2css.forEach(function(r) { if (String(r) === r) { styles += selector(r) + rule(r); } else { styles += r.selectors.map(selector) + rule(r.rule); } }); var el = document.createElement('style'); el.textContent = styles; // Use querySelector instead of document.head to ensure that in // ShadowDOM Polyfill that we have a wrapped head to append to. var h = document.querySelector('head'); // document.write + document.head.appendChild = crazytown // use insertBefore instead for correctness in ShadowDOM Polyfill h.insertBefore(el, h.firstChild); })();
Fix inserting touch action stylesheet for Shadow DOM Polyfill
Fix inserting touch action stylesheet for Shadow DOM Polyfill
JavaScript
bsd-3-clause
roblarsen/pointer-events.js
b7fcfc3e333218e30e10187523176d45b6bd297d
lib/Chunk.js
lib/Chunk.js
let zlib = require('zlib'), NBT = require('kld-nbt'), Tag = NBT.Tag, ReadBuffer = NBT.ReadBuffer; module.exports = class Chunk { constructor() { this.data = null; } static loadCompressedChunk(compressedData, compressionFormat) { var data; if (compressionFormat == 1) { data = zlib.gunzipSync(compressedData); } else if (compressionFormat == 2) { data = zlib.unzipSync(compressedData); } else { throw new Error("Unrecognized chunk compression format: " + compressionFormat); } let readBuffer = new ReadBuffer(data); let result = new Chunk(); result.data = Tag.readFromBuffer(readBuffer); result.data.loadFromBuffer(readBuffer); return result; } };
let zlib = require('zlib'), NBT = require('kld-nbt'), Tag = NBT.Tag, ReadBuffer = NBT.ReadBuffer, utils = require('./utils'); module.exports = class Chunk { constructor() { this.data = null; } static loadCompressedChunk(compressedData, compressionFormat) { var data; if (compressionFormat == 1) { data = zlib.gunzipSync(compressedData); } else if (compressionFormat == 2) { data = zlib.unzipSync(compressedData); } else { throw new Error("Unrecognized chunk compression format: " + compressionFormat); } let readBuffer = new ReadBuffer(data); let result = new Chunk(); result.data = Tag.readFromBuffer(readBuffer); result.data.loadFromBuffer(readBuffer); return result; } getBlockType(position) { let section = this.getSection(position); var result = null; if (section !== null) { let blocks = section.findTag("Blocks"); let data = section.findTag("Data"); if (blocks !== null && data != null) { let blockOffset = utils.blockOffsetFromPosition(position); let type = blocks.byteValues[blockOffset]; let dataByte = blocks.byteValues[blockOffset >> 1]; let data = (blockOffset % 2 == 0) ? dataByte & 0x0F : (dataByte >> 4) & 0x0F; result = { type: type, data: data }; } } return result; } getSection(position) { var result = null; if (this.data !== null && 0 <= position.y && position.y < 256) { let chunkY = position.y >> 4; let level = this.data.findTag("Level"); let sections = level.findTag("Sections"); for (var i = 0; i < sections.elements.length; i++) { let candidate = sections.elements[i]; let yIndex = candidate.findTag("Y"); if (yIndex !== null && yIndex.byteValue === chunkY) { result = candidate; break; } } } // TODO: generate new empty section for y index return result; } };
Add ability to get block type for a position
Add ability to get block type for a position
JavaScript
bsd-3-clause
thelonious/kld-mc-world
e0a5f7e093df4ec140a6cc7828633bb6949e0475
client/models/areaOfStudy.js
client/models/areaOfStudy.js
var _ = require('lodash'); var React = require('react'); var RequirementSet = require("./requirementSet"); var AreaOfStudy = React.createClass({ render: function() { console.log('area-of-study render') var areaDetails = []//getAreaOfStudy(this.props.name, this.props.type); var requirementSets = _.map(areaDetails.sets, function(reqset) { return RequirementSet( {key:reqset.description, name: reqset.description, needs: reqset.needs, count: reqset.count, requirements: reqset.reqs, courses: this.props.courses}); }, this); return React.DOM.article( {id:areaDetails.id, className:"area-of-study"}, React.DOM.details(null, React.DOM.summary(null, React.DOM.h1(null, areaDetails.title)), requirementSets ) ); } }); module.exports = AreaOfStudy
var _ = require('lodash'); var React = require('react'); var RequirementSet = require("./requirementSet"); var AreaOfStudy = React.createClass({ render: function() { console.log('area-of-study render') var areaDetails = this.props;//getAreaOfStudy(this.props.name, this.props.type); var requirementSets = _.map(areaDetails.sets, function(reqset) { return RequirementSet({ key:reqset.description, name: reqset.description, needs: reqset.needs, count: reqset.count, requirements: reqset.reqs, courses: this.props.courses }); }, this); return React.DOM.article( {id:areaDetails.id, className:"area-of-study"}, React.DOM.details(null, React.DOM.summary(null, React.DOM.h1(null, areaDetails.title)), requirementSets ) ); } }); module.exports = AreaOfStudy
Clean up the area of study headings
Clean up the area of study headings
JavaScript
agpl-3.0
hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook
a73401e5c10457066171a9ee5060363163ea4e7b
public/modules/core/directives/display-trial-data.client.directive.js
public/modules/core/directives/display-trial-data.client.directive.js
'use strict'; // Display Trial Data for debugging angular.module('core').directive('displayTrialData', function() { return { restrict: 'AE', template: '<div><h3>Trial Data</h3><pre>Subject: {{trialDataJson()}}</pre></div>' } });
'use strict'; // Display Trial Data for debugging angular.module('core').directive('displayTrialData', function() { return { restrict: 'AE', template: '<div><h3>Trial Data</h3><pre>{{trialDataJson()}}</pre></div>' } });
Remove 'Subject:' from displayTrialData text
Remove 'Subject:' from displayTrialData text
JavaScript
mit
brennon/eim,brennon/eim,brennon/eim,brennon/eim
899639def4990c5524d0ca462ebf8f6ab4ca59f5
postcss.config.js
postcss.config.js
module.exports = () => ({ plugins: { 'postcss-easy-import': { extensions: [ '.pcss', '.css', '.postcss', '.sss' ] }, 'stylelint': { configFile: '.stylelintrc' }, 'postcss-mixins': {}, 'postcss-nesting': {}, 'postcss-custom-media': {}, 'postcss-selector-not': {}, 'postcss-discard-comments': {}, 'autoprefixer': { browsers: [ '> 1%', 'last 2 versions', 'Firefox ESR', 'not ie <= 11' ] }, 'cssnano': { preset: 'default' }, 'postcss-reporter': { clearReportedMessages: true, noPlugin: true } } });
module.exports = () => ({ plugins: { 'postcss-easy-import': { extensions: [ '.pcss', '.css', '.postcss', '.sss' ] }, stylelint: { configFile: '.stylelintrc' }, 'postcss-mixins': {}, 'postcss-nesting': {}, 'postcss-custom-media': {}, 'postcss-selector-not': {}, 'postcss-discard-comments': {}, autoprefixer: { browsers: [ '> 1%', 'last 2 versions', 'Firefox ESR', 'not ie <= 11' ] }, cssnano: { preset: 'default' }, 'postcss-reporter': { clearReportedMessages: true, noPlugin: true } } });
Fix quoted postcss plugins name
chore: Fix quoted postcss plugins name
JavaScript
mit
PolymerX/polymer-skeleton,PolymerX/polymer-skeleton
46dd15ee2eef96cd693cea63d4a06b1056533356
app/config/routes.js
app/config/routes.js
export default (app, route) => { route.named('hello') .maps('/hello') .to('hello:index') route.named('foo').maps('/foo/{bar}').to(async (req, res, {bar}) => { res.end(`Foo: ${bar}`) }) route.mounted('/bar', route => { route.named('bar_index').maps('/').to(async (req, res) => { res.end("Bar Index") }) route.named('bar_create').maps('/create').to(async (req, res) => { res.end("Bar Create") }) }) route.named('missing').maps('/missing').to('default:missingRoute') route.named('default').maps('/').to('default:index') }
export default (app, route) => { route.named('hello') .maps('/hello') .to('hello:index') route.named('foo').maps('/foo/{bar}').to(async ({req, res}, {bar}) => { res.end(`Foo: ${bar}`) }) route.mounted('/bar', route => { route.named('bar_index').maps('/').to(async ({req, res}) => { res.end("Bar Index") }) route.named('bar_create').maps('/create').to(async ({req, res}) => { res.end("Bar Create") }) }) route.named('missing').maps('/missing').to('default:missingRoute') route.named('default').maps('/').to('default:index') }
Fix args of inline controllers to use context
Fix args of inline controllers to use context
JavaScript
mit
CHH/learning-node,CHH/learning-node
c40d33e07a2e835f67bbe10e0bad9ceb66bbbf67
webpack.config.js
webpack.config.js
const path = require('path'); const webpack = require('webpack'); const WebpackNotifierPlugin = require('webpack-notifier'); const styleLintPlugin = require('stylelint-webpack-plugin'); const autoprefixer = require('autoprefixer'); const env = process.env.NODE_ENV; module.exports = { devtool: env === 'production' ? 'source-map' : 'eval', entry: './src', output: { path: path.join(__dirname, 'dist'), filename: 'app.js', publicPath: '/', }, plugins: env === 'production' ? [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { // dead_code: true, }, }), ] : [ new styleLintPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new WebpackNotifierPlugin({ title: 'Next-gen Build' }), ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.css$/, exclude: /node_modules/, loader: 'style!css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]' }, { test: /\.js$/, exclude: /node_modules/, loader: 'eslint' }, ], // noParse: /babel/, }, postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ], };
const path = require('path'); const webpack = require('webpack'); const WebpackNotifierPlugin = require('webpack-notifier'); const styleLintPlugin = require('stylelint-webpack-plugin'); const env = process.env.NODE_ENV; module.exports = { devtool: env === 'production' ? 'source-map' : 'eval', entry: './src', output: { path: path.join(__dirname, 'dist'), filename: 'app.js', }, plugins: env === 'production' ? [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin() ] : [ new styleLintPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new WebpackNotifierPlugin({ title: 'Next-gen Build' }), ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.js$/, exclude: /node_modules/, loader: 'eslint' }, { test: /\.css$/, exclude: /node_modules/, loader: 'style!css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]' }, ], }, };
Simplify webpack, unsuccessfull at fixing sourcemap output
Simplify webpack, unsuccessfull at fixing sourcemap output
JavaScript
mit
nazaninreihani/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen,nuruddeensalihu/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen
a7a6a8b5ea4a82660bb0ac7ed290e3d7a6b5c89b
src/store/checkout-store.js
src/store/checkout-store.js
import { Store } from 'consus-core/flux'; import StudentStore from './student-store'; let checkouts = []; let checkoutsByActionId = new Object(null); class CheckoutStore extends Store { getCheckoutByActionId(actionId) { return checkoutsByActionId[actionId]; } } const store = new CheckoutStore(); store.registerHandler('NEW_CHECKOUT', data => { let checkout = { studentId: data.studentId, itemAddresses: data.itemAddresses }; if (StudentStore.hasOverdueItem(data.studentId)){ throw new Error('Student has overdue item'); }else { checkoutsByActionId[data.actionId] = checkout; checkouts.push(checkout); } }); export default store;
import { Store } from 'consus-core/flux'; import StudentStore from './student-store'; import ItemStore from './item-store'; let checkouts = []; let checkoutsByActionId = new Object(null); class CheckoutStore extends Store { getCheckoutByActionId(actionId) { return checkoutsByActionId[actionId]; } } const store = new CheckoutStore(); store.registerHandler('NEW_CHECKOUT', data => { let checkout = { studentId: data.studentId, itemAddresses: data.itemAddresses }; data.itemAddresses.forEach(itemAddress => { if (ItemStore.getItemByAddress(itemAddress).status !== 'AVAILABLE') { throw new Error('An item in the cart is not available for checkout.'); } }); if (StudentStore.hasOverdueItem(data.studentId)) { throw new Error('Student has overdue item'); } else { checkoutsByActionId[data.actionId] = checkout; checkouts.push(checkout); } }); export default store;
Verify that the cart does not contain an unavailable item
Verify that the cart does not contain an unavailable item
JavaScript
unlicense
TheFourFifths/consus,TheFourFifths/consus
49b7b66ac4c3c40893e53e244a2cba7d915d235d
gulp/unit-tests.js
gulp/unit-tests.js
'use strict'; var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var wiredep = require('wiredep'); gulp.task('test', function () { var bowerDeps = wiredep({ directory: 'app/bower_components', exclude: ['bootstrap-sass-official'], dependencies: true, devDependencies: true }); var testFiles = bowerDeps.js.concat([ 'app/scripts/**/*.js', 'test/unit/**/*.js' ]); return gulp.src(testFiles) .pipe($.karma({ configFile: 'test/karma.conf.js', action: 'run' })) .on('error', function (err) { // Make sure failed tests cause gulp to exit non-zero throw err; }); });
'use strict'; var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var wiredep = require('wiredep'); var bowerDeps = wiredep({ directory: 'app/bower_components', exclude: ['bootstrap-sass-official'], dependencies: true, devDependencies: true }); var testFiles = bowerDeps.js.concat([ 'app/scripts/**/*.js', 'test/unit/**/*.js' ]); gulp.task('test', function () { return gulp.src(testFiles) .pipe($.karma({ configFile: 'test/karma.conf.js', action: 'run' })) .on('error', function (err) { // Make sure failed tests cause gulp to exit non-zero throw err; }); }); gulp.task('watch:test', function () { return gulp.src(testFiles) .pipe($.karma({ configFile: 'test/karma.conf.js', action: 'watch' })) .on('error', function (err) { // Make sure failed tests cause gulp to exit non-zero throw err; }); });
Refactor unit tests, add watch task.
Refactor unit tests, add watch task.
JavaScript
mit
tvararu/angular-famous-playground
92e0b46c931e5aa3189db50ad758d5db00cbda9f
server/src/services/scripts/scripts-model.js
server/src/services/scripts/scripts-model.js
'use strict'; // scripts-model.js - A mongoose model // // See http://mongoosejs.com/docs/models.html // for more of what you can do here. const mongoose = require('mongoose'); const Schema = mongoose.Schema; const scriptsSchema = new Schema({ text: { type: String, required: true }, createdAt: { type: Date, 'default': Date.now }, updatedAt: { type: Date, 'default': Date.now } }); const scriptsModel = mongoose.model('scripts', scriptsSchema); module.exports = scriptsModel;
'use strict'; // scripts-model.js - A mongoose model // // See http://mongoosejs.com/docs/models.html // for more of what you can do here. const mongoose = require('mongoose'); const Schema = mongoose.Schema; const scriptsSchema = new Schema({ issue: { type: String, required: true }, title: { type: String, required: true }, text: { type: String, required: true }, createdAt: { type: Date, 'default': Date.now }, updatedAt: { type: Date, 'default': Date.now } }); const scriptsModel = mongoose.model('scripts', scriptsSchema); module.exports = scriptsModel;
Add script issue and title fields
Add script issue and title fields
JavaScript
mit
andreagoulet/callmyreps,andreagoulet/callmyreps,andreagoulet/callmyreps,andreagoulet/callmyreps,andreagoulet/callmyreps
feabc4db34f6a1b15972f1c77306e83a53d61914
src/AsyncCreatable.js
src/AsyncCreatable.js
import React from 'react'; import Select from './Select'; function reduce(obj, props = {}){ return Object.keys(obj) .reduce((props, key) => { const value = obj[key]; if (value !== undefined) props[key] = value; return props; }, props); } const AsyncCreatable = React.createClass({ displayName: 'AsyncCreatableSelect', focus () { this.select.focus(); }, render () { return ( <Select.Async {...this.props}> {(asyncProps) => ( <Select.Creatable {...this.props}> {(creatableProps) => ( <Select {...reduce(asyncProps, reduce(creatableProps, {}))} onInputChange={(input) => { creatableProps.onInputChange(input); return asyncProps.onInputChange(input); }} ref={(ref) => { this.select = ref; creatableProps.ref(ref); asyncProps.ref(ref); }} /> )} </Select.Creatable> )} </Select.Async> ); } }); module.exports = AsyncCreatable;
import React from 'react'; import createClass from 'create-react-class'; import Select from './Select'; function reduce(obj, props = {}){ return Object.keys(obj) .reduce((props, key) => { const value = obj[key]; if (value !== undefined) props[key] = value; return props; }, props); } const AsyncCreatable = createClass({ displayName: 'AsyncCreatableSelect', focus () { this.select.focus(); }, render () { return ( <Select.Async {...this.props}> {(asyncProps) => ( <Select.Creatable {...this.props}> {(creatableProps) => ( <Select {...reduce(asyncProps, reduce(creatableProps, {}))} onInputChange={(input) => { creatableProps.onInputChange(input); return asyncProps.onInputChange(input); }} ref={(ref) => { this.select = ref; creatableProps.ref(ref); asyncProps.ref(ref); }} /> )} </Select.Creatable> )} </Select.Async> ); } }); module.exports = AsyncCreatable;
Migrate rest of src overto createClass pkg
Migrate rest of src overto createClass pkg
JavaScript
mit
submittable/react-select,serkanozer/react-select,OpenGov/react-select,mmpro/react-select,f-camacho/react-select,JedWatson/react-select,mobile5dev/react-select,JedWatson/react-select
3a1ea1dce763b04c46d2e13e39782d3249aa493f
example/src/main.js
example/src/main.js
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import Router from 'vue-router' import App from './App' import Home from './Home' import Eagle from 'eagle.js' import slideshows from './slideshows/slideshows.js' /* eslint-disable no-new */ Vue.use(Eagle) Vue.use(Router) var routes = [] slideshows.list.forEach(function (slideshow) { routes.push({ path: '/' + slideshow.infos.path, component: slideshow }) }) routes.push({ path: '*', component: Home }) routes.push({ path: '/', name: 'Home', component: Home }) console.log(routes) var router = new Router({ routes // hashbang: true // mode: 'history' }) new Vue({ el: '#app', router, template: '<App/>', components: { App } })
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import Router from 'vue-router' import App from './App' import Home from './Home' import Eagle from 'eagle.js' import 'eagle.js/dist/eagle.css' import slideshows from './slideshows/slideshows.js' /* eslint-disable no-new */ Vue.use(Eagle) Vue.use(Router) var routes = [] slideshows.list.forEach(function (slideshow) { routes.push({ path: '/' + slideshow.infos.path, component: slideshow }) }) routes.push({ path: '*', component: Home }) routes.push({ path: '/', name: 'Home', component: Home }) console.log(routes) var router = new Router({ routes // hashbang: true // mode: 'history' }) new Vue({ el: '#app', router, template: '<App/>', components: { App } })
Load dist css file in example
Load dist css file in example
JavaScript
isc
Zulko/eagle.js
9bb7d328e9e64eead6af6bb0ff06dc147ceed2d0
js/responsive-overlay-menu.js
js/responsive-overlay-menu.js
$(document).ready(function () { $(".menu-btn a").click(function () { $(".overlay").fadeToggle(200); $(this).toggleClass('btn-open').toggleClass('btn-close'); }); $('.overlay').on('click', function () { $(".overlay").fadeToggle(200); $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close'); }); $('.menu a').on('click', function () { $(".overlay").fadeToggle(200); $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close'); }); });
(function ($) { $(".menu-btn a").click(function () { event.preventDefault(); $(".overlay").fadeToggle(200); $(this).toggleClass('btn-open').toggleClass('btn-close'); }); $('.overlay').on('click', function () { $(".overlay").fadeToggle(200); $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close'); }); $('.menu a').on('click', function () { event.preventDefault(); $(".overlay").fadeToggle(200); $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close'); }); }(jQuery));
Fix js to preventDefault and work more places
Fix js to preventDefault and work more places
JavaScript
mit
marioloncarek/responsive-overlay-menu,marioloncarek/responsive-overlay-menu
1e615e33dc380729cfcf7ab52177c6a38dcf8b36
lib/frame.js
lib/frame.js
/* requestFrame / cancelFrame */"use strict" var array = require("prime/es5/array") var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame || global.msRequestAnimationFrame || function(callback){ return setTimeout(callback, 1e3 / 60) } var callbacks = [] var iterator = function(time){ var split = callbacks.splice(0) for (var i = 0, l = split.length; i < l; i++) split[i](time || (time = +(new Date))) } var cancel = function(callback){ var io = array.indexOf(callbacks, callback) if (io > -1) callbacks.splice(io, 1) } var request = function(callback){ var i = callbacks.push(callback) if (i === 1) requestFrame(iterator) return function(){ cancel(callback) } } exports.request = request exports.cancel = cancel
/* requestFrame / cancelFrame */"use strict" var array = require("prime/es5/array") var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame || global.msRequestAnimationFrame || function(callback){ return setTimeout(callback, 1e3 / 60) } var callbacks = [] var iterator = function(time){ var split = callbacks.splice(0, callbacks.length) for (var i = 0, l = split.length; i < l; i++) split[i](time || (time = +(new Date))) } var cancel = function(callback){ var io = array.indexOf(callbacks, callback) if (io > -1) callbacks.splice(io, 1) } var request = function(callback){ var i = callbacks.push(callback) if (i === 1) requestFrame(iterator) return function(){ cancel(callback) } } exports.request = request exports.cancel = cancel
Fix requestFrame in IE, where splice requires the deleteCount argument.
Fix requestFrame in IE, where splice requires the deleteCount argument.
JavaScript
mit
dehenne/moofx,dehenne/moofx,kamicane/moofx
2ee1a0be3b01cc2a3cfbf8d6bc0f17f12dffbecc
eloquent_js/chapter04/ch04_ex04.js
eloquent_js/chapter04/ch04_ex04.js
function deepEqual(obj1, obj2) { if (typeof obj1 != "object" || obj1 == null || typeof obj2 != "object" || obj2 == null) return obj1 === obj2; let keys1 = Object.keys(obj1), keys2 = Object.keys(obj2); if (keys1.length != keys2.length) return false; for (let key of keys1) { if (!(keys2.includes(key) && deepEqual(obj1[key], obj2[key]))) return false; } return true; }
function deepEqual(a, b) { if (!(isObject(a) && isObject(b))) return a === b; for (let key of Object.keys(a)) { if (!(key in b)) return false; if (!deepEqual(a[key], b[key])) return false; } return true; } function isObject(a) { return typeof a == "object" && a != null; }
Add chapter 4, exercise 4
Add chapter 4, exercise 4
JavaScript
mit
bewuethr/ctci
1ab6ab7f1e72bad5f39c55110ba65991f23c9df8
examples/ruleset.js
examples/ruleset.js
var EchoRule = require('../lib/rules/echo.js'), Heartbeat = require('../lib/rules/heartbeat.js') ; var rules = []; rules.push(new EchoRule()); rules.push(new Heartbeat()); module.exports = rules;
var EchoRule = require('../lib/rules/echo.js'), Heartbeat = require('../lib/rules/heartbeat.js'), LoadAverage = require('../lib/rules/load-average.js') ; var rules = []; rules.push(new EchoRule()); rules.push(new Heartbeat()); rules.push(new LoadAverage({ warn: { 1: 1.5, 5: 0.9, 15: 0.7 }, critical: { 1: 1.5, 5: 1.5, 15: 1.5 } })); module.exports = rules;
Add the `LoadAverage` rule to the example
Add the `LoadAverage` rule to the example
JavaScript
isc
ceejbot/numbat-analyzer,npm/numbat-analyzer,numbat-metrics/numbat-analyzer
936735753f179190f6391f1b2105246e4d10cdab
public/js/view.js
public/js/view.js
(function() { "use strict"; var lastKeys = ""; function fetchRedlines() { var baseUrl = $('#baseUrl').val(); var artworkUrl = $('#artworkUrl').val(); $.get(baseUrl + 'index').done(function(keys) { if (lastKeys === keys) { return; } lastKeys = keys; var items = []; var requests = $.map(keys.split('\n'), function(key) { return $.get(baseUrl + key).done(function(data) { var json = JSON.parse(data); var feedback = $('<div/>').text(json.feedback).addClass('feedback'); var artwork = $('<div/>').append($('<img/>').attr('src', artworkUrl)) .append($('<img/>').attr('src', json.image).addClass('redline')) .addClass('drawing'); var item = $('<div/>').append(feedback) .append(artwork) .attr('id', key); items.push(item); }).fail(function() { console.log('Failed to fetch data for key ' + key); }); }); $.when.apply($, requests).done(function () { $('#items').empty(); $.each(items, function(i, item) { $('#items').append(item); }); $('#submissions').text(items.length); }); }).fail(function() { console.log('Failed to fetch index file'); }); } $(function() { fetchRedlines(); setInterval(fetchRedlines, 1000); }); })();
(function() { "use strict"; var lastKeys = ""; function fetchRedlines() { var baseUrl = $('#baseUrl').val(); var artworkUrl = $('#artworkUrl').val(); $.get(baseUrl + 'index').done(function(keys) { if (lastKeys === keys) { return; } lastKeys = keys; var items = []; var requests = $.map(keys.split('\n'), function(key) { return $.get(baseUrl + key).done(function(data) { var json = JSON.parse(data); var feedback = $('<div/>').text(json.feedback).addClass('feedback'); var artwork = $('<div/>').append($('<img/>').attr('src', artworkUrl)) .append($('<img/>').attr('src', json.image).addClass('redline')) .addClass('drawing'); var item = $('<div/>').append(feedback) .append(artwork) .attr('id', key); items.push(item); }).fail(function() { console.log('Failed to fetch data for key ' + key); }); }); $.when.apply($, requests).done(function () { $('#items').empty(); $.each(items, function(i, item) { $('#items').append(item); }); $('#submissions').text(items.length); }); }).fail(function() { console.log('Failed to fetch index file'); }); } $(function() { fetchRedlines(); setInterval(fetchRedlines, 5000); }); })();
Increase interval to 5 seconds
Increase interval to 5 seconds
JavaScript
bsd-3-clause
Nullreff/redline,Nullreff/redline,Nullreff/redline
36b78042d3f5d38bb7ca96adb6cb1c0ae40deb49
main.js
main.js
var electron = require('electron'); // Module to control application life. var process = require('process'); const {app} = electron; const {BrowserWindow} = electron; let win; // Ensure that our win isn't garbage collected app.on('ready', function() { // Create the browser window. if (process.platform == 'win32') win = new BrowserWindow({width: 670, height: 510, frame: true, resizable: false}); else win = new BrowserWindow({width: 640, height: 480, frame: true, resizable: false}); // Load the main interface win.loadURL('file://' + __dirname + '/index.html'); // Uncomment this line to open the DevTools upon launch. //win.webContents.openDevTools({'mode':'undocked'}); win.on('closed', function() { // Dereference the window object so our app exits win = null; }); }); // Quit when all windows are closed. app.on('window-all-closed', function() { app.quit(); });
var electron = require('electron'); // Module to control application life. var process = require('process'); const {app} = electron; const {BrowserWindow} = electron; let win; // Ensure that our win isn't garbage collected app.on('ready', function() { // Create the browser window. if (process.platform == 'win32') win = new BrowserWindow({width: 670, height: 510, frame: true, resizable: false}); else win = new BrowserWindow({width: 640, height: 480, frame: true, resizable: false}); // Load the main interface win.loadURL('file://' + __dirname + '/index.html'); // Uncomment this line to open the DevTools upon launch. //win.webContents.openDevTools({'mode':'undocked'}); //Disable the menubar for dev versions win.setMenu(null); win.on('closed', function() { // Dereference the window object so our app exits win = null; }); }); // Quit when all windows are closed. app.on('window-all-closed', function() { app.quit(); });
Disable the menubar when running from source
Disable the menubar when running from source
JavaScript
mit
NoahAndrews/qmk_firmware_flasher,NoahAndrews/qmk_firmware_flasher,NoahAndrews/qmk_firmware_flasher
e8f93882daad04d6a74c864ac2c32d301c199254
lib/index.js
lib/index.js
var browserify = require('browserify-middleware') var babelify = require('babelify') module.exports = function (entries, brOptions, baOptions) { brOptions = brOptions || {} brOptions.transform = brOptions.transform || [] baOptions = baOptions || {} baOptions.stage = baOptions.stage || 1 brOptions.transform.unshift(babelify.configure(baOptions)) return browserify(entries, brOptions) }
var browserify = require('browserify-middleware') var babelify = require('babelify') function babelifyMiddleware(entries, brOptions, baOptions) { brOptions = brOptions || {} brOptions.transform = brOptions.transform || [] baOptions = baOptions || {} baOptions.stage = baOptions.stage || 1 brOptions.transform.unshift(babelify.configure(baOptions)) return browserify(entries, brOptions) } babelifyMiddleware.browserifySettings = browserify.settings module.exports = babelifyMiddleware
Make browserify default settings accessible
Make browserify default settings accessible
JavaScript
mit
luisfarzati/express-babelify-middleware,luisfarzati/express-babelify-middleware
649c9c09c9a66e085b33346f5062976801543423
examples/routing/src/reducers/user.js
examples/routing/src/reducers/user.js
/* Define your initial state here. * * If you change the type from object to something else, do not forget to update * src/container/App.js accordingly. */ const initialState = {}; module.exports = function(state = initialState, action) { /* Keep the reducer clean - do not mutate the original state. */ //let nextState = Object.assign({}, state); switch(action.type) { /* case 'YOUR_ACTION': { // Modify next state depending on the action and return it return nextState; } break; */ default: { /* Return original state if no actions were consumed. */ return state; } } }
import {LOGIN} from '../actions/const'; /* Define your initial state here. * * If you change the type from object to something else, do not forget to update * src/container/App.js accordingly. */ const initialState = { login: false }; module.exports = function(state = initialState, action) { /* Keep the reducer clean - do not mutate the original state. */ let nextState = Object.assign({}, state); switch(action.type) { case LOGIN: { nextState.login = true; return nextState; } default: { /* Return original state if no actions were consumed. */ return state; } } }
Change login state When LOGIN action was triggered.
Change login state When LOGIN action was triggered.
JavaScript
mit
stylesuxx/generator-react-webpack-redux,stylesuxx/generator-react-webpack-redux
e3e031e4634522e0764a722ad37791c9913ce1cd
domStorage.js
domStorage.js
function DomStorage() { var cache = {}; function getFromCache(selector){ if(!cache[selector]){ cache[selector] = $(selector); } return cache[selector]; } function updateInCache(selector){ if(!cache[selector]){ throw new TypeError("The selector you want to update does not exist in cache"); } else{ cache[selector] = $(selector); } } function getCache(){ return cache; } function flushCache(){ cache = {}; } return { get:getFromCache, update:updateInCache, getCache:getCache, flush:flushCache }; }
function DomStorage() { var cache = {}; function getFromCache(selector){ if(!selector) throw new TypeError("Please provide a selector"); if(!cache[selector]){ cache[selector] = $(selector); } return cache[selector]; } function updateInCache(selector){ if(!selector) throw new TypeError("Please provide a selector"); if(!cache[selector]){ throw new TypeError("The selector you want to update does not exist in cache"); } else{ cache[selector] = $(selector); } } function getCache(){ return cache; } function flushCache(){ cache = {}; } return { get:getFromCache, update:updateInCache, getCache:getCache, flush:flushCache }; } class DomCache{ constructor{ } }
Check if a user has given a valid selector when trying to get or update
Check if a user has given a valid selector when trying to get or update
JavaScript
mit
kounelios13/Dom-Storage,kounelios13/Dom-Storage
3ff467f3c1a3c5c9ea911403373229650760850e
bin/server.js
bin/server.js
import config from '../config' import server from '../server/main' import _debug from 'debug' const debug = _debug('app:bin:server') const port = config.server_port const host = config.server_host server.listen(port) debug(`Server is now running at ${host}:${port}.`)
import config from '../config' import server from '../server/main' import _debug from 'debug' const debug = _debug('app:bin:server') const port = config.server_port const host = config.server_host server.listen(port) debug(`Server is now running at http://${host}:${port}.`)
Make the app link clickable
chore(compile): Make the app link clickable This small change makes the link clickable in some terminal emulators (like xfce-terminal), which makes it easier to open the app in a browser.
JavaScript
mit
josedab/react-redux-i18n-starter-kit,josedab/react-redux-i18n-starter-kit
e1ee7a46a12715ce5d8bcfc7bf3180a6b254f228
client/common/layout/layout.js
client/common/layout/layout.js
'use strict'; var _ = require('lodash'); // // Observe quicksearch focus to tweak icon style // N.wire.once('navigate.done', function () { $('.navbar-search .search-query') .focus(function () { $(this).next('div').addClass('focused'); }) .blur(function () { $(this).next('div').removeClass('focused'); }); }); // // Update "active" tab of the navbar_menu when moving to another page. // N.wire.on('navigate.done', function navbar_menu_change_active(target) { var apiPath = target.apiPath, tabs, active; function matchLengthOf(subject) { var index = 0 , length = Math.min(apiPath.length, subject.length); while (index < length && subject.charCodeAt(index) === apiPath.charCodeAt(index)) { index += 1; } return index; } tabs = $('#navbar_menu').find('[data-api-path]'); tabs.removeClass('active'); // Select the most specific tab - with the longest API path match. active = _.max(tabs, function (tab) { return matchLengthOf($(tab).attr('data-api-path')); }); $(active).addClass('active'); });
'use strict'; var _ = require('lodash'); // // Observe quicksearch focus to tweak icon style // N.wire.once('navigate.done', function () { $('.navbar-search .search-query') .focus(function () { $(this).next('div').addClass('focused'); }) .blur(function () { $(this).next('div').removeClass('focused'); }); }); // // Update "active" tab of the navbar_menu when moving to another page. // N.wire.on('navigate.done', function navbar_menu_change_active(target) { var targetPath = target.apiPath.split('.'), tabs, active; tabs = $('#navbar_menu').find('[data-api-path]'); tabs.removeClass('active'); // Select the most specific tab - with the longest API path match. active = _.max(tabs, function (tab) { var tabPath = $(tab).data('apiPath').split('.') , index = -1 , length = Math.min(tabPath.length, targetPath.length); do { index += 1; } while (index < length && tabPath[index] === targetPath[index]); return index; }); $(active).addClass('active'); });
Fix tab selection on the navbar.
Fix tab selection on the navbar. Split API paths by dots to prevent matching of the dots.
JavaScript
mit
nodeca/nodeca.core,nodeca/nodeca.core
94863a27ba7fccb8236592c5b046ad32d7b48341
source/Vibrato/core/RegExp.js
source/Vibrato/core/RegExp.js
// -------------------------------------------------------------------------- \\ // File: RegExp.js \\ // Module: Core \\ // Requires: Core.js \\ // Author: Neil Jenkins \\ // License: © 2010–2011 Opera Software ASA. All rights reserved. \\ // -------------------------------------------------------------------------- \\ "use strict"; /** Property: RegExp.email Type: RegExp A regular expression for detecting an email address. */ RegExp.email = /\b([\w\-.%+]+@(?:[\w\-]+\.)+[A-Z]{2,4})\b/i; /** Property: RegExp.url Type: RegExp A regular expression for detecting a url. Regexp by John Gruber, see <http://daringfireball.net/2010/07/improved_regex_for_matching_urls> */ RegExp.url = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;
// -------------------------------------------------------------------------- \\ // File: RegExp.js \\ // Module: Core \\ // Requires: Core.js \\ // Author: Neil Jenkins \\ // License: © 2010–2011 Opera Software ASA. All rights reserved. \\ // -------------------------------------------------------------------------- \\ "use strict"; /** Property: RegExp.email Type: RegExp A regular expression for detecting an email address. */ RegExp.email = /\b([\w\-.%+]+@(?:[\w\-]+\.)+[A-Z]{2,4})\b/i; /** Property: RegExp.url Type: RegExp A regular expression for detecting a url. Regexp by John Gruber, see <http://daringfireball.net/2010/07/improved_regex_for_matching_urls> */ RegExp.url = /\b(?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])/i;
Remove capture group from URL reg exp.
Remove capture group from URL reg exp. You get the whole match anyway. And now you can more easily use the source of the regexp as a part for constructing more complicated regular expressions. e.g. var x = new RegExp( RegExp.url.source + "|" + RegExp.email.source, 'i' );
JavaScript
mit
adityab/overture,Hokua/overture,linagora/overture,linagora/overture,fastmail/overture
fc1a61eb29f6cd38f1694fda155a8173432d1999
tasks/help/index.js
tasks/help/index.js
module.exports = function(target) { if (tasks[target]) console.log(tasks[target].help) else console.log("No help documentation exists for " + target + ".") }
var fs = require('fs') module.exports = function(target) { fs.readFile('doc/' + target + '.md', function(err, data) { if (err) console.log("No help documentation exists for " + target + ".") else console.log(data) }) }
Load markdown docs in help command
Load markdown docs in help command Signed-off-by: Nathan Stier <013f9af474b4ba6f842b41368c6f02c1ee9e9e08@gmail.com>
JavaScript
mit
YWebCA/ywca-cli
88a4ce42993665dba7eef5798334419954f55a67
lib/gulp-index-file-stream.js
lib/gulp-index-file-stream.js
var Readable = require('stream').Readable; var path = require('path-posix'); var util = require('util'); var File = require('vinyl'); // Because the index.html files in our site don't necessarily // come from individual files, it's easiest for us to just // create a stream that emits Vinyl File objects rather than // using gulp.src(). function IndexFileStream(indexStatic) { Readable.call(this, { objectMode: true }); this._baseDir = __dirname; this._indexStatic = indexStatic; this._urls = indexStatic.URLS.slice(); } util.inherits(IndexFileStream, Readable); IndexFileStream.prototype._read = function() { if (this._urls.length == 0) return this.push(null); var url = this._urls.pop(); var indexFile = path.join( this._baseDir, path.join.apply(path, url.split('/').slice(1, -1)), 'index.html' ); this.push(new File({ cwd: this._baseDir, base: this._baseDir, path: indexFile, contents: new Buffer(this._indexStatic.generate(url, { baseURL: path.relative(url, '/') })) })); }; module.exports = IndexFileStream;
var Readable = require('stream').Readable; var posixPath = require('path-posix'); var util = require('util'); var File = require('vinyl'); // Because the index.html files in our site don't necessarily // come from individual files, it's easiest for us to just // create a stream that emits Vinyl File objects rather than // using gulp.src(). function IndexFileStream(indexStatic) { Readable.call(this, { objectMode: true }); this._baseDir = __dirname; this._indexStatic = indexStatic; this._urls = indexStatic.URLS.slice(); } util.inherits(IndexFileStream, Readable); IndexFileStream.prototype._read = function() { if (this._urls.length == 0) return this.push(null); var url = this._urls.pop(); var indexFile = posixPath.join( this._baseDir, posixPath.join.apply(posixPath, url.split('/').slice(1, -1)), 'index.html' ); this.push(new File({ cwd: this._baseDir, base: this._baseDir, path: indexFile, contents: new Buffer(this._indexStatic.generate(url, { baseURL: posixPath.relative(url, '/') })) })); }; module.exports = IndexFileStream;
Change path name to posixPath
Change path name to posixPath
JavaScript
mpl-2.0
Pomax/teach.mozilla.org,fredericksilva/teach.webmaker.org,PaulaPaul/teach.mozilla.org,toolness/teach.webmaker.org,alicoding/teach.mozilla.org,AnthonyBobsin/teach.webmaker.org,cadecairos/teach.mozilla.org,fredericksilva/teach.webmaker.org,emmairwin/teach.webmaker.org,mozilla/teach.webmaker.org,ScottDowne/teach.webmaker.org,asdofindia/teach.webmaker.org,alicoding/teach.webmaker.org,Pomax/teach.webmaker.org,emmairwin/teach.webmaker.org,mmmavis/teach.webmaker.org,mozilla/learning.mozilla.org,mrinaljain/teach.webmaker.org,Pomax/teach.mozilla.org,mmmavis/teach.webmaker.org,alicoding/teach.webmaker.org,ScottDowne/teach.webmaker.org,mozilla/teach.mozilla.org,mmmavis/teach.mozilla.org,PaulaPaul/teach.mozilla.org,mozilla/teach.webmaker.org,mozilla/teach.mozilla.org,mmmavis/teach.mozilla.org,asdofindia/teach.webmaker.org,Pomax/teach.webmaker.org,toolness/teach.webmaker.org,alicoding/teach.mozilla.org,cadecairos/teach.mozilla.org,mrinaljain/teach.webmaker.org,AnthonyBobsin/teach.webmaker.org
d77f875ffaf501002c30c49ab7c433730a8fce8e
src/modules/lists/components/connector/jsomConnector.service.js
src/modules/lists/components/connector/jsomConnector.service.js
angular .module('ngSharepoint.Lists') .factory('JSOMConnector', function($q, $sp) { return ({ getLists: function() { return $q(function(resolve, reject) { var context = $sp.getContext(); var lists = context.get_web().get_lists(); context.load(lists); context.executeQueryAsync(function(sender, args) { var result = []; var listEnumerator = lists.getEnumerator(); while (listEnumerator.moveNext()) { var list = lists.get_current(); result.push(list); } resolve(result); }, reject); }); } }); });
angular .module('ngSharepoint.Lists') .factory('JSOMConnector', function($q, $sp) { return ({ getLists: function() { return $q(function(resolve, reject) { var context = $sp.getContext(); var lists = context.get_web().get_lists(); context.load(lists); context.executeQueryAsync(function() { var result = []; var listEnumerator = lists.getEnumerator(); while (listEnumerator.moveNext()) { var list = listEnumerator.get_current(); result.push(list); } resolve(result); }, reject); }); } }); });
Use enumerator instead of lists
Use enumerator instead of lists
JavaScript
apache-2.0
maxjoehnk/ngSharepoint
6e73dbf020236063f8db213f2459c4d56fa2f661
lib/components/Application.js
lib/components/Application.js
import React, { Component } from 'react' import firebase, { reference, signIn } from '../firebase'; import { pick, map, extend } from 'lodash'; import Input from './Input'; import MessageContainer from './MessageContainer'; // import Search from './Search'; // import Users from './Users'; export default class Application extends Component { constructor() { super(); this.state = { messages: [], } } // componentDidMount() { // firebase.database().ref('messages').on('value', (snapshot) => { // }); // } storeMessage(message) { firebase.database().ref('messages').push(Object.assign(message, { id: Date.now() })); this.state.messages.push(Object.assign(message, { id: Date.now() })) this.setState({ messages: this.state.messages }) } render() { return ( <div className="application"> <header className="headerSection"> {/* <Search /> */} </header> <div className="messageSection"> <MessageContainer messages={this.state.messages}/> </div> <aside className="usersSection"> {/* <Users /> */} </aside> <div> <Input sendMessage={this.storeMessage.bind(this)}/> </div> </div> ) } }
import React, { Component } from 'react' import firebase, { reference, signIn } from '../firebase'; import { pick, map, extend } from 'lodash'; import Input from './Input'; import MessageContainer from './MessageContainer'; // import Search from './Search'; // import Users from './Users'; export default class Application extends Component { constructor() { super(); this.state = { messages: [], } } componentDidMount() { firebase.database().ref('messages').on('value', (snapshot) => { const itemsFromFirebase = this.createArrayFromFB(snapshot.val()); this.setState({ messages: itemsFromFirebase ? itemsFromFirebase : [] }) }); } createArrayFromFB(object) { const firebaseKeys = object ? Object.keys(object) : []; const messages = []; firebaseKeys.map((key) => { let singleMessage = object[key] singleMessage['firebaseId'] = key messages.push(singleMessage); }); return messages } storeMessage(message) { firebase.database().ref('messages').push(Object.assign(message, { id: Date.now() })); this.state.messages.push(Object.assign(message, { id: Date.now() })) this.setState({ messages: this.state.messages }) } render() { return ( <div className="application"> <header className="headerSection"> {/* <Search /> */} </header> <div className="messageSection"> <MessageContainer messages={this.state.messages}/> </div> <aside className="usersSection"> {/* <Users /> */} </aside> <div> <Input sendMessage={this.storeMessage.bind(this)}/> </div> </div> ) } }
Add items to firebase and repopulate on page load or refresh
Add items to firebase and repopulate on page load or refresh
JavaScript
mit
mlimberg/shoot-the-breeze,mlimberg/shoot-the-breeze
521eed5e6a64f1bf28210d03372cdbb353bb019e
scripts/script.js
scripts/script.js
(function(document, MazeGenerator, MazePainter, MazeInteraction) { 'use strict'; // DOM Elements var canvas = document.getElementById('maze'); var bGenerate = document.getElementById('bGenerate'); var bSolve = document.getElementById('bSolve'); // Start painting loop MazePainter.startPainting(); bGenerate.addEventListener('click', function() { // Initialize modules MazeGenerator.init(canvas.width, canvas.height, 20); MazePainter.init(canvas, 20, '#fff', '#f00', '#000', '#0f0', '#0f0', '#0f0', '#00f'); MazeGenerator.generate(); MazeGenerator.selectEntry(); MazeGenerator.selectExit(); MazeInteraction.init(canvas, 20, MazeGenerator.getMaze()); MazeInteraction.startListeningUserEvents(); }); bSolve.addEventListener('click', function() { if (MazePainter.isMazePainted()) { MazeGenerator.solve(); } }); }(document, MazeGenerator, MazePainter, MazeInteraction));
(function(document, MazeGenerator, MazePainter, MazeInteraction) { 'use strict'; // DOM Elements var canvas = document.getElementById('maze'); var bGenerate = document.getElementById('bGenerate'); var bSolve = document.getElementById('bSolve'); // Initialization variables var cellSize = 20; var cellColor = '#fff'; var frontierColor = '#f00'; var wallColor = '#000'; var entryColor = '#0f0'; var exitColor = '#0f0'; var solutionColor = '#0f0'; var userSolutionColor = '#00f'; // Start painting loop MazePainter.startPainting(); bGenerate.addEventListener('click', function() { // Initialize modules MazeGenerator.init(canvas.width, canvas.height, cellSize); MazePainter.init(canvas, cellSize, cellColor, frontierColor, wallColor, entryColor, exitColor, solutionColor, userSolutionColor); MazeGenerator.generate(); MazeGenerator.selectEntry(); MazeGenerator.selectExit(); MazeInteraction.init(canvas, cellSize, MazeGenerator.getMaze()); MazeInteraction.startListeningUserEvents(); }); bSolve.addEventListener('click', function() { if (MazePainter.isMazePainted()) { MazeGenerator.solve(); } }); }(document, MazeGenerator, MazePainter, MazeInteraction));
Use variables to initialize the maze
Use variables to initialize the maze
JavaScript
mit
jghinestrosa/maze-generator,jghinestrosa/maze-generator
c3da45397839ff6e5857b6413471ca64fac99b54
src/article/models/Heading.js
src/article/models/Heading.js
import { TextNode, TEXT } from 'substance' export default class Heading extends TextNode {} Heading.schema = { type: 'heading', level: { type: 'number', default: 1 }, content: TEXT() }
import { TextNode, TEXT } from 'substance' import { RICH_TEXT_ANNOS, EXTENDED_FORMATTING, LINKS_AND_XREFS, INLINE_NODES } from './modelConstants' export default class Heading extends TextNode {} Heading.schema = { type: 'heading', level: { type: 'number', default: 1 }, content: TEXT(RICH_TEXT_ANNOS.concat(EXTENDED_FORMATTING).concat(LINKS_AND_XREFS).concat(INLINE_NODES).concat(['break'])) }
Allow annotations and line-breaks in headings.
Allow annotations and line-breaks in headings.
JavaScript
mit
substance/texture,substance/texture
ee3544448dc1755c99b10e0afe52d295deffbdd8
script/postinstall.js
script/postinstall.js
#!/usr/bin/env node var cp = require('child_process') var fs = require('fs') var path = require('path') var script = path.join(__dirname, 'postinstall') if (process.platform === 'win32') { script += '.cmd' } else { script += '.sh' } // Read + execute permission fs.chmodSync(script, fs.constants.S_IRUSR | fs.constants.S_IXUSR) fs.chmodSync(path.join(__dirname, '..', 'bin', 'apm'), fs.constants.S_IRUSR | fs.constants.S_IXUSR) fs.chmodSync(path.join(__dirname, '..', 'bin', 'npm'), fs.constants.S_IRUSR | fs.constants.S_IXUSR) fs.chmodSync(path.join(__dirname, '..', 'bin', 'python-interceptor.sh'), fs.constants.S_IRUSR | fs.constants.S_IXUSR) var child = cp.spawn(script, [], { stdio: ['pipe', 'pipe', 'pipe'], shell: true }) child.stderr.pipe(process.stderr) child.stdout.pipe(process.stdout)
#!/usr/bin/env node var cp = require('child_process') var fs = require('fs') var path = require('path') var script = path.join(__dirname, 'postinstall') if (process.platform === 'win32') { script += '.cmd' } else { script += '.sh' } // Make sure all the scripts have the necessary permissions when we execute them // (npm does not preserve permissions when publishing packages on Windows, // so this is especially needed to allow apm to be published successfully on Windows) fs.chmodSync(script, 0o755) fs.chmodSync(path.join(__dirname, '..', 'bin', 'apm'), 0o755) fs.chmodSync(path.join(__dirname, '..', 'bin', 'npm'), 0o755) fs.chmodSync(path.join(__dirname, '..', 'bin', 'python-interceptor.sh'), 0o755) var child = cp.spawn(script, [], { stdio: ['pipe', 'pipe', 'pipe'], shell: true }) child.stderr.pipe(process.stderr) child.stdout.pipe(process.stdout)
Mark all scripts as 0o755
Mark all scripts as 0o755 This gives execute permission for everyone even if Atom is installed as root: https://github.com/atom/atom/issues/19367
JavaScript
mit
atom/apm,atom/apm,atom/apm,atom/apm
36d7c61c7d6f7c6dc4e9bb9191f20890ab148e8c
lib/support/browser_script.js
lib/support/browser_script.js
'use strict'; let fs = require('fs'), path = require('path'), Promise = require('bluebird'), filters = require('./filters'); Promise.promisifyAll(fs); /* Find and parse any browser scripts in rootFolder. Returns a Promise that resolves to an array of scripts. Each script is represented by an object with the following keys: - default: true if script is bundled with Browsertime. - path: the path to the script file on disk - source: the javascript source */ function parseBrowserScripts(rootFolder, isDefault) { function toFullPath(filename) { return path.join(rootFolder, filename); } function fileToScriptObject(filepath) { return fs.readFileAsync(filepath, 'utf8') .then((contents) => { return { default: isDefault, path: filepath, source: contents }; }); } return fs.readdirAsync(rootFolder) .map(toFullPath) .filter(filters.onlyFiles) .filter(filters.onlyWithExtension('.js')) .map(fileToScriptObject); } module.exports = { parseBrowserScripts: parseBrowserScripts, defaultScripts: parseBrowserScripts(path.resolve(__dirname, '..', '..', 'browserscripts')) };
'use strict'; let fs = require('fs'), path = require('path'), Promise = require('bluebird'), filters = require('./filters'); Promise.promisifyAll(fs); /* Find and parse any browser scripts in rootFolder. Returns a Promise that resolves to an array of scripts. Each script is represented by an object with the following keys: - default: true if script is bundled with Browsertime. - path: the path to the script file on disk - source: the javascript source */ function parseBrowserScripts(rootFolder, isDefault) { function toFullPath(filename) { return path.join(rootFolder, filename); } function fileToScriptObject(filepath) { return fs.readFileAsync(filepath, 'utf8') .then((contents) => { return { default: isDefault, path: filepath, source: contents }; }); } return fs.readdirAsync(rootFolder) .map(toFullPath) .filter(filters.onlyFiles) .filter(filters.onlyWithExtension('.js')) .map(fileToScriptObject); } module.exports = { parseBrowserScripts: parseBrowserScripts, get defaultScripts() { return parseBrowserScripts(path.resolve(__dirname, '..', '..', 'browserscripts')); } };
Configure Bluebird before first use of Promise.
Configure Bluebird before first use of Promise. Turn browser_scripts#defaultScripts into a get property, so it's not executed when the file is being required. This to avoid: Error: cannot enable long stack traces after promises have been created
JavaScript
apache-2.0
sitespeedio/browsertime,tobli/browsertime,sitespeedio/browsertime,sitespeedio/browsertime,sitespeedio/browsertime
83d2edc294966aa1c5d29ef16ddf623f6983cce7
index.js
index.js
"use strict"; /** * Properties to prefix. */ var postcss = require("postcss"), props = [ "hyphens", "line-break", "text-align-last", "text-emphasis", "text-emphasis-color", "text-emphasis-style", "word-break", // writing modes "writing-mode", "text-orientation", "text-combine-upright" ]; /** * PostCSS plugin to prefix ePub3 properties. * @param {Object} style */ function plugin(style) { style.eachDecl(function(decl) { if (decl.value) { if (props.indexOf(decl.prop) >= 0) { decl.parent.insertBefore(decl, decl.clone({prop: "-epub-" + decl.prop})); } } }); } /* * ...and export for use... */ module.exports = { postcss: plugin, process: function(css, opts) { return postcss(plugin).process(css, opts).css; } };
"use strict"; /** * Properties to prefix. */ var postcss = require("postcss"), props = [ // text "hyphens", "line-break", "text-align-last", "text-emphasis", "text-emphasis-color", "text-emphasis-style", "word-break", // writing modes "writing-mode", "text-orientation", "text-combine-upright", // text to speech "cue", "cue-before", "cue-after", "pause", "rest", "speak", "speak-as", "voice-family" ]; /** * PostCSS plugin to prefix ePub3 properties. * @param {Object} style */ function plugin(style) { style.eachDecl(function(decl) { if (decl.value) { if (props.indexOf(decl.prop) >= 0) { decl.parent.insertBefore(decl, decl.clone({prop: "-epub-" + decl.prop})); } } }); } /* * ...and export for use... */ module.exports = { postcss: plugin, process: function(css, opts) { return postcss(plugin).process(css, opts).css; } };
Add speech prefixes - still required in 2012, so should be left in due to reader issues
Add speech prefixes - still required in 2012, so should be left in due to reader issues
JavaScript
mit
Rycochet/postcss-epub,antyakushev/postcss-epub
68d0f077935e3d54d08556cb9ec646b30e443acf
index.js
index.js
var net = require('net'); var config = require('hyperflowMonitoringPlugin.config.js'); var MonitoringPlugin = function () { }; MonitoringPlugin.prototype.sendMetrics = function () { var that = this; //TODO: Create connection once and then try to reuse it var parts = config.metricCollector.split(':'); var host = parts[0]; var port = parts[1]; var client = net.connect({host: host, port: port}, function () { var metricReport = config.serverName + ' nTasksLeft ' + that.getTasksLeft() + ' ' + parseInt(Date.now() / 1000) + '\r\n'; client.write(metricReport); client.destroy(); }); }; MonitoringPlugin.prototype.getTasksLeft = function () { return this.engine.nTasksLeft; }; MonitoringPlugin.prototype.init = function (rcl, wflib, engine) { if (this.hasOwnProperty('initialized') && this.initialized === true) { return; } this.rcl = rcl; this.wflib = wflib; this.engine = engine; var that = this; setInterval(function () { that.sendMetrics(); }, 1000); this.initialized = true; }; module.exports = MonitoringPlugin;
var net = require('net'); var config = require('hyperflowMonitoringPlugin.config.js'); var MonitoringPlugin = function () { }; MonitoringPlugin.prototype.sendMetrics = function () { var that = this; //TODO: Create connection once and then try to reuse it var parts = config.metricCollector.split(':'); var host = parts[0]; var port = 9001; if (parts.length > 1) { port = parseInt(parts[1]); } var client = net.connect({host: host, port: port}, function () { var metricReport = config.serverName + ' nTasksLeft ' + that.getTasksLeft() + ' ' + parseInt(Date.now() / 1000) + '\r\n'; client.write(metricReport); client.destroy(); }); }; MonitoringPlugin.prototype.getTasksLeft = function () { return this.engine.nTasksLeft; }; MonitoringPlugin.prototype.init = function (rcl, wflib, engine) { if (this.hasOwnProperty('initialized') && this.initialized === true) { return; } this.rcl = rcl; this.wflib = wflib; this.engine = engine; var that = this; setInterval(function () { that.sendMetrics(); }, 1000); this.initialized = true; }; module.exports = MonitoringPlugin;
Handle supplying metric collector by env var.
Handle supplying metric collector by env var.
JavaScript
mit
dice-cyfronet/hyperflow-monitoring-plugin
92b28424a9d10ded0ebf59ef2a044596d99627cd
index.js
index.js
const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const webpackConfig = require('./webpack.config.local'); new WebpackDevServer(webpack(webpackConfig), { publicPath: '/dist/', hot: true, historyApiFallback: true }).listen(3000, 'localhost', (err) => { if (err) { console.log(err); } console.log(`Webpack dev server listening at localhost:3000`); });
const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const args = process.argv; const webpackConfig = require(`./webpack.config.${args[2].substring(2)}`); new WebpackDevServer(webpack(webpackConfig), { publicPath: '/dist/', hot: true, historyApiFallback: true }).listen(3000, 'localhost', (err) => { if (err) { console.log(err); } console.log(`Webpack dev server listening at localhost:3000`); });
Add option to choose between local and npm
[server] Add option to choose between local and npm
JavaScript
mit
KleeGroup/focus-showcase
04ff61e25b17b68a417908758529e2fbb829ac8d
test/ui/fixtures.js
test/ui/fixtures.js
import m from 'mithril'; import AppComponent from '../../app/scripts/components/app.js'; import AIPlayer from '../../app/scripts/models/ai-player.js'; import { qs } from './utils.js'; export function _before() { // Minimize the transition duration to speed up tests (interestingly, a // duration of 0ms will prevent transitionEnd from firing) const style = document.createElement('style'); style.innerHTML = '* {transition-duration: 200ms !important;}'; document.head.appendChild(style); // Also zero out the AI Player's delay between each swift movement AIPlayer.waitDelay = 0; } export function _beforeEach() { document.body.appendChild(document.createElement('main')); m.mount(qs('main'), AppComponent); } export function _afterEach() { m.mount(qs('main'), null); }
import m from 'mithril'; import AppComponent from '../../app/scripts/components/app.js'; import AIPlayer from '../../app/scripts/models/ai-player.js'; import { qs } from './utils.js'; export function _before() { // Minimize the transition duration to speed up tests (interestingly, a // duration of 0ms will prevent transitionEnd from firing) const style = document.createElement('style'); style.innerHTML = '* {transition-duration: 100ms !important;}'; document.head.appendChild(style); // Also zero out the AI Player's delay between each swift movement AIPlayer.waitDelay = 0; } export function _beforeEach() { document.body.appendChild(document.createElement('main')); m.mount(qs('main'), AppComponent); } export function _afterEach() { m.mount(qs('main'), null); }
Reduce test transition-delay from 200ms to 100ms
Reduce test transition-delay from 200ms to 100ms
JavaScript
mit
caleb531/connect-four
9579909492ac9d80cfec0d9c9858ce7d89760aa1
examples/flux-chat/js/app.js
examples/flux-chat/js/app.js
/** * This file is provided by Facebook for testing and evaluation purposes * only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @jsx React.DOM */ // This file bootstraps the entire application. var ChatApp = require('./components/ChatApp.react'); var ChatExampleData = require('./ChatExampleData'); var ChatWebAPIUtils = require('./utils/ChatWebAPIUtils'); var React = require('react'); ChatExampleData.init(); // load example data into localstorage ChatWebAPIUtils.getAllMessages(); React.renderComponent( <ChatApp />, document.getElementById('react') );
/** * This file is provided by Facebook for testing and evaluation purposes * only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @jsx React.DOM */ // This file bootstraps the entire application. var ChatApp = require('./components/ChatApp.react'); var ChatExampleData = require('./ChatExampleData'); var ChatWebAPIUtils = require('./utils/ChatWebAPIUtils'); var React = require('react'); window.React = React; // export for http://fb.me/react-devtools ChatExampleData.init(); // load example data into localstorage ChatWebAPIUtils.getAllMessages(); React.renderComponent( <ChatApp />, document.getElementById('react') );
Enable React devtools by exposing React (setting window.React)
Enable React devtools by exposing React (setting window.React)
JavaScript
bsd-3-clause
eclectriq/flux,ludiculous/flux,ayarulin/flux,nikhyl/flux,debbas/ChatV2,JanChw/flux,crsr/flux,keikun17/flux,jmandel/flux,gfogle/elm-todomvc,Chen-Han/flux,ephetic/flux,ayarulin/flux,superphung/flux,prabhash1785/flux,rstefek/flux,UIKit0/flux-1,Demian-Moschin/flux,avinnakota/flux,mircle/flux,viviancpy/flux,alexeybondarenko/flux,vl-lapikov/flux,cold-brew-coding/flux,bilboJ/flux,JanChw/flux,wandrejevic/flux,thebergamo/flux,gnoesiboe/flux,zshift/flux,vl-lapikov/flux,ludiculous/flux,oopchoi/flux,Binzzzz/flux,dingdingvsjj/flux,glitch100/flux,Eric-Vandenberg/flux,maximvl/flux,knrm/flux,kris1226/flux,viviancpy/flux,amoskyler/flux,MykolaBova/flux,jinkea/flux,maksymshtyria/flux,cjmanetta/flux,thadiggitystank/flux,yanarchy/flux,Zagorakiss/flux,zhanglingkang/flux,steveleec/flux,cgack/flux,tungmv7/flux,bilboJ/flux,jeremyhu9/flux,ayarulin/flux,rohannair/flux,bertomartin/flux,dmlinn/flux,prabhash1785/flux,pj8063/flux,noahlt/flux,lifebeyondfife/flux-todomvc,usufruct/flux,ksivam/flux,alemontree/flux,fauzan182/flux,hokennethk/flux,slapheadted/flux-nukebox,bartcharbon/flux,alexeygusak/flux,ataker/flux,zhanglingkang/flux,chenrui2014/flux,keikun17/flux,maksymshtyria/flux,Jonekee/flux,haruair/flux,birendra-ideas2it/flux,thewarpaint/flux,kiopl/flux,aaron-goshine/flux,jeremyhu9/flux,ShannonStoner/flux,MykolaBova/flux,danielchatfield/flux,kiopl/flux,fauzan182/flux,harrykiselev/flux,danielchatfield/flux,hoozi/flux,akhilxavierm/flux,pj8063/flux,crzidea/flux,chrismoulton/flux,DimitarRuskov/flux,andela-cijeomah/flux,alexeybondarenko/flux,JunyaOnishi/flux,stevemao/flux,jeffj/flux,bartcharbon/flux,tungmv7/flux,hanan198501/flux,justin3737/flux,gaurav1981/flux,sibinx7/flux,kwangkim/flux,rkho/flux,lilien1010/flux,haruair/flux,micahlmartin/flux,kwangkim/flux,rstefek/flux,alucas/flux,harrykiselev/flux,harrykiselev/flux,djfm/flux,andela-cijeomah/flux,thewarpaint/flux,cold-brew-coding/flux,chienchienchen/flux,garylgh/flux,runn1ng/flux,tinygrasshopper/flux,nvoron23/flux,jarl-alejandro/flux,mcanthony/flux,tcxq42aa/flux,kris1226/flux,bartcharbon/flux,crsr/flux,crzidea/flux,tungmv7/flux,jarl-alejandro/flux,dingdingvsjj/flux,noahlt/flux,latkins/flux,mandaltapesh/flux,keikun17/flux,jdholdren/flux,ShannonStoner/flux,crsgypin/flux,Chen-Han/flux,Eric-Vandenberg/flux,davidgbe/flux,chienchienchen/flux,jugend/flux,venkateshdaram434/flux,noahlt/flux,steveleec/flux,djfm/flux,gnoesiboe/flux,sahat/flux,prabhash1785/flux,james4388/flux,kangkot/flux,mzbac/flux,magus0219/flux,zhzenghui/flux,nvoron23/flux,baiwyc119/flux,siddhartharay007/flux,Eric-Vandenberg/flux,mandaltapesh/flux,mzbac/flux,RomanTsopin/flux,baijuachari/flux,chenckang/flux,crsgypin/flux,oopchoi/flux,rtfeldman/flux,Zagorakiss/flux,knrm/flux,gaurav1981/flux,Zagorakiss/flux,reinaldo13/flux,hoozi/flux,unidevel/flux,roshow/flux,RomanTsopin/flux,fauzan182/flux,lishengzxc/flux,gfogle/elm-todomvc,Aweary/flux,cgack/flux,ksivam/flux,cgack/flux,latkins/flux,rkho/flux,yanarchy/flux,ephetic/flux,gnoesiboe/flux,unidevel/flux,thewarpaint/flux,tom-mats/flux,soulcm/flux,bertomartin/flux,DimitarRuskov/flux,knrm/flux,lishengzxc/flux,chrismoulton/flux,avinnakota/flux,nikhyl/flux,gajus/flux,stevemao/flux,lgvalle/flux,latkins/flux,kaushik94/flux,YakovAvramenko/flux,tinygrasshopper/flux,magus0219/flux,Aweary/flux,DimitarRuskov/flux,tbutman/flux,nikhyl/flux,baiwyc119/flux,venkateshdaram434/flux,lgvalle/flux,georgetoothman/flux-todo,CedarLogic/flux,lifebeyondfife/flux-todomvc,rtfeldman/flux,alexeygusak/flux,Aweary/flux,doron2402/flux,thebergamo/flux,runn1ng/flux,yejodido/flux,ataker/flux,taylorhxu/flux,taylorhxu/flux,juliangamble/flux,lauramoore/flux,zshift/flux,usufruct/flux,gaurav1981/flux,briantopping/flux,aaron-goshine/flux,robhogfeldt-fron15/flux,lauramoore/flux,shunyitian/flux,mattvanhorn/flux,jonathanpeterwu/flux,amoskyler/flux,jarl-alejandro/flux,davidgbe/flux,songguangyu/flux,tcxq42aa/flux,gajus/flux,tom-mats/flux,albi34/flux,unidevel/flux,djfm/flux,doxiaodong/flux,nvoron23/flux,thadiggitystank/flux,hokennethk/flux,grandsong/flux,aecca/flux,wrrnwng/flux,birendra-ideas2it/flux,blazenko/flux,kaushik94/flux,lyip1992/flux,ruistime/flux,lifebeyondfife/flux-todomvc,dmlinn/flux,viviancpy/flux,lishengzxc/flux,baijuachari/flux,tcat/flux,james4388/flux,bilboJ/flux,UIKit0/flux-1,oopchoi/flux,crsgypin/flux,gold3bear/flux,maksymshtyria/flux,jmandel/flux,0rangeT1ger/flux,doron2402/flux,tom-mats/flux,0rangeT1ger/flux,lilien1010/flux,alexeybondarenko/flux,UIKit0/flux-1,dbenson24/flux,micahlmartin/flux,tcxq42aa/flux,tcat/flux,robhogfeldt-fron15/flux,superphung/flux,danielchatfield/flux,monkeyFeathers/flux,wrrnwng/flux,rachidmrad/flux,haruair/flux,vijayasingh523/flux,alemontree/flux,ruistime/flux,justin3737/flux,chikamichi/flux,jugend/flux,dbenson24/flux,gajus/flux,juliangamble/flux,alucas/flux,steveleec/flux,Binzzzz/flux,MjAbuz/flux,doxiaodong/flux,zshift/flux,aijiekj/flux,ruistime/flux,debbas/ChatV2,johan/flux,jinkea/flux,eclectriq/flux,icefoggy/flux,crzidea/flux,garylgh/flux,lgvalle/flux,reinaldo13/flux,kangkot/flux,topogigiovanni/flux,Chen-Han/flux,vijayasingh523/flux,rkho/flux,songguangyu/flux,mircle/flux,jonathanpeterwu/flux,zachwooddoughty/flux,slapheadted/flux-nukebox,Lhuihui/flux,hanan198501/flux,sibinx7/flux,chenckang/flux,v2018z/flux,alemontree/flux,rachidmrad/flux,debbas/ChatV2,gougouGet/flux,ephetic/flux,JunyaOnishi/flux,mcanthony/flux,siddhartharay007/flux,zhzenghui/flux,sahat/flux,v2018z/flux,micahlmartin/flux,CedarLogic/flux,juliangamble/flux,grandsong/flux,akhilxavierm/flux,jeffj/flux,YakovAvramenko/flux,LeeChSien/flux,kris1226/flux,maximvl/flux,soulcm/flux,albi34/flux,Lhuihui/flux,avinnakota/flux,icefoggy/flux,ataker/flux,lyip1992/flux,chikamichi/flux,zachwooddoughty/flux,johan/flux,rohannair/flux,shunyitian/flux,rtfeldman/flux,chenrui2014/flux,roshow/flux,topogigiovanni/flux,Jonekee/flux,gougouGet/flux,blazenko/flux,mattvanhorn/flux,LeeChSien/flux,monkeyFeathers/flux,tbutman/flux,wandrejevic/flux,chenckang/flux,georgetoothman/flux-todo,MjAbuz/flux,glitch100/flux,amoskyler/flux,slapheadted/flux-nukebox,jdholdren/flux,chienchienchen/flux,Demian-Moschin/flux,aijiekj/flux,yejodido/flux,tcat/flux,reinaldo13/flux,cjmanetta/flux,briantopping/flux,aecca/flux,gold3bear/flux,crsr/flux
5bc3d461c0837f1300baeb39c47062d15b2676d7
client/app/bundles/Index/containers/TableHeadCell.js
client/app/bundles/Index/containers/TableHeadCell.js
import { connect } from 'react-redux' import merge from 'lodash/merge' import clone from 'lodash/clone' import pickBy from 'lodash/pickBy' import { encode } from 'querystring' import TableHeadCell from '../components/TableHeadCell' const mapStateToProps = (state, ownProps) => { const { params, field } = ownProps const currentDirection = params.sort_direction const isCurrentSortField = ( params.sort_field == field.field && params.sort_model == field.model ) let linkParams = merge(clone(params), { sort_field: field.field, sort_model: field.model }) if (isCurrentSortField) { linkParams.sort_direction = currentDirection == 'ASC' ? 'DESC' : 'ASC' } let href = `/${ownProps.model}?${encode(pickBy(linkParams))}` const displayName = field.name.split('_').join(' ') return { href, isCurrentSortField, currentDirection, displayName, } } const mapDispatchToProps = (dispatch, ownProps) => ({}) export default connect(mapStateToProps, mapDispatchToProps)(TableHeadCell)
import { connect } from 'react-redux' import merge from 'lodash/merge' import clone from 'lodash/clone' import pickBy from 'lodash/pickBy' import { encode } from 'querystring' import TableHeadCell from '../components/TableHeadCell' const mapStateToProps = (state, ownProps) => { const { params, field } = ownProps const currentDirection = params.sort_direction const isCurrentSortField = ( params.sort_field == field.field && (field.relation == 'own' || params.sort_model == field.model) ) let linkParams = merge(clone(params), { sort_field: field.field, sort_model: (field.relation == 'own' ? null : field.model) }) if (isCurrentSortField) { linkParams.sort_direction = currentDirection == 'ASC' ? 'DESC' : 'ASC' } let href = `/${ownProps.model}?${encode(pickBy(linkParams))}` const displayName = field.name.split('_').join(' ') return { href, isCurrentSortField, currentDirection, displayName, } } const mapDispatchToProps = (dispatch, ownProps) => ({}) export default connect(mapStateToProps, mapDispatchToProps)(TableHeadCell)
Fix for broken sorting on own fields: remove sort_model from params if the field relation is own
Fix for broken sorting on own fields: remove sort_model from params if the field relation is own
JavaScript
mit
clarat-org/claradmin,clarat-org/claradmin,clarat-org/claradmin,clarat-org/claradmin
fb845792abc681eb600b9a17da11120c8064bd07
packages/strapi-plugin-users-permissions/config/layout.js
packages/strapi-plugin-users-permissions/config/layout.js
module.exports = { user: { actions: { create: 'User.create', // Use the User plugin's controller. update: 'User.update', destroy: 'User.destroy', deleteall: 'User.destroyAll', }, attributes: { username: { className: 'col-md-6' }, email: { className: 'col-md-6' }, provider: { className: 'd-none' }, resetPasswordToken: { className: 'd-none' }, role: { className: 'd-none' } } } };
module.exports = { user: { actions: { create: 'User.create', // Use the User plugin's controller. update: 'User.update', destroy: 'User.destroy', deleteall: 'User.destroyAll', }, attributes: { username: { className: 'col-md-6' }, email: { className: 'col-md-6' }, resetPasswordToken: { className: 'd-none' }, role: { className: 'd-none' } } } };
Fix to allow provider to be shown in the content manager
Fix to allow provider to be shown in the content manager
JavaScript
mit
wistityhq/strapi,wistityhq/strapi
0c2e09addecb2384efe3bc310c0afee033586d86
index.js
index.js
'use strict'; var execFile = require('child_process').execFile; module.exports = function (str, cb) { execFile('osascript', ['-e', str], function (err, stdout) { if (err) { cb(err); return; } cb(err, stdout.trim()); }); };
'use strict'; var execFile = require('child_process').execFile; module.exports = function (str, cb) { if (process.platform !== 'darwin') { throw new Error('Only OS X systems are supported'); } execFile('osascript', ['-e', str], function (err, stdout) { if (err) { cb(err); return; } cb(err, stdout.trim()); }); };
Throw error if used on another OS than OS X
Throw error if used on another OS than OS X
JavaScript
mit
sindresorhus/run-applescript
032243593b312553e384dc068255abc5aea77473
index.js
index.js
"use strict"; var util = require('util'); var minimist = require('minimist'); /** * Parse arguments and return command object * @param {array} argv Command line arguments * @param {object} opts Argument parsing options and commands * @return {object} Command object */ module.exports = function(argv, opts) { if (!argv) argv = process.argv.slice(2); opts = opts || {}; opts.commands = opts.commands || {}; opts.stopEarly = true; var global_args = minimist(argv, opts); var command = global_args._[0]; var options = opts.commands[command] || {}; var callback = options.callback || options.cb; if (opts.inheritCommon) { options = util._extend(opts, options); } var args = minimist(global_args._.slice(1), options); function execCommand() { if (typeof callback === 'function') { return callback.apply(null, [args].concat(arguments)); } return false; }; return { name: command, common: global_args, args: args, exec: execCommand, }; };
"use strict"; var util = require('util'); var minimist = require('minimist'); /** * Parse arguments and return command object * @param {array} argv Command line arguments * @param {object} opts Argument parsing options and commands * @return {object} Command object */ module.exports = function(argv, opts) { if (!argv) argv = process.argv.slice(2); opts = opts || {}; opts.commands = opts.commands || {}; opts.stopEarly = true; var global_args = minimist(argv, opts); var command = global_args._[0]; var options = opts.commands[command] || {}; var callback = options.callback || options.cb; if (opts.inheritCommon) { options = util._extend(opts, options); } var args = minimist(global_args._.slice(1), options); return { name: command, common: global_args, args: args, exec: callback && callback.bind(null, args), }; };
Use bind instead of intermediate function
Use bind instead of intermediate function Exec method is 'undefined' if no command callback were defined. Signed-off-by: Harri Kovalainen <2ecf1d4f49b9d136d53b819dc389c152487e9e18@gmail.com>
JavaScript
mit
hakovala/node-simpleton
fe52ed79a76c1fa2a3368da23722ce9f5959e227
index.js
index.js
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-inject-asset-map', // Add asset map hash to asset-map controller postBuild: function (results) { console.log('Injecting asset map hash...'); var fs = require('fs'), path = require('path'), assetMap = results['graph']['tree']['assetMap'], jsPath = path.join(results.directory, assetMap['assets/art19.js']); // TODO: allow specifying name of js file // TODO: I'd love a cleaner way to do this, but I'm not sure sure how since this has to be done after build. var js = fs.readFileSync(jsPath, 'utf-8'), assetMapKey = 'assetMapHash', hackedJs = js.replace(new RegExp(assetMapKey + ': undefined'), assetMapKey + ': ' + JSON.stringify(assetMap)), hackedCompressed = js.replace(new RegExp(assetMapKey + ':void 0'), assetMapKey + ':' + JSON.stringify(assetMap)); // Inject in temp fs.writeFileSync(jsPath, hackedJs, 'utf-8'); // Inject in dist (this assumes dist is using JS compression.) fs.writeFileSync(path.join('./dist', assetMap['assets/art19.js']), hackedCompressed, 'utf-8'); console.log('Done! Asset paths are available in all components, controllers, and routes via assetMap.assetMapHash.'); } };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-inject-asset-map', // Add asset map hash to asset-map controller postBuild: function (results) { var fs = require('fs'), path = require('path'), colors = require('colors'), tree = results['graph']['tree'], assetMap = tree._inputNodes[0].assetMap, jsPath = path.join(results.directory, assetMap['assets/art19.js']), // TODO: allow specifying name of js file js = fs.readFileSync(jsPath, 'utf-8'), assetMapKey = 'assetMapHash', expression = new RegExp(assetMapKey + ':\\s?(void 0|undefined)'), injectedJs = js.replace(expression, assetMapKey + ': ' + JSON.stringify(assetMap)); console.log('\nInjecting asset map hash...'.rainbow); // Write to temp and dist fs.writeFileSync(jsPath, injectedJs, 'utf-8'); fs.writeFileSync(path.join('./dist', assetMap['assets/art19.js']), injectedJs, 'utf-8'); console.log('Done! Asset paths are available in all components, controllers, and routes via assetMap.assetMapHash.'.rainbow); } };
Update to work with new versions of ember-cli
Update to work with new versions of ember-cli
JavaScript
mit
jcaffey/ember-cli-inject-asset-map,jcaffey/ember-cli-inject-asset-map
d49e5b628ef3c352e6664ab290b831b68bd65e3b
notifications/SiteDownNotification.js
notifications/SiteDownNotification.js
"use strict"; var Mail = require('./channels/Mail'); var Console = require('./channels/Console'); class SiteDownNotification { constructor(site) { this.site = site; this.message = site.getAttribute('url') + ' is down!'; } toMail() { return new Mail().setBody(this.message); } toConsole() { return new Console().setBody(this.message); } via() { return ['mail', 'console']; } } module.exports = SiteDownNotification;
"use strict"; var Mail = require('./channels/Mail'); var Console = require('./channels/Console'); class SiteDownNotification { constructor(site) { this.site = site; this.message = site.getAttribute('url') + ' is down!'; } toMail() { return new Mail().setBody(this.message); } toConsole() { return new Console().setBody(this.message); } via() { return (this.site.notifications) ? this.site.notifications : ['console']; } } module.exports = SiteDownNotification;
Send notification based on the sites settings
Send notification based on the sites settings
JavaScript
mit
jonathandey/uptime-monitor,jonathandey/uptime-monitor
7c39d6c44216d85785e064c724f1b11ce0b46745
index.js
index.js
#!/usr/bin/env node var cli = require('cli').enable('version'); var fs = require('fs'); var path = require('path'); var cwd = process.cwd(); var options = cli.parse({ 'append': ['a', 'append to the given FILEs, do not overwrite'], 'ignore-interrupts': ['i', 'ignore interrupt signals'], 'suppress': ['s', 'do NOT output to stdout'] }); var fsWriteFunc = options.append ? 'appendFile' : 'writeFile'; function writeToFiles (data, files) { if (!files.length) { return output(data); } fs[fsWriteFunc](path.resolve(cwd, files.shift()), data, function (err) { if (err) throw err; writeToFiles(data, files); }); } function output (data) { if (!options.suppress) { cli.output(data); } } function interceptInt () { if (!options['ignore-interrupts']) { process.exit(); } } process.on('SIGINT', interceptInt); cli.withStdin(function (stdin) { writeToFiles(stdin, cli.args); });
#!/usr/bin/env node var cli = require('cli').enable('version').setApp('./package.json'); var fs = require('fs'); var path = require('path'); var cwd = process.cwd(); var options = cli.parse({ 'append': ['a', 'append to the given FILEs, do not overwrite'], 'ignore-interrupts': ['i', 'ignore interrupt signals'], 'suppress': ['s', 'do NOT output to stdout'] }); var fsWriteFunc = options.append ? 'appendFile' : 'writeFile'; function writeToFiles (data, files) { if (!files.length) { return output(data); } fs[fsWriteFunc](path.resolve(cwd, files.shift()), data, function (err) { if (err) throw err; writeToFiles(data, files); }); } function output (data) { if (!options.suppress) { cli.output(data); } } function interceptInt () { if (!options['ignore-interrupts']) { process.exit(); } } process.on('SIGINT', interceptInt); cli.withStdin(function (stdin) { writeToFiles(stdin, cli.args); });
Fix ntee -h/--help not showing right name and version and showing cli's ones instead
Fix ntee -h/--help not showing right name and version and showing cli's ones instead
JavaScript
mit
stefanmaric/ntee
cfe3214bc9f571c7e428c85dcd4fcb4845ad5832
index.js
index.js
module.exports = Storage function Storage () { if (!(this instanceof Storage)) return new Storage() this.chunks = [] } Storage.prototype.put = function (index, buf, cb) { this.chunks[index] = buf if (cb) process.nextTick(cb) } function nextTick (cb, err, val) { process.nextTick(function () { cb(err, val) }) } Storage.prototype.get = function (index, opts, cb) { if (typeof opts === 'function') return this.get(index, null, opts) var buf = this.chunks[index] if (!buf) return nextTick(cb, new Error('Chunk not found')) if (!opts) return nextTick(cb, null, buf) var offset = opts.offset || 0 var len = opts.length || (buf.length - offset) nextTick(cb, null, buf.slice(offset, len + offset)) }
module.exports = Storage function Storage (chunkLength) { if (!(this instanceof Storage)) return new Storage() this.chunks = [] this.chunkLength = Number(chunkLength) this.closed = false if (!this.chunkLength) throw new Error('First argument must be a chunk length') } Storage.prototype.put = function (index, buf, cb) { if (this.closed) return nextTick(cb, new Error('Storage is closed')) if (buf.length !== this.chunkLength) { return nextTick(cb, new Error('Chunk length must be ' + this.chunkLength)) } this.chunks[index] = buf if (cb) process.nextTick(cb) } Storage.prototype.get = function (index, opts, cb) { if (typeof opts === 'function') return this.get(index, null, opts) if (this.closed) return nextTick(cb, new Error('Storage is closed')) var buf = this.chunks[index] if (!buf) return nextTick(cb, new Error('Chunk not found')) if (!opts) return nextTick(cb, null, buf) var offset = opts.offset || 0 var len = opts.length || (buf.length - offset) nextTick(cb, null, buf.slice(offset, len + offset)) } Storage.prototype.close = Storage.prototype.destroy = function (cb) { if (this.closed) return nextTick(cb, new Error('Storage is closed')) this.closed = true this.chunks = null nextTick(cb, null) } function nextTick (cb, err, val) { process.nextTick(function () { if (cb) cb(err, val) }) }
Add close and destroy; force fixed chunk length
Add close and destroy; force fixed chunk length
JavaScript
mit
mafintosh/memory-chunk-store
eea34dcd016c2b497ff5af29c149d3e97530e566
index.js
index.js
'use strict'; var consecutiveSlash = /(:)?\/+/g; var endsWithExtension = /[^\/]*\.[^\/]+$/g; var fn = function(match, c) { return c ? '://' : '/'; }; var pppath = function(parts, filename) { if (typeof parts === 'string') { parts = [parts]; } if (filename && !endsWithExtension.test(parts[parts.length-1])) { parts.push(filename); } return parts.join('/').replace(consecutiveSlash, fn); }; module.exports = exports = pppath;
'use strict'; var consecutiveSlash = /(:)?\/+/g; var endsWithExtension = /[^\/]*\.[^\/]+$/g; var fn = function(match, c) { return c ? '://' : '/'; }; var pppath = function(parts, filename) { if (typeof parts === 'string') { parts = [parts]; } if (filename && parts[parts.length-1].search(endsWithExtension) === -1) { parts.push(filename); } return parts.join('/').replace(consecutiveSlash, fn); }; module.exports = exports = pppath;
Use `String.search` instead of `RegExp.test`
Use `String.search` instead of `RegExp.test`
JavaScript
mit
yuanqing/pppath
869ba7c3b24aa0d8b3d15481df4a7de5327a64e9
lib/white.js
lib/white.js
var generatePairs = function(string) { var pairs = []; string = string.toLowerCase(); for (var i = 0; i < string.length - 1; i++) { pair = string.substr(i, 2); if (!/\s/.test(pair)) { pairs.push(pair); } } return pairs; } var whiteSimilarity = function(string1, string2) { string1 = string1.toUpperCase() .replace(/[^A-Z]+/g, ''); string2 = string1.toUpperCase() .replace(/[^A-Z]+/g, ''); var pairs1 = generatePairs(string1); var pairs2 = generatePairs(string2); var union = pairs1.length + pairs2.length; var hitCount = 0; for (x in pairs1) { for (y in pairs2) { if (pairs1[x] == pairs2[y]) { hitCount++; } } } score = ((2.0 * hitCount) / union).toFixed(2); return score; } module.exports = whiteSimilarity;
var generatePairs = function(string) { superPairs = string.toUpperCase() .replace(/[^A-Z ]+/g, '') .split(/\s+/); superPairs = superPairs .map(function(word) { breaks = []; for (var i = 0; i < word.length - 1; i++) { breaks.push(word.slice(i, i + 2)); } return breaks; }); pairs = [].concat.apply([], superPairs); return pairs; } var whiteSimilarity = function(string1, string2) { var pairs1 = generatePairs(string1); var pairs2 = generatePairs(string2); var union = pairs1.length + pairs2.length; var hitCount = 0; for (x in pairs1) { for (y in pairs2) { if (pairs1[x] == pairs2[y]) { hitCount++; pairs2[y] = ''; } } } score = ((2.0 * hitCount) / union).toFixed(2); return score; } module.exports = whiteSimilarity;
Make pair generation extensible to multiple words
Make pair generation extensible to multiple words
JavaScript
mit
sanchitgera/Lingual
62c1b14f0e0da04c0952865a74ede42b21ae864b
index.js
index.js
module.exports = function (paths, ignores) { let result = [] let edge = String.prototype for (let i = 0, ignoresLength = ignores.length; i < ignoresLength; i++) { let ignore = ignores[i] if (ignore.lastIndexOf('.') > ignore.lastIndexOf('/')) { edge = edge.endsWith } else { edge = edge.startsWith } for (let j = 0, pathsLength = paths.length; j < pathsLength; j++) { let path = paths[j] if (!edge.call(path, ignore)) { result[result.length] = path } } } return result }
function startsWith (value, start) { return value.slice(0, start.length) === start } function endsWith (value, end) { return value.slice(value.length - end.length) === end } module.exports = function (paths, ignores) { let result = [] let edge for (let i = 0, ignoresLength = ignores.length; i < ignoresLength; i++) { let ignore = ignores[i] if (ignore.lastIndexOf('.') > ignore.lastIndexOf('/')) { edge = endsWith } else { edge = startsWith } for (let j = 0, pathsLength = paths.length; j < pathsLength; j++) { let path = paths[j] if (!edge(path, ignore)) { result[result.length] = path } } } return result }
Use startsWith and endsWith functions
Use startsWith and endsWith functions
JavaScript
mit
whaaaley/path-ignore
5b057575255fc56845c37bae3289da0a72fe93a4
src/routerViewPort.js
src/routerViewPort.js
import {TemplateDirective, View, ViewPort, ViewFactory, InitAttrs} from 'templating'; import {Injector, Inject} from 'di'; @TemplateDirective({selector: 'router-view-port'}) export class RouterViewPort { @Inject(ViewFactory, ViewPort, 'executionContext', Injector, InitAttrs) constructor(viewFactory, viewPort, executionContext, attrs) { this.viewFactory = viewFactory; this.viewPort = viewPort; this.executionContext = executionContext; this.view = null; if ('router' in this.executionContext) { this.executionContext.router.registerViewPort(this, attrs.name); } } createComponentView(directive, providers){ return this.viewFactory.createComponentView({ component: directive, providers: providers, viewPort: this.viewPort }); } process(viewPortInstruction) { this.tryRemoveView(); this.view = viewPortInstruction.component; this.viewPort.append(this.view); } tryRemoveView() { if (this.view) { this.view.remove(); this.view = null; } } }
import {TemplateDirective, View, ViewPort, ViewFactory, InitAttrs} from 'templating'; import {Injector, Inject} from 'di'; @TemplateDirective({selector: 'router-view-port'}) export class RouterViewPort { @Inject(ViewFactory, ViewPort, 'executionContext', Injector, InitAttrs) constructor(viewFactory, viewPort, executionContext, attrs) { this.viewFactory = viewFactory; this.viewPort = viewPort; this.executionContext = executionContext; this.view = null; if ('router' in this.executionContext) { this.executionContext.router.registerViewPort(this, attrs.name); } } createComponentView(directive, providers){ return this.viewFactory.createComponentView({ component: directive, providers: providers, viewPort: this.viewPort }); } process(viewPortInstruction) { this.tryRemoveView(); this.view = viewPortInstruction.component; this.view.appendTo(this.viewPort); } tryRemoveView() { if (this.view) { this.view.remove(); this.view = null; } } }
Update the newest templating API
chore(templating): Update the newest templating API
JavaScript
apache-2.0
shangyilim/router,JanPietrzyk/router,rakeshbhavsar/router,excellalabs/router,shangyilim/router,loomio/router,kyroskoh/router,angular/router,excellalabs/router,JanPietrzyk/router,kyroskoh/router,IgorMinar/router,AyogoHealth/router,rakeshbhavsar/router,AyogoHealth/router,shangyilim/router,IgorMinar/router,IgorMinar/router,loomio/router
02b11e3eef293f87a32bae4ff747dcf4f66d436b
index.js
index.js
var path = require('path'), servestatic = require('serve-static'); var basedir = path.dirname(require.resolve('govuk_template_mustache/package.json')); module.exports = { setup: function (app, options) { options = options || {}; options.path = options.path || '/govuk-assets'; app.use(options.path, servestatic(path.join(basedir, './assets'), options)); app.use(function (req, res, next) { res.locals.govukAssetPath = options.path + '/'; res.locals.partials = res.locals.partials || {}; res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template'); next(); }); } };
var path = require('path'), servestatic = require('serve-static'); var basedir = path.dirname(require.resolve('govuk_template_mustache/package.json')); module.exports = { setup: function (app, options) { options = options || {}; options.path = options.path || '/govuk-assets'; app.use(options.path, servestatic(path.join(basedir, './assets'), options)); app.use(function (req, res, next) { res.locals.govukAssetPath = req.baseUrl + options.path + '/'; res.locals.partials = res.locals.partials || {}; res.locals.partials['govuk-template'] = path.resolve(__dirname, './govuk_template'); next(); }); } };
Include req.baseUrl is asset path
Include req.baseUrl is asset path If app is namespaced under another route then this needs to be taken into account when importing assets
JavaScript
mit
UKHomeOffice/govuk-template-compiler,UKHomeOffice/govuk-template-compiler
288b361b388a23e4b4ea9aef10f659e5ba65a6ca
index.js
index.js
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-power-select' };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-power-select', contentFor: function(type /*, config */) { if (type === 'body-footer') { return `<div id="ember-power-select-wormhole"></div>` } } };
Add the wormhole destination in the {{content-for “body-footer”}}
Add the wormhole destination in the {{content-for “body-footer”}}
JavaScript
mit
cibernox/ember-power-select,Dremora/ember-power-select,cibernox/ember-power-select,chrisgame/ember-power-select,esbanarango/ember-power-select,esbanarango/ember-power-select,cibernox/ember-power-select,esbanarango/ember-power-select,cibernox/ember-power-select,chrisgame/ember-power-select,Dremora/ember-power-select
1e9c43f190abf3cddc7e7704e918abde3368a2ee
index.js
index.js
'use strict'; /* * Dependencies.. */ var Ware; Ware = require('ware'); /* * Components. */ var parse, stringify; parse = require('./lib/parse.js'); stringify = require('./lib/stringify.js'); /** * Construct an MDAST instance. * * @constructor {MDAST} */ function MDAST() { this.parser = new Ware(); } /** * Parse a value and apply plugins. * * @return {Root} */ function runParse(_, options) { var node; node = parse.apply(parse, arguments); this.parser.run(node, options); return node; } /** * Construct an MDAST instance and use a plugin. * * @return {MDAST} */ function use(plugin) { var self; self = this; if (!(self instanceof MDAST)) { self = new MDAST(); } self.parser.use(plugin); return self; } /* * Prototype. */ MDAST.prototype.parse = runParse; MDAST.prototype.stringify = stringify; MDAST.prototype.use = use; /* * Expose `mdast`. */ module.exports = { 'parse': parse, 'stringify': stringify, 'use': use };
'use strict'; /* * Dependencies.. */ var Ware; Ware = require('ware'); /* * Components. */ var parse, stringify; parse = require('./lib/parse.js'); stringify = require('./lib/stringify.js'); /** * Construct an MDAST instance. * * @constructor {MDAST} */ function MDAST() { this.ware = new Ware(); } /** * Parse a value and apply plugins. * * @return {Root} */ function runParse(_, options) { var node; node = parse.apply(parse, arguments); this.ware.run(node, options); return node; } /** * Construct an MDAST instance and use a plugin. * * @return {MDAST} */ function use(plugin) { var self; self = this; if (!(self instanceof MDAST)) { self = new MDAST(); } self.ware.use(plugin); return self; } /* * Prototype. */ MDAST.prototype.parse = runParse; MDAST.prototype.stringify = stringify; MDAST.prototype.use = use; /* * Expose `mdast`. */ module.exports = { 'parse': parse, 'stringify': stringify, 'use': use };
Rename `ware` internally from `parser` to `ware`
Rename `ware` internally from `parser` to `ware`
JavaScript
mit
eush77/remark,tanzania82/remarks,yukkurisinai/mdast,chcokr/mdast,ulrikaugustsson/mdast,yukkurisinai/mdast,ulrikaugustsson/mdast,eush77/remark,wooorm/remark,chcokr/mdast
068ce6d6a58dceb64c32173c37483f821ae8c31e
index.js
index.js
'use strict'; var cheerio = require('cheerio'); var _ = require('underscore'); var multiline = require('multiline'); var template = _.template(multiline(function() { /* <a href="<%= url %>" title="<%= title %>" class="fancybox"> <img src="<%= url %>" alt="<%= title %>"></img> </a> */ })); module.exports = { book: { assets: './assets', js: [ 'jquery.min.js', 'jquery.fancybox.pack.js', 'jquery.fancybox-buttons.js', 'plugin.js' ], css: [ 'jquery.fancybox.css', 'jquery.fancybox-buttons.css' ] }, hooks: { page: function(page) { var $ = cheerio.load(page.content); $('img').each(function(index, img) { var $img = $(img); $img.replaceWith(template({ url: $img.attr('src'), title: $img.attr('alt') })); }); page.content = $.html(); return page; } } };
'use strict'; var cheerio = require('cheerio'); var _ = require('underscore'); var multiline = require('multiline'); var template = _.template(multiline(function() { /* <a href="<%= url %>" title="<%= title %>" target="_self" class="fancybox"> <img src="<%= url %>" alt="<%= title %>"></img> </a> */ })); module.exports = { book: { assets: './assets', js: [ 'jquery.min.js', 'jquery.fancybox.pack.js', 'jquery.fancybox-buttons.js', 'plugin.js' ], css: [ 'jquery.fancybox.css', 'jquery.fancybox-buttons.css' ] }, hooks: { page: function(page) { var $ = cheerio.load(page.content); $('img').each(function(index, img) { var $img = $(img); $img.replaceWith(template({ url: $img.attr('src'), title: $img.attr('alt') })); }); page.content = $.html(); return page; } } };
Add target attribute to a.fancybox to prevent default theme's links following
Add target attribute to a.fancybox to prevent default theme's links following
JavaScript
mit
ly-tools/gitbook-plugin-fancybox,LingyuCoder/gitbook-plugin-fancybox
203d8265d7410a3a8c65366db265569c516f3f12
index.js
index.js
'use strict'; const got = require('got'); const awaitUrl = (url, option) => { const config = Object.assign({}, option, { interval : 1000, tries : 60 }); return new Promise((resolve, reject) => { const attempt = async (tries) => { const res = await got(url, { followRedirect : false, timeout : 5000 }); if (res.statusCode === 200) { resolve(); } else if (Math.max(1, tries) > 1) { setTimeout(attempt, config.interval, tries - 1); } else { reject(new RangeError(`Expected 200 response but got ${res.statusCode}`)); } }; attempt(config.tries).catch(reject); }); }; module.exports = awaitUrl;
'use strict'; const got = require('got'); const awaitUrl = (url, option) => { const config = Object.assign({}, option, { interval : 1000, tries : 60 }); return new Promise((resolve, reject) => { const attempt = async (tries) => { const res = await got(url, { followRedirect : false, timeout : { connect : 10000, socket : 10000, request : 10000 } }); if (res.statusCode === 200) { resolve(); } else if (Math.max(1, tries) > 1) { setTimeout(attempt, config.interval, tries - 1); } else { reject(new RangeError(`Expected 200 response but got ${res.statusCode}`)); } }; attempt(config.tries).catch(reject); }); }; module.exports = awaitUrl;
Increase timeouts for very slow servers
Increase timeouts for very slow servers
JavaScript
mpl-2.0
sholladay/await-url
c7ac887023341250eb1c4c6e9bb70ae5138b23f9
index.js
index.js
var es6tr = require("es6-transpiler"); var createES6TranspilerPreprocessor = function(args, config, logger, helper) { config = config || {}; var log = logger.create('preprocessor.es6-transpiler'); var defaultOptions = { }; var options = helper.merge(defaultOptions, args.options || {}, config.options || {}); var transformPath = args.transformPath || config.transformPath || function(filepath) { return filepath.replace(/\.es6.js$/, '.js').replace(/\.es6$/, '.js'); }; return function(content, file, done) { log.info('Processing "%s".', file.originalPath); file.path = transformPath(file.originalPath); options.filename = file.originalPath; var result = es6tr.run({ filename: options.filename }); var transpiledContent = result.src; result.errors.forEach(function(err) { log.error(err); }); if (result.errors.length) { return done(new Error('ES6-TRANSPILER COMPILE ERRORS\n' + result.errors.join('\n'))); } // TODO: add sourceMap to transpiledContent return done(null, transpiledContent); }; }; createES6TranspilerPreprocessor.$inject = ['args', 'config.es6TranspilerPreprocessor', 'logger', 'helper']; // export es6-transpiler preprocessor module.exports = { 'preprocessor:es6-transpiler': ['factory', createES6TranspilerPreprocessor] };
var es6tr = require("es6-transpiler"); var createES6TranspilerPreprocessor = function(args, config, logger, helper) { config = config || {}; var log = logger.create('preprocessor.es6-transpiler'); var defaultOptions = { }; var options = helper.merge(defaultOptions, args.options || {}, config.options || {}); var transformPath = args.transformPath || config.transformPath || function(filepath) { return filepath.replace(/\.es6.js$/, '.js').replace(/\.es6$/, '.js'); }; return function(content, file, done) { log.info('Processing "%s".', file.originalPath); file.path = transformPath(file.originalPath); options.filename = file.originalPath; var result = es6tr.run(options); var transpiledContent = result.src; result.errors.forEach(function(err) { log.error(err); }); if (result.errors.length) { return done(new Error('ES6-TRANSPILER COMPILE ERRORS\n' + result.errors.join('\n'))); } // TODO: add sourceMap to transpiledContent return done(null, transpiledContent); }; }; createES6TranspilerPreprocessor.$inject = ['args', 'config.es6TranspilerPreprocessor', 'logger', 'helper']; // export es6-transpiler preprocessor module.exports = { 'preprocessor:es6-transpiler': ['factory', createES6TranspilerPreprocessor] };
Fix options passed to es6-transpiler
Fix options passed to es6-transpiler Otherwise, `options` is useless.
JavaScript
bsd-3-clause
ouhouhsami/karma-es6-transpiler-preprocessor
3651031dc09ea89f35ffc67363af07f444f2caf7
index.js
index.js
'use strict'; var EventEmitter = require('events').EventEmitter; var Promise = require('bluebird'); var emitThen = function (event) { var args = Array.prototype.slice.call(arguments, 1); return Promise .bind(this) .return(this) .call('listeners', event) .map(function (listener) { var a1 = args[0], a2 = args[1]; switch (args.length) { case 0: return listener.call(this); case 1: return listener.call(this, a1) case 2: return listener.call(this, a1, a2); default: return listener.apply(this, args); } }) .return(null); }; emitThen.register = function () { EventEmitter.prototype.emitThen = emitThen; }; module.exports = emitThen;
'use strict'; var EventEmitter = require('events').EventEmitter; var Promise = require('bluebird'); function emitThen (event) { var args = Array.prototype.slice.call(arguments, 1); /* jshint validthis:true */ return Promise .bind(this) .return(this) .call('listeners', event) .map(function (listener) { var a1 = args[0], a2 = args[1]; switch (args.length) { case 0: return listener.call(this); case 1: return listener.call(this, a1) case 2: return listener.call(this, a1, a2); default: return listener.apply(this, args); } }) .return(null); } emitThen.register = function () { EventEmitter.prototype.emitThen = emitThen; }; module.exports = emitThen;
Use a named function instead of anon
Use a named function instead of anon
JavaScript
mit
bendrucker/emit-then
8fd6bc21784da5a9cb1bb22ba515b85fb9f8f1a3
index.js
index.js
var httpProxy = require('http-proxy'); var http = require('http'); var CORS_HEADERS = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE', 'access-control-max-age': '86400', 'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization" }; var proxy = httpProxy.createProxyServer(); http.createServer(function(req, res) { if (req.method === 'OPTIONS') { // Respond to OPTIONS requests advertising we support full CORS for * res.writeHead(200, CORS_HEADERS); res.end(); return } // Remove our original host so it doesn't mess up Google's header parsing. delete req.headers.host; proxy.web(req, res, { target: 'https://spreadsheets.google.com:443', xfwd: false }); // Add CORS headers to every other request also. proxy.on('proxyRes', function(proxyRes, req, res) { for (var key in CORS_HEADERS) { proxyRes.headers[key] = CORS_HEADERS[key]; } }); }).listen(process.env.PORT || 5000);
var httpProxy = require('http-proxy'); var http = require('http'); var CORS_HEADERS = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE', 'access-control-max-age': '86400', 'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization" }; var proxy = httpProxy.createProxyServer(); // Add CORS headers to every other request also. proxy.on('proxyRes', function(proxyRes, req, res) { for (var key in CORS_HEADERS) { proxyRes.headers[key] = CORS_HEADERS[key]; } }); proxy.on('error', function(err, req, res) { console.log(err); var json = { error: 'proxy_error', reason: err.message }; if (!res.headersSent) { res.writeHead(500, {'content-type': 'application/json'}); } res.end(JSON.stringify(json)); }); http.createServer(function(req, res) { if (req.method === 'OPTIONS') { // Respond to OPTIONS requests advertising we support full CORS for * res.writeHead(200, CORS_HEADERS); res.end(); return } // Remove our original host so it doesn't mess up Google's header parsing. delete req.headers.host; proxy.web(req, res, { target: 'https://spreadsheets.google.com:443', xfwd: false }); }).listen(process.env.PORT || 5000);
Move proxyRes out of request handler; trap errors
Move proxyRes out of request handler; trap errors
JavaScript
mpl-2.0
yourcelf/gspreadsheets-cors-proxy
10280069a4c1ecf5cbaebd8b0f9b67f3d9c219d2
index.js
index.js
'use strict'; var execFile = require('child_process').execFile; var wifiName = require('wifi-name'); function getPassword(ssid, cb) { var cmd = 'sudo'; var args = ['cat', '/etc/NetworkManager/system-connections/' + ssid]; var ret; execFile(cmd, args, function (err, stdout) { if (err) { cb(err); return; } ret = /^\s*psk=(.+)\s*$/gm.exec(stdout); ret = ret && ret.length ? ret[1] : null; if (!ret) { cb(new Error('Could not get password')); return; } cb(null, ret); }); } module.exports = function (ssid, cb) { if (process.platform !== 'linux') { throw new Error('Only Linux systems are supported'); } if (ssid && typeof ssid !== 'function') { getPassword(ssid, cb); return; } else if (ssid && !cb) { cb = ssid; } wifiName(function (err, name) { if (err) { cb(err); return; } getPassword(name, cb); }); };
'use strict'; var execFile = require('child_process').execFile; var wifiName = require('wifi-name'); function getPassword(ssid, cb) { var cmd = 'sudo'; var args = ['cat', '/etc/NetworkManager/system-connections/' + ssid]; var ret; execFile(cmd, args, function (err, stdout) { if (err) { cb(err); return; } ret = /^\s*(?:psk|password)=(.+)\s*$/gm.exec(stdout); ret = ret && ret.length ? ret[1] : null; if (!ret) { cb(new Error('Could not get password')); return; } cb(null, ret); }); } module.exports = function (ssid, cb) { if (process.platform !== 'linux') { throw new Error('Only Linux systems are supported'); } if (ssid && typeof ssid !== 'function') { getPassword(ssid, cb); return; } else if (ssid && !cb) { cb = ssid; } wifiName(function (err, name) { if (err) { cb(err); return; } getPassword(name, cb); }); };
Add support for WPA2 Enterprise
Add support for WPA2 Enterprise Fixes #1.
JavaScript
mit
kevva/linux-wifi-password
4683e61d4d3eb6fb696f5e5672831b1f0de0d3db
index.js
index.js
'use strict'; const EventEmitter = require('events'); const devtools = require('./lib/devtools.js'); const Chrome = require('./lib/chrome.js'); function CDP(options, callback) { if (typeof options === 'function') { callback = options; options = undefined; } const notifier = new EventEmitter(); if (typeof callback === 'function') { // allow to register the error callback later process.nextTick(() => { new Chrome(options, notifier); }); return notifier.once('connect', callback); } else { return new Promise((fulfill, reject) => { notifier.once('connect', fulfill); notifier.once('error', reject); new Chrome(options, notifier); }); } } module.exports = CDP; module.exports.Protocol = devtools.Protocol; module.exports.List = devtools.List; module.exports.New = devtools.New; module.exports.Activate = devtools.Activate; module.exports.Close = devtools.Close; module.exports.Version = devtools.Version;
'use strict'; const EventEmitter = require('events'); const dns = require('dns'); const devtools = require('./lib/devtools.js'); const Chrome = require('./lib/chrome.js'); // XXX reset the default that has been changed in // (https://github.com/nodejs/node/pull/39987) to prefer IPv4. since // implementations alway bind on 127.0.0.1 this solution should be fairly safe // (see #467) dns.setDefaultResultOrder('ipv4first'); function CDP(options, callback) { if (typeof options === 'function') { callback = options; options = undefined; } const notifier = new EventEmitter(); if (typeof callback === 'function') { // allow to register the error callback later process.nextTick(() => { new Chrome(options, notifier); }); return notifier.once('connect', callback); } else { return new Promise((fulfill, reject) => { notifier.once('connect', fulfill); notifier.once('error', reject); new Chrome(options, notifier); }); } } module.exports = CDP; module.exports.Protocol = devtools.Protocol; module.exports.List = devtools.List; module.exports.New = devtools.New; module.exports.Activate = devtools.Activate; module.exports.Close = devtools.Close; module.exports.Version = devtools.Version;
Revert the default DNS lookup order to IPv4-first
Revert the default DNS lookup order to IPv4-first Fix #467
JavaScript
mit
cyrus-and/chrome-remote-interface,cyrus-and/chrome-remote-interface
864ce5aa89a99b17051bb41ce243490b8be0d4a1
index.js
index.js
'use strict' var postcss = require('postcss') var isVendorPrefixed = require('is-vendor-prefixed') module.exports = postcss.plugin('postcss-remove-prefixes', function (options) { if (!options) { options = {}; } var ignore = options.ignore ? Array.isArray(options.ignore) ? options.ignore : false : []; if (ignore === false) { throw TypeError("options.ignore must be an array") } for (var i = 0; i < ignore.length; ++i) { var value = ignore[i]; if (typeof value === "string") { value = new RegExp(value + "$", "i") } else if (value instanceof RegExp) { } else { throw TypeError("options.ignore values can either be a string or a regular expression") } ignore[i] = value; } return function removePrefixes(root, result) { root.walkDecls(function (declaration) { if (isVendorPrefixed(declaration.prop) || isVendorPrefixed(declaration.value)) { var isIgnored = false; for (var i = 0; i < ignore.length; ++i) { var value = ignore[i]; if (value.test(declaration.prop)) { isIgnored = true; break; } } if (!isIgnored) { declaration.remove() } } }) } })
'use strict' var postcss = require('postcss') var isVendorPrefixed = require('is-vendor-prefixed') module.exports = postcss.plugin('postcss-remove-prefixes', function (options) { if (!options) { options = { ignore: [] } } if (!Array.isArray(options.ignore)) { throw TypeError("options.ignore must be an array") } var ignore = options.ignore.map(function (value) { if (typeof value === 'string') { return new RegExp(value + '$', 'i') } else if (value instanceof RegExp) { return value } else { throw TypeError('options.ignore values can either be a string or a regular expression') } }) return function removePrefixes(root, result) { root.walkDecls(function (declaration) { if (isVendorPrefixed(declaration.prop) || isVendorPrefixed(declaration.value)) { var isIgnored = false; for (var i = 0; i < ignore.length; ++i) { var value = ignore[i]; if (value.test(declaration.prop)) { isIgnored = true; break; } } if (!isIgnored) { declaration.remove() } } }) } })
Change code as per @johnotander's suggestion
Change code as per @johnotander's suggestion
JavaScript
mit
johnotander/postcss-remove-prefixes
48db09838c934b349250efbada6aadcc95fece9c
index.js
index.js
/* jshint node: true */ 'use strict'; var path = require('path'); var filterInitializers = require('fastboot-filter-initializers'); var VersionChecker = require('ember-cli-version-checker'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-cli-head', treeForApp: function(defaultTree) { var checker = new VersionChecker(this); var emberVersion = checker.for('ember', 'bower'); var trees = [defaultTree]; // 2.9.0-beta.1 - 2.9.0-beta.5 used glimmer2 (but 2.9.0 did not) // 2.10.0-beta.1+ includes glimmer2 if (!(emberVersion.gt('2.9.0-beta') && emberVersion.lt('2.9.0')) && !emberVersion.gt('2.10.0-beta')) { trees.push(this.treeGenerator(path.resolve(this.root, 'app-lt-2-10'))); } var tree = mergeTrees(trees, { overwrite: true }); return filterInitializers(tree); } };
/* jshint node: true */ 'use strict'; var path = require('path'); var filterInitializers = require('fastboot-filter-initializers'); var VersionChecker = require('ember-cli-version-checker'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-cli-head', treeForApp: function(defaultTree) { var checker = new VersionChecker(this); var emberVersion = checker.for('ember-source', 'npm'); if (!emberVersion.version) { emberVersion = checker.for('ember', 'bower'); } var trees = [defaultTree]; // 2.9.0-beta.1 - 2.9.0-beta.5 used glimmer2 (but 2.9.0 did not) // 2.10.0-beta.1+ includes glimmer2 if (!(emberVersion.gt('2.9.0-beta') && emberVersion.lt('2.9.0')) && !emberVersion.gt('2.10.0-beta')) { trees.push(this.treeGenerator(path.resolve(this.root, 'app-lt-2-10'))); } var tree = mergeTrees(trees, { overwrite: true }); return filterInitializers(tree); } };
Check ember-source version from NPM, if not found use ember from bower
Check ember-source version from NPM, if not found use ember from bower
JavaScript
mit
ronco/ember-cli-head,ronco/ember-cli-head