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
62b43e17c7f22f339b9d0e84792a63dbcaf6d83c
EPFL_People.user.js
EPFL_People.user.js
// ==UserScript== // @name EPFL People // @namespace none // @description A script to improve browsing on people.epfl.ch // @include http://people.epfl.ch/* // @version 1 // @grant none // @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js // @author EPFL-dojo // ==/UserScript== //Avoid conflicts this.$ = this.jQuery = jQuery.noConflict(true); $(document).ready(function() { // get the h1 name content $.h1name = $("h1").text(); // get the sciper number $.sciper = $('a[href*="http://people.epfl.ch/cgi-bin/people?id="]').attr('href').match(/id=([0-9]{6})/)[1]; // change the main title content to add the sciper in it $("h1").text($.h1name + " #" + $.sciper + " ()"); $.get("/cgi-bin/people/showcv?id=" + $.sciper + "&op=admindata&type=show&lang=en&cvlang=en", function(data){ $.username = data.match(/Username: (\w+)\s/)[1] $("h1").text($.h1name + " #" + $.sciper + " (" + $.username + ")"); }) });
// ==UserScript== // @name EPFL People // @namespace none // @description A script to improve browsing on people.epfl.ch // @include http://people.epfl.ch/* // @version 1 // @grant none // @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js // @author EPFL-dojo // ==/UserScript== //Avoid conflicts this.$ = this.jQuery = jQuery.noConflict(true); $(document).ready(function() { // get the h1 name content $.epfl_user = { "name": $("h1").text(), "sciper": $('a[href*="http://people.epfl.ch/cgi-bin/people?id="]').attr('href').match(/id=([0-9]{6})/)[1] }; // change the main title content to add the sciper in it $("h1").text($.epfl_user["name"] + " #" + $.epfl_user["sciper"] + " ()"); $.get("/cgi-bin/people/showcv?id=" + $.epfl_user["sciper"] + "&op=admindata&type=show&lang=en&cvlang=en", function(data){ $.epfl_user["username"] = data.match(/Username: (\w+)\s/)[1]; $("h1").text($.epfl_user["name"] + " #" + $.epfl_user["sciper"] + " (" + $.epfl_user["username"]+ ")"); }) });
Save only one variable (dict)
Save only one variable (dict)
JavaScript
unlicense
epfl-dojo/EPFL_People_UserScript
c85b6344fcaaa605fb5aa58de659a0e5e042d1e3
src/js/controller/about.js
src/js/controller/about.js
'use strict'; var cfg = require('../app-config').config; // // Controller // var AboutCtrl = function($scope) { $scope.state.about = { toggle: function(to) { $scope.state.lightbox = (to) ? 'about' : undefined; } }; // // scope variables // $scope.version = cfg.appVersion; $scope.date = new Date(); // // scope functions // }; module.exports = AboutCtrl;
'use strict'; var cfg = require('../app-config').config; // // Controller // var AboutCtrl = function($scope) { $scope.state.about = { toggle: function(to) { $scope.state.lightbox = (to) ? 'about' : undefined; } }; // // scope variables // $scope.version = cfg.appVersion + ' (beta)'; $scope.date = new Date(); // // scope functions // }; module.exports = AboutCtrl;
Add beta ta to version
Add beta ta to version
JavaScript
mit
whiteout-io/mail-html5,kalatestimine/mail-html5,halitalf/mail-html5,sheafferusa/mail-html5,whiteout-io/mail,b-deng/mail-html5,dopry/mail-html5,dopry/mail-html5,kalatestimine/mail-html5,clochix/mail-html5,tanx/hoodiecrow,dopry/mail-html5,b-deng/mail-html5,whiteout-io/mail,dopry/mail-html5,halitalf/mail-html5,halitalf/mail-html5,b-deng/mail-html5,b-deng/mail-html5,whiteout-io/mail-html5,sheafferusa/mail-html5,sheafferusa/mail-html5,kalatestimine/mail-html5,whiteout-io/mail-html5,whiteout-io/mail-html5,whiteout-io/mail,tanx/hoodiecrow,clochix/mail-html5,tanx/hoodiecrow,halitalf/mail-html5,kalatestimine/mail-html5,whiteout-io/mail,clochix/mail-html5,clochix/mail-html5,sheafferusa/mail-html5
b36005ed996391dbf9502aaffbed6e0fc1297d28
main.js
main.js
var app = require('app'); var BrowserWindow = require('browser-window'); var glob = require('glob'); var mainWindow = null; // Require and setup each JS file in the main-process dir glob('main-process/**/*.js', function (error, files) { files.forEach(function (file) { require('./' + file).setup(); }); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); app.on('ready', () => { mainWindow = new BrowserWindow({ width: 800, height: 900 }); mainWindow.loadURL('file://' + __dirname + '/index.html'); // mainWindow.openDevTools(); mainWindow.on('closed', () => { mainWindow = null; }); });
var app = require('app'); var BrowserWindow = require('browser-window'); var glob = require('glob'); var mainWindow = null; // Require and setup each JS file in the main-process dir glob('main-process/**/*.js', function (error, files) { files.forEach(function (file) { require('./' + file).setup(); }); }); function createWindow () { mainWindow = new BrowserWindow({ width: 800, height: 900 }); mainWindow.loadURL('file://' + __dirname + '/index.html'); mainWindow.on('closed', function() { mainWindow = null; }); } app.on('ready', createWindow); app.on('window-all-closed', function () { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', function () { if (mainWindow === null) { createWindow(); } });
Handle OS X no window situation
Handle OS X no window situation Same setup as quick start guide
JavaScript
mit
PanCheng111/XDF_Personal_Analysis,electron/electron-api-demos,electron/electron-api-demos,electron/electron-api-demos,blep/electron-api-demos,blep/electron-api-demos,blep/electron-api-demos,blep/electron-api-demos,PanCheng111/XDF_Personal_Analysis,PanCheng111/XDF_Personal_Analysis
9f5a15819d2f6503f33e5b27b0d30be239e5e72a
main.js
main.js
console.log("I'm ready");
// Init the app after page loaded. window.onload = initPage; // The entry function. function initPage() { if (!canvasSupport()) { // If Canvas is not supported on the browser, do nothing but tell the user. alert("Sorry, your browser does not support HTML5 Canvas"); return false; } drawScreen(); } function drawScreen() { var canvas = document.getElementById("theCanvas"); if (!canvas) { throw new Error("The canvas element does not exists!"); } } // Does the browser support HTML5 Canvas ? function canvasSupport() { var canvas = document.createElement("canvas"); return !!(canvas.getContext && canvas.getContext("2d")); }
Make sure Canvas is supported on the browser
Make sure Canvas is supported on the browser
JavaScript
mit
rainyjune/canvas-guesstheletter,rainyjune/canvas-guesstheletter
b77e8e11e199428578ca8074a6367d9c740d1182
{{cookiecutter.repo_name}}/webapp/webapp/webpack/config.dev.js
{{cookiecutter.repo_name}}/webapp/webapp/webpack/config.dev.js
/* eslint-disable */ const path = require('path'); const webpack = require('webpack'); const makeConfig = require('./config.base'); // The app/ dir const app_root = path.resolve(__dirname, '..'); const filenameTemplate = 'webapp/[name]'; const config = makeConfig({ filenameTemplate: filenameTemplate, mode: 'development', devtool: 'eval-source-map', namedModules: true, minimize: false, // Needed for inline CSS (via JS) - see set-public-path.js for more info prependSources: [path.resolve(app_root, 'webpack', 'set-public-path.js')], // This must be same as Django's STATIC_URL setting publicPath: '/static/', plugins: [], performance: { hints: 'warning', }, }); console.log("Using DEV config"); module.exports = config;
/* eslint-disable */ const path = require('path'); const webpack = require('webpack'); const makeConfig = require('./config.base'); // The app/ dir const app_root = path.resolve(__dirname, '..'); const filenameTemplate = 'webapp/[name]'; const config = makeConfig({ filenameTemplate: filenameTemplate, mode: 'development', devtool: 'eval-source-map', namedModules: true, minimize: false, // Needed for inline CSS (via JS) - see set-public-path.js for more info prependSources: [path.resolve(app_root, 'webpack', 'set-public-path.js')], // This must be same as Django's STATIC_URL setting publicPath: '/assets/', plugins: [], performance: { hints: 'warning', }, }); console.log("Using DEV config"); module.exports = config;
Fix wrong public URL for static in webpack
Fix wrong public URL for static in webpack After a recent change, `STATIC_URL` is now `assets` in the webapp. The webpack config has not been updated though, and the frontend was trying an old URL.
JavaScript
isc
thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template,thorgate/django-project-template
285c390eb811461d517f777a03167d9f44913af5
views/components/touch-feedback.android.js
views/components/touch-feedback.android.js
import React from "react-native"; const { TouchableNativeFeedback } = React; export default class TouchFeedback extends React.Component { render() { return ( <TouchableNativeFeedback {...this.props} background={TouchableNativeFeedback.Ripple(this.props.pressColor)}> {this.props.children} </TouchableNativeFeedback> ); } } TouchFeedback.propTypes = { pressColor: React.PropTypes.string, children: React.PropTypes.node };
import React from "react-native"; import VersionCodes from "../../modules/version-codes"; const { TouchableNativeFeedback, Platform } = React; export default class TouchFeedback extends React.Component { render() { return ( <TouchableNativeFeedback {...this.props} background={ Platform.Version >= VersionCodes.LOLLIPOP ? TouchableNativeFeedback.Ripple(this.props.pressColor) : TouchableNativeFeedback.SelectableBackground() } > {this.props.children} </TouchableNativeFeedback> ); } } TouchFeedback.propTypes = { pressColor: React.PropTypes.string, children: React.PropTypes.node };
Fix crash on Android 4.x
Fix crash on Android 4.x
JavaScript
unknown
wesley1001/io.scrollback.neighborhoods,wesley1001/io.scrollback.neighborhoods,scrollback/io.scrollback.neighborhoods,scrollback/io.scrollback.neighborhoods
32c88d9541ed8b948d82c27e84d974d6340d3cb8
views/controllers/room-title-controller.js
views/controllers/room-title-controller.js
import React from "react-native"; import RoomTitle from "../components/room-title"; import controller from "./controller"; const { InteractionManager } = React; @controller export default class RoomTitleController extends React.Component { constructor(props) { super(props); const displayName = this.props.room.replace(/-+/g, " ").replace(/\w\S*/g, s => s.charAt(0).toUpperCase() + s.slice(1)).trim(); this.state = { room: { displayName } }; } componentDidMount() { setTimeout(() => this._onDataArrived(this.store.getRoomById(this.props.room)), 0); } _onDataArrived(room) { InteractionManager.runAfterInteractions(() => { if (this._mounted) { this.setState({ room }); } }); } render() { return <RoomTitle {...this.state} />; } } RoomTitleController.propTypes = { room: React.PropTypes.string.isRequired };
import React from "react-native"; import RoomTitle from "../components/room-title"; import controller from "./controller"; const { InteractionManager } = React; @controller export default class RoomTitleController extends React.Component { constructor(props) { super(props); const displayName = this.props.room.replace(/-+/g, " ").replace(/\w\S*/g, s => s.charAt(0).toUpperCase() + s.slice(1)).trim(); this.state = { room: { displayName } }; } componentDidMount() { this._updateData(); this.handle("statechange", changes => { if (changes.entities && changes.entities[this.props.room]) { this._updateData(); } }); } _updateData() { InteractionManager.runAfterInteractions(() => { if (this._mounted) { const room = this.store.getRoom(this.props.room); if (room.displayName) { this.setState({ room }); } } }); } render() { return <RoomTitle {...this.state} />; } } RoomTitleController.propTypes = { room: React.PropTypes.string.isRequired };
Update room title on store change
Update room title on store change
JavaScript
unknown
scrollback/io.scrollback.neighborhoods,wesley1001/io.scrollback.neighborhoods,wesley1001/io.scrollback.neighborhoods,scrollback/io.scrollback.neighborhoods
5cb17c421ddbb9cc6ddf46b22db5255042c6f7d8
www/static/js/jsfiddle-integration-babel.js
www/static/js/jsfiddle-integration-babel.js
// Do not delete or move this file. // Many fiddles reference it so we have to keep it here. (function() { var tag = document.querySelector( 'script[type="application/javascript;version=1.7"]' ); if (!tag || tag.textContent.indexOf('window.onload=function(){') !== -1) { alert('Bad JSFiddle configuration, please fork the original React JSFiddle'); } tag.setAttribute('type', 'text/babel'); tag.textContent = tag.textContent.replace(/^\/\/<!\[CDATA\[/, ''); })();
// Do not delete or move this file. // Many fiddles reference it so we have to keep it here. (function() { var tag = document.querySelector( 'script[type="application/javascript;version=1.7"]' ); if (!tag || tag.textContent.indexOf('window.onload=function(){') !== -1) { alert('Bad JSFiddle configuration, please fork the original React JSFiddle'); } tag.setAttribute('type', 'text/babel'); tag.textContent = tag.textContent.replace(/^\/\/<!\[CDATA\[/, ''); })();
Fix lint error in master
Fix lint error in master
JavaScript
mit
apaatsio/react,pyitphyoaung/react,maxschmeling/react,krasimir/react,billfeller/react,empyrical/react,yangshun/react,ericyang321/react,aickin/react,brigand/react,jdlehman/react,VioletLife/react,mjackson/react,jorrit/react,mhhegazy/react,camsong/react,pyitphyoaung/react,pyitphyoaung/react,Simek/react,jzmq/react,acdlite/react,chicoxyzzy/react,mjackson/react,empyrical/react,chenglou/react,jameszhan/react,VioletLife/react,silvestrijonathan/react,flarnie/react,mjackson/react,terminatorheart/react,apaatsio/react,empyrical/react,kaushik94/react,yungsters/react,krasimir/react,jzmq/react,cpojer/react,Simek/react,acdlite/react,Simek/react,jorrit/react,yangshun/react,roth1002/react,prometheansacrifice/react,yangshun/react,anushreesubramani/react,TheBlasfem/react,mjackson/react,camsong/react,TheBlasfem/react,krasimir/react,rickbeerendonk/react,empyrical/react,tomocchino/react,jdlehman/react,maxschmeling/react,chicoxyzzy/react,flarnie/react,cpojer/react,maxschmeling/react,mjackson/react,STRML/react,jorrit/react,nhunzaker/react,brigand/react,cpojer/react,apaatsio/react,cpojer/react,billfeller/react,camsong/react,yungsters/react,facebook/react,empyrical/react,ericyang321/react,cpojer/react,dilidili/react,chenglou/react,kaushik94/react,nhunzaker/react,acdlite/react,jameszhan/react,glenjamin/react,acdlite/react,jameszhan/react,anushreesubramani/react,prometheansacrifice/react,krasimir/react,dilidili/react,jorrit/react,pyitphyoaung/react,facebook/react,jdlehman/react,flarnie/react,silvestrijonathan/react,rickbeerendonk/react,mjackson/react,mosoft521/react,roth1002/react,brigand/react,jzmq/react,dilidili/react,rricard/react,pyitphyoaung/react,facebook/react,terminatorheart/react,Simek/react,TheBlasfem/react,ArunTesco/react,trueadm/react,chicoxyzzy/react,Simek/react,chenglou/react,trueadm/react,STRML/react,kaushik94/react,nhunzaker/react,TheBlasfem/react,STRML/react,terminatorheart/react,jdlehman/react,TheBlasfem/react,tomocchino/react,billfeller/react,billfeller/react,flarnie/react,pyitphyoaung/react,krasimir/react,yiminghe/react,silvestrijonathan/react,yiminghe/react,ArunTesco/react,jdlehman/react,trueadm/react,camsong/react,roth1002/react,anushreesubramani/react,anushreesubramani/react,kaushik94/react,brigand/react,nhunzaker/react,yangshun/react,chenglou/react,silvestrijonathan/react,nhunzaker/react,aickin/react,trueadm/react,tomocchino/react,STRML/react,aickin/react,chenglou/react,trueadm/react,VioletLife/react,syranide/react,TheBlasfem/react,yungsters/react,glenjamin/react,jameszhan/react,tomocchino/react,mhhegazy/react,Simek/react,krasimir/react,glenjamin/react,maxschmeling/react,tomocchino/react,cpojer/react,rricard/react,VioletLife/react,jorrit/react,jdlehman/react,prometheansacrifice/react,flarnie/react,rickbeerendonk/react,acdlite/react,syranide/react,silvestrijonathan/react,anushreesubramani/react,prometheansacrifice/react,dilidili/react,anushreesubramani/react,roth1002/react,camsong/react,silvestrijonathan/react,maxschmeling/react,mhhegazy/react,glenjamin/react,kaushik94/react,rickbeerendonk/react,flarnie/react,jorrit/react,yungsters/react,trueadm/react,ArunTesco/react,mosoft521/react,Simek/react,camsong/react,chenglou/react,anushreesubramani/react,dilidili/react,STRML/react,jdlehman/react,yiminghe/react,STRML/react,ericyang321/react,yangshun/react,jameszhan/react,aickin/react,mosoft521/react,aickin/react,billfeller/react,mhhegazy/react,glenjamin/react,jameszhan/react,facebook/react,apaatsio/react,brigand/react,kaushik94/react,roth1002/react,yiminghe/react,terminatorheart/react,trueadm/react,VioletLife/react,flarnie/react,brigand/react,jameszhan/react,VioletLife/react,yiminghe/react,syranide/react,billfeller/react,glenjamin/react,empyrical/react,mhhegazy/react,yiminghe/react,kaushik94/react,apaatsio/react,chicoxyzzy/react,rricard/react,roth1002/react,yiminghe/react,mosoft521/react,rickbeerendonk/react,nhunzaker/react,maxschmeling/react,chicoxyzzy/react,STRML/react,jzmq/react,krasimir/react,dilidili/react,apaatsio/react,nhunzaker/react,yangshun/react,rricard/react,chicoxyzzy/react,rickbeerendonk/react,facebook/react,chenglou/react,facebook/react,syranide/react,yungsters/react,jzmq/react,silvestrijonathan/react,camsong/react,jzmq/react,facebook/react,acdlite/react,terminatorheart/react,mjackson/react,billfeller/react,pyitphyoaung/react,prometheansacrifice/react,empyrical/react,mhhegazy/react,jorrit/react,jzmq/react,yungsters/react,rricard/react,chicoxyzzy/react,brigand/react,terminatorheart/react,ericyang321/react,dilidili/react,glenjamin/react,ericyang321/react,mosoft521/react,yungsters/react,acdlite/react,prometheansacrifice/react,yangshun/react,roth1002/react,ericyang321/react,VioletLife/react,rricard/react,rickbeerendonk/react,tomocchino/react,ericyang321/react,aickin/react,mosoft521/react,maxschmeling/react,apaatsio/react,aickin/react,mosoft521/react,cpojer/react,tomocchino/react,mhhegazy/react,prometheansacrifice/react
7d961ab16ca4db0bd91419cdfed8bb7f873ab36b
homeworks/dmitry.minchenko_wer1Kua/homework_2/script.js
homeworks/dmitry.minchenko_wer1Kua/homework_2/script.js
(function() { let height = 15, block = '#', space = ' '; if (height<2 || height>12) { return console.log('Error! Height must be >= 2 and <= 12'); } for (let i = 0; i < height; i++) { console.log(space.repeat(height-i) + block.repeat(i+1) + space.repeat(2) + block.repeat(1+i)); } })();
(function() { const HEIGHT = 15, BLOCK = '#', SPACE = ' '; if (HEIGHT<2 || HEIGHT>12) { return console.log('Error! Height must be >= 2 and <= 12'); } for (let i = 0; i < HEIGHT; i++) { console.log(SPACE.repeat(HEIGHT-i) + BLOCK.repeat(i+1) + SPACE.repeat(2) + BLOCK.repeat(1+i)); } })();
Change to const instead of let
Change to const instead of let
JavaScript
mit
MastersAcademy/js-course-2017,MastersAcademy/js-course-2017,MastersAcademy/js-course-2017
cf2fd636251dd9aeb60c224cfcbddf10dd65aea3
frontend/cordova/app/hooks/after_platform_add/add_plugins.js
frontend/cordova/app/hooks/after_platform_add/add_plugins.js
#!/usr/bin/env node //this hook installs all your plugins var pluginlist = [ "https://github.com/driftyco/ionic-plugins-keyboard.git", "cordova-plugin-vibration", "cordova-plugin-media", "https://github.com/apache/cordova-plugin-splashscreen.git", "https://github.com/extendedmind/Calendar-PhoneGap-Plugin.git", "https://github.com/extendedmind/cordova-plugin-local-notifications", "https://github.com/leohenning/KeepScreenOnPlugin", "https://github.com/extendedmind/cordova-webintent", "cordova-plugin-device", "cordova-plugin-whitelist" ]; // no need to configure below var fs = require('fs'); var path = require('path'); var sys = require('sys') var exec = require('child_process').exec; function puts(error, stdout, stderr) { sys.puts(stdout) } pluginlist.forEach(function(plug) { exec("cordova plugin add " + plug, puts); });
#!/usr/bin/env node //this hook installs all your plugins var pluginlist = [ "https://github.com/driftyco/ionic-plugins-keyboard.git#v1.0.4", "cordova-plugin-vibration", "cordova-plugin-media", "https://github.com/apache/cordova-plugin-splashscreen.git", "https://github.com/extendedmind/Calendar-PhoneGap-Plugin.git", "https://github.com/extendedmind/cordova-plugin-local-notifications", "https://github.com/leohenning/KeepScreenOnPlugin", "https://github.com/extendedmind/cordova-webintent", "cordova-plugin-device", "cordova-plugin-whitelist" ]; // no need to configure below var fs = require('fs'); var path = require('path'); var sys = require('sys') var exec = require('child_process').exec; function puts(error, stdout, stderr) { sys.puts(stdout) } pluginlist.forEach(function(plug) { exec("cordova plugin add " + plug, puts); });
Use specific version of Ionic Keyboard plugin
Use specific version of Ionic Keyboard plugin
JavaScript
agpl-3.0
extendedmind/extendedmind,ttiurani/extendedmind,extendedmind/extendedmind,extendedmind/extendedmind,ttiurani/extendedmind,extendedmind/extendedmind,extendedmind/extendedmind,ttiurani/extendedmind,extendedmind/extendedmind,extendedmind/extendedmind,ttiurani/extendedmind,ttiurani/extendedmind,ttiurani/extendedmind
0a4d8a5b194a5c636b0aa6225dadd2ab9ff7e150
parseFiles.js
parseFiles.js
var dir = require('node-dir'); dir.readFiles(__dirname, { exclude: ['LICENSE', '.gitignore', '.DS_Store'], excludeDir: ['node_modules', '.git'] }, function(err, content, next) { if (err) throw err; console.log('content:', content); next(); }, function(err, files) { if (err) throw err; console.log('finished reading files:', files); });
var dir = require('node-dir'); dir.readFiles(__dirname, { exclude: ['LICENSE', '.gitignore', '.DS_Store'], excludeDir: ['node_modules', '.git'] }, function(err, content, next) { if (err) throw err; var digitalOceanToken = findDigitalOceanToken(String(content)); var awsToken = findAwsToken(String(content)); if(awsToken != null || digitalOceanToken != null){ console.log("Key in commit. Remove and commit again"); process.exit(1); } next(); }, function(err, files) { if (err) throw err; //console.log('finished reading files:', files); }); function findDigitalOceanToken(content){ return content.match(/\"[a-zA-Z0-9]{63,65}\"/); } function findAwsToken(content){ return content.match(/\"AKIA[a-zA-Z0-9]{16,17}\"/); }
Add functionality to check for keys in commmit
Add functionality to check for keys in commmit
JavaScript
mit
DevOps-HeadBangers/target-project-node
53fd5fdf4afa38fd732728c283e9bc2277b7a5cb
index.js
index.js
const jsonMask = require('json-mask') const badCode = code => code >= 300 || code < 200 module.exports = function (opt) { opt = opt || {} function partialResponse(obj, fields) { if (!fields) return obj return jsonMask(obj, fields) } function wrap(orig) { return function (obj) { const param = this.req.query[opt.query || 'fields'] if (1 === arguments.length) { return orig(partialResponse(obj, param)) } if ('number' === typeof arguments[1] && !badCode(arguments[1])) { // res.json(body, status) backwards compat return orig(partialResponse(obj, param), arguments[1]) } if ('number' === typeof obj && !badCode(obj)) { // res.json(status, body) backwards compat return orig(obj, partialResponse(arguments[1], param)) } // The original actually returns this.send(body) return orig(obj, arguments[1]) } } return function (req, res, next) { if (badCode(res.statusCode)) return next() if (!res.__isJSONMaskWrapped) { res.json = wrap(res.json.bind(res)) if (req.jsonp) res.jsonp = wrap(res.jsonp.bind(res)) res.__isJSONMaskWrapped = true } next() } }
const jsonMask = require('json-mask') const badCode = code => code >= 300 || code < 200 module.exports = function (opt) { opt = opt || {} function partialResponse(obj, fields) { if (!fields) return obj return jsonMask(obj, fields) } function wrap(orig) { return function (obj) { const param = this.req.query[opt.query || 'fields'] if (1 === arguments.length && !badCode(obj)) { return orig(partialResponse(obj, param)) } if ('number' === typeof arguments[1] && !badCode(arguments[1])) { // res.json(body, status) backwards compat return orig(partialResponse(obj, param), arguments[1]) } if ('number' === typeof obj && !badCode(obj)) { // res.json(status, body) backwards compat return orig(obj, partialResponse(arguments[1], param)) } // The original actually returns this.send(body) return orig(obj, arguments[1]) } } return function (req, res, next) { if (!res.__isJSONMaskWrapped) { res.json = wrap(res.json.bind(res)) if (req.jsonp) res.jsonp = wrap(res.jsonp.bind(res)) res.__isJSONMaskWrapped = true } next() } }
Move badCode to the wrapping function
Move badCode to the wrapping function This moves the badCode to the wrapping funciton as the status will not be correct in the function where the middleware first gets called.
JavaScript
mit
nemtsov/express-partial-response
4cfecfa2d4734c968ca6d3d1b65ec7e720f63081
index.js
index.js
/** * Created by tshen on 16/7/15. */ 'use strict' import {NativeModules} from 'react-native'; const NativeSimpleFetch = NativeModules.SimpleFetch; const fetch = function (url, options) { const params = { url: url, method: options.method ? options.method.toUpperCase() : 'GET', headers: options.headers, timeout: 10000, body: options.body, gzipRequest: true }; console.log(params); return NativeSimpleFetch.sendRequest(params).then((res)=> { console.log(res); const statusCode = parseInt(res[0]); const body = res[1]; return { ok: statusCode >= 200 && statusCode <= 300, status: statusCode, json: ()=> { return new Promise((resolve, reject)=> { try { let obj = JSON.parse(body); resolve(obj); } catch (e) { if (typeof body === 'string') { resolve(body); } else { reject(e); } } }); } }; }, (err)=> { console.log(err); return err; }); }; module.exports = { fetch };
/** * Created by tshen on 16/7/15. */ 'use strict' import {NativeModules} from 'react-native'; const NativeSimpleFetch = NativeModules.SimpleFetch; const fetch = function (url, options) { const params = { url: url, method: options.method ? options.method.toUpperCase() : 'GET', headers: options.headers, timeout: 10000, body: options.body, gzipRequest: true }; return NativeSimpleFetch.sendRequest(params).then((res)=> { const status = parseInt(res[0]); const body = res[1]; return { ok: statusCode >= 200 && statusCode <= 300, status: status, json: ()=> { return new Promise((resolve, reject)=> { try { let obj = JSON.parse(body); resolve(obj); } catch (e) { if (typeof body === 'string') { resolve(body); } else { reject(e); } } }); } }; }); }; module.exports = { fetch };
Fix bug. Remove console logs.
Fix bug. Remove console logs.
JavaScript
mit
liaoyuan-io/react-native-simple-fetch
7b50be2427d450460b9b8c8ae8be6c81743bbf48
index.js
index.js
/* jshint node: true */ 'use strict'; // var path = require('path'); module.exports = { name: 'ember-power-select', contentFor: function(type, config) { if (config.environment !== 'test' && type === 'body-footer') { return '<div id="ember-power-select-wormhole"></div>'; } }, included: function(app) { this._super.included(app); // this.app.registry.availablePlugins['ember-cli-sass'] --->' 4.2.1', // I can use this to determine if the consumer app is using sass // and if so take a different approch. }, // treeForStyles: function(){ // debugger; // var tree = new Funnel(this.treePaths['addon-styles'], { // srcDir: '/', // destDir: '/app/styles' // }); // return tree; // } };  
/* jshint node: true */ 'use strict'; // var path = require('path'); module.exports = { name: 'ember-power-select', contentFor: function(type, config) { if (config.environment !== 'test' && type === 'body-footer') { return '<div id="ember-power-select-wormhole"></div>'; } }, included: function(app) { // Don't include the precompiled css file if the user uses ember-cli-sass if (!app.registry.availablePlugins['ember-cli-sass']) { app.import('vendor/ember-power-select.css'); } }, };  
Include precompiled styles automatically for non-sass users
Include precompiled styles automatically for non-sass users
JavaScript
mit
cibernox/ember-power-select,esbanarango/ember-power-select,chrisgame/ember-power-select,esbanarango/ember-power-select,cibernox/ember-power-select,Dremora/ember-power-select,chrisgame/ember-power-select,cibernox/ember-power-select,Dremora/ember-power-select,cibernox/ember-power-select,esbanarango/ember-power-select
429aa690a42e8f0f9282ca4a63bff052e45ea25e
packages/accounts-meetup/meetup_client.js
packages/accounts-meetup/meetup_client.js
(function () { Meteor.loginWithMeetup = function (options, callback) { // support both (options, callback) and (callback). if (!callback && typeof options === 'function') { callback = options; options = {}; } var config = Accounts.loginServiceConfiguration.findOne({service: 'meetup'}); if (!config) { callback && callback(new Accounts.ConfigError("Service not configured")); return; } var state = Random.id(); var scope = (options && options.requestPermissions) || []; var flatScope = _.map(scope, encodeURIComponent).join('+'); var loginUrl = 'https://secure.meetup.com/oauth2/authorize' + '?client_id=' + config.clientId + '&response_type=code' + '&scope=' + flatScope + '&redirect_uri=' + Meteor.absoluteUrl('_oauth/meetup?close') + '&state=' + state; Accounts.oauth.initiateLogin(state, loginUrl, callback, {width: 900, height: 450}); }; }) ();
(function () { Meteor.loginWithMeetup = function (options, callback) { // support both (options, callback) and (callback). if (!callback && typeof options === 'function') { callback = options; options = {}; } var config = Accounts.loginServiceConfiguration.findOne({service: 'meetup'}); if (!config) { callback && callback(new Accounts.ConfigError("Service not configured")); return; } var state = Random.id(); var scope = (options && options.requestPermissions) || []; var flatScope = _.map(scope, encodeURIComponent).join('+'); var loginUrl = 'https://secure.meetup.com/oauth2/authorize' + '?client_id=' + config.clientId + '&response_type=code' + '&scope=' + flatScope + '&redirect_uri=' + Meteor.absoluteUrl('_oauth/meetup?close') + '&state=' + state; // meetup box gets taller when permissions requested. var height = 620; if (_.without(scope, 'basic').length) height += 130; Accounts.oauth.initiateLogin(state, loginUrl, callback, {width: 900, height: height}); }; }) ();
Tweak the height of the popup box. Meetup varies the height of their box based on which permissions are requested.
Tweak the height of the popup box. Meetup varies the height of their box based on which permissions are requested.
JavaScript
mit
aldeed/meteor,sunny-g/meteor,pjump/meteor,shmiko/meteor,esteedqueen/meteor,wmkcc/meteor,framewr/meteor,Profab/meteor,ndarilek/meteor,steedos/meteor,allanalexandre/meteor,daltonrenaldo/meteor,Jonekee/meteor,vjau/meteor,Jeremy017/meteor,devgrok/meteor,jdivy/meteor,allanalexandre/meteor,Prithvi-A/meteor,joannekoong/meteor,modulexcite/meteor,ljack/meteor,TechplexEngineer/meteor,luohuazju/meteor,guazipi/meteor,chiefninew/meteor,chmac/meteor,jg3526/meteor,johnthepink/meteor,framewr/meteor,ndarilek/meteor,dfischer/meteor,nuvipannu/meteor,aramk/meteor,GrimDerp/meteor,deanius/meteor,mauricionr/meteor,judsonbsilva/meteor,youprofit/meteor,alphanso/meteor,deanius/meteor,Quicksteve/meteor,aramk/meteor,TechplexEngineer/meteor,brettle/meteor,mubassirhayat/meteor,guazipi/meteor,baysao/meteor,Eynaliyev/meteor,brdtrpp/meteor,Ken-Liu/meteor,h200863057/meteor,IveWong/meteor,eluck/meteor,zdd910/meteor,shadedprofit/meteor,emmerge/meteor,evilemon/meteor,vacjaliu/meteor,lieuwex/meteor,katopz/meteor,namho102/meteor,Quicksteve/meteor,dev-bobsong/meteor,servel333/meteor,Prithvi-A/meteor,somallg/meteor,lorensr/meteor,yanisIk/meteor,l0rd0fwar/meteor,AnthonyAstige/meteor,dfischer/meteor,michielvanoeffelen/meteor,SeanOceanHu/meteor,ericterpstra/meteor,alphanso/meteor,h200863057/meteor,akintoey/meteor,Hansoft/meteor,tdamsma/meteor,D1no/meteor,luohuazju/meteor,msavin/meteor,emmerge/meteor,sunny-g/meteor,calvintychan/meteor,allanalexandre/meteor,DCKT/meteor,ljack/meteor,Prithvi-A/meteor,ndarilek/meteor,akintoey/meteor,Prithvi-A/meteor,planet-training/meteor,cbonami/meteor,Hansoft/meteor,chasertech/meteor,shadedprofit/meteor,cog-64/meteor,AnjirHossain/meteor,Quicksteve/meteor,AlexR1712/meteor,codingang/meteor,tdamsma/meteor,codedogfish/meteor,dboyliao/meteor,cherbst/meteor,yanisIk/meteor,chengxiaole/meteor,iman-mafi/meteor,alexbeletsky/meteor,yyx990803/meteor,baiyunping333/meteor,cbonami/meteor,karlito40/meteor,meonkeys/meteor,wmkcc/meteor,jg3526/meteor,kencheung/meteor,dandv/meteor,Theviajerock/meteor,johnthepink/meteor,justintung/meteor,Paulyoufu/meteor-1,brdtrpp/meteor,akintoey/meteor,pandeysoni/meteor,l0rd0fwar/meteor,Hansoft/meteor,iman-mafi/meteor,guazipi/meteor,rabbyalone/meteor,somallg/meteor,codingang/meteor,chinasb/meteor,chiefninew/meteor,chengxiaole/meteor,Prithvi-A/meteor,meteor-velocity/meteor,qscripter/meteor,guazipi/meteor,devgrok/meteor,AnthonyAstige/meteor,aldeed/meteor,ndarilek/meteor,eluck/meteor,namho102/meteor,vacjaliu/meteor,AnjirHossain/meteor,bhargav175/meteor,michielvanoeffelen/meteor,Ken-Liu/meteor,somallg/meteor,codedogfish/meteor,deanius/meteor,emmerge/meteor,lorensr/meteor,Profab/meteor,lassombra/meteor,ashwathgovind/meteor,kidaa/meteor,oceanzou123/meteor,luohuazju/meteor,judsonbsilva/meteor,EduShareOntario/meteor,PatrickMcGuinness/meteor,saisai/meteor,justintung/meteor,shmiko/meteor,lpinto93/meteor,lassombra/meteor,benstoltz/meteor,mirstan/meteor,udhayam/meteor,dfischer/meteor,sclausen/meteor,Paulyoufu/meteor-1,newswim/meteor,jirengu/meteor,youprofit/meteor,chinasb/meteor,vjau/meteor,evilemon/meteor,TechplexEngineer/meteor,jdivy/meteor,jirengu/meteor,l0rd0fwar/meteor,yanisIk/meteor,saisai/meteor,namho102/meteor,michielvanoeffelen/meteor,msavin/meteor,alphanso/meteor,Theviajerock/meteor,servel333/meteor,Jeremy017/meteor,JesseQin/meteor,qscripter/meteor,IveWong/meteor,sitexa/meteor,brettle/meteor,mirstan/meteor,colinligertwood/meteor,dandv/meteor,chasertech/meteor,HugoRLopes/meteor,sitexa/meteor,yiliaofan/meteor,sdeveloper/meteor,justintung/meteor,h200863057/meteor,yalexx/meteor,h200863057/meteor,judsonbsilva/meteor,joannekoong/meteor,jenalgit/meteor,mauricionr/meteor,mirstan/meteor,Profab/meteor,EduShareOntario/meteor,SeanOceanHu/meteor,henrypan/meteor,neotim/meteor,justintung/meteor,baiyunping333/meteor,steedos/meteor,pjump/meteor,Profab/meteor,dev-bobsong/meteor,yanisIk/meteor,TribeMedia/meteor,yonglehou/meteor,mauricionr/meteor,DAB0mB/meteor,sunny-g/meteor,sitexa/meteor,whip112/meteor,steedos/meteor,EduShareOntario/meteor,aldeed/meteor,imanmafi/meteor,l0rd0fwar/meteor,tdamsma/meteor,allanalexandre/meteor,evilemon/meteor,neotim/meteor,eluck/meteor,paul-barry-kenzan/meteor,Puena/meteor,sclausen/meteor,Eynaliyev/meteor,skarekrow/meteor,lassombra/meteor,4commerce-technologies-AG/meteor,namho102/meteor,pandeysoni/meteor,michielvanoeffelen/meteor,l0rd0fwar/meteor,codingang/meteor,AnjirHossain/meteor,jirengu/meteor,chengxiaole/meteor,baysao/meteor,judsonbsilva/meteor,Hansoft/meteor,saisai/meteor,SeanOceanHu/meteor,brdtrpp/meteor,henrypan/meteor,vjau/meteor,paul-barry-kenzan/meteor,dfischer/meteor,chengxiaole/meteor,saisai/meteor,HugoRLopes/meteor,brettle/meteor,Ken-Liu/meteor,PatrickMcGuinness/meteor,DAB0mB/meteor,jirengu/meteor,JesseQin/meteor,namho102/meteor,jdivy/meteor,Jeremy017/meteor,yanisIk/meteor,JesseQin/meteor,Paulyoufu/meteor-1,kencheung/meteor,kengchau/meteor,dboyliao/meteor,TribeMedia/meteor,Urigo/meteor,elkingtonmcb/meteor,vjau/meteor,aleclarson/meteor,queso/meteor,henrypan/meteor,hristaki/meteor,framewr/meteor,yiliaofan/meteor,oceanzou123/meteor,luohuazju/meteor,eluck/meteor,chengxiaole/meteor,Puena/meteor,youprofit/meteor,evilemon/meteor,bhargav175/meteor,Eynaliyev/meteor,devgrok/meteor,lpinto93/meteor,nuvipannu/meteor,yonglehou/meteor,IveWong/meteor,sdeveloper/meteor,elkingtonmcb/meteor,nuvipannu/meteor,cbonami/meteor,Urigo/meteor,Jonekee/meteor,kencheung/meteor,yalexx/meteor,jenalgit/meteor,lassombra/meteor,justintung/meteor,kengchau/meteor,elkingtonmcb/meteor,somallg/meteor,deanius/meteor,calvintychan/meteor,yinhe007/meteor,Puena/meteor,queso/meteor,esteedqueen/meteor,rozzzly/meteor,msavin/meteor,Paulyoufu/meteor-1,katopz/meteor,jirengu/meteor,benjamn/meteor,aldeed/meteor,ashwathgovind/meteor,TechplexEngineer/meteor,codedogfish/meteor,framewr/meteor,jdivy/meteor,colinligertwood/meteor,qscripter/meteor,JesseQin/meteor,Eynaliyev/meteor,DAB0mB/meteor,jeblister/meteor,shrop/meteor,modulexcite/meteor,servel333/meteor,paul-barry-kenzan/meteor,lieuwex/meteor,karlito40/meteor,shmiko/meteor,Theviajerock/meteor,sdeveloper/meteor,aldeed/meteor,imanmafi/meteor,AnthonyAstige/meteor,DCKT/meteor,brdtrpp/meteor,neotim/meteor,LWHTarena/meteor,Puena/meteor,oceanzou123/meteor,whip112/meteor,kidaa/meteor,AnthonyAstige/meteor,dboyliao/meteor,Quicksteve/meteor,planet-training/meteor,sitexa/meteor,somallg/meteor,fashionsun/meteor,yonglehou/meteor,IveWong/meteor,fashionsun/meteor,tdamsma/meteor,luohuazju/meteor,johnthepink/meteor,benstoltz/meteor,joannekoong/meteor,esteedqueen/meteor,sclausen/meteor,newswim/meteor,mubassirhayat/meteor,kidaa/meteor,qscripter/meteor,chiefninew/meteor,yiliaofan/meteor,jrudio/meteor,TribeMedia/meteor,oceanzou123/meteor,akintoey/meteor,wmkcc/meteor,benstoltz/meteor,esteedqueen/meteor,allanalexandre/meteor,dboyliao/meteor,dandv/meteor,meonkeys/meteor,jirengu/meteor,GrimDerp/meteor,LWHTarena/meteor,AlexR1712/meteor,vjau/meteor,D1no/meteor,pandeysoni/meteor,jenalgit/meteor,chmac/meteor,pandeysoni/meteor,sclausen/meteor,ljack/meteor,ljack/meteor,SeanOceanHu/meteor,yonas/meteor-freebsd,saisai/meteor,planet-training/meteor,aleclarson/meteor,tdamsma/meteor,dandv/meteor,guazipi/meteor,fashionsun/meteor,elkingtonmcb/meteor,modulexcite/meteor,mubassirhayat/meteor,emmerge/meteor,yanisIk/meteor,zdd910/meteor,juansgaitan/meteor,mubassirhayat/meteor,daltonrenaldo/meteor,Profab/meteor,hristaki/meteor,4commerce-technologies-AG/meteor,HugoRLopes/meteor,brdtrpp/meteor,hristaki/meteor,oceanzou123/meteor,steedos/meteor,Puena/meteor,wmkcc/meteor,iman-mafi/meteor,pjump/meteor,aramk/meteor,judsonbsilva/meteor,yanisIk/meteor,juansgaitan/meteor,judsonbsilva/meteor,aldeed/meteor,luohuazju/meteor,TribeMedia/meteor,karlito40/meteor,queso/meteor,calvintychan/meteor,karlito40/meteor,yonas/meteor-freebsd,cog-64/meteor,jenalgit/meteor,bhargav175/meteor,skarekrow/meteor,papimomi/meteor,lieuwex/meteor,jrudio/meteor,imanmafi/meteor,yalexx/meteor,daltonrenaldo/meteor,karlito40/meteor,hristaki/meteor,TechplexEngineer/meteor,daltonrenaldo/meteor,alexbeletsky/meteor,kengchau/meteor,jagi/meteor,newswim/meteor,meonkeys/meteor,nuvipannu/meteor,jenalgit/meteor,devgrok/meteor,pjump/meteor,vjau/meteor,modulexcite/meteor,lawrenceAIO/meteor,chiefninew/meteor,EduShareOntario/meteor,papimomi/meteor,johnthepink/meteor,mirstan/meteor,yalexx/meteor,Quicksteve/meteor,namho102/meteor,AnthonyAstige/meteor,benjamn/meteor,michielvanoeffelen/meteor,servel333/meteor,JesseQin/meteor,wmkcc/meteor,michielvanoeffelen/meteor,shrop/meteor,steedos/meteor,mirstan/meteor,HugoRLopes/meteor,alphanso/meteor,colinligertwood/meteor,stevenliuit/meteor,calvintychan/meteor,servel333/meteor,brettle/meteor,D1no/meteor,Eynaliyev/meteor,dboyliao/meteor,skarekrow/meteor,codingang/meteor,zdd910/meteor,Jonekee/meteor,paul-barry-kenzan/meteor,williambr/meteor,jagi/meteor,meonkeys/meteor,jdivy/meteor,dev-bobsong/meteor,SeanOceanHu/meteor,codingang/meteor,Urigo/meteor,Eynaliyev/meteor,HugoRLopes/meteor,EduShareOntario/meteor,brettle/meteor,GrimDerp/meteor,IveWong/meteor,arunoda/meteor,SeanOceanHu/meteor,framewr/meteor,Jonekee/meteor,yyx990803/meteor,lassombra/meteor,sdeveloper/meteor,TribeMedia/meteor,Theviajerock/meteor,servel333/meteor,alphanso/meteor,udhayam/meteor,shmiko/meteor,meteor-velocity/meteor,yonas/meteor-freebsd,yonas/meteor-freebsd,mjmasn/meteor,brdtrpp/meteor,rozzzly/meteor,yinhe007/meteor,lieuwex/meteor,mirstan/meteor,HugoRLopes/meteor,benjamn/meteor,yyx990803/meteor,kidaa/meteor,mubassirhayat/meteor,cog-64/meteor,arunoda/meteor,brdtrpp/meteor,eluck/meteor,queso/meteor,dev-bobsong/meteor,papimomi/meteor,bhargav175/meteor,imanmafi/meteor,chinasb/meteor,cog-64/meteor,D1no/meteor,tdamsma/meteor,johnthepink/meteor,codedogfish/meteor,yyx990803/meteor,ljack/meteor,daslicht/meteor,vacjaliu/meteor,karlito40/meteor,sclausen/meteor,dandv/meteor,yonglehou/meteor,AlexR1712/meteor,daslicht/meteor,kengchau/meteor,lpinto93/meteor,kengchau/meteor,lorensr/meteor,lpinto93/meteor,meonkeys/meteor,newswim/meteor,sdeveloper/meteor,wmkcc/meteor,AnjirHossain/meteor,guazipi/meteor,neotim/meteor,cog-64/meteor,jagi/meteor,lawrenceAIO/meteor,Ken-Liu/meteor,ndarilek/meteor,ericterpstra/meteor,jeblister/meteor,DCKT/meteor,colinligertwood/meteor,pandeysoni/meteor,ashwathgovind/meteor,h200863057/meteor,mjmasn/meteor,Eynaliyev/meteor,benjamn/meteor,Paulyoufu/meteor-1,somallg/meteor,chasertech/meteor,planet-training/meteor,nuvipannu/meteor,chasertech/meteor,imanmafi/meteor,mubassirhayat/meteor,kengchau/meteor,4commerce-technologies-AG/meteor,jg3526/meteor,chmac/meteor,chiefninew/meteor,daslicht/meteor,dfischer/meteor,judsonbsilva/meteor,ashwathgovind/meteor,deanius/meteor,chiefninew/meteor,colinligertwood/meteor,DAB0mB/meteor,chmac/meteor,sunny-g/meteor,youprofit/meteor,brdtrpp/meteor,shadedprofit/meteor,lorensr/meteor,framewr/meteor,lawrenceAIO/meteor,shrop/meteor,shrop/meteor,zdd910/meteor,Quicksteve/meteor,ljack/meteor,qscripter/meteor,justintung/meteor,johnthepink/meteor,benjamn/meteor,arunoda/meteor,yinhe007/meteor,rabbyalone/meteor,benjamn/meteor,stevenliuit/meteor,codingang/meteor,brettle/meteor,saisai/meteor,modulexcite/meteor,imanmafi/meteor,yanisIk/meteor,lawrenceAIO/meteor,modulexcite/meteor,shadedprofit/meteor,PatrickMcGuinness/meteor,yyx990803/meteor,D1no/meteor,hristaki/meteor,daslicht/meteor,allanalexandre/meteor,IveWong/meteor,somallg/meteor,msavin/meteor,yalexx/meteor,Urigo/meteor,chinasb/meteor,shmiko/meteor,cbonami/meteor,4commerce-technologies-AG/meteor,ashwathgovind/meteor,h200863057/meteor,Profab/meteor,chasertech/meteor,baiyunping333/meteor,jg3526/meteor,lorensr/meteor,TribeMedia/meteor,queso/meteor,iman-mafi/meteor,cherbst/meteor,jenalgit/meteor,daltonrenaldo/meteor,calvintychan/meteor,benstoltz/meteor,GrimDerp/meteor,Theviajerock/meteor,cbonami/meteor,benstoltz/meteor,chiefninew/meteor,jirengu/meteor,PatrickMcGuinness/meteor,yiliaofan/meteor,yinhe007/meteor,jeblister/meteor,lieuwex/meteor,codedogfish/meteor,jg3526/meteor,SeanOceanHu/meteor,SeanOceanHu/meteor,pandeysoni/meteor,Hansoft/meteor,jagi/meteor,arunoda/meteor,calvintychan/meteor,AnthonyAstige/meteor,Puena/meteor,guazipi/meteor,williambr/meteor,dboyliao/meteor,jg3526/meteor,baysao/meteor,LWHTarena/meteor,dandv/meteor,l0rd0fwar/meteor,lawrenceAIO/meteor,stevenliuit/meteor,kencheung/meteor,arunoda/meteor,hristaki/meteor,akintoey/meteor,luohuazju/meteor,ericterpstra/meteor,henrypan/meteor,alexbeletsky/meteor,steedos/meteor,GrimDerp/meteor,meteor-velocity/meteor,qscripter/meteor,justintung/meteor,chasertech/meteor,queso/meteor,aramk/meteor,daltonrenaldo/meteor,namho102/meteor,meteor-velocity/meteor,mubassirhayat/meteor,stevenliuit/meteor,yiliaofan/meteor,benjamn/meteor,rozzzly/meteor,kencheung/meteor,Urigo/meteor,joannekoong/meteor,cherbst/meteor,newswim/meteor,Puena/meteor,udhayam/meteor,emmerge/meteor,alexbeletsky/meteor,katopz/meteor,Jeremy017/meteor,esteedqueen/meteor,daltonrenaldo/meteor,yinhe007/meteor,Theviajerock/meteor,arunoda/meteor,meteor-velocity/meteor,yalexx/meteor,yiliaofan/meteor,sdeveloper/meteor,daltonrenaldo/meteor,framewr/meteor,JesseQin/meteor,evilemon/meteor,jagi/meteor,akintoey/meteor,mjmasn/meteor,4commerce-technologies-AG/meteor,williambr/meteor,chmac/meteor,oceanzou123/meteor,planet-training/meteor,bhargav175/meteor,mauricionr/meteor,shrop/meteor,newswim/meteor,Eynaliyev/meteor,IveWong/meteor,jdivy/meteor,chinasb/meteor,yonas/meteor-freebsd,henrypan/meteor,williambr/meteor,nuvipannu/meteor,msavin/meteor,ljack/meteor,l0rd0fwar/meteor,yonglehou/meteor,alphanso/meteor,johnthepink/meteor,sclausen/meteor,planet-training/meteor,papimomi/meteor,newswim/meteor,h200863057/meteor,karlito40/meteor,Paulyoufu/meteor-1,Prithvi-A/meteor,wmkcc/meteor,jeblister/meteor,katopz/meteor,lieuwex/meteor,meonkeys/meteor,katopz/meteor,rozzzly/meteor,chmac/meteor,baiyunping333/meteor,dfischer/meteor,JesseQin/meteor,emmerge/meteor,meteor-velocity/meteor,skarekrow/meteor,TechplexEngineer/meteor,rabbyalone/meteor,neotim/meteor,dandv/meteor,ashwathgovind/meteor,AnjirHossain/meteor,AlexR1712/meteor,ndarilek/meteor,PatrickMcGuinness/meteor,tdamsma/meteor,lorensr/meteor,jenalgit/meteor,arunoda/meteor,lawrenceAIO/meteor,mauricionr/meteor,Ken-Liu/meteor,rabbyalone/meteor,rabbyalone/meteor,ericterpstra/meteor,D1no/meteor,elkingtonmcb/meteor,tdamsma/meteor,HugoRLopes/meteor,michielvanoeffelen/meteor,AlexR1712/meteor,daslicht/meteor,yyx990803/meteor,servel333/meteor,Jonekee/meteor,Profab/meteor,D1no/meteor,udhayam/meteor,mubassirhayat/meteor,EduShareOntario/meteor,Jeremy017/meteor,henrypan/meteor,dboyliao/meteor,TechplexEngineer/meteor,alphanso/meteor,skarekrow/meteor,codedogfish/meteor,williambr/meteor,cog-64/meteor,DCKT/meteor,benstoltz/meteor,elkingtonmcb/meteor,baysao/meteor,dev-bobsong/meteor,joannekoong/meteor,deanius/meteor,alexbeletsky/meteor,whip112/meteor,esteedqueen/meteor,stevenliuit/meteor,jrudio/meteor,pjump/meteor,evilemon/meteor,Quicksteve/meteor,shmiko/meteor,Hansoft/meteor,jagi/meteor,lieuwex/meteor,alexbeletsky/meteor,chinasb/meteor,eluck/meteor,cbonami/meteor,cherbst/meteor,sunny-g/meteor,skarekrow/meteor,brettle/meteor,papimomi/meteor,devgrok/meteor,chinasb/meteor,zdd910/meteor,dboyliao/meteor,mauricionr/meteor,juansgaitan/meteor,Urigo/meteor,yonglehou/meteor,GrimDerp/meteor,iman-mafi/meteor,yonglehou/meteor,cog-64/meteor,chengxiaole/meteor,aldeed/meteor,rabbyalone/meteor,shmiko/meteor,jeblister/meteor,williambr/meteor,sunny-g/meteor,pjump/meteor,PatrickMcGuinness/meteor,LWHTarena/meteor,AnjirHossain/meteor,DCKT/meteor,ericterpstra/meteor,youprofit/meteor,cherbst/meteor,zdd910/meteor,lpinto93/meteor,papimomi/meteor,eluck/meteor,evilemon/meteor,baiyunping333/meteor,Urigo/meteor,youprofit/meteor,udhayam/meteor,chengxiaole/meteor,udhayam/meteor,benstoltz/meteor,pjump/meteor,servel333/meteor,hristaki/meteor,kidaa/meteor,whip112/meteor,Prithvi-A/meteor,AlexR1712/meteor,D1no/meteor,lorensr/meteor,AlexR1712/meteor,4commerce-technologies-AG/meteor,yiliaofan/meteor,AnthonyAstige/meteor,saisai/meteor,DAB0mB/meteor,oceanzou123/meteor,jrudio/meteor,katopz/meteor,cbonami/meteor,LWHTarena/meteor,shadedprofit/meteor,dev-bobsong/meteor,sunny-g/meteor,shrop/meteor,nuvipannu/meteor,baiyunping333/meteor,chiefninew/meteor,papimomi/meteor,baysao/meteor,juansgaitan/meteor,karlito40/meteor,msavin/meteor,Jonekee/meteor,HugoRLopes/meteor,colinligertwood/meteor,LWHTarena/meteor,rozzzly/meteor,allanalexandre/meteor,yinhe007/meteor,whip112/meteor,sclausen/meteor,joannekoong/meteor,Jeremy017/meteor,DAB0mB/meteor,codingang/meteor,henrypan/meteor,msavin/meteor,Jeremy017/meteor,sdeveloper/meteor,sitexa/meteor,GrimDerp/meteor,meonkeys/meteor,fashionsun/meteor,devgrok/meteor,ashwathgovind/meteor,modulexcite/meteor,mauricionr/meteor,Paulyoufu/meteor-1,lpinto93/meteor,pandeysoni/meteor,whip112/meteor,mjmasn/meteor,TribeMedia/meteor,4commerce-technologies-AG/meteor,calvintychan/meteor,youprofit/meteor,udhayam/meteor,rozzzly/meteor,aramk/meteor,stevenliuit/meteor,skarekrow/meteor,eluck/meteor,DCKT/meteor,cherbst/meteor,yalexx/meteor,baysao/meteor,mirstan/meteor,shrop/meteor,williambr/meteor,aramk/meteor,codedogfish/meteor,mjmasn/meteor,daslicht/meteor,bhargav175/meteor,iman-mafi/meteor,vjau/meteor,shadedprofit/meteor,jrudio/meteor,Jonekee/meteor,rozzzly/meteor,paul-barry-kenzan/meteor,somallg/meteor,chmac/meteor,yinhe007/meteor,katopz/meteor,sitexa/meteor,juansgaitan/meteor,fashionsun/meteor,mjmasn/meteor,mjmasn/meteor,esteedqueen/meteor,alexbeletsky/meteor,rabbyalone/meteor,planet-training/meteor,baysao/meteor,jeblister/meteor,dev-bobsong/meteor,kencheung/meteor,Ken-Liu/meteor,colinligertwood/meteor,yonas/meteor-freebsd,yyx990803/meteor,fashionsun/meteor,meteor-velocity/meteor,lpinto93/meteor,fashionsun/meteor,Hansoft/meteor,daslicht/meteor,alexbeletsky/meteor,jdivy/meteor,vacjaliu/meteor,ericterpstra/meteor,vacjaliu/meteor,neotim/meteor,juansgaitan/meteor,AnjirHossain/meteor,devgrok/meteor,imanmafi/meteor,iman-mafi/meteor,lassombra/meteor,joannekoong/meteor,Ken-Liu/meteor,ndarilek/meteor,juansgaitan/meteor,paul-barry-kenzan/meteor,sunny-g/meteor,kidaa/meteor,lassombra/meteor,EduShareOntario/meteor,deanius/meteor,steedos/meteor,whip112/meteor,stevenliuit/meteor,jg3526/meteor,jeblister/meteor,yonas/meteor-freebsd,akintoey/meteor,AnthonyAstige/meteor,Theviajerock/meteor,vacjaliu/meteor,kidaa/meteor,ljack/meteor,lawrenceAIO/meteor,sitexa/meteor,shadedprofit/meteor,jagi/meteor,bhargav175/meteor,ndarilek/meteor,baiyunping333/meteor,ericterpstra/meteor,allanalexandre/meteor,vacjaliu/meteor,queso/meteor,zdd910/meteor,qscripter/meteor,emmerge/meteor,jrudio/meteor,LWHTarena/meteor,neotim/meteor,aramk/meteor,elkingtonmcb/meteor,DAB0mB/meteor,dfischer/meteor,planet-training/meteor,DCKT/meteor,PatrickMcGuinness/meteor,aleclarson/meteor,cherbst/meteor,kencheung/meteor,chasertech/meteor,paul-barry-kenzan/meteor,kengchau/meteor
5317b7fb100af66af865bcd82ed32c2dc3a1643c
index.js
index.js
var elixir = require('laravel-elixir'); var gulp = require('gulp'); var imagemin = require('gulp-imagemin'); var pngquant = require('imagemin-pngquant'); var notify = require('gulp-notify'); var _ = require('underscore'); var utilities = require('laravel-elixir/ingredients/helpers/utilities'); /* |---------------------------------------------------------------- | ImageMin Processor |---------------------------------------------------------------- | | This task will trigger your images to be processed using | imagemin processor. | | Minify PNG, JPEG, GIF and SVG images | */ elixir.extend('imagemin', function(src, output, options) { var config = this; var baseDir = config.assetsDir + 'img'; src = utilities.buildGulpSrc(src, baseDir, '**/*'); options = _.extend({ progressive: true, svgoPlugins: [{removeViewBox: false}], use: [pngquant()] }, options); gulp.task('imagemin', function() { return gulp.src(src) .pipe(imagemin(options)) .pipe(gulp.dest(output || 'public/img')) .pipe(notify({ title: 'ImageMin Complete!', message: 'All images have be optimised.', icon: __dirname + '/../laravel-elixir/icons/pass.png' })); }); this.registerWatcher('imagemin', [ baseDir + '/**/*.png', baseDir + '/**/*.gif', baseDir + '/**/*.svg', baseDir + '/**/*.jpg', baseDir + '/**/*.jpeg' ]); return this.queueTask('imagemin'); });
var elixir = require('laravel-elixir'); var gulp = require('gulp'); var imagemin = require('gulp-imagemin'); var pngquant = require('imagemin-pngquant'); var notify = require('gulp-notify'); var _ = require('underscore'); var utilities = require('laravel-elixir/ingredients/commands/utilities'); /* |---------------------------------------------------------------- | ImageMin Processor |---------------------------------------------------------------- | | This task will trigger your images to be processed using | imagemin processor. | | Minify PNG, JPEG, GIF and SVG images | */ elixir.extend('imagemin', function(src, output, options) { var config = this; var baseDir = config.assetsDir + 'img'; src = utilities.buildGulpSrc(src, baseDir, '**/*'); options = _.extend({ progressive: true, svgoPlugins: [{removeViewBox: false}], use: [pngquant()] }, options); gulp.task('imagemin', function() { return gulp.src(src) .pipe(imagemin(options)) .pipe(gulp.dest(output || 'public/img')) .pipe(notify({ title: 'ImageMin Complete!', message: 'All images have be optimised.', icon: __dirname + '/../laravel-elixir/icons/pass.png' })); }); this.registerWatcher('imagemin', [ baseDir + '/**/*.png', baseDir + '/**/*.gif', baseDir + '/**/*.svg', baseDir + '/**/*.jpg', baseDir + '/**/*.jpeg' ]); return this.queueTask('imagemin'); });
Fix utilities path from helpers to commands
Fix utilities path from helpers to commands
JavaScript
mit
waldemarfm/laravel-elixir-imagemin,nathanmac/laravel-elixir-imagemin
e5b7f40ea0e1751213048b3d50e49dc36438c3e3
website/src/app/project/experiments/experiment/components/notes/mc-experiment-notes.component.js
website/src/app/project/experiments/experiment/components/notes/mc-experiment-notes.component.js
angular.module('materialscommons').component('mcExperimentNotes', { templateUrl: 'app/project/experiments/experiment/components/notes/mc-experiment-notes.html', bindings: { experiment: '=' } });
angular.module('materialscommons').component('mcExperimentNotes', { templateUrl: 'app/project/experiments/experiment/components/notes/mc-experiment-notes.html', controller: MCExperimentNotesComponentController, bindings: { experiment: '=' } }); class MCExperimentNotesComponentController { /*@ngInject*/ constructor($scope) { $scope.editorOptions = {}; } addNote() { } }
Add controller (to be filled out).
Add controller (to be filled out).
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
a91e08c79733eac0ff55f16840bbefc39adb6aa8
index.js
index.js
const vm = require('vm') module.exports = class Guards { constructor () { this.guardRegex = /[^=<>!']=[^=]/ this.templateRegex = /[^|]\|[^|]/ this.optionsVM = { displayErrors: true, filename: 'guards' } } getStack () { const origin = Error.prepareStackTrace const error = new Error() Error.prepareStackTrace = (_, stack) => stack Error.captureStackTrace(error, this.getStack) const stack = error.stack Error.prepareStackTrace = origin // V8 stack traces. return stack } equal (constants) { return template => { const guards = this.parse(template.raw[0]) const lineOffset = this.getStack()[1].getLineNumber() const firstTruthyGuard = ( guards.map( g => this.runInVM(g.eval, constants, lineOffset) ) ).findIndex(a => a === true) if (firstTruthyGuard === -1) this.error(`Non-exhaustive patterns in guards at line ${lineOffset}!`) // First truthy guard is returned, like in Haskell. return guards[firstTruthyGuard].result } } error (e) { console.error(e) process.exit(1) } parse (template) { // Inline guards need filtering. return template .split(this.templateRegex) .filter(g => g.trim() !== '') .map((g, i) => { // Remove break line and extract the guard. const parts = g.trim().split(this.guardRegex) return { eval: parts[0], result: JSON.parse(`${parts[1].trim().replace(/'/g, '"')}`) } }) } runInVM (code, sandbox, lineOffset) { const options = Object.assign({}, this.optionsVM, { lineOffset: lineOffset }) return vm.runInNewContext(code, sandbox, options) } }
class Guards { constructor () { this.guardRegex = /[^=<>!']=[^=]/ this.templateRegex = /[^|]\|[^|]/ } buildPredicate (constants, guard) { return new Function( '', [ `const { ${this.destructureProps(constants)} } = ${JSON.stringify(constants)}`, `return ${guard}` ].join(';') ) } destructureProps (constants) { return Object.keys(constants).join(',') } equal (constants) { const self = this // Inline guards need filtering. return template => template.raw[0] .split(this.templateRegex) .filter(g => g.trim() !== '') .map((g, i) => { // Remove break line and extract the guard. const parts = g.trim().split(this.guardRegex) return [ parts[0], JSON.parse(`${parts[1].trim().replace(/'/g, '"')}`) ] }) .find(g => self.buildPredicate(constants, g[0])())[1] } } module.exports = (c, t) => (new Guards()).equal(c, t)
Drop v8 vm for native implementation, update tests accordingly :rocket:.
Drop v8 vm for native implementation, update tests accordingly :rocket:. - Implements and closes #1 by @edmulraney. - Better performance & browser support.
JavaScript
mit
yamafaktory/pattern-guard
e3a2c979b160201b53cb38660733f495be2b449a
index.js
index.js
'use strict'; var extend = require('extend'); var express = require('express'); var bodyParser = require('body-parser'); var router = express.Router(); var defaults = { loginEndpoint: '/login', logoutEndpoint: '/logout', idField: 'email', passwordField: 'password' }; module.exports = function (options) { options = options || {}; options = extend({}, defaults, options); router.use(bodyParser.json()); router.use(bodyParser.urlencoded({ extended: false })); router.post(options.loginEndpoint, function (req, res) { var body = req.body; var idField = options.idField; var passwordField = options.passwordField; if (body[idField] && body[passwordField]) { res.json('ok'); } else { res.status(400).json('Invalid arguments, expected `' + idField + '` and `' + passwordField + '` to be present.'); } }); router.post(options.logoutEndpoint, function (req, res) { }); return router; };
'use strict'; var extend = require('extend'); var express = require('express'); var bodyParser = require('body-parser'); var bcrypt = require('bcrypt'); var router = express.Router(); var defaults = { loginEndpoint: '/login', logoutEndpoint: '/logout', idField: 'email', passwordField: 'password', passwordHashField: 'password_hash' }; module.exports = function (options) { options = options || {}; options = extend({}, defaults, options); var getUser = options.getUser; var validatePassword = options.validatePassword || bcrypt.compareSync; // Setup router specific middleware router.use(bodyParser.json()); router.use(bodyParser.urlencoded({ extended: false })); // Login endpoints router.post(options.loginEndpoint, function (req, res) { var body = req.body; var idField = options.idField; var passwordField = options.passwordField; var id = body[idField]; var password = body[passwordField]; if (id && password) { getUser(id, function (err, user) { if (err) { return res.status(500).json(err); } var hash; if (!user || user[options.passwordHashField]) { hash = user[options.passwordHashField]; if (validatePassword(password, hash)) { delete user[options.passwordHashField]; res.json({ user: user }); } else { res.status(401).json('Unauthorized'); } } else { res.status(400).json('Invalid user data.'); } }); } else { res.status(400).json('Invalid arguments, expected `' + idField + '` and `' + passwordField + '` to be present.'); } }); router.post(options.logoutEndpoint, function (req, res) { }); return router; };
Add getUser and validatePassword to login
Add getUser and validatePassword to login
JavaScript
isc
knownasilya/just-auth
a3fd89525c5eb04e8bdcc5289fbe1e907d038821
src/plugins/plugin-shim.js
src/plugins/plugin-shim.js
/** * Add shim config for configuring the dependencies and exports for * older, traditional "browser globals" scripts that do not use define() * to declare the dependencies and set a module value. */ (function(seajs, global) { // seajs.config({ // alias: { // "jquery": { // src: "lib/jquery.js", // exports: "jQuery" or function // }, // "jquery.easing": { // src: "lib/jquery.easing.js", // deps: ["jquery"] // } // }) seajs.on("config", onConfig) onConfig(seajs.config.data) function onConfig(data) { if (!data) return var alias = data.alias for (var id in alias) { (function(item) { if (item.src) { // Set dependencies item.deps && define(item.src, item.deps) // Define the proxy cmd module define(id, [seajs.resolve(item.src)], function() { var exports = item.exports return typeof exports === "function" ? exports() : typeof exports === "string" ? global[exports] : exports }) } })(alias[id]) } } })(seajs, typeof global === "undefined" ? this : global);
/** * Add shim config for configuring the dependencies and exports for * older, traditional "browser globals" scripts that do not use define() * to declare the dependencies and set a module value. */ (function(seajs, global) { // seajs.config({ // alias: { // "jquery": { // src: "lib/jquery.js", // exports: "jQuery" or function // }, // "jquery.easing": { // src: "lib/jquery.easing.js", // deps: ["jquery"] // } // }) seajs.on("config", onConfig) onConfig(seajs.config.data) function onConfig(data) { if (!data) return var alias = data.alias for (var id in alias) { (function(item) { if (item.src) { // Set dependencies item.deps && define(item.src, item.deps) // Define the proxy cmd module define(id, [seajs.resolve(item.src)], function() { var exports = item.exports return typeof exports === "function" ? exports() : typeof exports === "string" ? global[exports] : exports }) } else { // Define the proxy cmd module use an exist object when src file have been loaded before define(id, item.deps, function() { var exports = item.exports return typeof exports === "function" ? exports() : typeof exports === "string" ? global[exports] : exports }) } })(alias[id]) } } })(seajs, typeof global === "undefined" ? this : global);
Fix the bug when src key is undefined,the shim plugin do not work.
Fix the bug when src key is undefined,the shim plugin do not work. When an alias item, the 'src' key is not defined, the code do not work well with the exports value.
JavaScript
mit
moccen/seajs,Lyfme/seajs,coolyhx/seajs,zaoli/seajs,baiduoduo/seajs,twoubt/seajs,tonny-zhang/seajs,mosoft521/seajs,wenber/seajs,miusuncle/seajs,yern/seajs,Gatsbyy/seajs,imcys/seajs,angelLYK/seajs,kuier/seajs,MrZhengliang/seajs,twoubt/seajs,JeffLi1993/seajs,lianggaolin/seajs,yern/seajs,uestcNaldo/seajs,121595113/seajs,uestcNaldo/seajs,lianggaolin/seajs,hbdrawn/seajs,121595113/seajs,evilemon/seajs,mosoft521/seajs,hbdrawn/seajs,liupeng110112/seajs,angelLYK/seajs,sheldonzf/seajs,lee-my/seajs,jishichang/seajs,sheldonzf/seajs,imcys/seajs,JeffLi1993/seajs,AlvinWei1024/seajs,kaijiemo/seajs,wenber/seajs,chinakids/seajs,twoubt/seajs,Gatsbyy/seajs,zaoli/seajs,evilemon/seajs,PUSEN/seajs,baiduoduo/seajs,zwh6611/seajs,lee-my/seajs,coolyhx/seajs,yuhualingfeng/seajs,tonny-zhang/seajs,PUSEN/seajs,lovelykobe/seajs,eleanors/SeaJS,FrankElean/SeaJS,mosoft521/seajs,angelLYK/seajs,kuier/seajs,ysxlinux/seajs,yuhualingfeng/seajs,Lyfme/seajs,imcys/seajs,FrankElean/SeaJS,evilemon/seajs,13693100472/seajs,JeffLi1993/seajs,lovelykobe/seajs,seajs/seajs,AlvinWei1024/seajs,jishichang/seajs,zaoli/seajs,LzhElite/seajs,uestcNaldo/seajs,AlvinWei1024/seajs,longze/seajs,MrZhengliang/seajs,LzhElite/seajs,kuier/seajs,coolyhx/seajs,lovelykobe/seajs,judastree/seajs,treejames/seajs,liupeng110112/seajs,LzhElite/seajs,kaijiemo/seajs,longze/seajs,zwh6611/seajs,tonny-zhang/seajs,ysxlinux/seajs,miusuncle/seajs,miusuncle/seajs,lee-my/seajs,treejames/seajs,chinakids/seajs,eleanors/SeaJS,judastree/seajs,zwh6611/seajs,PUSEN/seajs,ysxlinux/seajs,kaijiemo/seajs,liupeng110112/seajs,seajs/seajs,treejames/seajs,moccen/seajs,judastree/seajs,Gatsbyy/seajs,FrankElean/SeaJS,Lyfme/seajs,wenber/seajs,yern/seajs,longze/seajs,seajs/seajs,eleanors/SeaJS,moccen/seajs,sheldonzf/seajs,yuhualingfeng/seajs,13693100472/seajs,jishichang/seajs,MrZhengliang/seajs,baiduoduo/seajs,lianggaolin/seajs
d54150b9a86c3cc0a08376e3b1cf9c223a7c0096
index.js
index.js
;(_ => { 'use strict'; var tagContent = 'router2-content'; function matchHash() { var containers = document.querySelectorAll(`${tagContent}:not([hidden])`); var container; for (var i = 0; i < containers.length; i++) { containers[i].hidden = true; } var hash = window.location.hash.slice(1); // nothing to unhide... if (!hash) { return; } // this selector selects the children items too... that's incorrect var containers = document.querySelectorAll(`${tagContent}`); for (var i = 0; i < containers.length; i++) { container = containers[i]; var matcher = new RegExp(`^${container.getAttribute('hash')}`); var match = matcher.test(hash); if (match) { container.hidden = false; return; } } throw new Error(`hash "${hash}" does not match any content`); } window.addEventListener('hashchange', (e) => { matchHash(); }); window.addEventListener('load', (e) => { matchHash(); }); })();
;(_ => { 'use strict'; var tagContent = 'router2-content'; function matchHash(parent, hash) { var containers; var container; var _hash = hash || window.location.hash; if (!parent) { containers = document.querySelectorAll(`${tagContent}:not([hidden])`); for (var i = 0; i < containers.length; i++) { containers[i].hidden = true; } _hash = _hash.slice(1); // nothing to unhide... if (!_hash) { return; } containers = document.querySelectorAll(`${tagContent}`); } else { containers = parent.querySelectorAll(`${tagContent}`); if (_hash[0] === '/') { _hash = _hash.slice(1); } if (containers.length === 0) { return; } } // this selector selects the children items too... that's incorrect for (var i = 0; i < containers.length; i++) { container = containers[i]; var matcher = new RegExp(`^${container.getAttribute('hash')}`); var match = matcher.test(_hash); if (match) { container.hidden = false; matchHash(container, _hash.split(matcher)[1]); return; } } throw new Error(`hash "${_hash}" does not match any content`); } window.addEventListener('hashchange', (e) => { matchHash(); }); window.addEventListener('load', (e) => { matchHash(); }); })();
Complete the test for case 3
Complete the test for case 3
JavaScript
isc
m3co/router3,m3co/router3
4840f0296869dc9e78856cf577d766e3ce3ccabe
index.js
index.js
'use strict'; var server = require('./lib/server/')(); var config = require('config'); function ngrokIsAvailable() { try { require.resolve('ngrok'); return true; } catch (e) { return false; } } if (config.isValid()) { var port = config.get("port") || 8080; server.listen(port, function () { console.log('listening on port ' + port); if (process.env.NODE_ENV === 'development' && ngrokIsAvailable()) { require('ngrok').connect(port, function (err, url) { if (err) { console.error('ngrok error', err); return; } console.log('publicly accessible https url is: ' + url); }); } }); } else { config.getConfigValidityReport().errors.forEach(function(error){ console.log(error); }); console.error("\n\nInvalid configuration detected. Aborted server startup.\n"); return; }
'use strict'; var server = require('./lib/server/')(); var config = require('config'); function ngrokIsAvailable() { try { require.resolve('ngrok'); return true; } catch (e) { return false; } } /** * Make sure to configuration is valid before attempting to start the server. */ if (!config.isValid()) { config.getConfigValidityReport().errors.forEach(function(error){ console.log(error); }); console.error("\n\nInvalid configuration detected. Aborted server startup.\n"); return; } var port = config.get("port") || 8080; server.listen(port, function () { console.log('listening on port ' + port); if (process.env.NODE_ENV === 'development' && ngrokIsAvailable()) { require('ngrok').connect(port, function (err, url) { if (err) { console.error('ngrok error', err); return; } console.log('publicly accessible https url is: ' + url); }); } });
Rearrange code to reduce nesting as requested by PR comment.
Rearrange code to reduce nesting as requested by PR comment.
JavaScript
mit
syjulian/Frontier,codeforhuntsville/Frontier
8aca8785d53d7c0568020a128df8e4fcb7865d2b
index.js
index.js
'use strict'; require('whatwg-fetch'); const path = require('path'), querystring = require('querystring').parse; const registry = 'http://npm-registry.herokuapp.com'; const query = querystring(window.location.search.slice(1)).q; if (query) { window.fetch(path.join(registry, query)) .then((response) => response.json()) .then((info) => { document.write(`Redirecting to ${info.homepage}...`); window.location = info.homepage; }); } else { document.write('<form method="get"><input type="text" name="q"><input type="submit" value="Go"></form>'); }
'use strict'; require('whatwg-fetch'); const url = require('url'), querystring = require('querystring').parse; const registry = 'http://npm-registry.herokuapp.com'; const query = querystring(window.location.search.slice(1)).q; if (query) { window.fetch(url.resolve(registry, query)) .then((response) => response.json()) .then((info) => { document.write(`Redirecting to ${info.homepage}...`); window.location = info.homepage; }); } else { document.write('<form method="get"><input type="text" name="q"><input type="submit" value="Go"></form>'); }
Use url.resolve to get the url
Use url.resolve to get the url
JavaScript
mit
npmdocs/www
349a44df9340accdccbf829317dce9e359442e8c
service.js
service.js
var find = require('reactor/find'), serializer = require('./serializer'), url = require('url'); function say () { var all = [].slice.call(arguments), filtered = all.filter(function (argument) { return argument !== say }); console.log.apply(console, filtered); if (filtered.length != all.length) process.exit(1); } exports.create = function (base, context) { var reactor = require('reactor').createReactor(); find(base, 'stencil').forEach(function (route) { reactor.get(route.route, function (params, request, response, next) { var pathInfo = params.pathInfo ? '/' + params.pathInfo : ''; context.generate(route.script, { pathInfo: pathInfo }, function (error, stencil) { if (error) { next(error); } else { response.setHeader("Content-Type", "text/html; charset=utf8"); response.end(serializer(stencil.document.documentElement)); } }); }); }); return function (req, res, next){ if (!reactor.react(req.method, url.parse(req.url).pathname, req, res, next)) next(); } }
var find = require('reactor/find'), serializer = require('./serializer'), url = require('url'); function say () { var all = [].slice.call(arguments), filtered = all.filter(function (argument) { return argument !== say }); console.log.apply(console, filtered); if (filtered.length != all.length) process.exit(1); } exports.create = function (base, context) { var reactor = require('reactor').createReactor(); find(base, 'stencil').forEach(function (route) { reactor.get(route.route, function (params, request, response, next) { var pathInfo = params.pathInfo ? '/' + params.pathInfo : ''; context.generate(route.script, { request: request, response: response, pathInfo: pathInfo }, function (error, stencil) { if (error) { next(error); } else { response.setHeader("Content-Type", "text/html; charset=utf8"); response.end(serializer(stencil.document.documentElement)); } }); }); }); return function (req, res, next){ if (!reactor.react(req.method, url.parse(req.url).pathname, req, res, next)) next(); } }
Add `request` and `response` to context.
Add `request` and `response` to context. Add `request` and `response` to context in the service. Closes #106.
JavaScript
mit
bigeasy/stencil,bigeasy/stencil,bigeasy/stencil
5afa8d8796312b693964d133e626f23f3ba3a67c
src/main.js
src/main.js
import React from 'react'; import App from './App'; import config from './config'; var mountNode = document.getElementById('main'); React.render(<App config={config.params} />, mountNode);
import React from 'react'; import App from './App'; var mountNode = document.getElementById('main'); const config = { name: window.GROUP_NAME, description: window.GROUP_DESCRIPTION, rootUrl: window.ROOT_URL, formContact: window.FORM_CONTACT, headerMenuLinks: window.HEADER_MENU_LINKS, twitterUsername: window.TWITTER_USERNAME, twitterWidgetId: window.TWITTER_WIDGET_ID }; React.render(<App config={config} />, mountNode);
Use global variables instead of configuration file (no need to recompile the JS code to see the changes)
Use global variables instead of configuration file (no need to recompile the JS code to see the changes)
JavaScript
apache-2.0
naltaki/naltaki-front,naltaki/naltaki-front
5570a14c93b71af910e89fc4f2a6f8d7435451ed
src/main.js
src/main.js
import electron from 'electron'; import path from 'path'; import Menu from './remote/Menu'; import config from './config'; const app = electron.app; // Report crashes to our server. // electron.CrashReporter.start(); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is GCed. let mainWindow = null; app.on('window-all-closed', () => { app.quit(); }); app.on('ready', () => { // Create the browser window. mainWindow = new electron.BrowserWindow({width: 1100, height: 600}); mainWindow.loadURL(`file://${path.resolve(__dirname, '../web/index.html')}`); // Open the devtools. if (config.__DEV__) { mainWindow.openDevTools(); } // Setup the menu bar Menu.setupMenu(); mainWindow.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); });
import electron from 'electron'; import path from 'path'; import process from 'process'; import Menu from './remote/Menu'; import config from './config'; const app = electron.app; // Report crashes to our server. // electron.CrashReporter.start(); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is GCed. let mainWindow = null; app.on('window-all-closed', () => { app.quit(); process.exit(0); }); app.on('ready', () => { // Create the browser window. mainWindow = new electron.BrowserWindow({width: 1100, height: 600}); mainWindow.loadURL(`file://${path.resolve(__dirname, '../web/index.html')}`); // Open the devtools. if (config.__DEV__) { mainWindow.openDevTools(); } // Setup the menu bar Menu.setupMenu(); mainWindow.on('closed', () => { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); });
Call process.exit() when all windows are closed
[XDE] Call process.exit() when all windows are closed
JavaScript
mit
exponentjs/xde,exponentjs/xde
1d0bbe6b09e8c2beeb4cf4cb9c9c20944f194275
index.js
index.js
var Promise = require('bluebird'); var mapObj = require('map-obj'); var assign = require('object-assign'); function FileWebpackPlugin(files) { this.files = files || {}; } FileWebpackPlugin.prototype.apply = function(compiler) { var self = this; compiler.plugin('emit', function(compiler, done) { var data = {}; var assetPromises = mapObj(self.files, function(filename, asyncTemplate) { var promise = Promise .fromNode(asyncTemplate.bind(null, data)) .then(createAssetFromContents) return [filename, promise]; }); Promise.props(assetPromises) .then(function(assets) { assign(compiler.assets, assets); done(); }, function(err) { done(err); }); }); }; function createAssetFromContents(contents) { return { source: function() { return contents; }, size: function() { return contents.length; } }; } module.exports = FileWebpackPlugin;
var Promise = require('bluebird'); var mapObj = require('map-obj'); var assign = require('object-assign'); function FileWebpackPlugin(files) { this.files = files || {}; } FileWebpackPlugin.prototype.apply = function(compiler) { var self = this; compiler.plugin('emit', function(compiler, done) { var data = {}; var assetPromises = mapObj(self.files, function(filename, asyncTemplate) { var promise = Promise .fromNode(asyncTemplate.bind(null, data)) .then(createAssetFromContents) return [filename, promise]; }); Promise.props(assetPromises) .then(function(assets) { assign(compiler.assets, assets); }) .nodeify(done); }); }; function createAssetFromContents(contents) { return { source: function() { return contents; }, size: function() { return contents.length; } }; } module.exports = FileWebpackPlugin;
Use Bluebird's nodeify to handle resulting promise
Use Bluebird's nodeify to handle resulting promise
JavaScript
mit
markdalgleish/file-webpack-plugin
a84c9a76cbb4b65bf6c8a4f3483025a509bfab76
src/api/mqttPublishMessage.js
src/api/mqttPublishMessage.js
const apiPutMqttMessage = { schema: { summary: 'Retrieve a list of all keys present in the specified namespace.', description: '', body: { type: 'object', properties: { topic: { type: 'string', description: 'Name of namespace whose keys should be returned.', example: 'qliksense/new_data_notification/sales', }, message: { type: 'string', description: 'The message is a generic text string and can thus contain anything that can be represented in a string, including JSON, key-value pairs, plain text etc.', example: 'dt=20201028', }, }, required: ['topic', 'message'], }, response: { 201: { description: 'MQTT message successfully published.', type: 'object', }, 400: { description: 'Required parameter missing.', type: 'object', properties: { statusCode: { type: 'number' }, code: { type: 'string' }, error: { type: 'string' }, message: { type: 'string' }, time: { type: 'string' }, }, }, 500: { description: 'Internal error.', type: 'object', properties: { statusCode: { type: 'number' }, code: { type: 'string' }, error: { type: 'string' }, message: { type: 'string' }, time: { type: 'string' }, }, }, }, }, }; module.exports = { apiPutMqttMessage, };
const apiPutMqttMessage = { schema: { summary: 'Publish a message to a MQTT topic.', description: '', body: { type: 'object', properties: { topic: { type: 'string', description: 'Topic to which message should be published.', example: 'qliksense/new_data_notification/sales', }, message: { type: 'string', description: 'The message is a generic text string and can thus contain anything that can be represented in a string, including JSON, key-value pairs, plain text etc.', example: 'dt=20201028', }, }, required: ['topic', 'message'], }, response: { 201: { description: 'MQTT message successfully published.', type: 'object', }, 400: { description: 'Required parameter missing.', type: 'object', properties: { statusCode: { type: 'number' }, code: { type: 'string' }, error: { type: 'string' }, message: { type: 'string' }, time: { type: 'string' }, }, }, 500: { description: 'Internal error.', type: 'object', properties: { statusCode: { type: 'number' }, code: { type: 'string' }, error: { type: 'string' }, message: { type: 'string' }, time: { type: 'string' }, }, }, }, }, }; module.exports = { apiPutMqttMessage, };
Fix incorrect text for MQTT publish
docs: Fix incorrect text for MQTT publish Fixes #262
JavaScript
mit
mountaindude/butler
42f0f66acdef27a58599d59f72c6b8ae784975ab
src/blocks/scratch3_motion.js
src/blocks/scratch3_motion.js
function Scratch3MotionBlocks(runtime) { /** * The runtime instantiating this block package. * @type {Runtime} */ this.runtime = runtime; } /** * Retrieve the block primitives implemented by this package. * @return {Object.<string, Function>} Mapping of opcode to Function. */ Scratch3MotionBlocks.prototype.getPrimitives = function() { return { 'motion_gotoxy': this.goToXY, 'motion_turnright': this.turnRight }; }; Scratch3MotionBlocks.prototype.goToXY = function (args, util) { util.target.setXY(args.X, args.Y); }; Scratch3MotionBlocks.prototype.turnRight = function (args, util) { if (args.DEGREES !== args.DEGREES) { throw "Bad degrees" + args.DEGREES; } util.target.setDirection(args.DEGREES + util.target.direction); }; module.exports = Scratch3MotionBlocks;
var MathUtil = require('../util/math-util'); function Scratch3MotionBlocks(runtime) { /** * The runtime instantiating this block package. * @type {Runtime} */ this.runtime = runtime; } /** * Retrieve the block primitives implemented by this package. * @return {Object.<string, Function>} Mapping of opcode to Function. */ Scratch3MotionBlocks.prototype.getPrimitives = function() { return { 'motion_movesteps': this.moveSteps, 'motion_gotoxy': this.goToXY, 'motion_turnright': this.turnRight, 'motion_turnleft': this.turnLeft, 'motion_pointindirection': this.pointInDirection }; }; Scratch3MotionBlocks.prototype.moveSteps = function (args, util) { var radians = MathUtil.degToRad(util.target.direction); var dx = args.STEPS * Math.cos(radians); var dy = args.STEPS * Math.sin(radians); util.target.setXY(util.target.x + dx, util.target.y + dy); }; Scratch3MotionBlocks.prototype.goToXY = function (args, util) { util.target.setXY(args.X, args.Y); }; Scratch3MotionBlocks.prototype.turnRight = function (args, util) { util.target.setDirection(util.target.direction + args.DEGREES); }; Scratch3MotionBlocks.prototype.turnLeft = function (args, util) { util.target.setDirection(util.target.direction - args.DEGREES); }; Scratch3MotionBlocks.prototype.pointInDirection = function (args, util) { util.target.setDirection(args.DIRECTION); }; module.exports = Scratch3MotionBlocks;
Implement move steps, turn right, turn left, point in direction
Implement move steps, turn right, turn left, point in direction
JavaScript
bsd-3-clause
TheBrokenRail/scratch-vm,LLK/scratch-vm,LLK/scratch-vm,LLK/scratch-vm,TheBrokenRail/scratch-vm
ff95f103ac755324d36b4d3a60a61ad8014e9ce9
src/web3.js
src/web3.js
import Web3 from 'web3'; const web3 = new Web3(); export default web3; export const initWeb3 = (web3) => { if (window.web3) { web3.setProvider(window.web3.currentProvider); } else { web3.setProvider(new Web3.providers.HttpProvider('https://mainnet.infura.io/')); } window.web3 = web3; }
import Web3 from 'web3'; const web3 = new Web3(); export default web3; export const initWeb3 = (web3) => { if (window.web3) { web3.setProvider(window.web3.currentProvider); } else { web3.setProvider(new Web3.providers.HttpProvider('https://mainnet.infura.io/Tl5m5gSA2IY0XJe9BWrS')); } window.web3 = web3; }
Add api key... will have to remove eventually
Add api key... will have to remove eventually
JavaScript
mit
nanexcool/feeds,nanexcool/feeds
d3296125920a838a56c68ca2da1e9f9b4216bc03
preTest.js
preTest.js
//makes the bdd interface available (describe, it before, after, etc if(Meteor.settings.public.mocha_setup_args) { mocha.setup(Meteor.settings.public.mocha_setup_args); } else { mocha.setup("bdd"); }
//makes the bdd interface available (describe, it before, after, etc if(Meteor.settings && Meteor.settings.public.mocha_setup_args) { mocha.setup(Meteor.settings.public.mocha_setup_args); } else { mocha.setup("bdd"); }
Fix for when Mocha.settings are not available
Fix for when Mocha.settings are not available
JavaScript
mit
kelbongoo/meteor-mocha-web,abernix/meteor-mocha-web,mad-eye/meteor-mocha-web,mad-eye/meteor-mocha-web,kelbongoo/meteor-mocha-web,abernix/meteor-mocha-web
ba64925e6c6b07b42f8a28b9a141e1ada42c3550
src/components/MainNav/Breadcrumbs/Breadcrumbs.js
src/components/MainNav/Breadcrumbs/Breadcrumbs.js
import React from 'react'; import css from './Breadcrumbs.css'; const propTypes = { links: React.PropTypes.array, }; function Breadcrumbs(props) { const links = props.links.map((link, i) => { const linkElem = <li key={`breadcrumb_${i}`}><a href={link.path}>{link.label}</a></li>; const dividerElem = <li key={`divider${i}`}>{'>'}</li>; if (i !== props.links.length - 1) { return (linkElem + dividerElem); } return linkElem; }); return ( <ul className={css.navBreadcrumbs}> {links} </ul> ); } Breadcrumbs.propTypes = propTypes; export default Breadcrumbs;
import React from 'react'; import css from './Breadcrumbs.css'; const propTypes = { links: React.PropTypes.array, }; function Breadcrumbs(props) { const links = props.links.map((link, i) => { // eslint-disable-next-line react/no-array-index-key const linkElem = <li key={`breadcrumb_${i}`}><a href={link.path}>{link.label}</a></li>; // eslint-disable-next-line react/no-array-index-key const dividerElem = <li key={`divider${i}`}>{'>'}</li>; if (i !== props.links.length - 1) { return (linkElem + dividerElem); } return linkElem; }); return ( <ul className={css.navBreadcrumbs}> {links} </ul> ); } Breadcrumbs.propTypes = propTypes; export default Breadcrumbs;
Add eslint-disable-next-line comments to get rid of excessively pedantic react/no-array-index-key errors.
Add eslint-disable-next-line comments to get rid of excessively pedantic react/no-array-index-key errors.
JavaScript
apache-2.0
folio-org/stripes-core,folio-org/stripes-core,folio-org/stripes-core
470c616cf598fb14842d8326d6fe416952b79d8a
test/common.js
test/common.js
'use strict'; const hookModule = require("../src/"); class TallyHook extends hookModule.Hook { preProcess(thing) { thing.preTally = thing.preTally + 1; return true; } postProcess(thing) { thing.postTally = thing.postTally + 1; } } module.exports = { TallyHook };
'use strict'; const hookModule = require("../src/"); class TallyHook extends hookModule.Hook { preProcess(thing) { thing.preTally = thing.preTally + 1; return true; } postProcess(thing) { thing.postTally = thing.postTally + 1; } } class DelayableHook extends hookModule.Hook { constructor(options) { super(options) } preProcess() { this.delay( this.settings.preprocess || 500, "preProcess"); return true } execute() { this.delay(this.settings.execute || 200, "execute"); } postProcess() { this.delay(this.settings.postprocess || 100, "postProcess"); } delay(ms, str){ var ctr, rej, p = new Promise((resolve, reject) => { ctr = setTimeout(() => { console.log( `delayed ${str} by ${ms}ms`) resolve(); }, ms); rej = reject; }); p.cancel = function(){ clearTimeout(ctr); rej(Error("Cancelled"))}; return p; } } module.exports = { TallyHook, DelayableHook };
Add a DelayedHook test class.
Add a DelayedHook test class.
JavaScript
mit
StevenBlack/hooks-and-anchors
e49fd692e1281f91164d216708befd81a1a3c102
test/simple.js
test/simple.js
var test = require("tape") var crypto = require('crypto') var cryptoB = require('../') var assert = require('assert') function assertSame (fn) { test(fn.name, function (t) { fn(crypto, function (err, expected) { fn(cryptoB, function (err, actual) { t.equal(actual, expected) t.end() }) }) }) } assertSame(function sha1 (crypto, cb) { cb(null, crypto.createHash('sha1').update('hello', 'utf-8').digest('hex')) }) assertSame(function md5(crypto, cb) { cb(null, crypto.createHash('md5').update('hello', 'utf-8').digest('hex')) }) assert.equal(cryptoB.randomBytes(10).length, 10) test('randomBytes', function (t) { cryptoB.randomBytes(10, function(ex, bytes) { assert.ifError(ex) bytes.forEach(function(bite) { assert.equal(typeof bite, 'number') }) t.end() }) })
var test = require("tape") var crypto = require('crypto') var cryptoB = require('../') function assertSame (fn) { test(fn.name, function (t) { t.plan(1) fn(crypto, function (err, expected) { fn(cryptoB, function (err, actual) { t.equal(actual, expected) t.end() }) }) }) } assertSame(function sha1 (crypto, cb) { cb(null, crypto.createHash('sha1').update('hello', 'utf-8').digest('hex')) }) assertSame(function md5(crypto, cb) { cb(null, crypto.createHash('md5').update('hello', 'utf-8').digest('hex')) }) test('randomBytes', function (t) { t.plan(3 + 10) t.equal(cryptoB.randomBytes(10).length, 10) cryptoB.randomBytes(10, function(ex, bytes) { t.error(ex) t.equal(bytes.length, 10) bytes.forEach(function(bite) { t.equal(typeof bite, 'number') }) t.end() }) })
Use tape for asserts to better detect callbacks not being fired
Use tape for asserts to better detect callbacks not being fired
JavaScript
mit
crypto-browserify/crypto-browserify,crypto-browserify/crypto-browserify
4da17d2e30b07b73de2a5d7b548ca8ed4b9bc4f2
src/utils/hex-generator.js
src/utils/hex-generator.js
const hexWidth = 50; const hexPadding = 2; export default ({ width, height, columns, rows, renderSector }) => { const hexWidthUnit = hexWidth / 4; const hexHeight = (Math.sqrt(3) / 2) * hexWidth; const hexHeightUnit = hexHeight / 2; const hexArray = []; let isWithinHeight = true; let isWithinWidth = true; let i = 0; let j = 0; while (isWithinHeight) { const minRowHeight = hexHeightUnit * 2 * i; while (isWithinWidth) { const xOffset = j * 3 * hexWidthUnit; hexArray.push({ key: `${i}-${j}`, width: hexWidth - hexPadding, xOffset, yOffset: j % 2 ? minRowHeight + hexHeightUnit : minRowHeight, highlighted: renderSector && i < rows && j < columns, }); j += 1; isWithinWidth = xOffset + (2 * hexWidthUnit) < width; } j = 0; i += 1; isWithinWidth = true; isWithinHeight = minRowHeight - hexHeightUnit < height; } return hexArray; };
const defaultHexWidth = 50; const hexPadding = 2; export default ({ width, height, columns, rows, renderSector }) => { const scaledWidth = Math.min(height / (rows + 4), width / (columns + 4)); const horizHexOffset = Math.ceil((((width / scaledWidth) / (Math.sqrt(3) / 2)) - columns) / 2); const vertHexOffset = Math.ceil(((height / scaledWidth) - rows) / 2); const hexWidth = renderSector ? scaledWidth / (Math.sqrt(3) / 2) : defaultHexWidth; const hexWidthUnit = hexWidth / 4; const hexHeight = (Math.sqrt(3) / 2) * hexWidth; const hexHeightUnit = hexHeight / 2; const hexArray = []; let isWithinHeight = true; let isWithinWidth = true; let i = 0; let j = 0; while (isWithinHeight) { const minRowHeight = hexHeightUnit * 2 * i; while (isWithinWidth) { const xOffset = j * 3 * hexWidthUnit; hexArray.push({ key: `${i}-${j}`, width: hexWidth - hexPadding, xOffset, yOffset: j % 2 ? minRowHeight + hexHeightUnit : minRowHeight, highlighted: renderSector && i > vertHexOffset && i < rows + vertHexOffset && j > horizHexOffset && j < columns + horizHexOffset, }); j += 1; isWithinWidth = xOffset + (2 * hexWidthUnit) < width; } j = 0; i += 1; isWithinWidth = true; isWithinHeight = minRowHeight - hexHeightUnit < height; } return hexArray; };
Put the sector in the middle of the hex grid (very crude)
Put the sector in the middle of the hex grid (very crude)
JavaScript
mit
mpigsley/sectors-without-number,mpigsley/sectors-without-number
31663486624635748d6f2202504b0a187a102fcd
RcmBrightCoveLib/public/keep-aspect-ratio.js
RcmBrightCoveLib/public/keep-aspect-ratio.js
/** * This script keeps the height set on elements with regard to their * width for a given aspect ratio. Great for "display:block" elements * * Example usage: * * <div data-keep-aspect-ratio="16:9"> * * Author: Rod McNew * License: BSD */ new function () { var setHeights = function () { $.each($('[data-keep-aspect-ratio]'), function () { var ele = $(this); var ratioParts = ele.attr('data-keep-aspect-ratio').split(':'); var ratioWidth = ratioParts[0]; var ratioHeight = ratioParts[1]; var width = ele.width(); var newHeight = width * ratioHeight / ratioWidth; ele.css('height', newHeight); }) }; //Run onReady $(setHeights); //Run when window is resized $(window).resize(setHeights); //Run when target elements are resized without a window resize $('body').delegate('[data-keep-aspect-ratio]', 'resize', setHeights); };
/** * This script keeps the height set on elements with regard to their * width for a given aspect ratio. Great for "display:block" elements * * Example usage: * * <div data-keep-aspect-ratio="16:9"> * * Author: Rod McNew * License: BSD */ new function () { var setHeights = function () { $.each($('[data-keep-aspect-ratio]'), function () { var ele = $(this); var ratioParts = ele.attr('data-keep-aspect-ratio').split(':'); var ratioWidth = ratioParts[0]; var ratioHeight = ratioParts[1]; var width = ele.width(); var newHeight = width * ratioHeight / ratioWidth; ele.css('height', newHeight); }) }; //Run onReady $(setHeights); //Run when window is resized $(window).resize(setHeights); //Run when target elements are resized without a window resize $('body').on('resize', '[data-keep-aspect-ratio]', setHeights); $('body').on('orientationchange', '[data-keep-aspect-ratio]', setHeights); };
Fix for brightcove player when orintation is changed
Fix for brightcove player when orintation is changed
JavaScript
bsd-3-clause
jerv13/RcmPlugins,jerv13/RcmPlugins,bjanish/RcmPlugins,jerv13/RcmPlugins,innaDa/RcmPlugins,innaDa/RcmPlugins,innaDa/RcmPlugins,bjanish/RcmPlugins,bjanish/RcmPlugins
c57a584a3bc781db629ae15dd2912f62992f98f3
Resources/private/js/sylius-auto-complete.js
Resources/private/js/sylius-auto-complete.js
/* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ (function ( $ ) { 'use strict'; $.fn.extend({ autoComplete: function () { var element = $(this); var criteriaType = $(this).data('criteria-type'); var criteriaName = $(this).data('criteria-name'); element.dropdown({ delay: { search: 250 }, apiSettings: { dataType: 'JSON', cache: false, data: { criteria: {} }, beforeSend: function(settings) { settings.data.criteria[criteriaName] = {type: criteriaType, value: ''}; settings.data.criteria[criteriaName].value = settings.urlData.query; return settings; }, onResponse: function (response) { var choiceName = element.data('choice-name'); var choiceValue = element.data('choice-value'); var myResults = []; $.each(response._embedded.items, function (index, item) { myResults.push({ name: item[choiceName], value: item[choiceValue] }); }); return { success: true, results: myResults }; } } }); } }); })( jQuery );
/* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ (function ( $ ) { 'use strict'; $.fn.extend({ autoComplete: function () { var element = $(this); var criteriaType = $(this).data('criteria-type'); var criteriaName = $(this).data('criteria-name'); element.dropdown({ delay: { search: 250 }, forceSelection: false, apiSettings: { dataType: 'JSON', cache: false, data: { criteria: {} }, beforeSend: function(settings) { settings.data.criteria[criteriaName] = {type: criteriaType, value: ''}; settings.data.criteria[criteriaName].value = settings.urlData.query; return settings; }, onResponse: function (response) { var choiceName = element.data('choice-name'); var choiceValue = element.data('choice-value'); var myResults = []; $.each(response._embedded.items, function (index, item) { myResults.push({ name: item[choiceName], value: item[choiceValue] }); }); return { success: true, results: myResults }; } } }); } }); })( jQuery );
Use collection instead of array in all transformers, also use map method
[Resource][Core] Use collection instead of array in all transformers, also use map method
JavaScript
mit
Sylius/SyliusUiBundle,Sylius/SyliusUiBundle
62b292ddf6a6fb71097c5cfa527b625366c46a3f
src/components/slide/index.js
src/components/slide/index.js
import React, { Component, PropTypes } from 'react'; require('./slide.scss'); class Slide extends Component { render() { return ( <div className="slide"> <header className="slide__header"> <h1 className="slide__title">{this.props.title}</h1> </header> <ul> {this.props.children} </ul> <footer className="slide__footer"> {this.props.order} / {this.props.total} </footer> </div> ); } } export default Slide;
import React, { Component, PropTypes } from 'react'; require('./slide.scss'); class Slide extends Component { constructor(props) { super(props); this.isViewable = this.isViewable.bind(this); } isViewable() { return this.props.current === +this.props.order; } render() { return ( this.isViewable() && <div className="slide"> <header className="slide__header"> <h1 className="slide__title">{this.props.title}</h1> </header> <ul> {this.props.children} </ul> <footer className="slide__footer"> {this.props.order} / {this.props.total} </footer> </div> ); } } export default Slide;
Make slide viewable based on current and order
feature: Make slide viewable based on current and order A slide will be viewable only if the current property matches the order property.
JavaScript
mit
leadiv/react-slides,leadiv/react-slides
daed42ff845baa2abf1e0fd180d7fb0eb2a13b3d
lib/cli/file-set-pipeline/log.js
lib/cli/file-set-pipeline/log.js
/** * @author Titus Wormer * @copyright 2015 Titus Wormer * @license MIT * @module mdast:cli:log * @fileoverview Log a file context on successful completion. */ 'use strict'; /* * Dependencies. */ var report = require('vfile-reporter'); /** * Output diagnostics to stdout(4) or stderr(4). * * @param {CLI} context - CLI engine. */ function log(context) { var files = context.files; var frail = context.frail; var applicables = files.filter(function (file) { return file.namespace('mdast:cli').providedByUser; }); var hasFailed = files.some(function (file) { return file.hasFailed() || (frail && file.messages.length); }); var diagnostics = report(applicables, { 'quiet': context.quiet, 'silent': context.silent }); if (diagnostics) { context[hasFailed ? 'stderr' : 'stdout'](diagnostics); } } /* * Expose. */ module.exports = log;
/** * @author Titus Wormer * @copyright 2015 Titus Wormer * @license MIT * @module mdast:cli:log * @fileoverview Log a file context on successful completion. */ 'use strict'; /* * Dependencies. */ var report = require('vfile-reporter'); /** * Output diagnostics to stdout(4) or stderr(4). * * @param {CLI} context - CLI engine. */ function log(context) { var files = context.files; var applicables = files.filter(function (file) { return file.namespace('mdast:cli').providedByUser; }); var diagnostics = report(applicables, { 'quiet': context.quiet, 'silent': context.silent }); if (diagnostics) { context.stderr(diagnostics); } } /* * Expose. */ module.exports = log;
Move all info output of mdast(1) to stderr(4)
Move all info output of mdast(1) to stderr(4) This changes moves all reporting output, even when not including failure messages, from stout(4) to stderr(4). Thus, when piping only stdout(4) from mdast(1) into a file, only the markdown is written. Closes GH-47.
JavaScript
mit
ulrikaugustsson/mdast,eush77/remark,chcokr/mdast,ulrikaugustsson/mdast,yukkurisinai/mdast,tanzania82/remarks,yukkurisinai/mdast,wooorm/remark,chcokr/mdast,eush77/remark
a7f6773184b6a08d6fcc62ed82e331e114f731b8
static/js/json_selector.js
static/js/json_selector.js
// =================================================== // DOM Outline with event handlers // =================================================== $(function(){ var $selector_box = $("#selector"); var selector_val = ""; var DomOutlineHandlers = { 'click': function(e){ selector_val = $(e).data('json-selector'); $selector_box.val(selector_val); }, 'mouseover': function(e){ $(".DomOutline").show(); }, 'mouseout': function(e){ $(".DomOutline").hide(); }, } var DOutline = DomOutline({ handlers: DomOutlineHandlers, filter: 'code span:not(.hljs-attribute)' }) DOutline.start() });
// =================================================== // DOM Outline with event handlers // =================================================== $(function(){ var $selector_box = $("#selector"); var selector_val = ""; var DomOutlineHandlers = { 'click': function(e){ selector_val = $(e).attr('data-json-selector'); $selector_box.val(selector_val); }, 'mouseover': function(e){ $(".DomOutline").show(); }, 'mouseout': function(e){ $(".DomOutline").hide(); }, } var DOutline = DomOutline({ handlers: DomOutlineHandlers, filter: 'code span:not(.hljs-attribute)' }) DOutline.start() });
Use .attr instead of .data to get json selector. Prevents evaluation of [x] as array
Use .attr instead of .data to get json selector. Prevents evaluation of [x] as array
JavaScript
mit
joequery/JSON-Selector-Generator,joequery/JSON-Selector-Generator,joequery/JSON-Selector-Generator
38c8a46baee9cd61571cf26ba9c3942a98f3ce92
src/js/stores/ArrangeStore.js
src/js/stores/ArrangeStore.js
import { action, computed } from 'mobx' import { moveTabs, tabComparator } from '../libs' export default class ArrangeStore { constructor (store) { this.store = store } @computed get urlTabMap () { return this.store.windowStore.tabs.reduce((acc, tab) => { const { url } = tab acc[url] = acc[url] || [] acc[url].push(tab) return acc }, {}) } @computed get duplicatedTabs () { return Object.values(this.urlTabMap).filter(x => x.length > 1) } @action sortTabs = () => { this.store.windowStore.windows.map((win) => { const tabs = win.tabs.sort(tabComparator) moveTabs(tabs, win.id, 0) }) this.groupDuplicateTabs() } groupDuplicateTabs = () => { this.duplicatedTabs.map((tabs) => { moveTabs(tabs, tabs[0].windowId, -1) }) } }
import { action, computed } from 'mobx' import { moveTabs, tabComparator } from '../libs' const urlPattern = /.*:\/\/[^/]*/ const getDomain = (url) => { const matches = url.match(urlPattern) if (matches) { return matches[0] } return url } export default class ArrangeStore { constructor (store) { this.store = store } @computed get domainTabsMap () { return this.store.windowStore.tabs.reduce((acc, tab) => { const domain = getDomain(tab.url) acc[domain] = acc[domain] || [] acc[domain].push(tab) return acc }, {}) } @action sortTabs = async () => { await this.groupTabs() await this.sortInWindow() } groupTabs = async () => { await Promise.all( Object.entries(this.domainTabsMap).map( async ([ domain, tabs ]) => { if (tabs.length > 1) { const sortedTabs = tabs.sort(tabComparator) const { windowId, pinned } = sortedTabs[0] await moveTabs( sortedTabs.map(x => ({ ...x, pinned })), windowId ) } } ) ) } sortInWindow = async () => { const windows = await chrome.windows.getAll({ populate: true }) windows.map((win) => { const tabs = win.tabs.sort(tabComparator) moveTabs(tabs, win.id) }) } }
Update sortTabs to group tabs by domain then sort in window
Update sortTabs to group tabs by domain then sort in window
JavaScript
mit
xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2,xcv58/Tab-Manager-v2
bdca4d4b6b04ad011a25fd913ec4c7ed2ed04b1d
react/components/Onboarding/components/UI/CTAButton/index.js
react/components/Onboarding/components/UI/CTAButton/index.js
import theme from 'react/styles/theme'; import GenericButton from 'react/components/UI/GenericButton'; import styled from 'styled-components'; const CTAButton = styled(GenericButton).attrs({ f: 6, })` margin-top: ${theme.space[6]} `; export default CTAButton;
import GenericButton from 'react/components/UI/GenericButton'; import styled from 'styled-components'; const CTAButton = styled(GenericButton).attrs({ f: 6 })` margin-top: ${x => x.theme.space[6]} `; export default CTAButton;
Use theme propeties in CTAButton styled component
Use theme propeties in CTAButton styled component
JavaScript
mit
aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell
07bffcd4d825b86dbd3386c2f3866f770671c6cb
src/lib/units/day-of-month.js
src/lib/units/day-of-month.js
import { makeGetSet } from '../moment/get-set'; import { addFormatToken } from '../format/format'; import { addUnitAlias } from './aliases'; import { addUnitPriority } from './priorities'; import { addRegexToken, match1to2, match2 } from '../parse/regex'; import { addParseToken } from '../parse/token'; import { DATE } from './constants'; import toInt from '../utils/to-int'; // FORMATTING addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES addUnitAlias('date', 'D'); // PRIOROITY addUnitPriority('date', 9); // PARSING addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { return isStrict ? locale._dayOfMonthOrdinalParse : locale._dayOfMonthOrdinalParseLenient; }); addParseToken(['D', 'DD'], DATE); addParseToken('Do', function (input, array) { array[DATE] = toInt(input.match(match1to2)[0], 10); }); // MOMENTS export var getSetDayOfMonth = makeGetSet('Date', true);
import { makeGetSet } from '../moment/get-set'; import { addFormatToken } from '../format/format'; import { addUnitAlias } from './aliases'; import { addUnitPriority } from './priorities'; import { addRegexToken, match1to2, match2 } from '../parse/regex'; import { addParseToken } from '../parse/token'; import { DATE } from './constants'; import toInt from '../utils/to-int'; // FORMATTING addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES addUnitAlias('date', 'D'); // PRIOROITY addUnitPriority('date', 9); // PARSING addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { // TODO: Remove "ordinalParse" fallback in next major release. return isStrict ? (locale._dayOfMonthOrdinalParse || locale._ordinalParse) : locale._dayOfMonthOrdinalParseLenient; }); addParseToken(['D', 'DD'], DATE); addParseToken('Do', function (input, array) { array[DATE] = toInt(input.match(match1to2)[0], 10); }); // MOMENTS export var getSetDayOfMonth = makeGetSet('Date', true);
Add fallback for old name ordinalParse
Add fallback for old name ordinalParse
JavaScript
mit
PKRoma/moment,Oire/moment,julionc/moment,OtkurBiz/moment,ze-pequeno/moment,julionc/moment,OtkurBiz/moment,moment/moment,joelmheim/moment,xkxx/moment,monoblaine/moment,ze-pequeno/moment,moment/moment,Oire/moment,OtkurBiz/moment,xkxx/moment,monoblaine/moment,xkxx/moment,PKRoma/moment,joelmheim/moment,calebcauthon/moment,julionc/moment,joelmheim/moment,ze-pequeno/moment,moment/moment,mj1856/moment,calebcauthon/moment,PKRoma/moment,mj1856/moment,calebcauthon/moment,Oire/moment,mj1856/moment
06b9ff1d0759d289ae70fbd9717cf8129e3485bc
pages/home/index.js
pages/home/index.js
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import Layout from '../../components/Layout'; import { title, html } from './index.md'; class HomePage extends React.Component { static propTypes = { articles: PropTypes.array.isRequired, }; componentDidMount() { document.title = title; } render() { return ( <Layout> <div dangerouslySetInnerHTML={{ __html: html }} /> <h4>Articles</h4> <ul> {this.props.articles.map(article => <li><a href={article.url}>{article.title}</a> by {article.author}</li> )} </ul> <p> <br /><br /> </p> </Layout> ); } } export default HomePage;
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import Layout from '../../components/Layout'; import { title, html } from './index.md'; class HomePage extends React.Component { static propTypes = { articles: PropTypes.array.isRequired, }; componentDidMount() { document.title = title; } render() { return ( <Layout> <div dangerouslySetInnerHTML={{ __html: html }} /> <h4>Articles</h4> <ul> {this.props.articles.map((article, i) => <li key={i}><a href={article.url}>{article.title}</a> by {article.author}</li> )} </ul> <p> <br /><br /> </p> </Layout> ); } } export default HomePage;
Fix React warning on the home page (add key attribute to list items)
Fix React warning on the home page (add key attribute to list items)
JavaScript
mit
raffidil/garnanain,koistya/react-static-boilerplate,jamesrf/weddingwebsite,kyoyadmoon/fuzzy-hw1,gadflying/profileSite,RyanGosden/react-poll,srossross-tableau/hackathon,kyoyadmoon/fuzzy-hw1,leo60228/HouseRuler,jamesrf/weddingwebsite,gadflying/profileSite,leo60228/HouseRuler,RyanGosden/react-poll,kriasoft/react-static-boilerplate,koistya/react-static-boilerplate,lifeiscontent/OpenPoGoUI,willchertoff/planner,kriasoft/react-static-boilerplate,gmorel/me,zedd45/react-static-todos,raffidil/garnanain,zedd45/react-static-todos,gmorel/me,willchertoff/planner,lifeiscontent/OpenPoGoUI,srossross-tableau/hackathon
5afa1a697da48fb473d0e19fe6e5dbfc6913ca75
src/common/analytics/index.js
src/common/analytics/index.js
/** * Dependencies. */ let NullAnalytics = require('./NullAnalytics'); let Tracker = require('./Tracker'); /** * Constants. */ const ANALYTICS_KEY = process.env.ANALYTICS_KEY; /** * Locals. */ let enableAnalytics = window.ProductHuntAnalytics && ANALYTICS_KEY; let ProductHuntAnalytics = enableAnalytics ? window.ProductHuntAnalytics : NullAnalytics; let analytics = new ProductHuntAnalytics(process.env.ANALYTICS_KEY); /** * Export a new `Tracker`. */ module.exports = new Tracker(analytics);
/** * Dependencies. */ let NullAnalytics = require('./NullAnalytics'); let Tracker = require('./Tracker'); /** * Constants. */ const ANALYTICS_KEY = process.env.ANALYTICS_KEY; /** * Locals. * * Note(andreasklinger): window.ProductHuntAnalytics gets set by a custom built of the analytics.js * To recreate this use their make script - it offers a options to set the variable name. */ let enableAnalytics = window.ProductHuntAnalytics && ANALYTICS_KEY; let ProductHuntAnalytics = enableAnalytics ? window.ProductHuntAnalytics : NullAnalytics; let analytics = new ProductHuntAnalytics(process.env.ANALYTICS_KEY); /** * Export a new `Tracker`. */ module.exports = new Tracker(analytics);
Add note to explain where the custom name comes from
Add note to explain where the custom name comes from
JavaScript
isc
producthunt/producthunt-chrome-extension,producthunt/producthunt-chrome-extension
998601c34ba9537fa6230232379c1efad84e17bb
routes/new.js
routes/new.js
// This route will save the given url into the database // returning its "shorter" version var router = require('express').Router(); var isValid = require('valid-url').isWebUri; router.get('/http://:url', function(req, res) { var json = {}; json.original = 'http://' + req.params.url; json.shorter = getShortUrl(req, random()); + req.originalUrl res.send(json); }); router.get('/https://:url', function(req, res) { var json = {}; json.original = 'https://' + req.params.url; json.shorter = getShortUrl(req, random()); + req.originalUrl res.send(json); }); var getShortUrl = function (req, id) { var baseUrl = req.protocol + '://' + req.get('host') + '/'; return baseUrl + id; } var random = function() { // Let the IDs be numbers with up to 5 digits return Math.ceil(Math.random() * 100000); } module.exports = router;
// This route will save the given url into the database // returning its "shorter" version var router = require('express').Router(); var isValid = require('valid-url').isWebUri; // Using GET parameters in place of something like "/:url", because // with this last solution the server is fooled by the "http" in the // middle of the whole url. router.get('/', function(req, res) { var json = {}; json.original = req.param('url'); if (!isValid(json.original)) { json.err = 'invalid url'; } else { json.shorter = getShortUrl(req, random()); + req.originalUrl } res.send(json); }); var random = function() { // Let the IDs be numbers with up to 5 digits return Math.ceil(Math.random() * 100000); } module.exports = router;
Reduce code duplication using GET params
Reduce code duplication using GET params Replaced the two routes, one for http and another one for https, using GET parameter ?url=
JavaScript
mit
clobrano/fcc-url-shortener-microservice,clobrano/fcc-url-shortener-microservice
ede5962c9926c8a852ccbc307e3a970ede4d6954
build/server.js
build/server.js
console.time('Starting server'); require('promise-helpers'); var fs = require('fs'); var path = require('path'); var express = require('express'); var app = express(); /** * Serve static files such as css, js, images */ app.use('/images', express.static('dist/assets/images')); app.use('/javascripts', express.static('dist/assets/javascripts')); app.use('/css', express.static('dist/assets/css')); // Individual routes pulled from the routes directory fs.readdir(path.join(__dirname, '/routes'), function(err, files) { if(err) { require('trace'); require('clarify'); console.trace(err); } files.forEach(function(file) { require(path.join(__dirname, '/routes/') + file)(app); }); }); // Go go go app.listen(process.env.PORT || 3000); console.log('listening on localhost:' + (process.env.npm_config_port || 3000)); // Export our server for testing purposes module.exports = app; console.timeEnd('Starting server');
console.time('Starting server'); require('promise-helpers'); var fs = require('fs'); var path = require('path'); var express = require('express'); var app = express(); /** * Serve static files such as css, js, images */ app.use('/images', express.static('dist/assets/images')); app.use('/javascripts', express.static('dist/assets/javascripts')); app.use('/stylesheets', express.static('dist/assets/stylesheets')); // Individual routes pulled from the routes directory fs.readdir(path.join(__dirname, '/routes'), function(err, files) { if(err) { require('trace'); require('clarify'); console.trace(err); } files.forEach(function(file) { require(path.join(__dirname, '/routes/') + file)(app); }); }); // Go go go app.listen(process.env.PORT || 3000); console.log('listening on localhost:' + (process.env.npm_config_port || 3000)); // Export our server for testing purposes module.exports = app; console.timeEnd('Starting server');
Fix broken path to css caused by previous commit
Fix broken path to css caused by previous commit
JavaScript
mit
LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements
92dfcaa6e03959bc6b88701d8f269c0e344bad76
src/actions.js
src/actions.js
import assign from 'object-assign'; import { store } from './helpers'; export const MENU_SHOW = 'REACT_CONTEXTMENU_SHOW'; export const MENU_HIDE = 'REACT_CONTEXTMENU_HIDE'; export function dispatchGlobalEvent(eventName, opts, target = window) { // Compatibale with IE // @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work let event; if (typeof window.CustomEvent === 'function') { event = new window.CustomEvent(eventName, { detail: opts }); } else { event = document.createEvent('Event'); event.initEvent(eventName, false, true, opts); } if (target) { target.dispatchEvent(event); assign(store, opts); } } export function showMenu(opts = {}, target) { dispatchGlobalEvent(MENU_SHOW, assign({}, opts, {type: MENU_SHOW}), target); } export function hideMenu(opts = {}, target) { dispatchGlobalEvent(MENU_HIDE, assign({}, opts, {type: MENU_HIDE}), target); }
import assign from 'object-assign'; import { store } from './helpers'; export const MENU_SHOW = 'REACT_CONTEXTMENU_SHOW'; export const MENU_HIDE = 'REACT_CONTEXTMENU_HIDE'; export function dispatchGlobalEvent(eventName, opts, target = window) { // Compatibale with IE // @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work let event; if (typeof window.CustomEvent === 'function') { event = new window.CustomEvent(eventName, { detail: opts }); } else { event = document.createEvent('Event'); event.initCustomEvent(eventName, false, true, opts); } if (target) { target.dispatchEvent(event); assign(store, opts); } } export function showMenu(opts = {}, target) { dispatchGlobalEvent(MENU_SHOW, assign({}, opts, {type: MENU_SHOW}), target); } export function hideMenu(opts = {}, target) { dispatchGlobalEvent(MENU_HIDE, assign({}, opts, {type: MENU_HIDE}), target); }
Fix for IE11 custom event
Fix for IE11 custom event
JavaScript
mit
codeart1st/react-contextmenu,vkbansal/react-contextmenu,vkbansal/react-contextmenu,codeart1st/react-contextmenu,danbovey/react-contextmenu,danbovey/react-contextmenu
8712432a2c9d555ecdbae0b9c549f6554dd9be6d
assets/materialize/js/init.js
assets/materialize/js/init.js
(function($){ $(function(){ $('.button-collapse').sideNav(); }); // end of document ready })(jQuery); // end of jQuery name space // Keep one tab expanded while editing profile $('li div.collapsible-header').on('click',function(e){ if($(this).parents('li').hasClass('active')){ e.stopPropagation(); } }); // Expand "Home" upon loading Edit page $("document").ready(function() { setTimeout(function() { $("ul li:first-child div").trigger('click'); },10); }); $('#last_name').on('blur',function(e) { if( document.getElementById('username').value=='' && document.getElementById('first_name').value!='' && document.getElementById('last_name').value!='') { // combine firstname and lastname to create username var username = document.getElementById('first_name').value.substr(0,490) + document.getElementById('last_name').value.substr(0,49); username = username.replace(/\s+/g, ''); username = username.replace(/\'+/g, ''); username = username.replace(/-+/g, ''); username = username.toLowerCase(); document.getElementById('username').value = username; // username label should translate up var label = $('label[for="username"]'); label['addClass']('active'); // username underline should turn green document.getElementById('username').className = "validate valid"; } });
(function($){ $(function(){ $('.button-collapse').sideNav(); }); // end of document ready })(jQuery); // end of jQuery name space // Keep one tab expanded while editing profile /*$('li div.collapsible-header').on('click',function(e){ if($(this).parents('li').hasClass('active')){ e.stopPropagation(); } });*/ // Expand "Home" upon loading Edit page $("document").ready(function() { setTimeout(function() { $("ul li:first-child div").trigger('click'); },10); }); // Sign-up form: Auto generate username based on first name and llast name inputs $('#last_name').on('blur',function(e) { if( document.getElementById('username').value=='' && document.getElementById('first_name').value!='' && document.getElementById('last_name').value!='') { // combine firstname and lastname to create username var username = document.getElementById('first_name').value.substr(0,490) + document.getElementById('last_name').value.substr(0,49); username = username.replace(/\s+/g, ''); username = username.replace(/\'+/g, ''); username = username.replace(/-+/g, ''); username = username.toLowerCase(); document.getElementById('username').value = username; // username label should translate up var label = $('label[for="username"]'); label['addClass']('active'); // username underline should turn green document.getElementById('username').className = "validate valid"; } });
Allow collapse all accordion tabs in profileeditor
Allow collapse all accordion tabs in profileeditor
JavaScript
mit
VoodooWorks/profile-cms,VoodooWorks/profile-cms,VoodooWorks/profile-cms
4e7eaa000c897c36ed6cdbea6e5e53d49b2b2a76
src/components/pages/PatientsSummary/header/PTCustomCheckbox.js
src/components/pages/PatientsSummary/header/PTCustomCheckbox.js
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { Col } from 'react-bootstrap'; const PTCustomCheckbox = ({ title, name, isChecked, disabled = false, onChange }) => { const toggleCheckbox = () => !disabled && onChange(name); return <Col xs={6} sm={4}> <div className="wrap-fcustominp"> <div className={classNames('fcustominp-state', { disabled })} onClick={toggleCheckbox} > <div className="fcustominp"> <input type="checkbox" name={name} checked={isChecked} onChange={toggleCheckbox} /> <label htmlFor="patients-table-info-name" /> </div> <label htmlFor={name} className="fcustominp-label">{title}</label> </div> </div> </Col> } PTCustomCheckbox.propTypes = { title: PropTypes.string.isRequired, name: PropTypes.string.isRequired, isChecked: PropTypes.bool.isRequired, onChange: PropTypes.func, disabled: PropTypes.bool, }; export default PTCustomCheckbox
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { Col } from 'react-bootstrap'; const PTCustomCheckbox = ({ title, name, isChecked, disabled = false, onChange }) => { const toggleCheckbox = () => !disabled && onChange(name); return <Col xs={6} sm={4}> <div className="wrap-fcustominp"> <div className={classNames('fcustominp-state', { disabled })} onClick={toggleCheckbox} > <div className="fcustominp"> <input type="checkbox" id={`dashboard-${name}`} name={`dashboard-${name}`} checked={isChecked} onChange={toggleCheckbox} /> <label htmlFor={`dashboard-${name}`} /> </div> <label htmlFor={`dashboard-${name}`} className="fcustominp-label">{title}</label> </div> </div> </Col> } PTCustomCheckbox.propTypes = { title: PropTypes.string.isRequired, name: PropTypes.string.isRequired, isChecked: PropTypes.bool.isRequired, onChange: PropTypes.func, disabled: PropTypes.bool, }; export default PTCustomCheckbox
Fix checkboxes for Patient Summary.
Fix checkboxes for Patient Summary.
JavaScript
apache-2.0
PulseTile/PulseTile-React,PulseTile/PulseTile-React,PulseTile/PulseTile-React
f0e7098f88d7ceeae02ba60bb484f4cfa266bce7
src/plugins.js
src/plugins.js
/* @flow */ export const inMemory = (data : Object, transition : Function) => { let rootState = data; const read = () => rootState; const write = (fn : Function) => { const oldState = read(); const newState = fn(oldState); transition(oldState, newState); rootState = newState; return read(); }; return { read, write }; }; export const webStorage = ( { type, key } : Object, data : Object, transition : Function ) => { const store = window[`${type}Storage`]; const read = () => JSON.parse(store.getItem(key)); const write = (fn : Function) => { const oldState = read(); const newState = fn(oldState); transition(oldState, newState); store.setItem(key, JSON.stringify(newState)); return read(); }; return { read, write }; };
/* @flow */ export const inMemory = (initial : Object, transition : Function) => { let rootState = initial; const read = () => rootState; const write = (fn : Function) => { const oldState = read(); const newState = fn(oldState); transition(oldState, newState); rootState = newState; return read(); }; return { read, write }; }; export const webStorage = ( { type, key } : Object, initial : Object, transition : Function ) => { const store = window[`${type}Storage`]; const read = () => JSON.parse(store.getItem(key)); const write = (fn : Function) => { const oldState = read(); const newState = fn(oldState); transition(oldState, newState); store.setItem(key, JSON.stringify(newState)); return read(); }; return { read, write }; };
Rename data prop to initial
Rename data prop to initial
JavaScript
mit
jameshopkins/atom-store,jameshopkins/atom-store
6505b754bc31ce4062d1a4c2eecc172636dbba64
src/components/Node.js
src/components/Node.js
import React, { PropTypes } from 'react'; import { StyleSheet, css } from 'aphrodite'; const styles = StyleSheet.create({ node: { cursor: 'move', }, }); const renderState = (state, index) => ( <text key={state} x="5" y={37 + (18 * index)}> <tspan>{state}</tspan> <tspan x="155" textAnchor="end">99.9</tspan> </text> ); const Node = props => ( <g className={css(styles.node)} onMouseDown={props.onMouseDown} transform={`translate(${props.x} ${props.y})`} > <rect height={20 + (20 * props.states.length)} width="160" fill="#ff8" stroke="#333" ref={props.rectRef} /> <text x="5" y="15">{props.id}</text> <path d="M0,20 h160" stroke="#333" /> {props.states.map(renderState)} </g> ); Node.propTypes = { id: PropTypes.string.isRequired, states: PropTypes.arrayOf(PropTypes.string).isRequired, rectRef: PropTypes.func, onMouseDown: PropTypes.func, x: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, y: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, }; export default Node;
import React, { PropTypes } from 'react'; import { StyleSheet, css } from 'aphrodite'; const styles = StyleSheet.create({ node: { cursor: 'move', userSelect: 'none', }, }); const renderState = (state, index) => ( <text key={state} x="5" y={37 + (18 * index)}> <tspan>{state}</tspan> <tspan x="155" textAnchor="end">99.9</tspan> </text> ); const Node = props => ( <g className={css(styles.node)} onMouseDown={props.onMouseDown} transform={`translate(${props.x} ${props.y})`} > <rect height={20 + (20 * props.states.length)} width="160" fill="#ff8" stroke="#333" ref={props.rectRef} /> <text x="5" y="15">{props.id}</text> <path d="M0,20 h160" stroke="#333" /> {props.states.map(renderState)} </g> ); Node.propTypes = { id: PropTypes.string.isRequired, states: PropTypes.arrayOf(PropTypes.string).isRequired, rectRef: PropTypes.func, onMouseDown: PropTypes.func, x: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, y: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, }; export default Node;
Fix selecting node text when moving
Fix selecting node text when moving
JavaScript
mit
fhelwanger/bayesjs-editor,fhelwanger/bayesjs-editor
bbf64c4d45fc83b5143951f79f2a9c25d757cd65
addon/components/outside-click/component.js
addon/components/outside-click/component.js
import Ember from 'ember' import layout from './template' import PropTypeMixin, { PropTypes } from 'ember-prop-types' const { K } = Ember export default Ember.Component.extend(PropTypeMixin, { layout, propTypes: { onOutsideClick: PropTypes.func }, getDefaultProps() { return { onOutsideClick: K } }, init() { this._super(...arguments) this.handleDown = this.handleDown.bind(this) this.handleUp = this.handleUp.bind(this) }, didInsertElement() { this._super(...arguments) document.addEventListener('mousedown', this.handleDown, true) document.addEventListener('mouseup', this.handleUp, true) }, willDestroyElement() { this._super(...arguments) document.removeEventListener('mousedown', this.handleDown, true) document.removeEventListener('mouseup', this.handleUp, true) }, isOutside: false, handleDown(e) { if (this.isDestroyed || this.isDestroying) { return; } const el = this.$()[0]; if (!el.contains(e.target)) this.set('isOutside', true) }, handleUp(e) { if (this.isDestroyed || this.isDestroying) { return; } if (this.get('isOutside')) this.get('onOutsideClick')(e) this.set('isOutside', false) } })
import Ember from 'ember' import layout from './template' import PropTypeMixin, { PropTypes } from 'ember-prop-types' const { K } = Ember export default Ember.Component.extend(PropTypeMixin, { layout, propTypes: { onOutsideClick: PropTypes.func }, getDefaultProps() { return { onOutsideClick: K } }, init() { this._super(...arguments) this.handleDown = this.handleDown.bind(this) this.handleUp = this.handleUp.bind(this) }, didInsertElement() { this._super(...arguments) document.addEventListener('mousedown', this.handleDown, true) document.addEventListener('mouseup', this.handleUp, true) }, willDestroyElement() { this._super(...arguments) document.removeEventListener('mousedown', this.handleDown, true) document.removeEventListener('mouseup', this.handleUp, true) }, isOutside: false, handleDown(e) { const el = this.$()[0]; if (this.isDestroyed || this.isDestroying) return; if (!el.contains(e.target)) this.set('isOutside', true) }, handleUp(e) { if (this.get('isOutside')) this.get('onOutsideClick')(e) if (this.isDestroyed || this.isDestroying) return; this.set('isOutside', false) } })
Move destroy checks just before set
Move destroy checks just before set
JavaScript
mit
nucleartide/ember-outside-click,nucleartide/ember-outside-click
ec5e284f43cd890a2d24f775f77f0fc5f3810dfc
src/App.js
src/App.js
import React from 'react'; import './App.css'; import logo from './logo.png'; export default function App() { return ( <div> <h1> Welcome to <img src={logo} className="App--logo" alt="React logo" /> React </h1> <p> To get started, edit <code>src/App.js</code> and save the file to update. </p> </div> ); }
import React from 'react'; import './App.css'; import logo from './logo.png'; export default function App() { return ( <div> <h1> Welcome to <img src={logo} className="App--logo" alt="logo" /> React </h1> <p> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); }
Make it fit in one line
Make it fit in one line
JavaScript
bsd-3-clause
emvu/create-react-app,HelpfulHuman/helpful-react-scripts,Timer/create-react-app,christiantinauer/create-react-app,yosharepoint/react-scripts-ts-sp,powerreviews/create-react-app,CodingZeal/create-react-app,lolaent/create-react-app,xiaohu-developer/create-react-app,HelpfulHuman/helpful-react-scripts,andyeskridge/create-react-app,Clearcover/web-build,mikechau/create-react-app,brysgo/create-react-app,TondaHack/create-react-app,timlogemann/create-react-app,timlogemann/create-react-app,andyhite/create-react-app,peopleticker/create-react-app,ConnectedHomes/create-react-web-app,jdcrensh/create-react-app,scyankai/create-react-app,matart15/create-react-app,jayphelps/create-react-app,accurat/accurapp,andyhite/create-react-app,cr101/create-react-app,in2core/create-react-app,matart15/create-react-app,DivineGod/create-react-app,mangomint/create-react-app,Psychwire/create-react-app,kst404/e8e-react-scripts,Bogala/create-react-app-awesome-ts,reedsa/create-react-app,dsopel94/create-react-app,andrewmaudsley/create-react-app,lopezator/create-react-app,liamhu/create-react-app,stockspiking/create-react-app,prometheusresearch/create-react-app,Bogala/create-react-app-awesome-ts,ro-savage/create-react-app,xiaohu-developer/create-react-app,Sonu-sj/cardMatcher,ontruck/create-react-app,maletor/create-react-app,igetgames/spectacle-create-react-app,paweljedrzejczyk/create-react-app,digitalorigin/create-react-app,pdillon/create-react-app,g3r4n/create-esri-react-app,gutenye/create-react-app,Clearcover/web-build,Bogala/create-react-app-awesome-ts,andyhite/create-react-app,0xaio/create-react-app,vgmr/create-ts-app,johnslay/create-react-app,iamdoron/create-react-app,appier/create-react-app,gutenye/create-react-app,lolaent/create-react-app,pdillon/create-react-app,amido/create-react-app,johnslay/create-react-app,digitalorigin/create-react-app,tharakawj/create-react-app,svrcekmichal/react-scripts,powerreviews/create-react-app,andyeskridge/create-react-app,ontruck/create-react-app,romaindso/create-react-app,Exocortex/create-react-app,g3r4n/create-esri-react-app,ro-savage/create-react-app,sigmacomputing/create-react-app,Place1/create-react-app-typescript,pdillon/create-react-app,facebookincubator/create-react-app,iamdoron/create-react-app,HelpfulHuman/helpful-react-scripts,devex-web-frontend/create-react-app-dx,lolaent/create-react-app,Sonu-sj/cardMatcher,RobzDoom/frame_trap,infernojs/create-inferno-app,magic-FE/create-magic-component,romaindso/create-react-app,svrcekmichal/react-scripts,facebookincubator/create-react-app,Exocortex/create-react-app,infernojs/create-inferno-app,scyankai/create-react-app,liamhu/create-react-app,accurat/accurapp,maletor/create-react-app,dpoineau/create-react-app,viankakrisna/create-react-app,ConnectedHomes/create-react-web-app,1Body/prayer-app,viankakrisna/create-react-app,dpoineau/create-react-app,prometheusresearch/create-react-app,paweljedrzejczyk/create-react-app,Bogala/create-react-app-awesome-ts,IamJoseph/create-react-app,TryKickoff/create-kickoff-app,lopezator/create-react-app,gutenye/create-react-app,Psychwire/create-react-app,picter/create-react-app,tharakawj/create-react-app,CodingZeal/create-react-app,magic-FE/create-magic-component,igetgames/spectacle-create-react-app,in2core/create-react-app,accurat/accurapp,kst404/e8e-react-scripts,viankakrisna/create-react-app,bttf/create-react-app,tharakawj/create-react-app,RobzDoom/frame_trap,g3r4n/create-esri-react-app,shrynx/react-super-scripts,Place1/create-react-app-typescript,1Body/prayer-app,prontotools/create-react-app,jayphelps/create-react-app,mangomint/create-react-app,cr101/create-react-app,christiantinauer/create-react-app,sigmacomputing/create-react-app,Timer/create-react-app,1Body/prayer-app,bttf/create-react-app,johnslay/create-react-app,just-boris/create-preact-app,dsopel94/create-react-app,maletor/create-react-app,ConnectedHomes/create-react-web-app,ConnectedHomes/create-react-web-app,peopleticker/create-react-app,1Body/prayer-app,amido/create-react-app,yosharepoint/react-scripts-ts-sp,flybayer/create-react-webextension,josephfinlayson/create-react-app,bttf/create-react-app,mikechau/create-react-app,DivineGod/create-react-app,svrcekmichal/react-scripts,sigmacomputing/create-react-app,Exocortex/create-react-app,jdcrensh/create-react-app,dsopel94/create-react-app,GreenGremlin/create-react-app,xiaohu-developer/create-react-app,reedsa/create-react-app,andrewmaudsley/create-react-app,flybayer/create-react-webextension,Place1/create-react-app-typescript,stockspiking/create-react-app,d3ce1t/create-react-app,iamdoron/create-react-app,GreenGremlin/create-react-app,paweljedrzejczyk/create-react-app,Psychwire/create-react-app,vgmr/create-ts-app,andrewmaudsley/create-react-app,facebookincubator/create-react-app,emvu/create-react-app,jayphelps/create-react-app,prometheusresearch/create-react-app,ontruck/create-react-app,brysgo/create-react-app,TondaHack/create-react-app,josephfinlayson/create-react-app,digitalorigin/create-react-app,mangomint/create-react-app,DivineGod/create-react-app,in2core/create-react-app,magic-FE/create-magic-component,christiantinauer/create-react-app,andyeskridge/create-react-app,timlogemann/create-react-app,vgmr/create-ts-app,devex-web-frontend/create-react-app-dx,igetgames/spectacle-create-react-app,flybayer/create-react-webextension,jdcrensh/create-react-app,stockspiking/create-react-app,infernojs/create-inferno-app,shrynx/react-super-scripts,matart15/create-react-app,Timer/create-react-app,devex-web-frontend/create-react-app-dx,d3ce1t/create-react-app,picter/create-react-app,scyankai/create-react-app,romaindso/create-react-app,d3ce1t/create-react-app,mikechau/create-react-app,yosharepoint/react-scripts-ts-sp,IamJoseph/create-react-app,d3ce1t/create-react-app,ro-savage/create-react-app,liamhu/create-react-app,Sonu-sj/cardMatcher,GreenGremlin/create-react-app,vgmr/create-ts-app,Timer/create-react-app,yosharepoint/react-scripts-ts-sp,0xaio/create-react-app,appier/create-react-app,dpoineau/create-react-app,shrynx/react-super-scripts,prontotools/create-react-app,peopleticker/create-react-app,reedsa/create-react-app,just-boris/create-preact-app,jdcrensh/create-react-app,accurat/accurapp,GreenGremlin/create-react-app,whobutsb/create-redux-app,Place1/create-react-app-typescript,timlogemann/create-react-app,RobzDoom/frame_trap,amido/create-react-app,cr101/create-react-app,whobutsb/create-redux-app,TondaHack/create-react-app,mangomint/create-react-app,brysgo/create-react-app,kst404/e8e-react-scripts,TryKickoff/create-kickoff-app,Clearcover/web-build,CodingZeal/create-react-app,lopezator/create-react-app,0xaio/create-react-app,just-boris/create-preact-app,picter/create-react-app,powerreviews/create-react-app,christiantinauer/create-react-app,devex-web-frontend/create-react-app-dx,IamJoseph/create-react-app,appier/create-react-app,TryKickoff/create-kickoff-app,josephfinlayson/create-react-app,prontotools/create-react-app,emvu/create-react-app
e96df96e13e47ab983fbdbcf58bd00ebd0ff9e5b
public/js/layout.js
public/js/layout.js
var fixedWidth = 220; var minWidth = 660; var fixedPadding = 100; function layoutWidth() { var wWidth = $(window).width(); var bodyPadding = Math.max(Math.floor(wWidth / fixedWidth)-3, 1) * 100; if ($(".container").length) { var width = wWidth - bodyPadding; var newWidth = Math.floor(width / fixedWidth) * fixedWidth; if (newWidth < minWidth) newWidth = minWidth; $(".container").width(newWidth); } } $(document).ready(function() { layoutWidth(); $(window).resize(function(){ layoutWidth(); }); });
var fixedWidth = 220; var minWidth = 660; var fixedPadding = 100; var delayResize = null; function layoutWidth() { var wWidth = $(window).width(); var bodyPadding = Math.max(Math.floor(wWidth / fixedWidth)-3, 1) * 100; if ($(".container").length) { var width = wWidth - bodyPadding; var newWidth = Math.floor(width / fixedWidth) * fixedWidth; if (newWidth < minWidth) newWidth = minWidth; $(".container").width(newWidth); } } function layoutResize() { clearTimeout(delayResize); delayResize = setTimeout(layoutWidth, 250); } $(document).ready(function() { layoutWidth(); $(window).resize(function(){ layoutResize(); }); });
Add timeout when resizing container (prevent close multicall that can cause performance issue)
Add timeout when resizing container (prevent close multicall that can cause performance issue)
JavaScript
mit
hernantas/MangaReader,hernantas/MangaReader,hernantas/MangaReader
3fd410806d1f9cc2f922efde78539671306bd739
server/app.js
server/app.js
Meteor.startup(function () { Tiqs._ensureIndex({text: 1}); }); Meteor.methods({ associateTags: function(text, tags) { Tiqs.upsert({text: text}, {$addToSet: {tags: {$each: tags}}}); _.each(tags, function(tag) { Tiqs.upsert({text: tag}, {$addToSet: {tags: text}}); }); } });
Meteor.startup(function () { Tiqs._ensureIndex({text: 1}); }); Meteor.methods({ associateTags: function(text, tags) { Tiqs.upsert({text: text}, {$addToSet: {tags: {$each: tags}}, $setOnInsert: {createdAt: Date.now()} } ); _.each(tags, function(tag) { Tiqs.upsert({text: tag}, {$addToSet: {tags: text}, $setOnInsert: {createdAt: Date.now()}} ); }); } });
Add createdAt field to Tiqs collection
Add createdAt field to Tiqs collection
JavaScript
mit
imiric/tiq-web,imiric/tiq-web
f0a2fefc7eced759ad5c639c85df44194c3a89f8
rules/temporary-hrdata.js
rules/temporary-hrdata.js
function (user, context, callback) { // This is a rule to specifically allow access to _HRData for specific ClientIDs // _HRData comes from WorkDay, through LDAP Connector // Ideally the RPs who need this data should request it directly from WorkDay, so this is a work-around. // Applications that are ALLOWED to see _HRData var ALLOWED_CLIENTIDS = [ 'IU80mVpKPtIZyUZtya9ZnSTs6fKLt3JO', //biztera.com 'R4djNlyXSl3i8N2KXWkfylghDa9kFQ84' //mozilla.tap.thinksmart.com ]; if (ALLOWED_CLIENTIDS.indexOf(context.clientID) >= 0) { var extend = require('extend'); context.samlConfiguration = context.samlConfiguration || {}; //Remap SAML attributes as SAML cannot show Javascript objects for(var value in user._HRData){ var nname = "http://schemas.security.allizom.org/claims/HRData/"+encodeURIComponent(value); var nvalue = "_HRData."+value; var obj = {}; obj[nname] = nvalue; context.samlConfiguration.mappings = extend(true, context.samlConfiguration.mappings, obj); } callback(null, user, context); } else { // Wipe _HRData (do use non-dot notation) user['_HRData'] = {"placeholder": "empty"}; callback(null, user, context); } }
function (user, context, callback) { // This is a rule to specifically allow access to _HRData for specific ClientIDs // _HRData comes from WorkDay, through LDAP Connector // Ideally the RPs who need this data should request it directly from WorkDay, so this is a work-around. // Applications that are ALLOWED to see _HRData var ALLOWED_CLIENTIDS = [ 'IU80mVpKPtIZyUZtya9ZnSTs6fKLt3JO', //biztera.com 'R4djNlyXSl3i8N2KXWkfylghDa9kFQ84', //mozilla.tap.thinksmart.com 'fNzzMG3XfkxQJcnUpgrGyH2deII3nFFM' //pto1.dmz.mdc1.mozilla.com ]; if (ALLOWED_CLIENTIDS.indexOf(context.clientID) >= 0) { var extend = require('extend'); context.samlConfiguration = context.samlConfiguration || {}; //Remap SAML attributes as SAML cannot show Javascript objects for(var value in user._HRData){ var nname = "http://schemas.security.allizom.org/claims/HRData/"+encodeURIComponent(value); var nvalue = "_HRData."+value; var obj = {}; obj[nname] = nvalue; context.samlConfiguration.mappings = extend(true, context.samlConfiguration.mappings, obj); } callback(null, user, context); } else { // Wipe _HRData (do use non-dot notation) user['_HRData'] = {"placeholder": "empty"}; callback(null, user, context); } }
Add pto app to hrdata rule
Add pto app to hrdata rule this will allow the pto app to get manager info and no longer need an LDAP connection
JavaScript
mpl-2.0
mozilla-iam/auth0-deploy,jdow/auth0-deploy,jdow/auth0-deploy,mozilla-iam/auth0-deploy
2f61e76a50034cd06611bf0086d57deeaf61a2dd
schema/me/save_artwork.js
schema/me/save_artwork.js
import gravity from '../../lib/loaders/gravity'; import { GraphQLString, GraphQLBoolean } from 'graphql'; import { mutationWithClientMutationId } from 'graphql-relay'; import { artworkFields } from '../artwork/index'; export default mutationWithClientMutationId({ name: 'SaveArtwork', decription: 'Save (or remove) an artwork to (from) a users default collection.', inputFields: { artwork_id: { type: GraphQLString, }, remove: { type: GraphQLBoolean, }, }, outputFields: artworkFields(), mutateAndGetPayload: ({ artwork_id, remove, }, request, { rootValue: { accessToken, userID } }) => { if (!accessToken) return new Error('You need to be signed in to perform this action'); const saveMethod = remove ? 'DELETE' : 'POST'; return gravity.with(accessToken, { method: saveMethod, })(`/collection/saved-artwork/artwork/${artwork_id}`, { user_id: userID, }).then(() => gravity(`artwork/${artwork_id}`)); }, });
import gravity from '../../lib/loaders/gravity'; import { GraphQLString, GraphQLBoolean } from 'graphql'; import { mutationWithClientMutationId } from 'graphql-relay'; import { ArtworkType } from '../artwork/index'; export default mutationWithClientMutationId({ name: 'SaveArtwork', decription: 'Save (or remove) an artwork to (from) a users default collection.', inputFields: { artwork_id: { type: GraphQLString, }, remove: { type: GraphQLBoolean, }, }, outputFields: { artwork: { type: ArtworkType, resolve: ({ artwork_id }) => gravity(`artwork/${artwork_id}`), }, }, mutateAndGetPayload: ({ artwork_id, remove, }, request, { rootValue: { accessToken, userID } }) => { if (!accessToken) return new Error('You need to be signed in to perform this action'); const saveMethod = remove ? 'DELETE' : 'POST'; return gravity.with(accessToken, { method: saveMethod, })(`/collection/saved-artwork/artwork/${artwork_id}`, { user_id: userID, }).then(() => ({ artwork_id })); }, });
Return artwork node instead of fields
Return artwork node instead of fields
JavaScript
mit
mzikherman/metaphysics-1,craigspaeth/metaphysics,artsy/metaphysics,craigspaeth/metaphysics,artsy/metaphysics,mzikherman/metaphysics-1,artsy/metaphysics,mzikherman/metaphysics-1,broskoski/metaphysics,mzikherman/metaphysics-1
27e1d21c375b16697c4ca4eef0f6c14193262797
test/DropdownAlert-test.js
test/DropdownAlert-test.js
const React = require('react') const should = require('should') const { shallow } = require('enzyme') const { expect } = require('chai') import DropdownAlert from '../DropdownAlert' import { View, Text, StyleSheet, TouchableHighlight, Animated, Modal, StatusBar, Image } from "react-native" describe('DropdownAlert', () => { let dropdownAlert before(() => { dropdownAlert = shallow(<DropdownAlert />) }) it('should exist', () => { DropdownAlert.should.be.ok }) })
const React = require('react') const should = require('should') const { shallow } = require('enzyme') const { expect } = require('chai') import DropdownAlert from '../DropdownAlert' import { View, Text, StyleSheet, TouchableHighlight, Animated, Modal, StatusBar, Image } from "react-native" describe('DropdownAlert', () => { it('should exist', () => { let wrapper = shallow(<DropdownAlert />) should.exist(wrapper) }) it('should find custom sub components', () => { let wrapper = shallow(<DropdownAlert imageUri={'https://facebook.github.io/react/img/logo_og.png'} />) wrapper.instance().alert('custom', 'Title', 'Message') wrapper.update() expect(wrapper.find(Modal)).to.have.length(1) expect(wrapper.find(StatusBar)).to.have.length(1) expect(wrapper.find(View)).to.have.length(2) expect(wrapper.find(Animated.View)).to.have.length(1) expect(wrapper.find(TouchableHighlight)).to.have.length(1) expect(wrapper.find(Text)).to.have.length(2) expect(wrapper.find(Image)).to.have.length(1) }) it('should dismiss', () => { let wrapper = shallow(<DropdownAlert />) wrapper.instance().dismiss() wrapper.update() wrapper.instance().should.be.ok }) })
Add sub components test; Add dismiss test
Add sub components test; Add dismiss test
JavaScript
mit
testshallpass/react-native-dropdownalert,testshallpass/react-native-dropdownalert,shotozuro/react-native-dropdownalert,devBrian/react-native-dropdownalert,devBrian/react-native-dropdownalert,shotozuro/react-native-dropdownalert,shotozuro/react-native-dropdownalert,devBrian/react-native-dropdownalert,testshallpass/react-native-dropdownalert
9f26f41123b6fcda8ade34325161d8d433f4ec61
test/unit/api/component.js
test/unit/api/component.js
import { Component } from '../../../src'; describe('api/Component', () => { if (!classStaticsInheritance()) { return; } describe('property getters', () => { it('observedAttributes', () => { class Test extends Component { static get observedAttributes() { return ['test']; } }; expect(Test.observedAttributes).to.deep.equal(['test']); }); it('props', () => { class Test extends Component { static get props() { return { test: { attribute: true } }; } }; expect(Test.props).to.deep.equal({ test: { attribute: true } }); }); }); describe('property initialisers', () => { it('observedAttributes', () => { class Test extends Component { static observedAttributes = ['test']; }; expect(Test.observedAttributes).to.deep.equal(['test']); }); it('props', () => { class Test extends Component { static props = { test: { attribute: true } }; }; expect(Test.props).to.deep.equal({ test: { attribute: true } }); }); }); });
import { Component } from '../../../src'; import { classStaticsInheritance } from '../lib/support'; describe('api/Component', () => { if (!classStaticsInheritance()) { return; } describe('property getters', () => { it('observedAttributes', () => { class Test extends Component { static get observedAttributes() { return ['test']; } }; expect(Test.observedAttributes).to.deep.equal(['test']); }); it('props', () => { class Test extends Component { static get props() { return { test: { attribute: true } }; } }; expect(Test.props).to.deep.equal({ test: { attribute: true } }); }); }); describe('property initialisers', () => { it('observedAttributes', () => { class Test extends Component { static observedAttributes = ['test']; }; expect(Test.observedAttributes).to.deep.equal(['test']); }); it('props', () => { class Test extends Component { static props = { test: { attribute: true } }; }; expect(Test.props).to.deep.equal({ test: { attribute: true } }); }); }); });
Fix test by adding a missing import.
test: Fix test by adding a missing import.
JavaScript
mit
skatejs/skatejs,skatejs/skatejs,skatejs/skatejs,chrisdarroch/skatejs,chrisdarroch/skatejs
cb04c26b0819fe742c80bc8f05ce3af3c32823e3
lib/node_modules/@stdlib/fs/read-file/examples/index.js
lib/node_modules/@stdlib/fs/read-file/examples/index.js
'use strict'; var readFile = require( './../lib' ); // Sync // var file = readFile.sync( __filename, 'utf8' ); // returns <string> console.log( file instanceof Error ); // => false file = readFile.sync( 'beepboop', { 'encoding': 'utf8' }); // returns <Error> console.log( file instanceof Error ); // => true // Async // readFile( __filename, onFile ); readFile( 'beepboop', onFile ); function onFile( error, data ) { if ( error ) { if ( error.code === 'ENOENT' ) { console.error( 'File does not exist.' ); } else { throw error; } } else { console.log( data ); } }
'use strict'; var readFile = require( './../lib' ); // Sync // var file = readFile.sync( __filename, 'utf8' ); // returns <string> console.log( file instanceof Error ); // => false file = readFile.sync( 'beepboop', { 'encoding': 'utf8' }); // returns <Error> console.log( file instanceof Error ); // => true // Async // readFile( __filename, onFile ); readFile( 'beepboop', onFile ); function onFile( error, data ) { if ( error ) { if ( error.code === 'ENOENT' ) { console.error( 'File does not exist.' ); } else { throw error; } } else { console.log( data ); } }
Remove extra trailing empty lines
Remove extra trailing empty lines
JavaScript
apache-2.0
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
ea22ee1596e2f9d93ce01349f06a3c99143f21bb
test/absUrl.js
test/absUrl.js
var should = require('chai').should(); var LocationUtil = require('../src/location-util.js').LocationUtil; describe('#absUrl', function () { it('should get full URL', function () { var l = new LocationUtil('http://example.com:8080/foo?bar=buz#frag'); l.absUrl().should.equal('http://example.com:8080/foo?bar=buz#frag'); }); });
var should = require('chai').should(); var LocationUtil = require('../src/location-util.js').LocationUtil; describe('#absUrl', function () { it('should get full URL', function () { var l = new LocationUtil('http://example.com:8080/foo?bar=buz#frag'); l.absUrl().should.equal('http://example.com:8080/foo?bar=buz#frag'); }); it('documents behavior', function () { var l = new LocationUtil('http://example.com:3000/foo?bar=buz#frag'); l.url('/user?id=123#name').absUrl().should.equal('http://example.com:3000/user?id=123#name'); l.path('/entry').absUrl().should.equal('http://example.com:3000/entry?id=123#name'); l.search('date', '20140401', 'id', null).absUrl().should.equal('http://example.com:3000/entry?date=20140401#name'); l.hash('').absUrl().should.equal('http://example.com:3000/entry?date=20140401'); }); });
Add some test cases that are in doc
Add some test cases that are in doc
JavaScript
mit
moznion/location-util
56efaa7f095ffef29decbb0942f37f24851b4847
js/DataObjectPreviewer.js
js/DataObjectPreviewer.js
(function($) { $.entwine('ss', function($){ $('.ss-gridfield-orderable tbody .handle').entwine({ onmousedown: function () { this.closest('tbody').addClass('ss-gridfield-sorting'); }, onmouseup: function () { this.closest('tbody').removeClass('ss-gridfield-sorting'); } }); $('.dataobjectpreview').entwine({ onadd: function () { var $tr = this.closest('tr'); if ($tr.length && $tr.hasClass('ui-sortable-helper')) { return; } var $iframe = $('<iframe style="width: 100%; overflow: hidden" scrolling="no"></iframe>'); $iframe.bind('load', function () { var iframeWindow = $iframe.get(0).contentWindow, $iframeWindow = $(iframeWindow), iframeBody = iframeWindow.document.body, iframeHeight; $iframeWindow.resize(function () { var newHeight = iframeBody.offsetHeight; if (newHeight !== iframeHeight) { $iframe.height(newHeight + "px"); iframeHeight = newHeight; } }); if ($iframe.is(":visible")) { $iframeWindow.resize(); } }); $iframe.attr('src', this.data('src')); this.append($iframe); } }); }); }(jQuery));
(function($) { function getDocumentHeight(doc) { return Math.max( doc.documentElement.clientHeight, doc.body.scrollHeight, doc.documentElement.scrollHeight, doc.body.offsetHeight, doc.documentElement.offsetHeight); } $.entwine('ss', function($){ $('.ss-gridfield-orderable tbody .handle').entwine({ onmousedown: function () { this.closest('tbody').addClass('ss-gridfield-sorting'); }, onmouseup: function () { this.closest('tbody').removeClass('ss-gridfield-sorting'); } }); $('.dataobjectpreview').entwine({ onadd: function () { var $tr = this.closest('tr'); if ($tr.length && $tr.hasClass('ui-sortable-helper')) { return; } var $iframe = $('<iframe style="width: 100%; overflow: hidden" scrolling="no"></iframe>'); $iframe.bind('load', function () { var iframeWindow = $iframe.get(0).contentWindow, $iframeWindow = $(iframeWindow), iframeHeight; $iframeWindow.resize(function () { var newHeight = getDocumentHeight( iframeWindow.document ); if (newHeight !== iframeHeight) { $iframe.height(newHeight + "px"); iframeHeight = newHeight; } }); if ($iframe.is(":visible")) { $iframeWindow.resize(); } }); $iframe.attr('src', this.data('src')); this.append($iframe); } }); }); }(jQuery));
Use a cross-browser compatible method of determining document height
Use a cross-browser compatible method of determining document height The automatic setting of height for the preview iframe stopped working in Chrome. This change fixes this.
JavaScript
mit
heyday/silverstripe-dataobjectpreview,heyday/silverstripe-dataobjectpreview
cadc76aaac836b8a13fd0c6da5b36b70d8c54ad7
example/examples/HLSSource.js
example/examples/HLSSource.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Hls from 'hls.js'; const propTypes = { src: PropTypes.string.isRequired, type: PropTypes.string, video: PropTypes.object, }; export default class HLSSource extends Component { constructor(props, context) { super(props, context); this.hls = new Hls(); } componentDidMount() { // `src` is the property get from this component // `video` is the property insert from `Video` component // `video` is the html5 video element const { src, video } = this.props; // load hls video source base on hls.js if (Hls.isSupported()) { this.hls.loadSource(src); this.hls.attachMedia(video); this.hls.on(Hls.Events.MANIFEST_PARSED, () => { video.play(); }); } } render() { return ( <source src={this.props.src} type={this.props.type || 'application/x-mpegURL'} /> ); } } HLSSource.propTypes = propTypes;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Hls from 'hls.js'; const propTypes = { src: PropTypes.string.isRequired, type: PropTypes.string, video: PropTypes.object, }; export default class HLSSource extends Component { constructor(props, context) { super(props, context); this.hls = new Hls(); } componentDidMount() { // `src` is the property get from this component // `video` is the property insert from `Video` component // `video` is the html5 video element const { src, video } = this.props; // load hls video source base on hls.js if (Hls.isSupported()) { this.hls.loadSource(src); this.hls.attachMedia(video); this.hls.on(Hls.Events.MANIFEST_PARSED, () => { video.play(); }); } } componentWillUnmount() { // destroy hls video source if (this.hls) { this.hls.destroy(); } } render() { return ( <source src={this.props.src} type={this.props.type || 'application/x-mpegURL'} /> ); } } HLSSource.propTypes = propTypes;
Destroy HLS source before component unmount
Destroy HLS source before component unmount
JavaScript
mit
video-react/video-react,video-react/video-react
a60b407bf182c852b9d6e841e1f0511fb770411b
client/templates/course/sidebar/section/add-lesson/add-lesson.js
client/templates/course/sidebar/section/add-lesson/add-lesson.js
Template.sectionAddLesson.events({ 'click .add-lesson-button': function (event, template) { // Get lesson name var lessonName = template.find(".lesson-name").value; // Create temporary lesson object var lessonObject = {'name': lessonName}; // Add lesson to database, // getting lesson ID in return var lessonId = Lessons.insert(lessonObject); if (!this.lessonIDs) { this.lessonIDs = []; } // Add lesson ID to array this.lessonIDs.push(lessonId); // Get course sections array from parent template var courseSections = Template.parentData().sections; // Get course ID from parent template var courseID = Template.parentData()._id; // Save course.lessonIDs array to database Courses.update(courseID, {$set: {"sections": courseSections}}); } });
Template.sectionAddLesson.events({ 'click .add-lesson-button': function (event, template) { // Get lesson name var lessonName = template.find(".lesson-name").value; // Create temporary lesson object var lessonObject = {'name': lessonName}; // Add lesson to database, // getting lesson ID in return var lessonId = Lessons.insert(lessonObject); if (!this.lessonIDs) { this.lessonIDs = []; } // Add lesson ID to array this.lessonIDs.push(lessonId); // Get course sections array from parent template var courseSections = Template.parentData().sections; // Get course ID from parent template var courseID = Template.parentData()._id; // Save course.lessonIDs array to database Courses.update(courseID, {$set: {"sections": courseSections}}); // Clear the lesson name field $(".lesson-name").val(''); } });
Clear lesson field on add.
Clear lesson field on add.
JavaScript
agpl-3.0
Crowducate/crowducate-platform,Crowducate/crowducate-platform,Crowducate/crowducate-next,Crowducate/crowducate-next,KshirsagarNaidu/bodhiprocessor,KshirsagarNaidu/bodhiprocessor
ef773f16dbaf0d2ef922f061d50fb1462c98036b
tests/index.js
tests/index.js
/** * Check If Image Path Exists */ var http = require('http'), url = 'http://sirocco.accuweather.com/adc_images2/english/feature/400x300/worstwx.jpg' ; http.get(url, function(response) { if (response.statusCode == '200') return; throw new Error(response.statusCode); }).on('error', function(error) { throw error; });
/** * Check If Image Path Exists */ var http = require('http'), url = 'http://sirocco.accuweather.com/adc_images2/english/feature/400x300/worstwx.jpg' ; http.get(url, function(response) { if (response.statusCode == '200') process.exit(0); throw new Error(response.statusCode); }).on('error', function(error) { throw error; });
Use process.exit to make test faster
Use process.exit to make test faster
JavaScript
apache-2.0
matthewspencer/worstweather
995d2be6e56ba2b2f1b44e1e0f05c56d842da448
src/components/candidatethumbnail/CandidateThumbnail.js
src/components/candidatethumbnail/CandidateThumbnail.js
import React from 'react'; import { Image } from 'react-bootstrap' import CandidateCounter from './CandidateCounter' import styles from './candidatethumbnail.css' export default class CandidateThumbnail extends React.Component { render() { return ( <div className="col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div className="card"> <div className="candidate-card-title"> <h3>{this.props.name}</h3> </div> <div className="candidate-card-divider"></div> <div className="candidate-card-image-link"> <Image className="candidate-card-image" src={this.props.img} responsive/> </div> <div className="candidate-card-counter"> <CandidateCounter counter={this.props.counter}/> </div> </div> </div> ); } }
import React from 'react'; import { Image } from 'react-bootstrap' import { Route } from 'react-router-dom' import CandidateCounter from './CandidateCounter' import styles from './candidatethumbnail.css' export default class CandidateThumbnail extends React.Component { render() { return ( <Route render={({ history}) => ( <div className="col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div className="card" onClick = {() => { history.push('/election/dkijakarta/candidate/'+this.props.name) }}> <div className="candidate-card-title"> <h3>{this.props.name}</h3> </div> <div className="candidate-card-divider"></div> <div className="candidate-card-image-link" > <Image className="candidate-card-image" src={this.props.img} responsive/> </div> <div className="candidate-card-counter"> <CandidateCounter counter={this.props.counter}/> </div> </div> </div> )} /> ); } }
Add link from candidate thumbnail to candidate detail page
Add link from candidate thumbnail to candidate detail page
JavaScript
mit
imrenagi/rojak-web-frontend,imrenagi/rojak-web-frontend
ed0df4c15952d3b00ca0de3b01cc4697ee6e9570
app/react/data/exclude_images.js
app/react/data/exclude_images.js
module.exports = [ 'https://upload.wikimedia.org/wikipedia/en/e/e7/Cscr-featured.svg', '.webm', 'https://upload.wikimedia.org/wikipedia/en/4/4a/Commons-logo.svg', 'https://upload.wikimedia.org/wikipedia/en/f/fd/Portal-puzzle.svg', 'https://upload.wikimedia.org/wikipedia/en/4/48/Folder_Hexagonal_Icon.svg', 'https://upload.wikimedia.org/wikipedia/commons/a/a8/Office-book.svg', '.tif', 'Commons-logo', 'assets/file-type-icons', '_Icon.svg', 'Question_book-new.svg', 'P_vip.svg', 'Cscr-featured.svg', 'Portal-puzzle.svg', 'Office-book.svg', 'commons/thumb/b/b4/Ambox_important.svg/600px-Ambox_important' ]
module.exports = [ 'https://upload.wikimedia.org/wikipedia/en/e/e7/Cscr-featured.svg', '.webm', 'https://upload.wikimedia.org/wikipedia/en/4/4a/Commons-logo.svg', 'https://upload.wikimedia.org/wikipedia/en/f/fd/Portal-puzzle.svg', 'https://upload.wikimedia.org/wikipedia/en/4/48/Folder_Hexagonal_Icon.svg', 'https://upload.wikimedia.org/wikipedia/commons/a/a8/Office-book.svg', '.tif', 'Commons-logo', 'assets/file-type-icons', '_Icon.svg', 'Question_book-new.svg', 'P_vip.svg', 'Cscr-featured.svg', 'Portal-puzzle.svg', 'Office-book.svg' ]
Revert "Added new exclude image"
Revert "Added new exclude image" This reverts commit cbc4520fcc0b6744113bee40ee21571eb787ea25.
JavaScript
mit
WikiEducationFoundation/Wiki-Playlist,WikiEducationFoundation/Wiki-Playlist,WikiEducationFoundation/Wiki-Playlist
317f7ca114f80cf2c4d995938b9f262b50fa02fb
app/scenes/SearchScreen/index.js
app/scenes/SearchScreen/index.js
import React, { Component } from 'react'; import { View } from 'react-native'; import RepoSearchBar from './components/RepoSearchBar'; import RepoSearchButton from './components/RepoSearchButton'; import RepoList from './components/RepoList'; export default class SearchScreen extends Component { constructor(props) { super(props); this.state = { username: '', repos: [] }; } render() { return ( <View style={{ flex: 1, flexDirection: 'column', }}> <RepoSearchBar /> <RepoSearchButton /> <RepoList /> </View> ); } }
import React, { Component } from 'react'; import { View } from 'react-native'; import RepoSearchBar from './components/RepoSearchBar'; import RepoSearchButton from './components/RepoSearchButton'; import RepoList from './components/RepoList'; export default class SearchScreen extends Component { constructor(props) { super(props); this.state = { username: '', repos: [] }; } render() { return ( <View style={{ flex: 1, flexDirection: 'column', }}> <RepoSearchBar /> <RepoSearchButton /> <RepoList /> </View> ); } changeUsername(newUsername) { this.setState({ username: newUsername }); } updateRepos(newRepos) { this.setSate({ repos: newRepos }); } }
Add helper functions to change screen states
Add helper functions to change screen states
JavaScript
mit
msanatan/GitHubProjects,msanatan/GitHubProjects,msanatan/GitHubProjects
4036b9f7009c65aa1889b80ddbb81f2ad95dc873
src/handler_adaptor.js
src/handler_adaptor.js
define(['lib/def', 'handler'], function(Def, Handler) { var HandlerAdaptor = Def.type(Handler, function(handler) { Handler.call(this); this.def_prop('handler', handler); }); HandlerAdaptor.def_method(function on_message(msg, cont) { if (this.handler.match(msg)) return msg.respond(this.handler.execute(msg), cont); return cont(msg); }); return HandlerAdaptor; });
define(['lib/def', 'handler'], function(Def, Handler) { var HandlerAdaptor = Def.type(Handler, function(handler) { this.constructor.__super__.call(this); this.def_prop('handler', handler); }); HandlerAdaptor.def_method(function on_message(msg, cont) { if (this.handler.match(msg)) return msg.respond(this.handler.execute(msg), cont); return cont(msg); }); return HandlerAdaptor; });
Refactor constructor to take advantage of __super__ member.
Refactor constructor to take advantage of __super__ member.
JavaScript
mit
bassettmb/slack-bot-dev
2b82c65e398a66d3dc23f0fdf366549e5565219f
src/main/webapp/resources/js/utilities/url-utilities.js
src/main/webapp/resources/js/utilities/url-utilities.js
/** * Since IRIDA can be served within a container, all requests need to have * the correct base url. This will add, if required, the base url. * * NOTE: THIS ONLY NEEDS TO BE CALLED FOR LINKS, ASYNCHRONOUS REQUESTS WILL * BE AUTOMATICALLY HANDLED. * * @param {string} url * @return {string|*} */ export function setBaseUrl(url) { // Remove any leading slashes url = url.replace(/^\/+/, ""); /* Get the base url which is set via the thymeleaf template engine. */ const BASE_URL = window.TL?._BASE_URL || "/"; /* Check to make sure that the given url has not already been given the base url. */ if ( (BASE_URL !== "/" && url.startsWith(BASE_URL)) || url.startsWith("http") ) { return url; } /* Create the new url */ return `${BASE_URL}${url}`; }
/** * Since IRIDA can be served within a container, all requests need to have * the correct base url. This will add, if required, the base url. * * NOTE: THIS ONLY NEEDS TO BE CALLED FOR LINKS, ASYNCHRONOUS REQUESTS WILL * BE AUTOMATICALLY HANDLED. * * @param {string} url * @return {string|*} */ export function setBaseUrl(url) { /* Get the base url which is set via the thymeleaf template engine. */ const BASE_URL = window.TL?._BASE_URL || "/"; /* Check to make sure that the given url has not already been given the base url. */ if (url.startsWith(BASE_URL) || url.startsWith("http")) { return url; } // Remove any leading slashes url = url.replace(/^\/+/, ""); /* Create the new url */ return `${BASE_URL}${url}`; }
Check to see if the url has the context path first.
Check to see if the url has the context path first.
JavaScript
apache-2.0
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
ff2bb7a079a88eb9a60061de9f4481cee1141889
spec/specs.js
spec/specs.js
describe('pingPong', function() { it("is true for a number that is divisible by 3", function() { expect(pingPong(6)).to.equal(true); }); it("is true for a number that is divisible by 5", function() { expect(pingPong(10)).to.equal(true); }); });
describe('pingPong', function() { it("is true for a number that is divisible by 3", function() { expect(pingPong(6)).to.equal(true); }); it("is true for a number that is divisible by 5", function() { expect(pingPong(10)).to.equal(true); }); it("is true for a number that is divisible by 15", function() { expect(pingPong(30)).to.equal.(true); }); });
Add an additional spec test for userNumbers divisible by 15
Add an additional spec test for userNumbers divisible by 15
JavaScript
mit
kcmdouglas/pingpong,kcmdouglas/pingpong
1dde5df3c6fdfe555f7258d1a697735bc6f3b7a8
src/App.js
src/App.js
import React from 'react'; import { HashRouter as Router, Switch, Route, Link } from "react-router-dom"; import ComponentsPage from './pages/Components'; import ContentPage from './pages/Content'; import UtilsPage from './pages/Utils'; function App() { return ( <Router> <div className="p-5"> <h1>Gateway</h1> <p>Gateway is Findaway's boilerplate for React sites/applications.</p> <p>This repository can be copied to start any react project.</p> <p>By default this repository contains CSS (SCSS), React Components, and utilities to help get any project up-and-running quickly with consistency to all other projects.</p> <ul className="list-inline"> <li><Link to="content">Content</Link></li> <li><Link to="components">Components</Link></li> <li><Link to="utils">Utils</Link></li> </ul> <Switch> <Route path="/components"> <ComponentsPage /> </Route> <Route path="/content"> <ContentPage /> </Route> <Route path="/utils"> <UtilsPage /> </Route> </Switch> </div> </Router> ); } export default App;
import React from 'react'; import { HashRouter as Router, Switch, Route, Link } from "react-router-dom"; import ComponentsPage from './pages/Components'; import ContentPage from './pages/Content'; import UtilsPage from './pages/Utils'; function App() { return ( <Router> <div className="p-5"> <h1>Gateway</h1> <p>Gateway is Findaway's boilerplate for React sites/applications.</p> <p>This repository can be copied to start any react project. Get the latest from <a href="https://github.com/FindawayWorld/gateway">https://github.com/FindawayWorld/gateway</a></p> <p>By default this repository contains CSS (SCSS), React Components, and utilities to help get any project up-and-running quickly with consistency to all other projects.</p> <p></p> <ul className="list-inline"> <li><Link to="content">Content</Link></li> <li><Link to="components">Components</Link></li> <li><Link to="utils">Utils</Link></li> </ul> <Switch> <Route path="/components"> <ComponentsPage /> </Route> <Route path="/content"> <ContentPage /> </Route> <Route path="/utils"> <UtilsPage /> </Route> </Switch> </div> </Router> ); } export default App;
Add link to GH repo
Add link to GH repo
JavaScript
mit
FindawayWorld/gateway,FindawayWorld/gateway
3a6dafd545da6f7ccb271915eb1b9a5f76cfe277
src/App.js
src/App.js
import React from 'react'; import { BrowserRouter, Match, Miss } from 'react-router' import Header from './components/Header'; import CTA from './components/CTA'; import Footer from './components/Footer'; import routes from './config/routes'; import FourOhFour from './components/404'; const App = () => ( // <BrowserRouter history={history}> <BrowserRouter> <div> <Header /> { routes.map((route, index) => ( // rendering `Match`s with different // components but the same pattern as before <Match // FIXME: index as key key={index} pattern={route.pattern} // component={route.main} render={matchProps => { const Component = route.main; // TODO: double check where to put scrolling window.scroll(0, 0); return ( <div className="content"> <Component {...matchProps} /> <CTA matchProps={matchProps} /> </div> ); }} exactly={route.exactly} /> )) } <Miss component={FourOhFour} /> <Footer /> </div> </BrowserRouter> ); export default App;
import React from 'react'; import { BrowserRouter, Match, Miss } from 'react-router' import Header from './components/Header'; import CTA from './components/CTA'; import Footer from './components/Footer'; import routes from './config/routes'; import FourOhFour from './components/404'; const App = () => ( // <BrowserRouter history={history}> <BrowserRouter> <div> <Header /> { routes.map((route, index) => ( // rendering `Match`s with different // components but the same pattern as before <Match key={route.pattern} pattern={route.pattern} // component={route.main} render={matchProps => { const Component = route.main; // TODO: double check where to put scrolling window.scroll(0, 0); return ( <div className="content"> <Component {...matchProps} /> <CTA matchProps={matchProps} /> </div> ); }} exactly={route.exactly} /> )) } <Miss component={FourOhFour} /> <Footer /> </div> </BrowserRouter> ); export default App;
Fix index as key anti pattern
Fix index as key anti pattern
JavaScript
mit
emyarod/afw,emyarod/afw
1ebfc2f9d228811b45955e1d7ddd1f61407a3809
src/App.js
src/App.js
import React from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import Home from './Home'; const App = () => ( <React.Fragment> <Router> <Route exact path="/" component={Home} /> </Router> </React.Fragment> ); export default App;
import React from 'react'; import CssBaseline from '@material-ui/core/CssBaseline'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import Home from './Home'; const App = () => ( <React.Fragment> <CssBaseline /> <Router> <Route exact path="/" component={Home} /> </Router> </React.Fragment> ); export default App;
Use CssNormalize to normalize padding/margin for entire app
Use CssNormalize to normalize padding/margin for entire app
JavaScript
mit
jasongforbes/jforbes.io,jasongforbes/jforbes.io,jasongforbes/jforbes.io
22d63bf978e351a22515248600a8cd7a1d56a07d
src/pages/home/page.js
src/pages/home/page.js
import React from 'react'; import ReactDom from 'react-dom'; import { Link } from 'react-router'; import _ from 'lodash'; import client from '../../common/store/Contentful'; import marked from 'marked'; import styles from "./style.css"; export default class HomePage extends React.Component { constructor(props) { super(props); var self = this; this.state = { fonts: this.props.fontStore.fonts, content: '' }; client.getEntries({ 'content_type': 'page', 'fields.title': 'Home' }) .then(function (entries) { var content = _.get(entries, 'items[0].fields.content'); console.log(content) self.setState({ content }); }) .catch(function(error) { console.error(error); }); } render() { var fontItems = _.map(this.state.fonts, function(font, index) { var link = '/karaoke/' + font.name; return ( <li key={ index } style={{ backgroundColor: font.color }}> <Link to={ link }> <p>{ font.name }</p> </Link> </li> ); }); return ( <div id="content"> <ul className={ styles.directory }> { fontItems } </ul> <div className={ styles['page-content'] } dangerouslySetInnerHTML={{__html: marked(this.state.content)}}> </div> </div> ); } }
import React from 'react'; import ReactDom from 'react-dom'; import { Link } from 'react-router'; import _ from 'lodash'; import client from '../../common/store/Contentful'; import marked from 'marked'; import styles from "./style.css"; export default class HomePage extends React.Component { constructor(props) { super(props); var self = this; this.state = { fonts: this.props.fontStore.fonts, content: '' }; client.getEntries({ 'content_type': 'page', 'fields.title': 'Home' }) .then(function (entries) { var content = _.get(entries, 'items[0].fields.content'); self.setState({ content }); }) .catch(function(error) { console.error(error); }); } render() { var fontItems = _.map(this.state.fonts, function(font, index) { var link = '/karaoke/' + font.name; return ( <li key={ index } style={{ backgroundColor: font.color }}> <Link to={ link }> <p>{ font.name }</p> </Link> </li> ); }); return ( <div id="content"> <ul className={ styles.directory }> { fontItems } </ul> <div className={ styles['page-content'] } dangerouslySetInnerHTML={{__html: marked(this.state.content)}}> </div> </div> ); } }
Remove my dumb logging statement
Remove my dumb logging statement
JavaScript
mit
mhgbrown/typography-karaoke,mhgbrown/typography-karaoke
1f79c994d96907273b45b36fe1cbf06340e71c41
src/cli.js
src/cli.js
#!/usr/bin/env node import yargs from 'yargs'; import path from 'path'; import fs from 'fs'; import * as pose from '.'; import actions from './actions'; const opts = yargs .usage('$ pose <action> [options]') .help('help') .epilog(actions.trim()) .options({ name: { alias: ['as'], default: path.basename(process.cwd()), desc: 'Name of template', }, entry: { alias: ['e'], default: process.cwd(), defaultDescription: 'cwd', desc: 'Entry of template', }, help: { alias: ['h'], }, }).argv; const action = opts._[0]; if (!action) { console.log('Type "pose help" to get started.'); process.exit(); } [ opts._pose = path.join(process.env.HOME, '.pose'), opts._templates = path.join(opts._pose, 'templates'), ].forEach(dir => { fs.mkdir(dir, () => null); }); if (typeof pose[action] === 'function') { pose[action](opts); } else { console.error(`Unknown action "${action}"`); } export { action, opts };
#!/usr/bin/env node import yargs from 'yargs'; import path from 'path'; import fs from 'fs'; import * as pose from '.'; import actions from './actions'; const opts = yargs .usage('$ pose <action> [options]') .help('help') .epilog(actions.trim()) .options({ name: { alias: ['as'], default: path.basename(process.cwd()), desc: 'Name of template', }, entry: { alias: ['from'], default: process.cwd(), defaultDescription: 'cwd', desc: 'Entry of template', }, help: { alias: ['h'], }, }).argv; const action = opts._[0]; if (!action) { console.log('Type "pose help" to get started.'); process.exit(); } [ opts._pose = path.join(process.env.HOME, '.pose'), opts._templates = path.join(opts._pose, 'templates'), ].forEach(dir => { fs.mkdir(dir, () => null); }); if (typeof pose[action] === 'function') { pose[action](opts); } else { console.error(`Unknown action "${action}"`); } export { action, opts };
Remove -e in favor of --from
Remove -e in favor of --from
JavaScript
mit
seanc/pose
5d3474ab83dcf9931ee480fbe7d1119642e7355f
test/conf/karma-sauce.conf.js
test/conf/karma-sauce.conf.js
module.exports = function(config) { var commonConfig = (require("./karma-common.conf"))(config); var customLaunchers = { sl_chrome: { base: "SauceLabs", browserName: "chrome", platform: "Windows 8.1" }, sl_firefox: { base: "SauceLabs", browserName: "firefox", platform: "Windows 8.1" }, sl_safari: { base: "SauceLabs", browserName: "safari", platform: "OS X 10.10" }, sl_ie_11: { base: "SauceLabs", browserName: "internet explorer", platform: "Windows 8.1" } }; var options = { reporters: ["verbose", "saucelabs"], sauceLabs: { testName: "Vivliostyle.js", recordScreenshots: false, startConnect: false, // Sauce Connect is started by Travis CI tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, captureTimeout: 120000, customLaunchers: customLaunchers, browsers: Object.keys(customLaunchers), singleRun: true }; for (var key in commonConfig) { if (commonConfig.hasOwnProperty(key)) { options[key] = commonConfig[key]; } } config.set(options); };
module.exports = function(config) { var commonConfig = (require("./karma-common.conf"))(config); var customLaunchers = { sl_chrome: { base: "SauceLabs", browserName: "chrome", platform: "Windows 8.1" }, sl_firefox: { base: "SauceLabs", browserName: "firefox", platform: "Windows 8.1", version: "beta" }, sl_safari: { base: "SauceLabs", browserName: "safari", platform: "OS X 10.10" }, sl_ie_11: { base: "SauceLabs", browserName: "internet explorer", platform: "Windows 8.1" } }; var options = { reporters: ["verbose", "saucelabs"], sauceLabs: { testName: "Vivliostyle.js", recordScreenshots: false, startConnect: false, // Sauce Connect is started by Travis CI tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, captureTimeout: 120000, customLaunchers: customLaunchers, browsers: Object.keys(customLaunchers), singleRun: true }; for (var key in commonConfig) { if (commonConfig.hasOwnProperty(key)) { options[key] = commonConfig[key]; } } config.set(options); };
Use beta version of Firefox (supports vertical writing-mode) in tests on Sauce Labs
Use beta version of Firefox (supports vertical writing-mode) in tests on Sauce Labs
JavaScript
apache-2.0
kuad9/vivliostyle.js_study,vivliostyle/vivliostyle.js,nulltask/vivliostyle.js,vivliostyle/vivliostyle.js,kuad9/vivliostyle.js_study,vivliostyle/vivliostyle.js,nulltask/vivliostyle.js,kuad9/vivliostyle.js_study,nulltask/vivliostyle.js,vivliostyle/vivliostyle.js,kuad9/vivliostyle.js_study,nulltask/vivliostyle.js
8e4e5ef743051f64d41e6e3e027faf6daaf10b89
test/showdir-href-encoding.js
test/showdir-href-encoding.js
var test = require('tap').test, ecstatic = require('../lib/ecstatic'), http = require('http'), request = require('request'), path = require('path'); var root = __dirname + '/public', baseDir = 'base'; test('url encoding in href', function (t) { var port = Math.floor(Math.random() * ((1<<16) - 1e4) + 1e4); var uri = 'http://localhost:' + port + path.join('/', baseDir, 'show-dir-href-encoding'); var server = http.createServer( ecstatic({ root: root, baseDir: baseDir, showDir: true, autoIndex: false }) ); server.listen(port, function () { request.get({ uri: uri }, function(err, res, body) { t.match(body, /href="\/base\/show\-dir\-href\-encoding\/aname\+aplus\.txt"/, 'We found the right href'); server.close(); t.end(); }); }); });
var test = require('tap').test, ecstatic = require('../lib/ecstatic'), http = require('http'), request = require('request'), path = require('path'); var root = __dirname + '/public', baseDir = 'base'; test('url encoding in href', function (t) { var port = Math.floor(Math.random() * ((1<<16) - 1e4) + 1e4); var uri = 'http://localhost:' + port + path.join('/', baseDir, 'show-dir-href-encoding'); var server = http.createServer( ecstatic({ root: root, baseDir: baseDir, showDir: true, autoIndex: false }) ); server.listen(port, function () { request.get({ uri: uri }, function(err, res, body) { t.match(body, /href="\/base\/show\-dir\-href\-encoding\/aname%2Baplus\.txt"/, 'We found the right href'); server.close(); t.end(); }); }); });
Fix test broken by encodeURIComponent change
Fix test broken by encodeURIComponent change
JavaScript
mit
mk-pmb/node-ecstatic,krikx/node-ecstatic,mk-pmb/node-ecstatic,jfhbrook/node-ecstatic,dotnetCarpenter/node-ecstatic,mk-pmb/node-ecstatic,dotnetCarpenter/node-ecstatic,krikx/node-ecstatic,dotnetCarpenter/node-ecstatic,ngs/node-ecstatic,jfhbrook/node-ecstatic,ngs/node-ecstatic,jfhbrook/node-ecstatic
f4c10acf35c802049cb59fec2af813766821c83f
src/String.js
src/String.js
/** * Has Vowels * * hasVowel tests if the String calling the function has a vowels * * @param {void} * @return {Boolean} returns true or false indicating if the string * has a vowel or not */ String.prototype.hasVowels = function() { var inputString = this; return /[aeiou]/gi.test(inputString); }; /** * To Upper * * toUpper converts its calling string to all uppercase characters * * @param {void} * @return {String} returns an upperCase version of the calling string */ String.prototype.toUpper = function() { // the 'this' keyword represents the string calling the function return this.replace(/[a-z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)-32); }); }; String.prototype.toLower = function() { // the 'this' keyword represents the string calling the function return this.replace(/[A-Z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)+32); }); }; /** * Uc First * * ucFirst capitalises the first character of its calling string * * @param {void} * @return {String} returns the calling string with the first character * capitalised */ String.prototype.ucFirst = function() { return ''; };
/** * Has Vowels * * hasVowel tests if the String calling the function has a vowels * * @param {void} * @return {Boolean} returns true or false indicating if the string * has a vowel or not */ String.prototype.hasVowels = function() { var inputString = this; return /[aeiou]/gi.test(inputString); }; /** * To Upper * * toUpper converts its calling string to all uppercase characters * * @param {void} * @return {String} returns an upperCase version of the calling string */ String.prototype.toUpper = function() { // the 'this' keyword represents the string calling the function return this.replace(/[a-z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)-32); }); }; String.prototype.toLower = function() { // the 'this' keyword represents the string calling the function return this.replace(/[A-Z]/g, function(item, position, string) { return String.fromCharCode(string.charCodeAt(position)+32); }); }; /** * Uc First * * ucFirst capitalises the first character of its calling string * * @param {void} * @return {String} returns the calling string with the first character * capitalised */ String.prototype.ucFirst = function() { return this.replace(/^[a-z]/g, function(item, position, string) { return item.toUpper(); }); };
Implement ucFirst() to pass test
Implement ucFirst() to pass test
JavaScript
mit
andela-oolutola/string-class,andela-oolutola/string-class
242dff01801b14ea10df218d0d967e9afef2b144
app/assets/javascripts/displayMap.js
app/assets/javascripts/displayMap.js
function initMap() { var map; var $business_object; var biz_loc_collection; var i; $business_object = $('#businesses').data('url'); biz_loc_collection = []; for (i = 0; i < $business_object.length; ++i) { biz_loc_collection.push({ lat: $business_object[i].latitude, lng: $business_object[i].longitude}); } map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 47.6062, lng: -122.3321}, // center: should be the lat and long of leading biz zoom: 12 }); for (i = 0; i < biz_loc_collection.length; ++i) { marker = new google.maps.Marker({ map: map, draggable: false, animation: google.maps.Animation.DROP, position: biz_loc_collection[i] }); marker.addListener('click', toggleBounce); } function toggleBounce() { if (marker.getAnimation() !== null) { marker.setAnimation(null); } else { marker.setAnimation(google.maps.Animation.BOUNCE); } } }
function initMap() { var map; var $business_object; var biz_loc_collection; var i; $business_object = $('#businesses').data('url'); biz_loc_collection = []; for (i = 0; i < $business_object.length; ++i) { biz_loc_collection.push({ lat: $business_object[i].latitude, lng: $business_object[i].longitude}); } map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 47.6062, lng: -122.3321}, // center: should be the lat and long of leading biz zoom: 12 }); biz_loc_collection.forEach(addMarker); function addMarker(business){ var marker; marker = new google.maps.Marker({ map: map, draggable: false, animation: google.maps.Animation.DROP, position: business }); marker.addListener('click', toggleBounce); } function toggleBounce() { var marker; marker = this; if (marker.getAnimation() !== null) { marker.setAnimation(null); } else { marker.setAnimation(google.maps.Animation.BOUNCE); setTimeout(function(){ marker.setAnimation(null); }, 750); } } }
Fix the marker bouncing function.
Fix the marker bouncing function.
JavaScript
mit
DBC-Huskies/flight-app,DBC-Huskies/flight-app,DBC-Huskies/flight-app
a59413dc688077d0f1c4d8ae26fce464b837faa6
src/scripts/scripts.js
src/scripts/scripts.js
$(document).foundation(); $('a.disabled').click(function(e) { e.preventDefault(); }); // Show shadow when content slides under the page header $(document).ready(function() { var $content = $('#site-body .content'); var $header = $('#page-head .inner'); if ($header.length > 0) { $content.css('margin-top', $header.outerHeight()); $(document).resize(function() { $content.css('margin-top', $header.outerHeight()); }); $(window).scroll(function() { if($(this).scrollTop() > 0) { $header.addClass('overlay'); } else { $header.removeClass('overlay'); } }); } });
$(document).foundation(); $('a.disabled').click(function(e) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); }); // Show shadow when content slides under the page header $(document).ready(function() { var $content = $('#site-body .content'); var $header = $('#page-head .inner'); if ($header.length > 0) { $content.css('margin-top', $header.outerHeight()); $(document).resize(function() { $content.css('margin-top', $header.outerHeight()); }); $(window).scroll(function() { if($(this).scrollTop() > 0) { $header.addClass('overlay'); } else { $header.removeClass('overlay'); } }); } // ================================================================ // Fake form submits and confirmation buttons. // // To create a confirmation button add ( data-confirm-action="message" ) // to the button. This will trigger a confirmation box. If the answer // is affirmative the button action will fire. // // For fake submit buttons add ( data-trigger-submit="id" ) and replace // id with the id of the submit button. // ================================================================ $('[data-confirm-action]').click(function(e) { var message = $(this).attr('data-confirm-action'); var confirm = window.confirm(message); if (!confirm) { e.preventDefault(); e.stopImmediatePropagation(); } }); $('[data-trigger-submit]').click(function(e) { e.preventDefault(); var id = $(this).attr('data-trigger-submit'); $('#' + id).click(); }); });
Implement fake form submits and confirmation buttons
Implement fake form submits and confirmation buttons
JavaScript
bsd-3-clause
flipside-org/aw-datacollection,flipside-org/aw-datacollection,flipside-org/aw-datacollection
8dc0bd8327a0acef05a611fa57a7b256951db69f
lib/util/spawn-promise.js
lib/util/spawn-promise.js
'use babel' import {getPath} from 'consistent-path' import {BufferedProcess} from 'atom' export default (command, args, cwd = null) => new Promise((resolve, reject) => { let output = null const stdout = (_output) => output = _output const exit = (code) => { if (code !== 0) { reject(new Error('Exit status ' + code)) } else { resolve(output) } } const env = Object.assign({}, {path: getPath()}, process.env) const options = {cwd, env} /* eslint no-new: 0 */ new BufferedProcess({command, args, options, stdout, exit}) })
'use babel' import getPath from 'consistent-path' import {BufferedProcess} from 'atom' export default (command, args, cwd = null) => new Promise((resolve, reject) => { let output = null const stdout = (_output) => output = _output const exit = (code) => { if (code !== 0) { reject(new Error('Exit status ' + code)) } else { resolve(output) } } const env = Object.assign({}, {path: getPath()}, process.env) const options = {cwd, env} /* eslint no-new: 0 */ new BufferedProcess({command, args, options, stdout, exit}) })
Update consistent-path import for 2.x
Update consistent-path import for 2.x
JavaScript
mit
timdp/atom-npm-helper
ba8371191ca468d1648e83324455d24a314725f8
src/portal.js
src/portal.js
import { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDom from 'react-dom'; class Portal extends Component { componentWillMount() { this.popup = document.createElement('div'); document.body.appendChild(this.popup); this.renderLayer(); } componentDidUpdate() { this.renderLayer(); } componentWillUnmount() { ReactDom.unmountComponentAtNode(this.popup); document.body.removeChild(this.popup); } renderLayer() { ReactDom.unstable_renderSubtreeIntoContainer(this, this.props.children, this.popup); } render() { return null; } } Portal.propTypes = { children: PropTypes.node, // eslint-disable-line }; export default Portal;
import { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDom from 'react-dom'; const useCreatePortal = typeof ReactDom.unstable_createPortal === 'function'; class Portal extends Component { componentWillMount() { this.popup = document.createElement('div'); document.body.appendChild(this.popup); this.renderLayer(); } componentDidUpdate() { this.renderLayer(); } componentWillUnmount() { if (!useCreatePortal) { ReactDom.unmountComponentAtNode(this.popup); } document.body.removeChild(this.popup); } renderLayer() { if (!useCreatePortal) { ReactDom.unstable_renderSubtreeIntoContainer(this, this.props.children, this.popup); } } render() { if (useCreatePortal) { return ReactDom.unstable_createPortal(this.props.children, this.popup); } return null; } } Portal.propTypes = { children: PropTypes.node, // eslint-disable-line }; export default Portal;
Add support for new React Core (v16)
Add support for new React Core (v16) Old react (v15) still working
JavaScript
mit
pradel/react-minimalist-portal
9cadbca18e044b0b20b7a3316c7007eb1540711b
test/builder/graphql/query.js
test/builder/graphql/query.js
import {parse, Source} from 'graphql'; import {createSpecBuilderClass} from './base'; import {RepositoryBuilder} from './repository'; import {PullRequestBuilder} from './pr'; class SearchResultItemBuilder { static resolve() { return this; } constructor(...args) { this.args = args; this._value = null; } bePullRequest(block = () => {}) { const b = new PullRequestBuilder(...this.args); block(b); this._value = b.build(); } build() { return this._value; } } const SearchResultBuilder = createSpecBuilderClass('SearchResultItemConnection', { issueCount: {default: 0}, nodes: {linked: SearchResultItemBuilder, plural: true, singularName: 'node'}, }); const QueryBuilder = createSpecBuilderClass('Query', { repository: {linked: RepositoryBuilder}, search: {linked: SearchResultBuilder}, }); export function queryBuilder(...nodes) { return QueryBuilder.onFragmentQuery(nodes); } class RelayResponseBuilder extends QueryBuilder { static onOperation(op) { const doc = parse(new Source(op.text)); return this.onFullQuery(doc); } build() { return {data: super.build()}; } } export function relayResponseBuilder(op) { return RelayResponseBuilder.onOperation(op); }
import {parse, Source} from 'graphql'; import {createSpecBuilderClass} from './base'; import {RepositoryBuilder} from './repository'; import {PullRequestBuilder} from './pr'; class SearchResultItemBuilder { static resolve() { return this; } constructor(...args) { this.args = args; this._value = null; } bePullRequest(block = () => {}) { const b = new PullRequestBuilder(...this.args); block(b); this._value = b.build(); } build() { return this._value; } } const SearchResultBuilder = createSpecBuilderClass('SearchResultItemConnection', { issueCount: {default: 0}, nodes: {linked: SearchResultItemBuilder, plural: true, singularName: 'node'}, }); const QueryBuilder = createSpecBuilderClass('Query', { repository: {linked: RepositoryBuilder}, search: {linked: SearchResultBuilder}, }); export function queryBuilder(...nodes) { return QueryBuilder.onFragmentQuery(nodes); } class RelayResponseBuilder extends QueryBuilder { static onOperation(op) { const doc = parse(new Source(op.text)); return this.onFullQuery(doc); } constructor(...args) { super(...args); this._errors = []; } addError(string) { this._errors.push(string); return this; } build() { if (this._errors.length > 0) { return {data: null, errors: this._errors}; } return {data: super.build()}; } } export function relayResponseBuilder(op) { return RelayResponseBuilder.onOperation(op); }
Build a GraphQL response with errors reported
Build a GraphQL response with errors reported
JavaScript
mit
atom/github,atom/github,atom/github
ab050e711d90495e23b8b887df2a3dc58dae6ba3
app/src/App.test.js
app/src/App.test.js
import React from 'react'; import { mount, shallow } from 'enzyme'; import App from './App'; import TimeTable from 'timetablescreen'; describe('App', () => { beforeEach( () => { Object.defineProperty(window.location, 'href', { writable: true, value: 'localhost:3000/kara' }); }); it('renders without crashing', () => { shallow(<App />); }); it('shows error when state is updated to error', () => { const component = mount(<App />); component.setState({data: { error: 'error' }}); expect(component.find('.cs-error')).toHaveLength(1); }); it('shows timetable when state is updated to valid state', () => { const component = shallow(<App />); component.setState({data: {lat: 0, lon:0}}); component.update(); expect(component.find(TimeTable)).toHaveLength(1); }); });
import React from 'react'; import { mount, shallow } from 'enzyme'; import App from './App'; import TimeTable from 'timetablescreen'; describe('App', () => { beforeEach( () => { Object.defineProperty(window.location, 'href', { writable: true, value: 'localhost:3000/kara' }); }); it('renders without crashing', () => { shallow(<App />); }); it('shows error when state is updated to error', () => { const component = mount(<App />); component.setState({data: { error: 'error' }}); expect(component.find('.cs-error')).toBeTruthy(); // TODO: Add error prefix and use toHaveLenght }); it('shows timetable when state is updated to valid state', () => { const component = shallow(<App />); component.setState({data: {lat: 0, lon:0}}); component.update(); expect(component.find(TimeTable)).toHaveLength(1); }); });
Test that there are errors instead of exact number
Test that there are errors instead of exact number
JavaScript
mit
kangasta/timetablescreen,kangasta/timetablescreen
2561471eea20a9d1ca762d402ba538661cfd2f64
module/Connector.js
module/Connector.js
const mysql = require('mysql') const qBuilder = require('./QueryBuilder') let query = '' let params = [] module.exports = (dbSetting) => { let connection = mysql.createConnection({ host: dbSetting.hostname, user: dbSetting.username, password: dbSetting.password, database: dbSetting.database }) connection.connect() return { makeQuery: () => { return qBuilder }, prepare: () => { query = qBuilder.prepare() }, setParameters: (params) => { qBuilder.setParameters(params) }, getParameters: () => { params = qBuilder.getParameters() }, execute: () => { // connection.query(query) }, get: () => { } } }
const mysql = require('mysql') const qBuilder = require('./QueryBuilder') let _query = '' let _params = [] module.exports = (dbSetting) => { let connection = mysql.createConnection({ host: dbSetting.hostname, user: dbSetting.username, password: dbSetting.password, database: dbSetting.database }) return { makeQuery: () => { return qBuilder }, prepare: () => { _query = qBuilder.prepare() }, setParameters: (params) => { _params = params qBuilder.setParameters(params) }, getParameters: () => { _params = qBuilder.getParameters() }, execute: () => { // connection.query(_query) }, get: () => { }, connectToDatabase: () => { connection.connect() }, endConnection: () => { connection.end() } } }
Add few functions and connect to query builder
Add few functions and connect to query builder
JavaScript
mit
evelikov92/mysql-qbuilder
0f3c7f95b03b5e6b3b731158185ae12078c9b606
web/test/bootstrap.test.js
web/test/bootstrap.test.js
var Sails = require('sails'); before(function (done) { Sails.lift({ //config }, function (err, sails) { if (err) return done(err); // load fixtures, etc done (err, sails); }); }); after(function (done) { Sails.lower(done); });
var Sails = require('sails'); before(function (done) { this.timeout(5 * 1000); Sails.lift({ //config }, function (err, sails) { if (err) return done(err); // load fixtures, etc done (err, sails); }); }); after(function (done) { Sails.lower(done); });
Allow sails lift to take longer than 2 seconds
Allow sails lift to take longer than 2 seconds
JavaScript
apache-2.0
section-io-gists/vclfiddle,vclfiddle/vclfiddle,vclfiddle/vclfiddle,vclfiddle/vclfiddle,vclfiddle/vclfiddle,section-io-gists/vclfiddle,section-io-gists/vclfiddle,section-io-gists/vclfiddle
d2d68cb5ff8982f897b2805f57b73724def65208
feder/main/static/init_map.js
feder/main/static/init_map.js
(function($) { $("#pl_map path").on("click", function() { document.location.pathname = $(this).data("href") }); $('[data-toggle="tooltip"]').tooltip({'container': 'body'}); })(jQuery);
(function($) { $("#pl_map path").on("click", function() { document.location.pathname = $(this).data("href") }); })(jQuery);
Remove unused tooltip initialization code
Remove unused tooltip initialization code
JavaScript
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
63d2829207a9968412fb332371774f3c1ca00601
src/config.js
src/config.js
var _ = require('underscore'); var fs = require('fs'); function Config(filePath) { var data = this.parse(filePath); this.validate(data); return Object.freeze(data); } Config.prototype.parse = function(filePath) { var content = fs.readFileSync(filePath, { encoding: 'utf8' }); return JSON.parse(content); }; Config.prototype.validate = function(data) { var pulsarApi = data.pulsarApi; if (!pulsarApi) { throw new Error('Define `pulsarApi` config options'); } this.validatePulsarApiInstance(pulsarApi, 'pulsarApi'); return _.each(pulsarApi.auxiliary, (function(_this) { return function(api, apiName) { if (!/^\w+\/\w+$/i.test(apiName)) { throw new Error("Wrong pulsarApi auxiliary API name: '" + apiName + "'. The acceptable format is: [{application}/{environment}]."); } return _this.validatePulsarApiInstance(api, apiName); }; })(this)); }; Config.prototype.validatePulsarApiInstance = function(api, apiName) { if (!api.url) { throw new Error("Define `" + apiName + ".url` in the config"); } }; module.exports = Config;
var _ = require('underscore'); var fs = require('fs'); /** * @param {String|Object} filePath. If param is a String then it is treated as a file path to a config file. * If param is an Object then it is treated as a parsed config file. * @constructor */ function Config(filePath) { var data; if (_.isObject(filePath)) { data = filePath; } else { data = this.parse(filePath); } this.validate(data); return Object.freeze(data); } Config.prototype.parse = function(filePath) { var content = fs.readFileSync(filePath, { encoding: 'utf8' }); return JSON.parse(content); }; Config.prototype.validate = function(data) { var pulsarApi = data.pulsarApi; if (!pulsarApi) { throw new Error('Define `pulsarApi` config options'); } this.validatePulsarApiInstance(pulsarApi, 'pulsarApi'); return _.each(pulsarApi.auxiliary, (function(_this) { return function(api, apiName) { if (!/^\w+\/\w+$/i.test(apiName)) { throw new Error("Wrong pulsarApi auxiliary API name: '" + apiName + "'. The acceptable format is: [{application}/{environment}]."); } return _this.validatePulsarApiInstance(api, apiName); }; })(this)); }; Config.prototype.validatePulsarApiInstance = function(api, apiName) { if (!api.url) { throw new Error("Define `" + apiName + ".url` in the config"); } }; module.exports = Config;
Allow to pass hash instead of filepath to Config.
Allow to pass hash instead of filepath to Config.
JavaScript
mit
vogdb/pulsar-rest-api-client-node,cargomedia/pulsar-rest-api-client-node
5609d591ab892348b17f0bccef800dcd46ca431f
test/index.js
test/index.js
GLOBAL.projRequire = function (module) { return require('../' + module); };
GLOBAL.projRequire = function (module) { return require('../' + module); }; const log = projRequire('lib'); const tc = require('test-console'); const test = require('tape');
Add imports to test suite
Add imports to test suite
JavaScript
mit
cuvva/cuvva-log-sentry-node,TheTree/branch,TheTree/branch,TheTree/branch
c50035bb85a86aa7adb292ef74385388c391912c
test/index.js
test/index.js
require('./unit/index'); require('./test_multiple_payloads'); require('./test_misc'); require('./test_loop'); require('./test_capture'); require('./test_arrivals'); require('./test_reuse'); require('./test_loop'); require('./test_probability'); require('./test_if'); //require('./test_worker_http'); //require('./test_environments.js'); //require('./test_think'); //require('./test_tls');
require('./unit/index'); require('./test_multiple_payloads'); require('./test_misc'); require('./test_loop'); require('./test_capture'); require('./test_arrivals'); require('./test_reuse'); require('./test_loop'); require('./test_probability'); require('./test_if'); require('./ws/test_options'); //require('./test_worker_http'); //require('./test_environments.js'); //require('./test_think'); //require('./test_tls');
Include WS TLS test in the test suite
Include WS TLS test in the test suite
JavaScript
mpl-2.0
hassy/artillery,erikerikson/artillery-core,shoreditch-ops/artillery-core,shoreditch-ops/artillery,hassy/artillery-core,erikerikson/artillery-core,shoreditch-ops/artillery-core,shoreditch-ops/artillery,hassy/artillery,shoreditch-ops/artillery,hassy/artillery-core,hassy/artillery
58b4a325f06e178c398d96513f5ac7bd69ad0b1e
src/export.js
src/export.js
'use strict' /** * @class Elastic */ var Elastic = { klass : klass, domain: { Layout : LayoutDomain, View : ViewDomain, Compontnt: ComponentDomain }, exception: { Runtime : RuntimeException, Logic : LogicException }, util: { History : History, Router : Router, Storage : Storage, Validator: Validator }, trait: { AsyncCallback: AsyncCallbackTrait, Observable : ObservableTrait } }; // for RequireJS if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { window.define(function() { return Elastic; }); } // for Node.js & browserify else if (typeof module == 'object' && module && typeof exports == 'object' && exports && module.exports == exports ) { module.exports = Elastic; } // for Browser else { window.Elastic = Elastic; }
'use strict' /** * @class Elastic */ var Elastic = { // like OOP klass : klass, // shorthand Layout : LayoutDomain, View : ViewDomain, Component: ComponentDomain, // classes domain: { Layout : LayoutDomain, View : ViewDomain, Compontnt: ComponentDomain }, exception: { Runtime : RuntimeException, Logic : LogicException }, util: { History : History, Router : Router, Storage : Storage, Validator: Validator }, trait: { AsyncCallback: AsyncCallbackTrait, Observable : ObservableTrait } }; // for RequireJS if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { window.define(function() { return Elastic; }); } // for Node.js & browserify else if (typeof module == 'object' && module && typeof exports == 'object' && exports && module.exports == exports ) { module.exports = Elastic; } // for Browser else { window.Elastic = Elastic; }
Add Domain class's shorthand name
Add Domain class's shorthand name
JavaScript
mit
ahomu/Elastic
8b6b89e438c963ed0f3cb563cdfd60b6c0d0a7e0
shared/util/set-notifications.js
shared/util/set-notifications.js
/* @flow */ import engine from '../engine' import {notifyCtlSetNotificationsRpc} from '../constants/types/flow-types' type NotificationChannels = { session?: true, users?: true, kbfs?: true, tracking?: true, favorites?: true, paperkeys?: true, keyfamily?: true, service?: true, chat?: true, } let channelsSet = {} export default function (channels: NotificationChannels): Promise<void> { return new Promise((resolve, reject) => { channelsSet = {...channelsSet, ...channels} const toSend = { session: !!channelsSet.session, users: !!channelsSet.users, kbfs: !!channelsSet.kbfs, tracking: !!channelsSet.tracking, favorites: !!channelsSet.favorites, paperkeys: !!channelsSet.paperkeys, keyfamily: !!channelsSet.keyfamily, service: !!channelsSet.service, app: !!channelsSet.app, chat: !!channelsSet.chat, } engine.listenOnConnect('setNotifications', () => { notifyCtlSetNotificationsRpc({ param: {channels: toSend}, callback: (error, response) => { if (error != null) { console.warn('error in toggling notifications: ', error) reject(error) } else { resolve() } }, }) }) }) }
/* @flow */ import engine from '../engine' import {notifyCtlSetNotificationsRpc} from '../constants/types/flow-types' type NotificationChannels = { chat?: true, favorites?: true, kbfs?: true, keyfamily?: true, paperkeys?: true, pgp?: true, service?: true, session?: true, tracking?: true, users?: true, } let channelsSet = {} export default function (channels: NotificationChannels): Promise<void> { return new Promise((resolve, reject) => { channelsSet = {...channelsSet, ...channels} const toSend = { app: !!channelsSet.app, chat: !!channelsSet.chat, favorites: !!channelsSet.favorites, kbfs: !!channelsSet.kbfs, keyfamily: !!channelsSet.keyfamily, paperkeys: !!channelsSet.paperkeys, pgp: !!channelsSet.pgp, service: !!channelsSet.service, session: !!channelsSet.session, tracking: !!channelsSet.tracking, users: !!channelsSet.users, } engine.listenOnConnect('setNotifications', () => { notifyCtlSetNotificationsRpc({ param: {channels: toSend}, callback: (error, response) => { if (error != null) { console.warn('error in toggling notifications: ', error) reject(error) } else { resolve() } }, }) }) }) }
Add pgp to notification channels
Add pgp to notification channels
JavaScript
bsd-3-clause
keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client
66b31b6659968968d3354fb5d114c77b72aac6af
test/mouse.js
test/mouse.js
var test = require('tape'); var robot = require('..'); var lastKnownPos, currentPos; test('Get the initial mouse position.', function(t) { t.plan(3); t.ok(lastKnownPos = robot.getMousePos(), 'successfully retrieved mouse position.'); t.ok(lastKnownPos.x !== undefined, 'mousepos.x is a valid value.'); t.ok(lastKnownPos.y !== undefined, 'mousepos.y is a valid value.'); }); test('Move the mouse.', function(t) { t.plan(3); lastKnownPos = robot.moveMouse(0, 0); t.ok(robot.moveMouse(100, 100), 'successfully moved the mouse.'); currentPos = robot.getMousePos(); t.ok(currentPos.x === 100, 'mousepos.x is correct.'); t.ok(currentPos.y === 100, 'mousepos.y is correct.'); });
var test = require('tape'); var robot = require('..'); var lastKnownPos, currentPos; //Increase delay to help test reliability. robot.setMouseDelay(100); test('Get the initial mouse position.', function(t) { t.plan(3); t.ok(lastKnownPos = robot.getMousePos(), 'successfully retrieved mouse position.'); t.ok(lastKnownPos.x !== undefined, 'mousepos.x is a valid value.'); t.ok(lastKnownPos.y !== undefined, 'mousepos.y is a valid value.'); }); test('Move the mouse.', function(t) { t.plan(3); lastKnownPos = robot.moveMouse(0, 0); t.ok(robot.moveMouse(100, 100), 'successfully moved the mouse.'); currentPos = robot.getMousePos(); t.ok(currentPos.x === 100, 'mousepos.x is correct.'); t.ok(currentPos.y === 100, 'mousepos.y is correct.'); });
Increase delay to help test reliability.
Increase delay to help test reliability.
JavaScript
mit
hristoterezov/robotjs,BHamrick1/robotjs,BHamrick1/robotjs,hristoterezov/robotjs,hristoterezov/robotjs,hristoterezov/robotjs,octalmage/robotjs,BHamrick1/robotjs,octalmage/robotjs,BHamrick1/robotjs,octalmage/robotjs,octalmage/robotjs
6fad96e50890876712c69221a0cc372a2533a4ed
assets/js/googlesitekit/constants.js
assets/js/googlesitekit/constants.js
/** * Core constants. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const VIEW_CONTEXT_DASHBOARD = 'dashboard'; export const VIEW_CONTEXT_PAGE_DASHBOARD = 'pageDashboard'; export const VIEW_CONTEXT_POSTS_LIST = 'postsList'; export const VIEW_CONTEXT_USER_INPUT = 'userInput'; export const VIEW_CONTEXT_ACTIVATION = 'activation'; export const VIEW_CONTEXT_DASHBOARD_SPLASH = 'splash'; export const VIEW_CONTEXT_ADMIN_BAR = 'adminBar'; export const VIEW_CONTEXT_SETTINGS = 'settings'; export const VIEW_CONTEXT_MODULE = 'module'; export const VIEW_CONTEXT_WP_DASHBOARD = 'WPDashboard';
/** * Core constants. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const VIEW_CONTEXT_DASHBOARD = 'dashboard'; export const VIEW_CONTEXT_PAGE_DASHBOARD = 'pageDashboard'; export const VIEW_CONTEXT_POSTS_LIST = 'postsList'; export const VIEW_CONTEXT_USER_INPUT = 'userInput'; export const VIEW_CONTEXT_ACTIVATION = 'activation'; export const VIEW_CONTEXT_DASHBOARD_SPLASH = 'splash'; export const VIEW_CONTEXT_ADMIN_BAR = 'adminBar'; export const VIEW_CONTEXT_SETTINGS = 'settings'; export const VIEW_CONTEXT_MODULE = 'module'; export const VIEW_CONTEXT_WP_DASHBOARD = 'wpDashboard';
Change VIEW_CONTEXT_WP_DASHBOARD to camel case.
Change VIEW_CONTEXT_WP_DASHBOARD to camel case.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
932c3d27364eb4cfb09189f90afb92c8bfeaa07c
src/server.js
src/server.js
/* * Initialize the Restify server. */ var restify = require('restify'); var config = require('./config'); var routes = require('./routes'); var log = require('./logging').getLogger(); exports.create = function () { var server = restify.createServer(); server.pre(restify.pre.sanitizePath()); server.name = config.info.name; server.use(function (req, res, next) { log.verbose(req.method + ' ' + req.url); next(); }); server.use(restify.fullResponse()); server.on('uncaughtException', function (req, res, route, err) { log.error({ statusCode: err.statusCode || 500, requestURL: req.url, stack: err.stack, error: err.message, message: 'Uncaught exception' }); res.send(err); }); routes.loadRoutes(server); return server; };
/* * Initialize the Restify server. */ var restify = require('restify'); var config = require('./config'); var routes = require('./routes'); var log = require('./logging').getLogger(); exports.create = function () { var server = restify.createServer(); server.server.setTimeout(600000); server.pre(restify.pre.sanitizePath()); server.name = config.info.name; server.use(function (req, res, next) { log.verbose(req.method + ' ' + req.url); next(); }); server.use(restify.fullResponse()); server.on('uncaughtException', function (req, res, route, err) { log.error({ statusCode: err.statusCode || 500, requestURL: req.url, stack: err.stack, error: err.message, message: 'Uncaught exception' }); res.send(err); }); routes.loadRoutes(server); return server; };
Set a nice, generous timeout on requests.
Set a nice, generous timeout on requests.
JavaScript
mit
deconst/content-service,deconst/content-service
3bfcbc3ce266e873e43b8faf15d7b9ca87e6a094
src/server.js
src/server.js
import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" import bodyParser from "body-parser" import mongoose, { Schema } from "mongoose" import schema from "./graphql" import Item from "./db/item" // Constants const CONFIG = require("./settings.yaml") const app = express() mongoose.Promise = global.Promise mongoose.connect( `mongodb://${CONFIG.mongodb.url}:${CONFIG.mongodb.port}/${CONFIG.mongodb.database}`, { useMongoClient: true } ) app.use( "/graphql", bodyParser.json({ limit: "15mb" }), graphqlExpress(() => ({ schema })) ) app.use( "/graphiql", graphiqlExpress({ endpointURL: "/graphql" }) ) export { app, CONFIG }
import bodyParser from "body-parser" import express from "express" import graphqlHTTP from "express-graphql" import { graphqlExpress, graphiqlExpress } from "graphql-server-express" import mongoose from "mongoose" import schema from "./graphql" import Item from "./db/item" import Update from "./db/update" // Constants const CONFIG = require("./settings.yaml") const app = express() mongoose.Promise = global.Promise mongoose.connect( `mongodb://${CONFIG.mongodb.url}:${CONFIG.mongodb.port}/${CONFIG.mongodb .database}`, { useMongoClient: true } ) mongoose.set("debug", true) app.use( "/graphql", bodyParser.json({ limit: "15mb" }), graphqlExpress(req => { return { schema, context: { loaders: {}, models: { items: Item, updates: Update } } } }) ) app.use( "/graphiql", graphiqlExpress({ endpointURL: "/graphql" }) ) export { app, CONFIG }
Add mongoose debugging and move models to context
Add mongoose debugging and move models to context
JavaScript
mit
DevNebulae/ads-pt-api
b4dddaee7e2f449d65302009eb90c0ff608f6029
jasmine/src/inverted-index.js
jasmine/src/inverted-index.js
var fs = require('fs'); function Index(){ 'use strict' this.createIndex = function(filePath){ fs.readFile(filePath , function doneReading(err, fileContents){ console.log(fileContents.toString()); }) } } var indexObj =new Index(); indexObj.createIndex('../books.json');
Create an index object that points to a JSON file
Create an index object that points to a JSON file
JavaScript
mit
andela-jwarugu/checkpoint-1,andela-jwarugu/checkpoint-1
86f7ec4efb24be276590df7c2304065a1b81027a
lib/response.js
lib/response.js
"use strict"; var Response = function(error, res) { res = res || {}; this.raw = res.body; this.headers = res.headers; this.status = res.statusCode || 500; if (error) { this._error = { error: (res.body || "Unknown error: empty response") }; } else { if (res.headers["content-type"].includes("application/json")) { try { this.json = res.body ? JSON.parse(res.body) : {}; } catch (ex) { this._error = { error: ex.toString() }; } } } }; Response.prototype.error = function() { if (!this._error && this.isError()) { this._error = this.json || {}; } return this._error; }; Response.prototype.isError = function() { return (this._error || this.isClientError() || this.isServerError()); }; Response.prototype.isSuccess = function() { return !this.isError(); }; Response.prototype.isClientError = function() { return this.status >= 400 && this.status < 500; }; Response.prototype.isServerError = function() { return this.status >= 500; }; module.exports = Response;
"use strict"; var Response = function(error, res) { res = res || {}; this.raw = res.body; this.headers = res.headers; this.status = res.statusCode || 500; if (error) { this._error = { error: (res.body || "Unknown error: empty response") }; } else { if (res.headers["content-type"].startsWith("application/json")) { try { this.json = res.body ? JSON.parse(res.body) : {}; } catch (ex) { this._error = { error: ex.toString() }; } } } }; Response.prototype.error = function() { if (!this._error && this.isError()) { this._error = this.json || {}; } return this._error; }; Response.prototype.isError = function() { return (this._error || this.isClientError() || this.isServerError()); }; Response.prototype.isSuccess = function() { return !this.isError(); }; Response.prototype.isClientError = function() { return this.status >= 400 && this.status < 500; }; Response.prototype.isServerError = function() { return this.status >= 500; }; module.exports = Response;
Use String.prototype.startsWith() instead of includes() for checking the content type
Use String.prototype.startsWith() instead of includes() for checking the content type
JavaScript
mit
skazska/m2x-nodejs,attm2x/m2x-nodejs