commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
c37dcfb3438de31be8ad7fc7dd5847d840bd05d6
app/assets/javascripts/angular/common/models/user-model.js
app/assets/javascripts/angular/common/models/user-model.js
(function(){ 'use strict'; angular .module('secondLead') .factory('UserModel',['Auth', 'Restangular', 'store', function(Auth, Restangular, store) { var baseUsers = Restangular.all('users'); return { getAll: baseUsers.getList().$object, getOne: function(userId) { return Restangular.one('users', userId).get() }, isLoggedIn: function (user) { return store.get('user'); }, register: function(newUser){ return baseUsers.post({"user": { first_name: newUser.firstName, last_name: newUser.lastName, email: newUser.email, username: newUser.username, password: newUser.password } }); }, login: function (user) { return Auth.login({ username: user.username, password: user.password }); } }; }]) })();
(function(){ 'use strict'; angular .module('secondLead') .factory('UserModel',['Auth', 'Restangular', '$rootScope', 'store', function(Auth, Restangular, $rootScope, store) { var baseUsers = Restangular.all('users'); var loggedIn = false; function setLoggedIn(state){ loggedIn = state; $rootScope.$broadcast('loggedIn:updated',state); }; return { currentUser: function() { return store.get('user'); }, getAll: baseUsers.getList().$object, getOne: function(userId) { return Restangular.one('users', userId).get() }, getStatus: function() { return { loggedIn: loggedIn } }, login: function (user) { var auth = Auth.login({ username: user.username, password: user.password }); return auth; }, register: function(newUser){ return baseUsers.post({"user": { first_name: newUser.firstName, last_name: newUser.lastName, email: newUser.email, username: newUser.username, password: newUser.password } }); }, setLoggedIn: setLoggedIn } ; }]) })();
Refactor user model to broadcast changes to login state
Refactor user model to broadcast changes to login state
JavaScript
mit
ac-adekunle/secondlead,ac-adekunle/secondlead,ac-adekunle/secondlead
e40b9eb6927bfeb12a1f2e477c009076bbb7bcab
lib/startup/restoreOverwrittenFilesWithOriginals.js
lib/startup/restoreOverwrittenFilesWithOriginals.js
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const glob = require('glob') const path = require('path') const fs = require('fs') const logger = require('../logger') const restoreOverwrittenFilesWithOriginals = () => { fs.copyFileSync(path.resolve(__dirname, '../../data/static/legal.md'), path.resolve(__dirname, '../../ftp/legal.md')) if (fs.existsSync('../../frontend/dist')) { fs.copyFileSync(path.resolve(__dirname, '../../data/static/JuiceShopJingle.vtt'), path.resolve(__dirname, '../../frontend/dist/frontend/assets/public/videos/JuiceShopJingle.vtt')) } glob(path.join(__dirname, '../../data/static/i18n/*.json'), (err, files) => { if (err) { logger.warn('Error listing JSON files in /data/static/i18n folder: ' + err.message) } else { files.forEach(filename => { fs.copyFileSync(filename, path.resolve(__dirname, '../../i18n/', filename.substring(filename.lastIndexOf('/') + 1))) }) } }) } module.exports = restoreOverwrittenFilesWithOriginals
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const glob = require('glob') const path = require('path') const fs = require('fs') const logger = require('../logger') const restoreOverwrittenFilesWithOriginals = () => { fs.copyFileSync(path.resolve(__dirname, '../../data/static/legal.md'), path.resolve(__dirname, '../../ftp/legal.md')) if (fs.existsSync(path.resolve(__dirname,'../../frontend/dist'))) { fs.copyFileSync(path.resolve(__dirname, '../../data/static/JuiceShopJingle.vtt'), path.resolve(__dirname, '../../frontend/dist/frontend/assets/public/videos/JuiceShopJingle.vtt')) } glob(path.join(__dirname, '../../data/static/i18n/*.json'), (err, files) => { if (err) { logger.warn('Error listing JSON files in /data/static/i18n folder: ' + err.message) } else { files.forEach(filename => { fs.copyFileSync(filename, path.resolve(__dirname, '../../i18n/', filename.substring(filename.lastIndexOf('/') + 1))) }) } }) } module.exports = restoreOverwrittenFilesWithOriginals
Check for correct folder before copying subtitle file
Check for correct folder before copying subtitle file
JavaScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
22bcd6224d7424504b4cc7f24c04ff62443d0d46
components/calendar/day.js
components/calendar/day.js
import Event from './event'; const Day = ({ events }) => { let id = 0; let eventList = []; for (let e of events) { eventList.push(<Event title={e.title} start_time={e.start_time} content={e.content} key={id}/>); id++; } const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ]; const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ]; const DAY = events[ 0 ].start_time; const DAY_NAME = DAY_NAMES[ DAY.getDay() ]; const DATE = DAY.getDate(); const MONTH_NAME = MONTH_NAMES[ DAY.getMonth() ]; return ( <div> <h2>{`${DAY_NAME} ${DATE}. ${MONTH_NAME}`}</h2> {eventList} <br /> </div> ); }; export default Day;
import Event from './event'; const Day = ({ events }) => { const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ]; const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ]; const DAY = events[ 0 ].start_time; const DAY_NAME = DAY_NAMES[ DAY.getDay() ]; const DATE = DAY.getDate(); const MONTH_NAME = MONTH_NAMES[ DAY.getMonth() ]; return ( <div> <h2>{`${DAY_NAME} ${DATE}. ${MONTH_NAME}`}</h2> { events.map((e, id) => { return <Event title={e.title} start_time={e.start_time} content={e.content} key={id}/> })} <br /> </div> ); }; export default Day;
Remove the for-loop in favor of mapping the array into event components
Remove the for-loop in favor of mapping the array into event components
JavaScript
mit
dotKom/glowing-fortnight,dotKom/glowing-fortnight
822874ab19a96ebdab6f7232fdfdc3cfe411ab6d
config/ldap.js
config/ldap.js
const LDAP = require('ldap-client'), config = require('./config'); let protocol = config.get('ssl') ? 'ldaps://' : 'ldap://'; let host = config.get('ldap').hostname; let port = config.get('ldap').port; module.exports = new LDAP({ uri: protocol + [host, port].join(':'), base: config.get('ldap').searchBase });
'use strict'; const LDAP = require('ldap-client'), config = require('./config'); let protocol = config.get('ldap').ssl ? 'ldaps://' : 'ldap://'; let host = config.get('ldap').hostname; let port = config.get('ldap').port; module.exports = new LDAP({ uri: protocol + [host, port].join(':'), base: config.get('ldap').searchBase });
Fix let bug on older node
Fix let bug on older node
JavaScript
apache-2.0
mfinelli/cautious-ldap,mfinelli/cautious-ldap
d4444f33c32a56db9dc5b59d1174c79b5f04aafa
client/store/configureStore.js
client/store/configureStore.js
import {applyMiddleware, createStore} from 'redux'; import rootReducer from '../reducers'; import thunkMiddleware from 'redux-thunk'; export default function configureStore (initialState) { const create = typeof window !== 'undefined' && window.devToolsExtension ? window.devToolsExtension()(createStore) : createStore; const createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(create); return createStoreWithMiddleware(rootReducer, initialState); }
import {applyMiddleware, compose, createStore} from 'redux'; import reducer from '../reducers'; import thunk from 'redux-thunk'; export default function configureStore (initialState) { return createStore( reducer, initialState, compose( applyMiddleware(thunk), typeof window !== 'undefined' && window.devToolsExtension ? window.devToolsExtension() : (f) => f ) ); }
Clean up store using compose
Clean up store using compose
JavaScript
mit
richardkall/react-starter,Thomas0c/react-starter,adamjking3/react-redux-apollo-starter
69ea3ae14fba2cca826f4c40d2e4ed8914029560
ghost/admin/app/utils/route.js
ghost/admin/app/utils/route.js
import Route from '@ember/routing/route'; import {inject as service} from '@ember/service'; Route.reopen({ config: service(), billing: service(), router: service(), actions: { willTransition(transition) { if (this.get('upgradeStatus.isRequired')) { transition.abort(); this.upgradeStatus.requireUpgrade(); return false; } else if (this.config.get('hostSettings.forceUpgrade')) { transition.abort(); // Catch and redirect every route in a force upgrade state this.billing.openBillingWindow(this.router.currentURL, '/pro'); return false; } else { return true; } } } });
import Route from '@ember/routing/route'; import {inject as service} from '@ember/service'; Route.reopen({ config: service(), billing: service(), router: service(), actions: { willTransition(transition) { if (this.get('upgradeStatus.isRequired')) { transition.abort(); this.upgradeStatus.requireUpgrade(); return false; } else if (this.config.get('hostSettings.forceUpgrade') && transition.to?.name !== 'signout') { transition.abort(); // Catch and redirect every route in a force upgrade state this.billing.openBillingWindow(this.router.currentURL, '/pro'); return false; } else { return true; } } } });
Allow signout in `forceUpgrade` state
Allow signout in `forceUpgrade` state
JavaScript
mit
TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost
d7c846fd0e3289c25f40046c36e5f3046e4b74ea
src/banks/CBE.js
src/banks/CBE.js
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["scraper"] }] */ import cheerio from 'cheerio'; import Bank from './Bank'; const banksNames = require('./banks_names.json'); export default class CBE extends Bank { constructor() { const url = 'http://www.cbe.org.eg/en/EconomicResearch/Statistics/Pages/ExchangeRatesListing.aspx'; super(banksNames.CBE, url); } /** * Scrape rates from html * @param {Object} html html of bank web page to scrape */ scraper(html) { const $ = cheerio.load(html); const tableRows = $('tbody').last().children(); tableRows.each((index, row) => { const currencyName = $(row) .children() .eq(0) .text() .trim(); const currencyBuy = $(row) .children() .eq(1) .text() .trim(); const currencySell = $(row) .children() .eq(2) .text() .trim(); }); const rates = []; return rates; } }
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["scraper"] }] */ import cheerio from 'cheerio'; import Bank from './Bank'; const banksNames = require('./banks_names.json'); export default class CBE extends Bank { constructor() { const url = 'http://www.cbe.org.eg/en/EconomicResearch/Statistics/Pages/ExchangeRatesListing.aspx'; super(banksNames.CBE, url); } static getCurrencyCode(name) { const dict = { 'US Dollar​': 'USD', 'Euro​': 'EUR', 'Pound Sterling​': 'GBP', 'Swiss Franc​': 'CHF', 'Japanese Yen 100​': 'JPY', 'Saudi Riyal​': 'SAR', 'Kuwaiti Dinar​': 'KWD', 'UAE Dirham​': 'AED', 'Chinese yuan​': 'CNY', }; return (dict[name]); } /** * Scrape rates from html * @param {Object} html html of bank web page to scrape */ scraper(html) { const $ = cheerio.load(html); const tableRows = $('tbody').last().children(); const rates = []; tableRows.each((index, row) => { const currencyName = $(row) .children() .eq(0) .text() .trim(); const currencyBuy = $(row) .children() .eq(1) .text() .trim(); const currencySell = $(row) .children() .eq(2) .text() .trim(); rates.push({ code: CBE.getCurrencyCode(currencyName), buy: currencyBuy, sell: currencySell, }); }); return rates; } }
Convert currency name to currency iso code
Convert currency name to currency iso code
JavaScript
mit
MMayla/egypt-banks-scraper
b453399b7913fec129a54b16f7e4e8e9f27f839d
src/server/api/put-drawing.js
src/server/api/put-drawing.js
import cuid from 'cuid'; import tinify from 'tinify'; import awsConfig from '@/config/tinify-aws'; import firebase from '@/config/firebase-admin'; tinify.key = process.env.TINYPNG_API_KEY; export default function putImages(req, res) { const drawingId = cuid(); const base64Data = req.body.source.split(',')[1].replace(/\s/g, '+'); const imgBuffer = Buffer.from(base64Data, 'base64'); const ref = firebase.database().ref(`/posts/${req.body.postid}/drawings/${drawingId}`); const publishedRef = firebase.database().ref(`/published/${req.body.postid}/drawings/${drawingId}`); tinify .fromBuffer(imgBuffer) .store(awsConfig(`bolg/drawings/${drawingId}.png`)) .meta() .then((meta) => { ref.set(meta.location); publishedRef.set(meta.location); res.send('ok'); }) .catch((err) => { res.error(err); }); }
import cuid from 'cuid'; import tinify from 'tinify'; import awsConfig from '@/config/tinify-aws'; import firebase from '@/config/firebase-admin'; tinify.key = process.env.TINYPNG_API_KEY; export default function putImages(req, res) { const drawingId = cuid(); const base64Data = req.body.source.split(',')[1].replace(/\s/g, '+'); const imgBuffer = Buffer.from(base64Data, 'base64'); const ref = firebase.database().ref(`/posts/${req.body.postid}/drawings/${drawingId}`); const publishedRef = firebase.database().ref(`/published/${req.body.postid}/drawings/${drawingId}`); tinify .fromBuffer(imgBuffer) .store(awsConfig(`bolg/drawings/${drawingId}.png`)) .meta() .then((meta) => { const cloudFront = `https://d3ieg3cxah9p4i.cloudfront.net/${meta.location.split('/bolg/')[1]}`; ref.set(cloudFront); publishedRef.set(cloudFront); res.send('ok'); }) .catch((err) => { res.error(err); }); }
Use cloudfront link to store drawings
Use cloudfront link to store drawings
JavaScript
mit
tuelsch/bolg,tuelsch/bolg
e8bf6e4214d906771ae27f2ba843825cc61eb62b
geotrek/jstests/_nav-utils.js
geotrek/jstests/_nav-utils.js
var fs = require('fs'); module.exports = (function() { const PATH_COOKIES = '/tmp/cookies.txt'; function setUp() { casper.options.viewportSize = {width: 1280, height: 768}; casper.options.waitTimeout = 10000; casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11'); casper.on('remote.message', function(msg) { this.echo("Error: " + msg, "ERROR"); }); casper.on('page.error', function(msg, trace) { this.echo("Error: " + msg, "ERROR"); for(var i=0; i<trace.length; i++) { var step = trace[i]; this.echo(' ' + step.file + ' (line ' + step.line + ')', "ERROR"); } }); } function saveCookies(path) { path = path || PATH_COOKIES; var cookies = JSON.stringify(phantom.cookies); fs.write(path, cookies, 600); } function loadCookies(path) { path = path || PATH_COOKIES; var data = fs.read(path); phantom.cookies = JSON.parse(data); } return { saveCookies: saveCookies, loadCookies: loadCookies }; })();
var fs = require('fs'); module.exports = (function() { const PATH_COOKIES = '/tmp/cookies.txt'; function setUp() { casper.options.viewportSize = {width: 1280, height: 768}; casper.options.waitTimeout = 10000; casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11'); casper.on('remote.message', function(msg) { this.echo("Error: " + msg, "ERROR"); }); casper.on('page.error', function(msg, trace) { this.echo("Error: " + msg, "ERROR"); for(var i=0; i<trace.length; i++) { var step = trace[i]; this.echo(' ' + step.file + ' (line ' + step.line + ')', "ERROR"); } }); } function saveCookies(path) { path = path || PATH_COOKIES; var cookies = JSON.stringify(phantom.cookies); fs.write(path, cookies, 600); } function loadCookies(path) { path = path || PATH_COOKIES; var data = fs.read(path); phantom.cookies = JSON.parse(data); } return { saveCookies: saveCookies, loadCookies: loadCookies, setUp: setUp }; })();
Fix nav test utils export
Fix nav test utils export
JavaScript
bsd-2-clause
GeotrekCE/Geotrek-admin,johan--/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,mabhub/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,camillemonchicourt/Geotrek,GeotrekCE/Geotrek-admin,mabhub/Geotrek,johan--/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,camillemonchicourt/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,johan--/Geotrek,camillemonchicourt/Geotrek,mabhub/Geotrek
74b8de8809ce6b2343657a996768b96320d7c242
src/gulpfile.js
src/gulpfile.js
var elixir = require('laravel-elixir'); elixir(function(mix) { mix.copy( 'node_modules/bootstrap/dist/fonts', 'public/fonts' ); mix.copy( 'node_modules/font-awesome/fonts', 'public/fonts' ); mix.copy( 'node_modules/ionicons/dist/fonts', 'public/fonts' ); mix.scripts([ '../../../node_modules/jquery/dist/jquery.min.js', '../../../node_modules/bootstrap/dist/js/bootstrap.min.js' ], 'public/js/vendor.js'); mix.scripts([ 'app.js' ], 'public/js/app.js'); mix.less([ '../../../node_modules/bootstrap/less/bootstrap.less', '../../../node_modules/font-awesome/less/font-awesome.less', '../../../node_modules/ionicons/dist/css/ionicons.min.css', 'admin-lte/AdminLTE.less', 'admin-lte/skins/_all-skins.less' ], 'public/css/vendor.css'); mix.less([ 'app.less' ], 'public/css/app.css'); mix.less([ 'welcome.less' ], 'public/css/welcome.css'); mix.version([ 'public/css/app.css', 'public/css/welcome.css', 'public/css/vendor.css', 'public/js/app.js', 'public/js/vendor.js' ]); });
var elixir = require('laravel-elixir'); elixir(function(mix) { mix.copy( 'node_modules/bootstrap/dist/fonts', 'public/build/fonts' ); mix.copy( 'node_modules/font-awesome/fonts', 'public/build/fonts' ); mix.copy( 'node_modules/ionicons/dist/fonts', 'public/build/fonts' ); mix.scripts([ '../../../node_modules/jquery/dist/jquery.min.js', '../../../node_modules/bootstrap/dist/js/bootstrap.min.js' ], 'public/js/vendor.js'); mix.scripts([ 'app.js' ], 'public/js/app.js'); mix.less([ '../../../node_modules/bootstrap/less/bootstrap.less', '../../../node_modules/font-awesome/less/font-awesome.less', '../../../node_modules/ionicons/dist/css/ionicons.min.css', 'adminlte/AdminLTE.less', 'adminlte/skins/_all-skins.less' ], 'public/css/vendor.css'); mix.less([ 'app.less' ], 'public/css/app.css'); mix.less([ 'welcome.less' ], 'public/css/welcome.css'); mix.version([ 'public/css/app.css', 'public/css/welcome.css', 'public/css/vendor.css', 'public/js/app.js', 'public/js/vendor.js' ]); });
Change path tot adminlte less file Copy the fonts to build folder because we will be using elixir
Change path tot adminlte less file Copy the fonts to build folder because we will be using elixir
JavaScript
mit
syahzul/admin-theme
7fa1ebf356afb1c8b7e1f0bc013428f1d4377fb1
src/Native/D3/index.js
src/Native/D3/index.js
Elm.Native.D3 = {}; import "JavaScript" import "Render" import "Color" import "Selection" import "Event" import "Transition" import "Voronoi"
Elm.Native.D3 = {}; import "JavaScript" import "Render" import "Color" import "Selection" import "Event" import "Transition" import "Voronoi" Elm.Native.D3.Scales = {}; import "Scales/Quantitative"
Index will include scales during compilation
Index will include scales during compilation
JavaScript
bsd-3-clause
NigelThorne/elm-d3,seliopou/elm-d3,NigelThorne/elm-d3
93b31e51d8a7e1017f7cd2d3603023ca4ecf1bc1
src/views/plugins/Markdown.js
src/views/plugins/Markdown.js
import MarkdownIt from 'markdown-it'; import gh from 'github-url-to-object'; function toAbsolute(baseUrl, src) { try { return new URL(src, baseUrl).toString(); } catch (e) { return src; } } const GH_CDN = 'https://raw.githubusercontent.com'; export default class extends MarkdownIt { constructor(opts) { super(opts); const rules = this.renderer.rules; this.renderer.rules = { ...rules, // Rewrite relative URLs. image(tokens, idx, ...args) { const token = tokens[idx]; // Rewrite repository-relative urls to the github CDN. const repository = opts.package.repository; if (repository && repository.type === 'git') { const github = gh(repository.url); if (github) { token.attrSet('src', toAbsolute( `${GH_CDN}/${github.user}/${github.repo}/${github.branch}/`, token.attrGet('src'))); } } return rules.image(tokens, idx, ...args); }, }; } }
import MarkdownIt from 'markdown-it'; import gh from 'github-url-to-object'; import { before } from 'meld'; function toAbsolute(baseUrl, src) { try { return new URL(src, baseUrl).toString(); } catch (e) { return src; } } const GH_CDN = 'https://raw.githubusercontent.com'; export default class extends MarkdownIt { constructor(opts) { super(opts); // Rewrite relative image URLs. before(this.renderer.rules, 'image', (tokens, idx) => { const token = tokens[idx]; // Rewrite repository-relative urls to the github CDN. const repository = opts.package.repository; if (repository && repository.type === 'git') { const github = gh(repository.url); if (github) { token.attrSet('src', toAbsolute( `${GH_CDN}/${github.user}/${github.repo}/${github.branch}/`, token.attrGet('src'))); } } }); } }
Use `meld` to override markdown image handling.
Use `meld` to override markdown image handling.
JavaScript
mit
ExtPlug/ExtPlug
301d8c45b157cd4b673f40a70965a19af2c4275d
addon/utils/get-mutable-attributes.js
addon/utils/get-mutable-attributes.js
import Ember from 'ember'; var getMutValue = Ember.__loader.require('ember-htmlbars/hooks/get-value')['default']; export default function getMutableAttributes(attrs) { return Object.keys(attrs).reduce((acc, attr) => { acc[attr] = getMutValue(attrs[attr]); return acc; }, {}); }
import Ember from 'ember'; const emberMajorMinorVersion = Ember.VERSION.match(/(\d+\.\d+)\.*/)[1]; const isGlimmer = Number(emberMajorMinorVersion) >= 2.10; let getMutValue; if (isGlimmer) { const { MUTABLE_CELL } = Ember.__loader.require('ember-views/compat/attrs'); getMutValue = (value) => { if (value && value[MUTABLE_CELL]) { return value.value; } else { return value; } }; } else { getMutValue = Ember.__loader.require('ember-glimmer/hooks/get-value')['default']; } export default function getMutableAttributes(attrs) { return Object.keys(attrs).reduce((acc, attr) => { acc[attr] = getMutValue(attrs[attr]); return acc; }, {}); }
Fix for getting mutable attributes in glimmer
Fix for getting mutable attributes in glimmer
JavaScript
mit
pswai/ember-cli-react,pswai/ember-cli-react
cab68ae620e449e49385a6125d233129d7d325cf
src/js/route.js
src/js/route.js
var route = function(name, params = {}, absolute = true) { var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', url = (absolute ? domain : '') + namedRoutes[name].uri return url.replace( /\{([^}]+)\}/gi, function (tag) { var key = tag.replace(/\{|\}/gi, ''); if (params[key] === undefined) { throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"'; } return params[key]; } ); } if (typeof exports !== 'undefined'){ exports.route = route }
var route = function(name, params = {}, absolute = true) { var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', url = (absolute ? domain : '') + namedRoutes[name].uri, arrayKey = 0; return url.replace( /\{([^}]+)\}/gi, function (tag) { var key = Array.isArray(params) ? arrayKey : tag.replace(/\{|\}/gi, ''); if (params[key] === undefined) { throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"'; } arrayKey++; return params[key]; } ); } if (typeof exports !== 'undefined'){ exports.route = route }
Add support for unkeyed params array.
Add support for unkeyed params array.
JavaScript
mit
tightenco/ziggy,tightenco/ziggy
6bb1a3ca881b6c7e0a20e5e049c211a79183ff6e
src/disclosures/js/dispatchers/get-school-values.js
src/disclosures/js/dispatchers/get-school-values.js
'use strict'; var stringToNum = require( '../utils/handle-string-input' ); var getSchoolValues = { var values = {}; init: function( ) { values.programLength = this.getProgramLength(); values.gradRate = this.getGradRate(); values.medianDebt = this.getMedianDebt(); values.defaultRate = this.getDefaultRate(); values.medianSalary = this.getMedianSalary(); return values; }, getProgramLength: function() { // Rounds up to the nearest number of years. // Might need to change later, to address 18 month or 30 month programs. return Math.ceil(window.programData.programLength / 12) || ''; }, getGradRate: function() { if ( window.programData.completionRate == 'None' ) { return window.schoolData.gradRate; } else { return window.programData.completionRate || window.schoolData.gradRate; } }, getMedianDebt: function() { return window.programData.medianStudentLoanCompleters || window.schoolData.medianMonthlyDebt; }, getDefaultRate: function() { return (window.programData.defaultRate / 100) || window.schoolData.defaultRate; }, getMedianSalary: function() { return window.programData.salary || window.schoolData.medianAnnualPay; } }; module.exports = getSchoolValues;
'use strict'; var getSchoolValues = { var values = {}; init: function( ) { values.programLength = this.getProgramLength(); values.gradRate = this.getGradRate(); values.medianDebt = this.getMedianDebt(); values.defaultRate = this.getDefaultRate(); values.medianSalary = this.getMedianSalary(); return values; }, getProgramLength: function() { // Rounds up to the nearest number of years. // Might need to change later, to address 18 month or 30 month programs. return Math.ceil(window.programData.programLength / 12) || ''; }, getGradRate: function() { if ( window.programData.completionRate == 'None' ) { return window.schoolData.gradRate; } else { return window.programData.completionRate || window.schoolData.gradRate; } }, getMedianDebt: function() { return window.programData.medianStudentLoanCompleters || window.schoolData.medianMonthlyDebt; }, getDefaultRate: function() { return (window.programData.defaultRate / 100) || window.schoolData.defaultRate; }, getMedianSalary: function() { return window.programData.salary || window.schoolData.medianAnnualPay; } }; module.exports = getSchoolValues;
Remove lingering but unneeded requirement call
Remove lingering but unneeded requirement call
JavaScript
cc0-1.0
mistergone/college-costs,mistergone/college-costs,mistergone/college-costs,mistergone/college-costs
c76fda7d6ed6ca449330a9d2b084732a9ffd295e
test/index.js
test/index.js
import test from "ava"; import {newUnibeautify, Beautifier} from "unibeautify"; import beautifier from "../dist"; test.beforeEach((t) => { t.context.unibeautify = newUnibeautify(); }); test("should successfully install beautifier", (t) => { const {unibeautify} = t.context; unibeautify.loadBeautifier(beautifier); t.is(unibeautify.beautifiers[0].name, beautifier.name); }); test("should successfully beautify JavaScript text", (t) => { const {unibeautify} = t.context; unibeautify.loadBeautifier(beautifier); const text = `function test(n){return n+1;}`; const beautifierResult = `function test(n) { return n + 1; }`; return unibeautify.beautify({ languageName: "JavaScript", options: { JavaScript: { indent_char: " ", indent_size: 2 } }, text }).then((results) => { t.is(results, beautifierResult); }); });
import test from "ava"; import { newUnibeautify, Beautifier } from "unibeautify"; import beautifier from "../dist"; test.beforeEach(t => { t.context.unibeautify = newUnibeautify(); }); test("should successfully install beautifier", t => { const { unibeautify } = t.context; unibeautify.loadBeautifier(beautifier); t.is(unibeautify.beautifiers[0].name, beautifier.name); }); test("should successfully beautify JavaScript text with 2 space indentation", t => { const { unibeautify } = t.context; unibeautify.loadBeautifier(beautifier); const text = `function test(n){return n+1;}`; const beautifierResult = `function test(n) { return n + 1; }`; return unibeautify .beautify({ languageName: "JavaScript", options: { JavaScript: { indent_char: " ", indent_size: 2 } }, text }) .then(results => { t.is(results, beautifierResult); }); }); test("should successfully beautify JavaScript text with double quotes", t => { const { unibeautify } = t.context; unibeautify.loadBeautifier(beautifier); const text = `console.log('hello world');`; const beautifierResult = `console.log("hello world");`; return unibeautify .beautify({ languageName: "JavaScript", options: { JavaScript: { indent_char: " ", indent_size: 2, convert_quotes: "double" } }, text }) .then(results => { t.is(results, beautifierResult); }); });
Add test for double quotes
Add test for double quotes
JavaScript
mit
Unibeautify/beautifier-prettydiff,Unibeautify/beautifier-prettydiff
00f048fe44190a4df276a6c9ddf2a80359ecd1a8
test/reverse_urlSpec.js
test/reverse_urlSpec.js
(function () { 'use strict'; describe('Unit: angular-reverse-url', function () { beforeEach(module('angular-reverse-url')); describe('reverseUrl filter', function () { }); }); }());
(function () { 'use strict'; var reverseUrl, $route; var routeMock = {}; routeMock.routes = { '/testRoute1/': { controller: 'TestController1', originalPath: '/test-route-1/' }, '/testRoute1/:params/': { controller: 'TestController1', originalPath: '/test-route-1/:param/' }, '/testRoute2/': { name: 'TestRoute2', originalPath: '/test-route-2/' }, }; describe('Unit: angular-reverse-url', function () { beforeEach(module('angular-reverse-url', function ($provide) { $provide.value('$route', routeMock); })); describe('reverseUrl filter', function () { beforeEach(inject(function ($injector) { $route = $injector.get('$route') reverseUrl = $injector.get('$filter')('reverseUrl'); })); it('should correctly match to a basic route by controller', function () { expect(reverseUrl('TestController1')).toEqual('#/test-route-1/'); }); it('should correctly match to a basic route by name', function () { expect(reverseUrl('TestRoute2')).toEqual('#/test-route-2/'); }); it('should correctly match to a route with params', function () { expect(reverseUrl('TestController1', {param: 'foobar'})).toEqual('#/test-route-1/foobar/'); }); }); }); }());
Add tests for existing functionality
Add tests for existing functionality
JavaScript
mit
incuna/angular-reverse-url
f7215986927ab3136b878bda5654d6fffc2d0fc1
app/components/github-team-notices.js
app/components/github-team-notices.js
import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; var GithubTeamNotices = DashboardWidgetComponent.extend({ init: function() { this._super(); this.set("contents", []); }, actions: { receiveEvent: function(data) { var items = Ember.A(JSON.parse(data)); this.updatePullRequests(items.pull_requests); // eventually Issues too } }, updatePullRequests: function(items) { var contents = this.get("contents"); if (!Ember.isEmpty(items)) { // Remove items that have disappeared. var itemsToRemove = []; contents.forEach(function(existingItem) { var isNotPresent = !items.findBy("url", existingItem.get("url")); if (isNotPresent) { itemsToRemove.pushObject(existingItem); } }); contents.removeObjects(itemsToRemove); // Process current items. items.forEach(function(item) { var existingItem = contents.findBy("url", item.url); if (Ember.isEmpty(existingItem)) { // Add new items. var newItem = contents.pushObject(Ember.Object.create(item)); newItem.set("dashEventType", "Pull Request"); } else { // Update existing items. existingItem.setProperties(item); } }); } } }); export default GithubTeamNotices;
import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; var GithubTeamNotices = DashboardWidgetComponent.extend({ init: function() { this._super(); this.set("contents", []); }, actions: { receiveEvent: function(data) { var items = Ember.A(JSON.parse(data)); this.updatePullRequests(items.pull_requests); // eventually Issues too } }, updatePullRequests: function(items) { var contents = this.get("contents"); if (!Ember.isEmpty(items)) { // Remove items that have disappeared. var itemsToRemove = []; contents.forEach(function(existingItem) { var isNotPresent = !items.findBy("id", existingItem.get("id")); if (isNotPresent) { itemsToRemove.pushObject(existingItem); } }); contents.removeObjects(itemsToRemove); // Process current items. items.forEach(function(item) { var existingItem = contents.findBy("url", item.id); if (Ember.isEmpty(existingItem)) { // Add new items. var newItem = contents.pushObject(Ember.Object.create(item)); newItem.set("dashEventType", "Pull Request"); } else { // Update existing items. existingItem.setProperties(item); } }); } } }); export default GithubTeamNotices;
Fix existing item recognition in "Code" widget.
Fix existing item recognition in "Code" widget.
JavaScript
mit
substantial/substantial-dash-client
b5c332043213eaf57bc56c00b24c51728a6f3041
test/server/app_test.js
test/server/app_test.js
var should = require('chai').should(), expect = require('chai').expect, supertest = require('supertest'), config = require('config'), port = config.get('port'), testingUrl = 'http://localhost:' + port, api = supertest(testingUrl) describe('Get /', () => { it('should render the homepage', (done) => { api.get('/') .expect(200, done) }) } ) describe('Post ', () =>{ var user = JSON.stringify({ email: "dude@gmail.com", password: "abcde"}) it('creates an account', (done) => { api.post('/signup') .set('Accept', 'application/json') .set('Content-Type', 'application/json') .send(user) .expect(200) .expect((res) => { user_response = res.body.user return (user_response.hasOwnProperty('email') && user_response.hasOwnProperty('username') && user_response.hasOwnProperty('firstName') && user_response.hasOwnProperty('lastName')) }) .end(done) })
var should = require('chai').should(), expect = require('chai').expect, supertest = require('supertest'), config = require('config'), port = config.get('port'), testingUrl = 'http://localhost:' + port, api = supertest(testingUrl) describe('Get /', () => { it('should render the homepage', (done) => { api.get('/') .expect(200, done) }) } ) describe('Post ', () =>{ var user = JSON.stringify({ email: "dude@gmail.com", password: "abcde"}) it('creates an account', (done) => { api.post('/signup') .set('Accept', 'application/json') .set('Content-Type', 'application/json') .send(user) .expect(200) .expect((res) => { user_response = res.body.user return (user_response.hasOwnProperty('email') && user_response.hasOwnProperty('username') && user_response.hasOwnProperty('firstName') && user_response.hasOwnProperty('lastName')) }) .end(done) })}) describe('Post ', () =>{ //need to have an exising user var user = JSON.stringify({ email: "dude@gmail.com", password: "abcde"}) it('logs into an account', (done) => { // user should already exist bc there is currently no setup or teardown api.post('/login') .set('Accept', 'application/json') .set('Content-Type', 'application/json') .send(user) .expect(200) .expect((res) => { login_response = res.body.user // not sure this is right either return ((login_response.hasOwnProperty('user') && login_response.hasOwnProperty('token'))) }) .end(done) } ) })
Add failing test for login
Add failing test for login
JavaScript
mit
tylergreen/react-redux-express-app,tylergreen/react-redux-express-app
3f5acc776fed90572762275e82bab94224c52bcf
app/src/index.js
app/src/index.js
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import MainScreen from './react/MainScreen'; import config from './config'; import SculptureApp from './app'; window.onload = () => { const manifest = chrome.runtime.getManifest(); console.log(`Version: ${manifest.version}`); config.applyLocalConfig(anyware_config); const app = new SculptureApp(config); ReactDOM.render(<MainScreen app={app} restart={() => chrome.runtime.reload()}/>, document.getElementById('anyware-root')); };
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import MainScreen from './react/MainScreen'; import config from './config'; import SculptureApp from './app'; // Read all all local storage and overwrite the corresponding values in the given config object // Returns a promise function applyFromLocalStorage(config) { return new Promise((resolve, reject) => { chrome.storage.local.get(null, (items) => { if (chrome.runtime.lastError) { reject(chrome.runtime.lastError); } else { for (let key of Object.keys(items)) { config[key] = items[key]; } resolve(true); } }); }); } window.onload = async () => { const manifest = chrome.runtime.getManifest(); console.log(`Version: ${manifest.version}`); // Apply config from Chrome local storage to anyware_config await applyFromLocalStorage(anyware_config); // Apply config from the global variable anyware_config config.applyLocalConfig(anyware_config); const app = new SculptureApp(config); ReactDOM.render(<MainScreen app={app} restart={() => chrome.runtime.reload()}/>, document.getElementById('anyware-root')); };
Support per-sculpture overrides in local storage
Support per-sculpture overrides in local storage
JavaScript
mit
anyWareSculpture/sculpture-client,anyWareSculpture/sculpture-client,anyWareSculpture/sculpture-client
217b9501b2b3e371e8c4c7fdbd534f9c1f6ca440
build/build.js
build/build.js
var extend = require('extend'); var path = require('path'); var cleanDist = require('./tasks/clean_dist'); var copy = require('./tasks/copy'); var sass = require('./tasks/sass'); var javascript = require('./tasks/javascript'); var polyfillJS = require('./tasks/polyfillJS'); module.exports = function(options) { /** * Default options for the build * * `components` is configuration for which components should be included in the * build. This defaults to only Govuk core stuff. The local build scripts also include * the "Build" category which contains styles for example pages */ var config = extend({ mode: 'development', cache: true, components: true, destination: 'dist' }, options); return new Promise(function(resolve, reject) { cleanDist(config) .then(function() { return copy.govUkTemplateAssets(config); }) .then(function() { return copy.govUkToolkitAssets(config); }) .then(function() { return copy.landregistryComponentAssets(config); }) .then(function() { return sass(config); }) .then(function() { return javascript.compile(config); }) .then(function() { resolve(path.join(config.destination, 'assets')); }) .catch(function(e) { reject(e); }); }); }
var extend = require('extend'); var path = require('path'); var cleanDist = require('./tasks/clean_dist'); var copy = require('./tasks/copy'); var sass = require('./tasks/sass'); var javascript = require('./tasks/javascript'); module.exports = function(options) { /** * Default options for the build * * `components` is configuration for which components should be included in the * build. This defaults to only Govuk core stuff. The local build scripts also include * the "Build" category which contains styles for example pages */ var config = extend({ mode: 'development', cache: true, components: true, destination: 'dist' }, options); return new Promise(function(resolve, reject) { cleanDist(config) .then(function() { return copy.govUkTemplateAssets(config); }) .then(function() { return copy.govUkToolkitAssets(config); }) .then(function() { return copy.landregistryComponentAssets(config); }) .then(function() { return sass(config); }) .then(function() { return javascript.compile(config); }) .then(function() { resolve(path.join(config.destination, 'assets')); }) .catch(function(e) { reject(e); }); }); }
Fix JS bug caused by previous commit
Fix JS bug 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
9393b0303d6b991ef27758ebadaed670a290d7fc
generators/app/templates/_app/_app.js
generators/app/templates/_app/_app.js
var express = require('express'), path = require('path'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'); var routes = require('./routes'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', routes.index); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() { // log a message to console! }); module.exports = app;
var express = require('express'), path = require('path'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'); var routes = require('./routes'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', routes.index); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() { // log a message to console! }); module.exports = app;
Fix 'body-parser deprecated urlencoded' warning
Fix 'body-parser deprecated urlencoded' warning
JavaScript
mit
christiannwamba/generator-wean,christiannwamba/generator-wean
72aa328e3dcd2118c03a45781d9674976fc447dc
src/utils/convertJsToSass.js
src/utils/convertJsToSass.js
function convertJsToSass(obj, syntax) { const suffix = syntax === 'sass' ? '' : ';' const keys = Object.keys(obj) const lines = keys.map(key => `$${key}: ${formatValue(obj[key], syntax)}${suffix}`) return lines.join('\n') } function formatNestedObject(obj, syntax) { const keys = Object.keys(obj) return keys.map(key => `${key}: ${formatValue(obj[key], syntax)}`).join(', ') } function withQuotesIfNecessary(value) { const hasQuotes = /^['"](\n|.)*['"]$/gm.test(value) const requiresQuotes = /^[0 ]/.test(value) return hasQuotes || !requiresQuotes ? value : `"${value}"` } function formatValue(value, syntax) { if (value instanceof Array) { return `(${value.map(formatValue).join(', ')})` } if (typeof value === 'object') { return `(${formatNestedObject(value, syntax)})` } if (typeof value === 'string') { return withQuotesIfNecessary(value) } return JSON.stringify(value) } module.exports = convertJsToSass
function convertJsToSass(obj, syntax) { const suffix = syntax === 'sass' ? '' : ';' const keys = Object.keys(obj) const lines = keys.map(key => `$${key}: ${formatValue(obj[key], syntax)}${suffix}`) return lines.join('\n') } function formatNestedObject(obj, syntax) { const keys = Object.keys(obj) return keys.map(key => `${key}: ${formatValue(obj[key], syntax)}`).join(', ') } function formatValue(value, syntax) { if (value instanceof Array) { return `(${value.map(formatValue).join(', ')})` } if (typeof value === 'object') { return `(${formatNestedObject(value, syntax)})` } if (typeof value === 'string') { return value } return JSON.stringify(value) } module.exports = convertJsToSass
Remove quotes from string because they break e.g. box shadows
Remove quotes from string because they break e.g. box shadows
JavaScript
mit
epegzz/sass-vars-loader,epegzz/sass-vars-loader,epegzz/sass-vars-loader
6951e92d15472187976538ed98cb9d572ce426bc
build/start.js
build/start.js
const childProcess = require("child_process"); const electron = require("electron"); const webpack = require("webpack"); const config = require("./webpack.app.config"); const compiler = webpack(config({ development: true })); let electronStarted = false; const watching = compiler.watch({}, (err, stats) => { if (err != null) { console.log(err); } else if (!electronStarted) { electronStarted = true; childProcess .spawn(electron, ["."], { stdio: "inherit" }) .on("close", () => { watching.close(); }); } console.log(stats.toString({ colors: true })); });
const childProcess = require("child_process"); const readline = require("readline"); const electron = require("electron"); const webpack = require("webpack"); const config = require("./webpack.app.config"); const compiler = webpack(config({ development: true })); let electronStarted = false; const clearTerminal = () => { if (process.stdout.isTTY) { const blankLines = "\n".repeat(process.stdout.rows); console.log(blankLines); readline.cursorTo(process.stdout, 0, 0); readline.clearScreenDown(process.stdout); } }; const watching = compiler.watch({}, (err, stats) => { if (err != null) { console.log(err); } else if (!electronStarted) { electronStarted = true; childProcess .spawn(electron, ["."], { stdio: "inherit" }) .on("close", () => { watching.close(); }); } if (stats != null) { clearTerminal(); console.log(stats.toString({ colors: true })); } });
Clear terminal with each webpack rebuild
Clear terminal with each webpack rebuild
JavaScript
mit
szwacz/electron-boilerplate,szwacz/electron-boilerplate
a57628e33816f3740ccb39dd295310f34583b85d
guides/place-my-order/steps/add-data/list.js
guides/place-my-order/steps/add-data/list.js
import { Component } from 'can'; import './list.less'; import view from './list.stache'; import Restaurant from '~/models/restaurant'; const RestaurantList = Component.extend({ tag: 'pmo-restaurant-list', view, ViewModel: { // EXTERNAL STATEFUL PROPERTIES // These properties are passed from another component. Example: // value: {type: "number"} // INTERNAL STATEFUL PROPERTIES // These properties are owned by this component. restaurants: { default() { return Restaurant.getList({}); } }, // DERIVED PROPERTIES // These properties combine other property values. Example: // get valueAndMessage(){ return this.value + this.message; } // METHODS // Functions that can be called by the view. Example: // incrementValue() { this.value++; } // SIDE EFFECTS // The following is a good place to perform changes to the DOM // or do things that don't fit in to one of the areas above. connectedCallback(element){ } } }); export default RestaurantList; export const ViewModel = RestaurantList.ViewModel; import Component from 'can-component'; import DefineMap from 'can-define/map/'; import './list.less'; import view from './list.stache'; import Restaurant from '~/models/restaurant'; export const ViewModel = DefineMap.extend({ restaurants: { value() { return Restaurant.getList({}); } } }); export default Component.extend({ tag: 'pmo-restaurant-list', ViewModel, view });
import { Component } from 'can'; import './list.less'; import view from './list.stache'; import Restaurant from '~/models/restaurant'; const RestaurantList = Component.extend({ tag: 'pmo-restaurant-list', view, ViewModel: { // EXTERNAL STATEFUL PROPERTIES // These properties are passed from another component. Example: // value: {type: "number"} // INTERNAL STATEFUL PROPERTIES // These properties are owned by this component. restaurants: { default() { return Restaurant.getList({}); } }, // DERIVED PROPERTIES // These properties combine other property values. Example: // get valueAndMessage(){ return this.value + this.message; } // METHODS // Functions that can be called by the view. Example: // incrementValue() { this.value++; } // SIDE EFFECTS // The following is a good place to perform changes to the DOM // or do things that don't fit in to one of the areas above. connectedCallback(element){ } } }); export default RestaurantList; export const ViewModel = RestaurantList.ViewModel;
Remove redundant source from PMO
Remove redundant source from PMO This removes the redundant source that was left over from the DoneJS 2 guide. Fixes #1156
JavaScript
mit
donejs/donejs,donejs/donejs
ffbd3bf025e9f8f72f8b4cb42e9be653ecdb08b3
js/FeaturedExperiences.ios.js
js/FeaturedExperiences.ios.js
/** * Copyright 2015-present 650 Industries. All rights reserved. * * @providesModule FeaturedExperiences */ 'use strict'; function setReferrer(newReferrer) { // NOOP. Shouldn't get here. } function getFeatured() { return [ { url: 'exp://exp.host/@exponent/floatyplane', manifest: { name: 'Floaty Plane', desc: 'Touch the plane until you die!', iconUrl: 'https://s3-us-west-2.amazonaws.com/examples-exp/floaty_icon.png', }, }, { url: 'exp://exp.host/@exponent/react-native-for-curious-people', manifest: { name: 'React Native for Curious People', desc: 'Learn about React Native.', iconUrl: 'https://s3.amazonaws.com/rnfcp/icon.png', }, }, { url: 'exp://exp.host/@exponent/pomodoro', manifest: { name: 'Pomodoro', desc: 'Be careful or the tomatoes might explode!', iconUrl: 'https://s3.amazonaws.com/pomodoro-exp/icon.png', }, }, ]; } module.exports = { setReferrer, getFeatured, };
/** * Copyright 2015-present 650 Industries. All rights reserved. * * @providesModule FeaturedExperiences */ 'use strict'; function setReferrer(newReferrer) { // NOOP. Shouldn't get here. } function getFeatured() { return [ { url: 'exp://exp.host/@exponent/floatyplane', manifest: { name: 'Floaty Plane', desc: 'Touch the plane until you die!', iconUrl: 'https://s3-us-west-2.amazonaws.com/examples-exp/floaty_icon.png', }, }, { url: 'exp://exp.host/@exponent/react-native-for-curious-people', manifest: { name: 'React Native for Curious People', desc: 'Learn about React Native.', iconUrl: 'https://s3.amazonaws.com/rnfcp/icon.png', }, }, { url: 'exp://exp.host/@exponent/pomodoro', manifest: { name: 'Pomodoro', desc: 'Be careful or the tomatoes might explode!', iconUrl: 'https://s3.amazonaws.com/pomodoro-exp/icon.png', }, }, { url: 'exp://exp.host/@notbrent/native-component-list', manifest: { name: 'Native Component List', desc: 'Demonstration of some native components.', iconUrl: 'https://s3.amazonaws.com/exp-brand-assets/ExponentEmptyManifest_192.png', }, }, ]; } module.exports = { setReferrer, getFeatured, };
Add native component list to featured experiences
Add native component list to featured experiences fbshipit-source-id: 7a6210a
JavaScript
bsd-3-clause
jolicloud/exponent,jolicloud/exponent,exponent/exponent,exponentjs/exponent,jolicloud/exponent,exponentjs/exponent,jolicloud/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,jolicloud/exponent,jolicloud/exponent,exponent/exponent,exponent/exponent,jolicloud/exponent,exponentjs/exponent,jolicloud/exponent,jolicloud/exponent,exponent/exponent,exponent/exponent
ae0031e09a40434d24bfa344bf099aa4c8cbaad5
src/components/Board.js
src/components/Board.js
import React, {Component, PropTypes} from 'react' import BoardContainer from './BoardContainer' import {Provider} from 'react-redux' import {createStore} from 'redux' import boardReducer from '../reducers/BoardReducer' let store = createStore(boardReducer, window && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) export default class Board extends Component { render () { return <Provider store={store}> <BoardContainer {...this.props} /> </Provider> } } Board.propTypes = { data: PropTypes.object.isRequired, onLaneScroll: PropTypes.func, onCardClick: PropTypes.func, eventBusHandle: PropTypes.func, laneSortFunction: PropTypes.func, draggable: PropTypes.bool, handleDragStart: PropTypes.func, handleDragEnd: PropTypes.func, onDataChange: PropTypes.func }
import React, {Component, PropTypes} from 'react' import BoardContainer from './BoardContainer' import {Provider} from 'react-redux' import {createStore} from 'redux' import boardReducer from '../reducers/BoardReducer' let store = createStore(boardReducer, typeof(window) !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) export default class Board extends Component { render () { return <Provider store={store}> <BoardContainer {...this.props} /> </Provider> } } Board.propTypes = { data: PropTypes.object.isRequired, onLaneScroll: PropTypes.func, onCardClick: PropTypes.func, eventBusHandle: PropTypes.func, laneSortFunction: PropTypes.func, draggable: PropTypes.bool, handleDragStart: PropTypes.func, handleDragEnd: PropTypes.func, onDataChange: PropTypes.func }
Use typeof(window) to check if being used in non browser environments
fix(): Use typeof(window) to check if being used in non browser environments https://github.com/rcdexta/react-trello/issues/15
JavaScript
mit
rcdexta/react-trello,rcdexta/react-trello
01c5311c3027c893ddd76cfbec42d88baece1564
lib/daab-run.js
lib/daab-run.js
#!/usr/bin/env node // daab run var fs = require('fs'); var spawn = require('child_process').spawn; var program = require('commander'); var auth = require('./auth'); program .allowUnknownOption() .parse(process.argv); if (! auth.hasToken()) { console.log('At first, try "daab login"'); process.exit(); } var hubot = spawn('bin/hubot', ['run'].concat(process.argv.slice(2)), { stdio: 'inherit' });
#!/usr/bin/env node // daab run var fs = require('fs'); var spawn = require('child_process').spawn; var program = require('commander'); var auth = require('./auth'); program .allowUnknownOption() .parse(process.argv); if (! auth.hasToken()) { console.log('At first, try "daab login"'); process.exit(); } var cmd = process.platform === 'win32' ? 'bin\\hubot.cmd' : 'bin/hubot'; var hubot = spawn(cmd, ['run'].concat(process.argv.slice(2)), { stdio: 'inherit' });
Fix launch command on windows platform.
Fix launch command on windows platform.
JavaScript
mit
lisb/daab,lisb/daab,lisb/daab
210c0478bd061571f62bb0a841400bd24e325acb
lib/check.js
lib/check.js
var check = { isNaN : function(value) { "use strict"; return isNaN(value); }, isZero : function(value) { "use strict"; return value === 0; }, isPositiveZero : function(value) { "use strict"; return value === 0 && 1 / value === Infinity; }, isNegativeZero : function(value) { "use strict"; return value === 0 && 1 / value === -Infinity; }, isFinite : function(value) { "use strict" return !isNaN(value) && value !== Infinity && value !== -Infinity; }, isInfinity : function(value) { "use strict"; return value === Infinity || value === -Infinity; }, isPositiveInfinity : function(value) { "use strict"; return value === Infinity; }, isNegativeInfinity : function(value) { "use strict"; return value === -Infinity; } }; module.exports = check;
var check = { isNaN : isNaN, isZero : function(value) { "use strict"; return value === 0; }, isPositiveZero : function(value) { "use strict"; return value === 0 && 1 / value === Infinity; }, isNegativeZero : function(value) { "use strict"; return value === 0 && 1 / value === -Infinity; }, isFinite : isFinite, isInfinity : function(value) { "use strict"; return value === Infinity || value === -Infinity; }, isPositiveInfinity : function(value) { "use strict"; return value === Infinity; }, isNegativeInfinity : function(value) { "use strict"; return value === -Infinity; } }; module.exports = check;
Make isFinite() and isNaN() direct ref copy of the builtin functions
Make isFinite() and isNaN() direct ref copy of the builtin functions
JavaScript
mit
kchapelier/node-mathp
38733fd891f6d3022a5c0bd7aef98c4ee7ad5b55
packages/ember-engines/lib/utils/deeply-non-duplicated-addon.js
packages/ember-engines/lib/utils/deeply-non-duplicated-addon.js
'use strict'; /** * Deduplicate one addon's children addons recursively from hostAddons. * * @private * @param {Object} hostAddons * @param {EmberAddon} dedupedAddon * @param {String} treeName */ module.exports = function deeplyNonDuplicatedAddon(hostAddons, dedupedAddon, treeName) { if (dedupedAddon.addons.length === 0) { return; } dedupedAddon._orginalAddons = dedupedAddon.addons; dedupedAddon.addons = dedupedAddon.addons.filter(addon => { // nested lazy engine will have it's own deeplyNonDuplicatedAddon, just keep it here if (addon.lazyLoading && addon.lazyLoading.enabled) { return true; } if (addon.addons.length > 0) { addon._orginalAddons = addon.addons; deeplyNonDuplicatedAddon(hostAddons, addon, treeName); } let hostAddon = hostAddons[addon.name]; if (hostAddon && hostAddon.cacheKeyForTree) { let innerCacheKey = addon.cacheKeyForTree(treeName); let hostAddonCacheKey = hostAddon.cacheKeyForTree(treeName); if ( innerCacheKey != null && innerCacheKey === hostAddonCacheKey ) { // the addon specifies cache key and it is the same as host instance of the addon, skip the tree return false; } } return true; }); }
'use strict'; // Array of addon names that should not be deduped. const ADDONS_TO_EXCLUDE_FROM_DEDUPE = [ 'ember-cli-babel', ]; /** * Deduplicate one addon's children addons recursively from hostAddons. * * @private * @param {Object} hostAddons * @param {EmberAddon} dedupedAddon * @param {String} treeName */ module.exports = function deeplyNonDuplicatedAddon(hostAddons, dedupedAddon, treeName) { if (dedupedAddon.addons.length === 0) { return; } dedupedAddon._orginalAddons = dedupedAddon.addons; dedupedAddon.addons = dedupedAddon.addons.filter(addon => { // nested lazy engine will have it's own deeplyNonDuplicatedAddon, just keep it here if (addon.lazyLoading && addon.lazyLoading.enabled) { return true; } if (ADDONS_TO_EXCLUDE_FROM_DEDUPE.includes(addon.name)) { return true; } if (addon.addons.length > 0) { addon._orginalAddons = addon.addons; deeplyNonDuplicatedAddon(hostAddons, addon, treeName); } let hostAddon = hostAddons[addon.name]; if (hostAddon && hostAddon.cacheKeyForTree) { let innerCacheKey = addon.cacheKeyForTree(treeName); let hostAddonCacheKey = hostAddon.cacheKeyForTree(treeName); if ( innerCacheKey != null && innerCacheKey === hostAddonCacheKey ) { // the addon specifies cache key and it is the same as host instance of the addon, skip the tree return false; } } return true; }); }
Add exclude list to addon dedupe logic
Add exclude list to addon dedupe logic
JavaScript
mit
ember-engines/ember-engines,ember-engines/ember-engines
5ecc6a9de257eb6872946a01f5929a2bfa94bf79
lib/macgyver.js
lib/macgyver.js
var pristineEnv = require('./pristine-env'); function macgyver(thing) { if (Object.prototype.toString.call(thing) === '[object Array]') { return (new pristineEnv().Array(0)).concat(thing); } else { return thing; } } module.exports = macgyver;
var pristineEnv = require('./pristine-env'); var pristineObject = pristineEnv().Object; var pristineArray = pristineEnv().Array; function macgyver(thing) { if (pristineObject.prototype.toString.call(thing) === '[object Array]') { return (new pristineArray()).concat(thing); } else { return thing; } } module.exports = macgyver;
Use pristine Object to work out if a thing is an array
Use pristine Object to work out if a thing is an array
JavaScript
mit
customcommander/macgyver
8d62ce5afa50ccbe21b516f3cc39d0c7ca20b922
lib/index.js
lib/index.js
require('./db/connection'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const logger = require('koa-logger'); const json = require('koa-json'); const onerror = require('koa-onerror'); const router = require('./routes'); const cors = require('./helpers/cors'); const auth = require('./helpers/auth'); (() => { const app = new Koa(); onerror(app); app.use(bodyParser({})) .use(json()) .use(logger()) .use(cors()) router.map(el => app.use(el.routes())); app.listen(3003); })();
require('./db/connection'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const logger = require('koa-logger'); const json = require('koa-json'); const onerror = require('koa-onerror'); const router = require('./routes'); const cors = require('./helpers/cors'); (() => { const app = new Koa(); onerror(app); app.use(bodyParser({})) .use(json()) .use(logger()) .use(cors()); router.map(el => app.use(el.routes())); app.listen(process.env.PORT || 3003); })();
ADD - PORT env var
ADD - PORT env var
JavaScript
apache-2.0
fkanout/NotifyDrive-API
30b859c827ed450fbf7a52a18aa92af79c11e5e4
lib/index.js
lib/index.js
'use strict'; var bunyan = require('bunyan'); var config = require('coyno-config'); function createLogger() { var log; if (!!config.log.pretty) { var PrettyStream = require('bunyan-prettystream'); var prettyStdOut = new PrettyStream(); prettyStdOut.pipe(process.stdout); log = bunyan.createLogger({ name: 'queue', streams: [{ level: config.log.level, type: 'raw', stream: prettyStdOut }] }); } else { log = bunyan.createLogger({name: 'queue'}); } return log; } module.exports = createLogger();
'use strict'; var bunyan = require('bunyan'); var config = require('coyno-config'); function createLogger() { var log; if (!!config.log.pretty) { var PrettyStream = require('bunyan-prettystream'); var prettyStdOut = new PrettyStream(); prettyStdOut.pipe(process.stdout); log = bunyan.createLogger({ name: 'queue', streams: [{ level: config.log.level, type: 'raw', stream: prettyStdOut }] }); } else { log = bunyan.createLogger({name: 'queue', level: config.log.level}); } return log; } module.exports = createLogger();
Handle log level correctly for raw logs
Handle log level correctly for raw logs
JavaScript
apache-2.0
blooks/log
fe4d6b89e779c357d6bdc00c46c6c28bc549ecc5
Source/Scene/Pass.js
Source/Scene/Pass.js
/*global define*/ define([ '../Core/freezeObject' ], function( freezeObject) { "use strict"; /** * The render pass for a command. * * @private */ var Pass = { GLOBE : 0, OPAQUE : 1, TRANSLUCENT : 2, OVERLAY : 3, NUMBER_OF_PASSES : 4 }; return freezeObject(Pass); });
/*global define*/ define([ '../Core/freezeObject' ], function( freezeObject) { "use strict"; /** * The render pass for a command. * * @private */ var Pass = { GLOBE : 0, OPAQUE : 1, // Commands are executed in order by pass up to the translucent pass. // Translucent geometry needs special handling (sorting/OIT). Overlays // are also special (they're executed last, they're not sorted by frustum). TRANSLUCENT : 2, OVERLAY : 3, NUMBER_OF_PASSES : 4 }; return freezeObject(Pass); });
Add comment about the order of passes.
Add comment about the order of passes.
JavaScript
apache-2.0
CesiumGS/cesium,AnimatedRNG/cesium,likangning93/cesium,denverpierce/cesium,jason-crow/cesium,ggetz/cesium,kiselev-dv/cesium,esraerik/cesium,esraerik/cesium,emackey/cesium,omh1280/cesium,soceur/cesium,jason-crow/cesium,emackey/cesium,YonatanKra/cesium,YonatanKra/cesium,omh1280/cesium,AnimatedRNG/cesium,kiselev-dv/cesium,hodbauer/cesium,josh-bernstein/cesium,geoscan/cesium,denverpierce/cesium,kiselev-dv/cesium,aelatgt/cesium,NaderCHASER/cesium,CesiumGS/cesium,omh1280/cesium,wallw-bits/cesium,emackey/cesium,ggetz/cesium,hodbauer/cesium,josh-bernstein/cesium,esraerik/cesium,progsung/cesium,kiselev-dv/cesium,denverpierce/cesium,wallw-bits/cesium,likangning93/cesium,AnalyticalGraphicsInc/cesium,soceur/cesium,AnalyticalGraphicsInc/cesium,oterral/cesium,likangning93/cesium,emackey/cesium,CesiumGS/cesium,likangning93/cesium,CesiumGS/cesium,hodbauer/cesium,oterral/cesium,wallw-bits/cesium,aelatgt/cesium,wallw-bits/cesium,CesiumGS/cesium,progsung/cesium,kaktus40/cesium,denverpierce/cesium,omh1280/cesium,ggetz/cesium,YonatanKra/cesium,YonatanKra/cesium,AnimatedRNG/cesium,esraerik/cesium,jasonbeverage/cesium,soceur/cesium,jason-crow/cesium,jasonbeverage/cesium,AnimatedRNG/cesium,kaktus40/cesium,jason-crow/cesium,geoscan/cesium,oterral/cesium,aelatgt/cesium,likangning93/cesium,ggetz/cesium,aelatgt/cesium,NaderCHASER/cesium,NaderCHASER/cesium
f315636aec6965e0fe1394775bc4e97a67ad11aa
CodeWars/js/death-by-coffee.js
CodeWars/js/death-by-coffee.js
// https://www.codewars.com/kata/death-by-coffee/javascript const coffeeLimits = function(y,m,d) { let healthNumber = y * 10000 + m * 100 + d; let currentHex; let current; let i; let result = [0,0]; for(i=1;i<=5000;i++){ current = healthNumber + i * 0xcafe; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[0]=i; break; } } for(i=1;i<=5000;i++){ current = healthNumber + i * 0xdecaf; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[1]=i; break; } } return result; }
// https://www.codewars.com/kata/death-by-coffee/javascript const coffeeLimits = function(y,m,d) { let healthNumber = y * 10000 + m * 100 + d; let currentHex; let current; let i; let result = [0,0]; for(i=1;i<=5000;i++){ current = healthNumber + i * 0xcafe; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[0]=i; break; } } for(i=1;i<=5000;i++){ current = healthNumber + i * 0xdecaf; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[1]=i; break; } } return result; } export { coffeeLimits };
Add export to use as module
Add export to use as module
JavaScript
mit
sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems
fcf4357086a308bf9a9164f496c167e02e01ba17
lib/template.js
lib/template.js
const Handlebars = require('handlebars'); Handlebars.registerHelper('removeBreak', (text) => { text = Handlebars.Utils.escapeExpression(text); text = text.replace(/(\r\n|\n|\r)/gm, ' '); return new Handlebars.SafeString(text); }); const Template = class { constructor(templateString, data) { this.template = Handlebars.compile(templateString || ''); this.data = data || {}; } setTemplate(templateString) { this.template = Handlebars.compile(templateString || ''); } parse(callback) { callback(this.template(this.data)); } }; module.exports = Template;
const Handlebars = require('handlebars'); Handlebars.registerHelper('removeBreak', (text) => { text = Handlebars.Utils.escapeExpression(text); text = text.replace(/(\r\n|\n|\r)/gm, ' '); return new Handlebars.SafeString(text); }); const Template = class { constructor(templateString, data) { this.template = Handlebars.compile(templateString || ''); this.data = data || {}; } parse(callback) { callback(this.template(this.data)); } }; module.exports = Template;
Remove class method of Template
Remove class method of Template
JavaScript
mit
t32k/stylestats
ffdfc42c910a9d09d4cddc9c5df46d44d1e10ca8
grunt/contrib-jshint.js
grunt/contrib-jshint.js
// Check JS assets for code quality module.exports = function(grunt) { grunt.config('jshint', { all: ['Gruntfile.js', 'scripts/main.js'], }); grunt.loadNpmTasks('grunt-contrib-jshint'); };
// Check JS assets for code quality module.exports = function(grunt) { grunt.config('jshint', { all: ['Gruntfile.js', 'grunt/*.js', 'scripts/main.js'], }); grunt.loadNpmTasks('grunt-contrib-jshint'); };
Include Grunt partials in jshint task.
Include Grunt partials in jshint task.
JavaScript
mit
yellowled/yl-bp,yellowled/yl-bp
db31f1d00912d3720c8b2af5257d8727347e4d94
lib/redis.js
lib/redis.js
const redis = require('redis') const config = require('config') const url = require('url') const logger = require('./logger.js')() const initRedisClient = function () { let client, redisInfo if (config.redis.url) { redisInfo = url.parse(config.redis.url) client = redis.createClient(redisInfo.port, redisInfo.hostname) } else { client = redis.createClient(config.redis.port, 'localhost') } const closeRedisConnection = function (error, exitCode) { if (error) { logger.error(error) } client.quit() client.on('end', function () { console.log('Disconnected from Redis') }) } // We do not want too many connections being made to Redis (especially for Streetmix production), // so before a process exits, close the connection to Redis. process.on('beforeExit', closeRedisConnection) process.on('SIGINT', closeRedisConnection) process.on('uncaughtException', closeRedisConnection) client.on('error', closeRedisConnection) client.on('connect', function () { console.log('Connected to Redis') const redisAuth = (config.redis.url && redisInfo) ? redisInfo.auth.split(':')[1] : config.redis.password if (redisAuth) { client.auth(redisAuth, function (error) { if (error) throw error }) } }) return client } module.exports = initRedisClient
const redis = require('redis') const config = require('config') const logger = require('./logger.js')() const initRedisClient = function () { let client, redisInfo if (config.redis.url) { redisInfo = new URL(config.redis.url) client = redis.createClient(redisInfo.port, redisInfo.hostname) } else { client = redis.createClient(config.redis.port, 'localhost') } const closeRedisConnection = function (error, exitCode) { if (error) { logger.error(error) } client.quit() client.on('end', function () { logger.info('Disconnected from Redis') }) } // We do not want too many connections being made to Redis (especially for Streetmix production), // so before a process exits, close the connection to Redis. process.on('beforeExit', closeRedisConnection) process.on('SIGINT', closeRedisConnection) process.on('uncaughtException', closeRedisConnection) client.on('error', closeRedisConnection) client.on('connect', function () { logger.info('Connected to Redis') // Use the password in the URL if provided; otherwise use the one provided by config const redisAuth = (config.redis.url && redisInfo) ? redisInfo.password : config.redis.password if (redisAuth) { client.auth(redisAuth, function (error) { if (error) throw error }) } }) return client } module.exports = initRedisClient
Replace deprecated url.parse() with WHATWG URL API
Replace deprecated url.parse() with WHATWG URL API
JavaScript
bsd-3-clause
codeforamerica/streetmix,codeforamerica/streetmix,codeforamerica/streetmix
8e279cc54dcc083bf49940a572b0574881bbeea8
www/lib/collections/photos.js
www/lib/collections/photos.js
Photo = function (doc) { _.extend(this, doc); }; _.extend(Photo.prototype, { getImgTag: function (dimension) { return { 'class': 'lazy', 'data-src': _.str.sprintf( '%s/photos/%s/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), 'data-src-retina': _.str.sprintf( '%s/photos/%s@2x/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), alt: this.title, width: dimension, height: dimension }; } }); Photos = new Mongo.Collection('Photos', { transform: function (doc) { return new Photo(doc); } });
Photo = function (doc) { _.extend(this, doc); }; _.extend(Photo.prototype, { getImgTag: function (dimension) { return { 'class': 'lazy', src: 'data:image/gif;base64,' + 'R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', 'data-src': _.str.sprintf( '%s/photos/%s/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), 'data-src-retina': _.str.sprintf( '%s/photos/%s@2x/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), alt: this.title, width: dimension, height: dimension }; } }); Photos = new Mongo.Collection('Photos', { transform: function (doc) { return new Photo(doc); } });
Use a placeholder png to hold the image size
Use a placeholder png to hold the image size
JavaScript
mit
nburka/black-white
54306bafd423daff49272d4605bf84ae7a7471c8
js/metronome.js
js/metronome.js
function Metronome(tempo, beatsPerMeasure){ this.tempo = Number(tempo); this.beatsPerMeasure = Number(beatsPerMeasure); this.interval = null; } Metronome.prototype.start = function(){ var millisecondsToWait = this.tempoToMilliseconds(this.tempo); this.interval = window.setInterval(this.updateCounterView, millisecondsToWait, this.beatsPerMeasure); } Metronome.prototype.tempoToMilliseconds = function(tempo){ return (1000 * 60)/tempo; } Metronome.prototype.updateCounterView = function(beatsPerMeasure){ var counter = document.getElementById("metronome-counter"); var pastBeat = Number(counter.innerHTML); if (pastBeat < beatsPerMeasure){ counter.innerHTML = pastBeat + 1; } else { counter.innerHTML = 1; } Metronome.prototype.stop = function(){ window.clearInterval(this.interval); } }
function Metronome(tempo, beatsPerMeasure){ this.tempo = Number(tempo); this.beatsPerMeasure = Number(beatsPerMeasure); this.interval = null; } Metronome.prototype.start = function(){ var millisecondsToWait = this.tempoToMilliseconds(this.tempo); this.interval = window.setInterval(this.updateCounterView, millisecondsToWait, this.beatsPerMeasure); } Metronome.prototype.tempoToMilliseconds = function(tempo){ return (1000 * 60)/tempo; } Metronome.prototype.updateCounterView = function(beatsPerMeasure){ var counter = document.getElementById("metronome-counter"); var pastBeat = Number(counter.innerHTML); if (pastBeat < beatsPerMeasure){ counter.innerHTML = pastBeat + 1; } else { counter.innerHTML = 1; } Metronome.prototype.stop = function(){ window.clearInterval(this.interval); counter.innerHTML = ""; } }
Clear counter when Metronome is stopped
Clear counter when Metronome is stopped
JavaScript
mit
dmilburn/beatrice,dmilburn/beatrice
dba8dc2f41ffdf023bbfb8dbf92826c6c799a0b0
js/nbpreview.js
js/nbpreview.js
(function () { var root = this; var $file_input = document.querySelector("input#file"); var $holder = document.querySelector("#notebook-holder"); var render_notebook = function (ipynb) { var notebook = root.notebook = nb.parse(ipynb); while ($holder.hasChildNodes()) { $holder.removeChild($holder.lastChild); } $holder.appendChild(notebook.render()); Prism.highlightAll(); }; $file_input.onchange = function (e) { var reader = new FileReader(); reader.onload = function (e) { var parsed = JSON.parse(this.result); render_notebook(parsed); }; reader.readAsText(this.files[0]); }; }).call(this);
(function () { var root = this; var $file_input = document.querySelector("input#file"); var $holder = document.querySelector("#notebook-holder"); var render_notebook = function (ipynb) { var notebook = root.notebook = nb.parse(ipynb); while ($holder.hasChildNodes()) { $holder.removeChild($holder.lastChild); } $holder.appendChild(notebook.render()); Prism.highlightAll(); }; var load_file = function (file) { var reader = new FileReader(); reader.onload = function (e) { var parsed = JSON.parse(this.result); render_notebook(parsed); }; reader.readAsText(file); }; $file_input.onchange = function (e) { load_file(this.files[0]); }; window.addEventListener('dragover', function (e) { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a root.document.body.style.opacity = 0.5; }, false); window.addEventListener('dragleave', function (e) { root.document.body.style.opacity = 1; }, false); window.addEventListener('drop', function (e) { e.stopPropagation(); e.preventDefault(); load_file(e.dataTransfer.files[0]); $file_input.style.display = "none"; root.document.body.style.opacity = 1; }, false); }).call(this);
Add support for dropping files into window.
Add support for dropping files into window.
JavaScript
mit
jsvine/nbpreview,jsvine/nbpreview
c3f9e5eff4b8b7e7de0e4a6f7da1faad077b23ee
templates/system/modules/ph7cms-donation/themes/base/js/donationbox.js
templates/system/modules/ph7cms-donation/themes/base/js/donationbox.js
/* * Author: Pierre-Henry Soria <hello@ph7cms.com> * Copyright: (c) 2015-2017, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $validationBox = (function () { $.get(pH7Url.base + 'ph7cms-donation/main/donationbox', function (oData) { $.colorbox({ width: '100%', maxWidth: '450px', maxHeight: '85%', speed: 500, scrolling: false, html: $(oData).find('#box_block') }) }) }); $validationBox();
/* * Author: Pierre-Henry Soria <hello@ph7cms.com> * Copyright: (c) 2015-2017, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $validationBox = (function () { $.get(pH7Url.base + 'ph7cms-donation/main/donationbox', function (oData) { $.colorbox({ width: '100%', width: '200px', height: '155px', speed: 500, scrolling: false, html: $(oData).find('#box_block') }) }) }); $validationBox();
Change size of donation popup
Change size of donation popup
JavaScript
mit
pH7Software/pH7-Social-Dating-CMS,pH7Software/pH7-Social-Dating-CMS,pH7Software/pH7-Social-Dating-CMS,pH7Software/pH7-Social-Dating-CMS
d4660759d672c90a23fe0944082cff0083d691a0
src/main.js
src/main.js
import Vue from 'vue'; import VueResource from 'vue-resource'; import VueRouter from 'vue-router'; import App from './App.vue'; import About from './components/About.vue'; import store from './store'; import routes from './router'; import components from './components'; import filters from './filters' Vue.use(VueResource); Vue.use(VueRouter); components(Vue); filters(Vue); export const router = new VueRouter({ routes: routes, base: __dirname }); new Vue({ router, store, el: '#app', components: { App } });
import Vue from 'vue'; import VueResource from 'vue-resource'; import VueRouter from 'vue-router'; import App from './App.vue'; import About from './components/About.vue'; import store from './store'; import routes from './router'; import components from './components'; import filters from './filters' Vue.use(VueResource); Vue.use(VueRouter); components(Vue); filters(Vue); export const router = new VueRouter({ mode: 'history', routes: routes, base: __dirname }); new Vue({ router, store, el: '#app', components: { App } });
Switch router to history mode
Switch router to history mode
JavaScript
mit
dmurtari/mbu-frontend,dmurtari/mbu-frontend
a1694721011727b4570e21d444e6b23835d42a1c
src/main.js
src/main.js
'use strict'; var resourcify = angular.module('resourcify', []); function resourcificator ($http, $q) { var $resourcifyError = angular.$$minErr('resourcify'), requestOptions = ['query', 'get', '$get', '$save', '$update', '$delete'], requestMethods = { 'query': 'GET', 'get': 'GET', '$get': 'GET', '$save': 'POST', '$update': 'PUT', '$delete': 'DELETE' }, validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'], bodyMethods = ['$save', '$update', '$delete', 'PUT', 'POST', 'DELETE', 'PATCH']; function validMethod (method) { if (!~validMethods.indexOf(method)) { throw $resourcifyError('requesttype', '"@{0}" is not a valid request method.', method); } return method; } function replaceParams (params, url) { } } resourcificator.$inject = ['$http', '$q']; resourcify.service('resourcify', resourcificator);
'use strict'; var resourcify = angular.module('resourcify', []); function resourcificator ($http, $q) { var $resourcifyError = angular.$$minErr('resourcify'), requestOptions = ['query', 'get', '$get', '$save', '$update', '$delete'], requestMethods = { 'query': 'GET', 'get': 'GET', '$get': 'GET', '$save': 'POST', '$update': 'PUT', '$delete': 'DELETE' }, bodyMethods = ['$save', '$update', '$delete', 'PUT', 'POST', 'DELETE', 'PATCH']; // Finds and replaces query params and path params function replaceParams (params, url) { var findParam = /[\/=](:\w*[a-zA-Z]\w*)/g, copiedPath = angular.copy(url); } } resourcificator.$inject = ['$http', '$q']; resourcify.service('resourcify', resourcificator);
Add regex for finding path params
Add regex for finding path params
JavaScript
mit
erikdonohoo/resourcify,erikdonohoo/resourcify
b3827c12d2092ec93813470ec0b9a81d4d554d08
lib/client/satisfactionratings.js
lib/client/satisfactionratings.js
//SatisfactionRatings.js: Client for the zendesk API. var util = require('util'), Client = require('./client').Client, defaultgroups = require('./helpers').defaultgroups; var SatisfactionRatings = exports.SatisfactionRatings = function (options) { this.jsonAPIName = 'satisfaction_ratings'; Client.call(this, options); }; // Inherit from Client base object util.inherits(SatisfactionRatings, Client); // ######################################################## SatisfactionRatings // ====================================== Listing SatisfactionRatings SatisfactionRatings.prototype.list = function (cb) { this.requestAll('GET', ['satisfaction_ratings'], cb);//all }; SatisfactionRatings.prototype.received = function (cb) { this.requestAll('GET', ['satisfaction_ratings', 'received'], cb);//all }; SatisfactionRatings.prototype.show = function (satisfactionRatingID, cb) { this.request('GET', ['satisfaction_ratings', satisfactionRatingID], cb);//all };
//SatisfactionRatings.js: Client for the zendesk API. var util = require('util'), Client = require('./client').Client, defaultgroups = require('./helpers').defaultgroups; var SatisfactionRatings = exports.SatisfactionRatings = function (options) { this.jsonAPIName = 'satisfaction_ratings'; Client.call(this, options); }; // Inherit from Client base object util.inherits(SatisfactionRatings, Client); // ######################################################## SatisfactionRatings // ====================================== Listing SatisfactionRatings SatisfactionRatings.prototype.list = function (cb) { this.requestAll('GET', ['satisfaction_ratings'], cb);//all }; SatisfactionRatings.prototype.received = function (cb) { this.requestAll('GET', ['satisfaction_ratings', 'received'], cb);//all }; SatisfactionRatings.prototype.show = function (satisfactionRatingID, cb) { this.request('GET', ['satisfaction_ratings', satisfactionRatingID], cb);//all }; // ====================================== Posting SatisfactionRatings SatisfactionRatings.prototype.create = function (ticketID, satisfactionRating, cb) { this.request('POST', ['tickets', ticketId, 'satisfaction_rating'], satisfactionRating, cb); };
Add support for creating Satisfaction Ratings
Add support for creating Satisfaction Ratings As documented at https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#create-a-satisfaction-rating
JavaScript
mit
blakmatrix/node-zendesk,blakmatrix/node-zendesk
789eb9cc78ecaf8e7e04dc8ca1dc8ac7b48f86de
src/node.js
src/node.js
import fs from 'fs'; import { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export const renderToStream = function(element) { return pdf(element).toBuffer(); }; export const renderToFile = function(element, filePath, callback) { const output = renderToStream(element); const stream = fs.createWriteStream(filePath); output.pipe(stream); return new Promise((resolve, reject) => { stream.on('finish', () => { if (callback) callback(output, filePath); resolve(output); }); stream.on('error', reject); }); }; export const render = renderToFile; export { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export default { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, renderToStream, renderToFile, render, };
import fs from 'fs'; import { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export const renderToStream = function(element) { return pdf(element).toBuffer(); }; export const renderToFile = function(element, filePath, callback) { const output = renderToStream(element); const stream = fs.createWriteStream(filePath); output.pipe(stream); return new Promise((resolve, reject) => { stream.on('finish', () => { if (callback) callback(output, filePath); resolve(output); }); stream.on('error', reject); }); }; const throwEnvironmentError = name => { throw new Error( `${name} is a web specific API. Or you're either using this component on Node, or your bundler is not loading react-pdf from the appropiate web build.`, ); }; export const PDFViewer = () => { throwEnvironmentError('PDFViewer'); }; export const PDFDownloadLink = () => { throwEnvironmentError('PDFDownloadLink'); }; export const BlobProvider = () => { throwEnvironmentError('BlobProvider'); }; export const render = renderToFile; export { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export default { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, renderToStream, renderToFile, render, };
Throw error when trying to use web specific APIs on Node
Throw error when trying to use web specific APIs on Node
JavaScript
mit
diegomura/react-pdf,diegomura/react-pdf
caf9ce480560406d0354cf20a93323e2e08ca7c1
src/app/rules/references.service.js
src/app/rules/references.service.js
define(['rules/rules.module' ], function() { angular.module('rules').factory('references', [ function() { function generateReference(query) { var url = ('#/rules/explain?inference=' + encodeURIComponent(angular.toJson(query, false))); var reference = { P854: [{ datatype: 'url', datavalue: { type: 'string', value: url }, snaktype: 'value', property: 'P854' }] }; return [{ snaks: reference, 'snaks-order': ['P854'] }]; } return { generateReference: generateReference }; }]); return {}; });
define(['rules/rules.module' ], function() { angular.module('rules').factory('references', [ function() { function generateReference(query) { var bindings = []; angular.forEach(query.bindings, function(binding) { if ('id' in binding) { bindings.push(binding.id); } }); var info = { rule: query.rule, query: query.query, bindings: bindings, constraints: query.constraints }; var url = ('#/rules/explain?inference=' + encodeURIComponent(angular.toJson(info, false))); var reference = { P854: [{ datatype: 'url', datavalue: { type: 'string', value: url }, snaktype: 'value', property: 'P854' }] }; return [{ snaks: reference, 'snaks-order': ['P854'] }]; } return { generateReference: generateReference }; }]); return {}; });
Reduce amount of information in reference links
Reduce amount of information in reference links
JavaScript
apache-2.0
Wikidata/SQID,Wikidata/WikidataClassBrowser,Wikidata/WikidataClassBrowser,Wikidata/SQID,Wikidata/SQID,Wikidata/WikidataClassBrowser,Wikidata/SQID,Wikidata/SQID,Wikidata/SQID,Wikidata/SQID
af9403793eefb5b3ee0217b077cb41a480251667
test/helpers.js
test/helpers.js
const Bluebird = require('bluebird'); const mongoose = require('mongoose'); const Alternative = require('../app/models/alternative'); const Election = require('../app/models/election'); const Vote = require('../app/models/vote'); const User = require('../app/models/user'); exports.dropDatabase = () => mongoose.connection.dropDatabase().then(() => mongoose.disconnect()); exports.clearCollections = () => Bluebird.map([Alternative, Election, Vote, User], collection => collection.remove() ); const hash = '$2a$10$qxTI.cWwa2kwcjx4SI9KAuV4KxuhtlGOk33L999UQf1rux.4PBz7y'; // 'password' const testUser = (exports.testUser = { username: 'testuser', cardKey: '99TESTCARDKEY', hash }); const adminUser = (exports.adminUser = { username: 'admin', admin: true, cardKey: '55TESTCARDKEY', hash }); exports.createUsers = () => User.create([testUser, adminUser]);
const Bluebird = require('bluebird'); const mongoose = require('mongoose'); const Alternative = require('../app/models/alternative'); const Election = require('../app/models/election'); const Vote = require('../app/models/vote'); const User = require('../app/models/user'); exports.dropDatabase = () => mongoose.connection.dropDatabase().then(() => mongoose.disconnect()); exports.clearCollections = () => Bluebird.map([Alternative, Election, Vote, User], collection => collection.remove() ); const hash = '$2a$10$qxTI.cWwa2kwcjx4SI9KAuV4KxuhtlGOk33L999UQf1rux.4PBz7y'; // 'password' const testUser = (exports.testUser = { username: 'testuser', cardKey: '99TESTCARDKEY', hash }); const adminUser = (exports.adminUser = { username: 'admin', admin: true, moderator: true, cardKey: '55TESTCARDKEY', hash }); exports.createUsers = () => User.create([testUser, adminUser]);
Make new code pass all new tests
Make new code pass all new tests This was done by setting the moderator flag in the helper function that creates admin users.
JavaScript
mit
webkom/vote,webkom/vote,webkom/vote,webkom/vote
1657a56ec025e6670d72c20f1cf87f80ab9c7de6
lib/throttle.js
lib/throttle.js
'use strict'; module.exports = (api) => { api.metasync.throttle = ( // Function throttling timeout, // time interval fn, // function to be executed once per timeout args // arguments array for fn (optional) ) => { let timer = null; let wait = false; return function throttled() { if (!timer) { timer = setTimeout(() => { timer = null; if (wait) throttled(); }, timeout); if (args) fn(...args); else fn(); wait = false; } else { wait = true; } }; }; api.metasync.debounce = ( timeout, fn, args = [] ) => { let timer; return () => { clearTimeout(timer); timer = setTimeout(() => fn(...args), timeout); }; }; api.metasync.timeout = ( // Set timeout for function execution timeout, // time interval asyncFunction, // async function to be executed // done - callback function done // callback function on done ) => { let finished = false; done = api.metasync.cb(done); const timer = setTimeout(() => { if (!finished) { finished = true; done(); } }, timeout); asyncFunction(() => { if (!finished) { clearTimeout(timer); finished = true; done(); } }); }; };
'use strict'; module.exports = (api) => { api.metasync.throttle = ( // Function throttling timeout, // time interval fn, // function to be executed once per timeout args // arguments array for fn (optional) ) => { let timer = null; let wait = false; return function throttled() { if (!timer) { timer = setTimeout(() => { timer = null; if (wait) throttled(); }, timeout); if (args) fn(...args); else fn(); wait = false; } else { wait = true; } }; }; api.metasync.debounce = ( timeout, fn, args = [] ) => { let timer; return () => { clearTimeout(timer); timer = setTimeout(() => fn(...args), timeout); }; }; api.metasync.timeout = ( // Set timeout for function execution timeout, // time interval asyncFunction, // async function to be executed // done - callback function done // callback function on done ) => { let finished = false; done = api.metasync.cb(done); const timer = setTimeout(() => { if (!finished) { finished = true; done(null); } }, timeout); asyncFunction((err, data) => { if (!finished) { clearTimeout(timer); finished = true; done(err, data); } }); }; };
Add null as error argument for callback
Add null as error argument for callback Refs: #13 PR-URL: https://github.com/metarhia/metasync/pull/152 Reviewed-By: Timur Shemsedinov <6dc7cb6a9fcface2186172df883b5c9ab417ae33@gmail.com>
JavaScript
mit
metarhia/MetaSync,DzyubSpirit/MetaSync,DzyubSpirit/MetaSync
204918caff2feeff82f10300364edd43b8e1f4ea
lib/versions.js
lib/versions.js
var semver = require('semver'); var versions = module.exports; /** Returns a number representation of the version number that can be compared with other such representations e.g. compareable('0.6.12') > compareable('0.6.10') */ versions.compareable = function compareable(ver) { var parts = ver.split('.'); return parseInt(parts.map(function(d){ while(d.length < 3) d = '0'+d; return d; }).join(''), 10); } /* Returns the matching version number in a list of sorted version numbers */ versions.find = function(version_spec, list, cb) { var v, i = list.length-1; if(version_spec.match(/^stable$/i)) { if(i >= 0) do { v = list[i--] }while(v && parseInt(v.split('.')[1]) % 2 != 0 && i >= 0);// search for an even number: e.g. 0.2.0 }else if(version_spec.match(/^latest$/i)) { v = list[list.length-1]; }else{ if(i >= 0) do { v = list[i--] }while(v && !semver.satisfies(v, version_spec) && i >= 0); if(!semver.satisfies(v, version_spec)) v = null; } if(!v) return cb(new Error('Version spec didn\'t match any available version')); cb(null, v); };
var semver = require('semver'); var versions = module.exports; /** Returns a number representation of the version number that can be compared with other such representations e.g. compareable('0.6.12') > compareable('0.6.10') */ versions.compareable = function compareable(ver) { var parts = ver.split('.'); return parseInt(parts.map(function(d){ while(d.length < 3) d = '0'+d; return d; }).join(''), 10); } /* Returns the matching version number in a list of sorted version numbers */ versions.find = function(version_spec, list, cb) { var v, i = list.length-1; if(version_spec.match(/^stable$/i)) { if(i >= 0) do { v = list[i--] }while(v && parseInt(v.split('.')[1]) % 2 != 0 && i >= 0);// search for an even number: e.g. 0.2.0 }else if(version_spec.match(/^latest$/i)) { v = list[list.length-1]; }else{ if(i >= 0) do { v = list[i--] }while(v && !semver.satisfies(v, version_spec) && i >= 0); if(!semver.satisfies(v, version_spec)) v = null; } if(!v) return cb(new Error('Version spec, "' + version_spec + '", didn\'t match any available version')); cb(null, v); };
Write out version spec that's being used, to make version errors more intuitive.
Write out version spec that's being used, to make version errors more intuitive.
JavaScript
mit
marcelklehr/nodist,marcelklehr/nodist,marcelklehr/nodist,nullivex/nodist,nullivex/nodist,nullivex/nodist
b933f6e2ba5915d248a954c4c322b91d452d5182
lib/errors/mfarequirederror.js
lib/errors/mfarequirederror.js
/** * Module dependencies. */ var TokenError = require('./tokenerror'); /** * `TokenError` error. * * @api public */ function MFARequiredError(message, uri, user) { TokenError.call(this, message, 'mfa_required', uri); Error.captureStackTrace(this, arguments.callee); this.name = 'MFARequiredError'; this.user = user; } /** * Inherit from `TokenError`. */ MFARequiredError.prototype.__proto__ = TokenError.prototype; /** * Expose `MFARequiredError`. */ module.exports = MFARequiredError;
/** * Module dependencies. */ var TokenError = require('./tokenerror'); /** * `TokenError` error. * * @api public */ function MFARequiredError(message, uri, user, areq) { TokenError.call(this, message, 'mfa_required', uri); Error.captureStackTrace(this, arguments.callee); this.name = 'MFARequiredError'; this.user = user; this.req = areq; } /** * Inherit from `TokenError`. */ MFARequiredError.prototype.__proto__ = TokenError.prototype; /** * Expose `MFARequiredError`. */ module.exports = MFARequiredError;
Add request to MFA error for keeping session context.
Add request to MFA error for keeping session context.
JavaScript
mit
jaredhanson/oauth2orize-2fa
adaa54ca513706ad15f858d318dd02895b3a6445
src/register-element.js
src/register-element.js
import * as privateMethods from './elements/private-methods.js'; const callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback']; export default function registerElement(tagName, Constructor) { // The WebIDL bindings generated this, thinking that they were in an ES6 world where the constructor they created // would be the same as the one registered with the system. So delete it and replace it with the one generated by // `document.registerElement`. delete window[Constructor.name]; const GeneratedConstructor = window[Constructor.name] = document.registerElement(tagName, Constructor); // Delete any custom element callbacks since native elements don't have them and we don't want that kind of // observable difference. Their presence only matters at registration time anyway. for (const callback of callbacks) { delete GeneratedConstructor[callback]; } // Register the appropriate private methods under the generated constructor name, since when they are looked up at // runtime it will be with that name. This is a band-aid until https://w3c.github.io/webcomponents/spec/custom/#es6 // lands. const privateMethodsForConstructor = privateMethods.getAll(Constructor.name); if (privateMethodsForConstructor) { const registerElementGeneratedName = GeneratedConstructor.name; privateMethods.setAll(registerElementGeneratedName, privateMethodsForConstructor); } }
import * as privateMethods from './elements/private-methods.js'; const callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback']; export default function registerElement(tagName, Constructor) { // The WebIDL bindings generated this, thinking that they were in an ES6 world where the constructor they created // would be the same as the one registered with the system. So delete it and replace it with the one generated by // `document.registerElement`. delete window[Constructor.name]; const GeneratedConstructor = window[Constructor.name] = document.registerElement(tagName, Constructor); // Delete any custom element callbacks since native elements don't have them and we don't want that kind of // observable difference. Their presence only matters at registration time anyway. for (const callback of callbacks) { delete GeneratedConstructor.prototype[callback]; } // Register the appropriate private methods under the generated constructor name, since when they are looked up at // runtime it will be with that name. This is a band-aid until https://w3c.github.io/webcomponents/spec/custom/#es6 // lands. const privateMethodsForConstructor = privateMethods.getAll(Constructor.name); if (privateMethodsForConstructor) { const registerElementGeneratedName = GeneratedConstructor.name; privateMethods.setAll(registerElementGeneratedName, privateMethodsForConstructor); } }
Fix logic for removing the custom element callbacks
Fix logic for removing the custom element callbacks
JavaScript
apache-2.0
domenic/html-as-custom-elements,domenic/html-as-custom-elements,zenorocha/html-as-custom-elements,valmzetvn/html-as-custom-elements,valmzetvn/html-as-custom-elements,valmzetvn/html-as-custom-elements,domenic/html-as-custom-elements,zenorocha/html-as-custom-elements
6e08a454f936d58fc5fc1720e7a74d94b3bc9c9e
demo/simple.js
demo/simple.js
'use strict'; var sandboxFactory = require('..'), MemoryFS = require('memory-fs'), memoryFS = new MemoryFS(), sandbox = sandboxFactory.create(memoryFS); memoryFS.mkdirpSync('/my/dir'); memoryFS.writeFileSync( '/my/dir/file1.js', 'console.log("File1"); require("./file2.js"); console.log("Then"); require("/my/dir"); console.log("End");' ); memoryFS.writeFileSync( '/my/dir/index.js', 'console.log("Index");' ); memoryFS.writeFileSync( '/my/dir/file2.js', 'console.log("File2");' ); sandbox.execute('require("/my/dir/file1");');
'use strict'; var sandboxFactory = require('..'), mockFS = require('mock-fs').fs(), sandbox = sandboxFactory.create(mockFS); mockFS.mkdirSync('/my'); mockFS.mkdirSync('/my/dir'); mockFS.writeFileSync( '/my/dir/file1.js', 'console.log("File1"); require("./file2.js"); console.log("Then"); require("/my/dir"); console.log("End");' ); mockFS.writeFileSync( '/my/dir/index.js', 'console.log("Index");' ); mockFS.writeFileSync( '/my/dir/file2.js', 'console.log("File2");' ); sandbox.execute('require("/my/dir/file1");');
Switch demo to use mock-fs rather than memory-fs
Switch demo to use mock-fs rather than memory-fs
JavaScript
mit
asmblah/playpit
f9069b0f601cfa508da172be105f1d0be35acd4c
js/views/ViewManager.js
js/views/ViewManager.js
import HomeView from './HomeView'; import JoinView from './JoinView'; export default class ViewManager { constructor(target) { this.target = target; this.home = new HomeView(); this.join = new JoinView(); this.load('home'); } load(viewName) { this[viewName].init().then(view => { // First remove all Childs while(this.target.firstChild) { this.target.removeChild(this.target.firstChild); } // Then load the view into it view.show(this.target); }); } }
import HomeView from './HomeView'; import JoinView from './JoinView'; export default class ViewManager { constructor(target) { this.target = target; // Register all known views this.home = new HomeView(); this.join = new JoinView(); // Define default view this.DEFAULT_VIEW = 'home'; // Init URL bar and history this.init(); } init() { if(location.hash == '') location.hash = '/'; // Load the view given in the URL this.load(location.hash.substr(2), true); // Check history back and forward to load the correct view window.addEventListener('popstate', event => { this.load(location.hash.substr(2), true); }); } load(viewName = '', nohistory = false) { // Check if view exists if(!this[viewName || this.DEFAULT_VIEW]) viewName = 'notfound'; // Init the new view (load template etc.) this[viewName || this.DEFAULT_VIEW].init().then(view => { // Push the new view to the URL and the history if(!nohistory) history.pushState(null, viewName || this.DEFAULT_VIEW, `#/${viewName}`); // Remove the old view while(this.target.firstChild) { this.target.removeChild(this.target.firstChild); } // Load the view view.show(this.target); }); } }
Add URL support with history.pushState
Add URL support with history.pushState
JavaScript
mit
richterdennis/CastleCrush,richterdennis/CastleCrush
e0fcee4687d0d97fefcef72bc828fcfb0a197da1
src/validations/html.js
src/validations/html.js
var Promise = require('es6-promise').Promise; var lodash = require('lodash'); var validateWithHtmllint = require('./html/htmllint.js'); var validateWithSlowparse = require('./html/slowparse.js'); function filterErrors(errors) { var indexedErrors = lodash(errors).indexBy('reason'); var suppressedTypes = indexedErrors. values(). map('suppresses'). flatten(). value(); return indexedErrors.omit(suppressedTypes).values().value(); } module.exports = function(source) { return Promise.all([ validateWithSlowparse(source), validateWithHtmllint(source), ]).then(function(results) { var filteredErrors = filterErrors(lodash.flatten(results)); return lodash.sortBy(filteredErrors, 'row'); }); };
var Promise = require('es6-promise').Promise; var lodash = require('lodash'); var validateWithHtmllint = require('./html/htmllint.js'); var validateWithSlowparse = require('./html/slowparse.js'); function filterErrors(errors) { var groupedErrors = lodash(errors).groupBy('reason'); var suppressedTypes = groupedErrors. values(). flatten(). map('suppresses'). flatten(). value(); return groupedErrors.omit(suppressedTypes).values().flatten().value(); } module.exports = function(source) { return Promise.all([ validateWithSlowparse(source), validateWithHtmllint(source), ]).then(function(results) { var filteredErrors = filterErrors(lodash.flatten(results)); return lodash.sortBy(filteredErrors, 'row'); }); };
Allow the same error on different lines
Allow the same error on different lines
JavaScript
mit
jwang1919/popcode,jwang1919/popcode,jwang1919/popcode,jwang1919/popcode,popcodeorg/popcode,outoftime/learnpad,outoftime/learnpad,popcodeorg/popcode,popcodeorg/popcode,popcodeorg/popcode
87f7091e84b9cad0589160584f85d979b21df4e8
lib/rules_inline/backticks.js
lib/rules_inline/backticks.js
// Parse backticks 'use strict'; module.exports = function backtick(state, silent) { var start, max, marker, matchStart, matchEnd, token, pos = state.pos, ch = state.src.charCodeAt(pos); if (ch !== 0x60/* ` */) { return false; } start = pos; pos++; max = state.posMax; while (pos < max && state.src.charCodeAt(pos) === 0x60/* ` */) { pos++; } marker = state.src.slice(start, pos); matchStart = matchEnd = pos; while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) { matchEnd = matchStart + 1; while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60/* ` */) { matchEnd++; } if (matchEnd - matchStart === marker.length) { if (!silent) { token = state.push('code_inline', 'code', 0); token.markup = marker; token.content = state.src.slice(pos, matchStart) .replace(/\n/g, ' ') .replace(/^ (.+) $/, '$1'); } state.pos = matchEnd; return true; } } if (!silent) { state.pending += marker; } state.pos += marker.length; return true; };
// Parse backticks 'use strict'; module.exports = function backtick(state, silent) { var start, max, marker, matchStart, matchEnd, token, pos = state.pos, ch = state.src.charCodeAt(pos); if (ch !== 0x60/* ` */) { return false; } start = pos; pos++; max = state.posMax; while (pos < max && state.src.charCodeAt(pos) === 0x60/* ` */) { pos++; } marker = state.src.slice(start, pos); matchStart = matchEnd = pos; while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) { matchEnd = matchStart + 1; while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60/* ` */) { matchEnd++; } if (matchEnd - matchStart === marker.length) { if (!silent) { token = state.push('code_inline', 'code', 0); token.markup = marker; token.content = state.src.slice(pos, matchStart) .replace(/\n/g, ' ') .replace(/^ (.+) $/, '$1'); token.position = start; token.size = (matchStart + 1) - token.position; } state.pos = matchEnd; return true; } } if (!silent) { state.pending += marker; } state.pos += marker.length; return true; };
Add position and size to code_inline
Add position and size to code_inline
JavaScript
mit
GerHobbelt/markdown-it,GerHobbelt/markdown-it
9b6c06ddb62f358a73e3d243c9533c068a5b0bda
app/assets/javascripts/directives/validation/reset_validation_status.js
app/assets/javascripts/directives/validation/reset_validation_status.js
ManageIQ.angular.app.directive('resetValidationStatus', ['$rootScope', function($rootScope) { return { require: 'ngModel', link: function (scope, elem, attrs, ctrl) { scope.$watch(attrs.ngModel, function() { adjustValidationStatus(ctrl.$modelValue, scope, ctrl, attrs, $rootScope); }); ctrl.$parsers.push(function(value) { adjustValidationStatus(value, scope, ctrl, attrs, $rootScope); return value; }); } } }]); var adjustValidationStatus = function(value, scope, ctrl, attrs, rootScope) { if(scope.checkAuthentication === true && angular.isDefined(scope.postValidationModel)) { var modelPostValidationObject = angular.copy(scope.postValidationModel[attrs.prefix]); delete modelPostValidationObject[ctrl.$name]; var modelObject = angular.copy(scope[scope.model]); if(angular.isDefined(modelObject[ctrl.$name])) { delete modelObject[ctrl.$name]; } if (value == scope.postValidationModel[attrs.prefix][ctrl.$name] && _.isMatch(modelObject, modelPostValidationObject)) { scope[scope.model][attrs.resetValidationStatus] = true; rootScope.$broadcast('clearErrorOnTab', {tab: attrs.prefix}); } else { scope[scope.model][attrs.resetValidationStatus] = false; rootScope.$broadcast('setErrorOnTab', {tab: attrs.prefix}); } } };
ManageIQ.angular.app.directive('resetValidationStatus', ['$rootScope', function($rootScope) { return { require: 'ngModel', link: function (scope, elem, attrs, ctrl) { scope.$watch(attrs.ngModel, function() { adjustValidationStatus(ctrl.$modelValue, scope, ctrl, attrs, $rootScope); }); ctrl.$parsers.push(function(value) { adjustValidationStatus(value, scope, ctrl, attrs, $rootScope); return value; }); } } }]); var adjustValidationStatus = function(value, scope, ctrl, attrs, rootScope) { if(scope.checkAuthentication === true && angular.isDefined(scope.postValidationModel) && angular.isDefined(scope.postValidationModel[attrs.prefix])) { var modelPostValidationObject = angular.copy(scope.postValidationModel[attrs.prefix]); delete modelPostValidationObject[ctrl.$name]; var modelObject = angular.copy(scope[scope.model]); if(angular.isDefined(modelObject[ctrl.$name])) { delete modelObject[ctrl.$name]; } if (value == scope.postValidationModel[attrs.prefix][ctrl.$name] && _.isMatch(modelObject, modelPostValidationObject)) { scope[scope.model][attrs.resetValidationStatus] = true; rootScope.$broadcast('clearErrorOnTab', {tab: attrs.prefix}); } else { scope[scope.model][attrs.resetValidationStatus] = false; rootScope.$broadcast('setErrorOnTab', {tab: attrs.prefix}); } } };
Check if postValidationModel is defined for the tab in question
Check if postValidationModel is defined for the tab in question
JavaScript
apache-2.0
fbladilo/manageiq,agrare/manageiq,durandom/manageiq,mkanoor/manageiq,borod108/manageiq,matobet/manageiq,NickLaMuro/manageiq,josejulio/manageiq,aufi/manageiq,maas-ufcg/manageiq,maas-ufcg/manageiq,d-m-u/manageiq,tinaafitz/manageiq,matobet/manageiq,mzazrivec/manageiq,kbrock/manageiq,ilackarms/manageiq,jvlcek/manageiq,romaintb/manageiq,ManageIQ/manageiq,romaintb/manageiq,billfitzgerald0120/manageiq,mkanoor/manageiq,gmcculloug/manageiq,romanblanco/manageiq,jameswnl/manageiq,djberg96/manageiq,NickLaMuro/manageiq,pkomanek/manageiq,jntullo/manageiq,d-m-u/manageiq,israel-hdez/manageiq,fbladilo/manageiq,josejulio/manageiq,tinaafitz/manageiq,israel-hdez/manageiq,skateman/manageiq,lpichler/manageiq,mresti/manageiq,gmcculloug/manageiq,mzazrivec/manageiq,chessbyte/manageiq,KevinLoiseau/manageiq,juliancheal/manageiq,mzazrivec/manageiq,KevinLoiseau/manageiq,kbrock/manageiq,skateman/manageiq,jvlcek/manageiq,romanblanco/manageiq,fbladilo/manageiq,maas-ufcg/manageiq,gerikis/manageiq,durandom/manageiq,matobet/manageiq,jntullo/manageiq,pkomanek/manageiq,romaintb/manageiq,branic/manageiq,branic/manageiq,d-m-u/manageiq,jrafanie/manageiq,branic/manageiq,ailisp/manageiq,romaintb/manageiq,ManageIQ/manageiq,jameswnl/manageiq,mfeifer/manageiq,juliancheal/manageiq,djberg96/manageiq,ailisp/manageiq,jameswnl/manageiq,gerikis/manageiq,syncrou/manageiq,lpichler/manageiq,jrafanie/manageiq,hstastna/manageiq,KevinLoiseau/manageiq,matobet/manageiq,tinaafitz/manageiq,romanblanco/manageiq,kbrock/manageiq,romaintb/manageiq,syncrou/manageiq,mresti/manageiq,mfeifer/manageiq,gmcculloug/manageiq,billfitzgerald0120/manageiq,yaacov/manageiq,mfeifer/manageiq,NaNi-Z/manageiq,syncrou/manageiq,gmcculloug/manageiq,mzazrivec/manageiq,KevinLoiseau/manageiq,josejulio/manageiq,kbrock/manageiq,juliancheal/manageiq,agrare/manageiq,ailisp/manageiq,mresti/manageiq,mfeifer/manageiq,josejulio/manageiq,skateman/manageiq,tzumainn/manageiq,djberg96/manageiq,andyvesel/manageiq,mresti/manageiq,ManageIQ/manageiq,andyvesel/manageiq,mkanoor/manageiq,d-m-u/manageiq,maas-ufcg/manageiq,yaacov/manageiq,tinaafitz/manageiq,lpichler/manageiq,romanblanco/manageiq,aufi/manageiq,jrafanie/manageiq,gerikis/manageiq,gerikis/manageiq,jntullo/manageiq,pkomanek/manageiq,maas-ufcg/manageiq,skateman/manageiq,ilackarms/manageiq,maas-ufcg/manageiq,djberg96/manageiq,hstastna/manageiq,mkanoor/manageiq,borod108/manageiq,NaNi-Z/manageiq,NaNi-Z/manageiq,borod108/manageiq,billfitzgerald0120/manageiq,tzumainn/manageiq,tzumainn/manageiq,chessbyte/manageiq,hstastna/manageiq,romaintb/manageiq,borod108/manageiq,branic/manageiq,ilackarms/manageiq,jameswnl/manageiq,NickLaMuro/manageiq,syncrou/manageiq,andyvesel/manageiq,NaNi-Z/manageiq,hstastna/manageiq,juliancheal/manageiq,KevinLoiseau/manageiq,durandom/manageiq,fbladilo/manageiq,NickLaMuro/manageiq,aufi/manageiq,agrare/manageiq,ailisp/manageiq,tzumainn/manageiq,durandom/manageiq,jvlcek/manageiq,aufi/manageiq,israel-hdez/manageiq,ilackarms/manageiq,yaacov/manageiq,billfitzgerald0120/manageiq,yaacov/manageiq,agrare/manageiq,jntullo/manageiq,andyvesel/manageiq,chessbyte/manageiq,jvlcek/manageiq,ManageIQ/manageiq,pkomanek/manageiq,israel-hdez/manageiq,lpichler/manageiq,KevinLoiseau/manageiq,chessbyte/manageiq,jrafanie/manageiq
9dd0b0983b9ae8cf45d9505494e0e0afad9094f7
oui.js
oui.js
#!/usr/bin/env node "use strict"; process.title = "oui"; var arg = process.argv[2], oui = require("./"), spin = require("char-spinner"); if (arg === "--update") { var interval = spin(); oui.update(true, function (err) { clearInterval(interval); if (err) process.stdout.write(err + "\n"); process.exit(err ? 1 : 0); }); } else if (!arg || arg === "--help") { process.stdout.write([ "", " Usage: oui mac [options]", "", " Options:", "", " --help display this help", " --update update the database", "", "" ].join("\n")); process.exit(1); } else { var result; try { result = oui(arg); } catch (err) { process.stdout.write(err.message + "\n"); process.exit(1); } if (result) { process.stdout.write(result + "\n"); } else { process.stdout.write(arg + " not found in database\n"); } process.exit(0); }
#!/usr/bin/env node "use strict"; process.title = "oui"; var arg = process.argv[2], oui = require("./"), spin = require("char-spinner"); if (arg === "--update") { var interval = spin(); oui.update(true, function (err) { clearInterval(interval); if (err) process.stdout.write(err + "\n"); process.exit(err ? 1 : 0); }); } else if (!arg || arg === "--help") { process.stdout.write([ "", " Usage: oui mac [options]", "", " Options:", "", " --help display this help", " --update update the database", "", "" ].join("\n")); process.exit(0); } else { var result; try { result = oui(arg); } catch (err) { process.stdout.write(err.message + "\n"); process.exit(1); } if (result) process.stdout.write(result + "\n"); else process.stdout.write(arg + " not found in database\n"); process.exit(0); }
Correct exit code on help
Correct exit code on help
JavaScript
bsd-2-clause
silverwind/oui
dd2ac1fb52cb9c154d0b9bf354fd22d250413d94
date.polyfill.js
date.polyfill.js
/** * Date.prototype.toISOString() * version 0.0.0 * Feature Chrome Firefox Internet Explorer Opera Safari Edge * Basic support 3 1 9 10.5 5 12 * ------------------------------------------------------------------------------- */ if (!Date.prototype.toISOString) { Date.prototype.toISOString = function () { function pad(number) { if (number < 10) { return '0' + number; } return number; } return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; }; }
/** * Date.prototype.toISOString() * version 0.0.0 * Feature Chrome Firefox Internet Explorer Opera Safari Edge * Basic support 3 1 9 10.5 5 12 * ------------------------------------------------------------------------------- */ if (!Date.prototype.toISOString) { Object.defineProperty(Array.prototype, 'toISOString', { configurable : true, writable : true, value : function () { function pad(number) { if (number < 10) { return '0' + number; } return number; } return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; } }); }
Define all Date toISOString properties with Object.defineProperty, using the descriptors configurable, writable and non-enumerable.
Define all Date toISOString properties with Object.defineProperty, using the descriptors configurable, writable and non-enumerable.
JavaScript
mit
uxitten/polyfill
df3f7f36a5dce3e85660106e79953facfd0c7555
assets/javascripts/p_slides.js
assets/javascripts/p_slides.js
$(".presentation").each(function() { var md = new Remarkable('full', { html: true }); var markup = md.render($(this).html()); var slides = markup.split('<hr>'); var new_document = []; for (var j = 0; j < slides.length; j++) new_document.push('<div class=slide>' + slides[j] + '</div>'); document.write(new_document.join("")); }); $(".presentation").remove(); // If you want to syntax highlight all your code in the same way then // you can uncomment and customize the next line // //$("pre>code").parent().addClass("syntax cpp"); w3c_slidy.add_listener(document.body, "touchend", w3c_slidy.mouse_button_click); $.syntax(); // Automatic detection for theme javascript. It will run after slides // have been generated for(i in document.styleSheets) { stylesheet = document.styleSheets[i].href; if (stylesheet && stylesheet.indexOf("theme") != -1) { theme = stylesheet.slice(stylesheet.lastIndexOf("/")+1, stylesheet.length); eval(theme.replace(".css", "()")); } }
$(".presentation").each(function() { var md = new Remarkable('full', { html: true//, // Here goes a real syntax highlighter //highlight: function (str, lang) { // return str; //} }); var markup = md.render($(this).html()); var slides = markup.split('<hr>'); var new_document = []; for (var j = 0; j < slides.length; j++) new_document.push('<div class=slide>' + slides[j] + '</div>'); document.write(new_document.join("")); }); $(".presentation").remove(); // If you want to syntax highlight all your code in the same way then // you can uncomment and customize the next line // //$("pre>code").parent().addClass("syntax cpp"); w3c_slidy.add_listener(document.body, "touchend", w3c_slidy.mouse_button_click); // XXX: Work Around // RemarkableJS above translates content of <pre> Tags into HTML. // Therefore empty lines will create new paragraphs. Remove those // paragraphs, so that the newlines stay intact for code highlighting. // Note: Indentation is lost and cannot be retrieved here // Note: The better solution is to ditch jquery-syntax and go with // something that can be used together with RemarkableJS. $("pre.syntax").map(function(element) { $(this).html($(this). html(). replace(/<p>/g, "\n"). replace(/<\/p>/g, "")); }); $.syntax(); // Automatic detection for theme javascript. It will run after slides // have been generated for(i in document.styleSheets) { stylesheet = document.styleSheets[i].href; if (stylesheet && stylesheet.indexOf("theme") != -1) { theme = stylesheet.slice(stylesheet.lastIndexOf("/")+1, stylesheet.length); eval(theme.replace(".css", "()")); } }
Add workaround to introduce slightly better syntax highlighting.
Add workaround to introduce slightly better syntax highlighting.
JavaScript
agpl-3.0
munen/p_slides,munen/p_slides
7556ac4105736e6414933cc6bc928c696a625083
readFile.js
readFile.js
/** * Created by Kanthanarasimhaiah on 14/11/13. */ fs = require('fs'); var num_of_tasks; var total_time; var fileName = process.argv[2]; fs.readFile(fileName, 'utf8', function (err,data) { if (err) { return console.log(err); } //console.log(data); var input=data.split('\n'); var line1 = input[0].split(' '); num_of_tasks=parseInt(line1[0], 10); total_time=parseInt(line1[1], 10); console.log("Numer of Tasks:", num_of_tasks); console.log("Total Time:", total_time); // read in the tasks var queue= []; for(var j=1;j<num_of_tasks;j++) { var task_data=input[j].split(' '); var task = {id : task_data[0], start_time : parseInt(task_data[1], 10), duration : parseInt(task_data[2], 10)}; queue.push(task); } function sort_function (a, b) { return a.start_time - b.start_time; } queue.sort(sort_function); console.log("Tasks:"); console.log(queue); });
/** * Created by Kanthanarasimhaiah on 14/11/13. */ fs = require('fs'); function readTasks (file) { var data = fs.readFileSync(file, 'utf8'); var input=data.split('\n'); var line1 = input[0].split(' '); var num_of_tasks=parseInt(line1[0], 10); var total_time=parseInt(line1[1], 10); // read in the tasks var queue= []; for(var j=1;j<num_of_tasks;j++) { var task_data=input[j].split(' '); var task = {id : task_data[0], start_time : parseInt(task_data[1], 10), duration : parseInt(task_data[2], 10)}; queue.push(task); } function sort_function (a, b) { return a.start_time - b.start_time; } queue.sort(sort_function); return {num_of_tasks: num_of_tasks, total_time: total_time, task_queue: queue}; } var fileName = process.argv[2]; var tasks = readTasks(fileName); console.log("Numer of Tasks:", tasks.num_of_tasks); console.log("Total Time:", tasks.total_time); console.log("Task Queue:"); console.log(tasks.task_queue);
Move task reading into a standalone function.
Move task reading into a standalone function. - Also, use readFileSync (synchronous).
JavaScript
mpl-2.0
kanaka/rbt_cfs
76a4a74053b07d7fe6a1d98ee0271173dbc58cf8
App/data/CaretakerRolesGateway/index.js
App/data/CaretakerRolesGateway/index.js
/* Makes API calls to fetch caretaker roles. However, until there is an API to call, it returns canned data. */ export default class CaretakerRolesGateway { static allRoles = null; static getAll() { if(this.allRoles === null) { //api call to get roles this.allRoles = [ {id: 1, name: 'Driver', description: 'Gives rides to things'}, {id: 2, name: 'Coordinator', description: 'Helps coordinate people sign ups'}, {id: 3, name: 'Groceries', description: 'Picks up groceries'}, {id: 4, name: 'Active Friend', description: 'Gets focus out and active (eg, walks) during vulnerable times'}, {id: 5, name: 'Chef', description: 'Cooks food cause yum'} ] } return this.allRoles; } }
/* Makes API calls to fetch caretaker roles. However, until there is an API to call, it returns canned data. */ const createCaretakerRolesGateway = () => { let allRoles = null; return { getAll: () => { if(allRoles === null) { //api call to get roles allRoles = [ {id: 1, name: 'Driver', description: 'Gives rides to things'}, {id: 2, name: 'Coordinator', description: 'Helps coordinate people sign ups'}, {id: 3, name: 'Groceries', description: 'Picks up groceries'}, {id: 4, name: 'Active Friend', description: 'Gets focus out and active (eg, walks) during vulnerable times'}, {id: 5, name: 'Chef', description: 'Cooks food cause yum'} ] } return allRoles; } } } export default createCaretakerRolesGateway();
Refactor CaretakerRolesGateway to use factory pattern
Refactor CaretakerRolesGateway to use factory pattern
JavaScript
mit
araneforseti/caretaker-app,araneforseti/caretaker-app,araneforseti/caretaker-app,araneforseti/caretaker-app
d8867d259040ce0eb240ede3edf9fc15415b299e
.eslintrc.js
.eslintrc.js
module.exports = { "extends": "airbnb", "parser": "babel-eslint", "plugins": [ "react" ], "rules": { "react/prop-types": 0, "space-before-function-paren": [2, { "anonymous": "never", "named": "always" }] } };
module.exports = { "extends": "airbnb", "parser": "babel-eslint", "plugins": [ "react" ], "rules": { "react/prop-types": 0, "react/jsx-boolean-value": 0, "consistent-return": 0, "space-before-function-paren": [2, { "anonymous": "never", "named": "always" }] } };
Add react rules to eslint file
Add react rules to eslint file
JavaScript
mit
mersocarlin/react-webpack-template,mersocarlin/react-webpack-template
8f3ea6b47eb1f4d0265676527652c333c36a21ca
app/latexCommands.js
app/latexCommands.js
module.exports = [ { action: '\\sqrt', label: '\\sqrt{X}' }, { action: '^', label: 'x^{X}' }, { action: '\\frac', label: '\\frac{X}{X}' }, { action: '\\int', label: '\\int_{X}^{X}' }, { action: '\\lim_', label: '\\lim_{X}' }, { action: '\\overrightarrow', label: '\\overrightarrow{X}' }, { action: '_', label: 'x_X' }, { action: '\\nthroot', label: '\\sqrt[X]{X}' }, { action: '\\sum', label: '\\sum_{X}^{X}' }, { action: '\\binom', label: '\\binom{X}{X}' }, { action: '\\sin' }, { action: '\\cos' }, { action: '\\tan' }, { action: '\\arcsin' }, { action: '\\arccos' }, { action: '\\arctan' }, { action: '\\not' }, { action: '\\vec', label: '\\vec{X}' }, { action: '\\bar', label: '\\bar{X}' }, { action: '\\underline', label: '\\underline{X}' }, { action: '\\overleftarrow', label: '\\overleftarrow{X}' }, { action: '|', label: '|X|'}, { action: '(', label: '(X)'} ]
module.exports = [ { action: '\\sqrt', label: '\\sqrt{X}' }, { action: '^', label: 'x^{X}' }, { action: '\\frac', label: '\\frac{X}{X}' }, { action: '\\int', label: '\\int_{X}^{X}' }, { action: '\\lim_', label: '\\lim_{X}' }, { action: '\\overrightarrow', label: '\\overrightarrow{X}' }, { action: '_', label: 'x_X' }, { action: '\\nthroot', label: '\\sqrt[X]{X}' }, { action: '\\sum', label: '\\sum_{X}^{X}' }, { action: '\\binom', label: '\\binom{X}{X}' }, { action: '\\sin' }, { action: '\\cos' }, { action: '\\tan' }, { action: '\\arcsin' }, { action: '\\arccos' }, { action: '\\arctan' }, { action: '\\vec', label: '\\vec{X}' }, { action: '\\bar', label: '\\bar{X}' }, { action: '\\underline', label: '\\underline{X}' }, { action: '\\overleftarrow', label: '\\overleftarrow{X}' }, { action: '|', label: '|X|'}, { action: '(', label: '(X)'} ]
Remove problematic not tool from the equation toolbar;
Remove problematic not tool from the equation toolbar; \not is used in conjunction with other commands such as \equiv or \infty. Mathquill however does not support this and changes \not to \neg.
JavaScript
mit
digabi/rich-text-editor,digabi/math-editor,digabi/math-editor,digabi/rich-text-editor,digabi/rich-text-editor
2030607c7012d78233deb3882f94bdac1fb6aff2
routes/index.js
routes/index.js
const UserController = require('../src/Http/Controllers/User'); const { define, wrap, post, get } = require('spirit-router'); const { json } = require('body-parser'); const express = require('spirit-express'); module.exports = define('/api', [ get('/users', UserController.index), get('/users/:user_id', ['user_id'], UserController.show), wrap(post('/users', ['body'], UserController.store), express(json())), ]);
const UserController = require('../src/Http/Controllers/User'); const { define, wrap, post, get, any, notFound } = require('spirit-router'); const { json } = require('body-parser'); const express = require('spirit-express'); const api = define('/api', [ get('/users', UserController.index), get('/users/:user_id', ['user_id'], UserController.show), wrap(post('/users', ['body'], UserController.store), express(json())), ]); module.exports = define([api, any('*', notFound())]);
Add default not found route
feat: Add default not found route
JavaScript
mit
diogoazevedos/corpus,diogoazevedos/corpus
212b6c3a0ffb9eb7595b3987fa77040cadd92054
.eslintrc.js
.eslintrc.js
module.exports = { extends: ["matrix-org"], plugins: [ "babel", ], env: { browser: true, node: true, }, rules: { "no-var": ["warn"], "prefer-rest-params": ["warn"], "prefer-spread": ["warn"], "one-var": ["warn"], "padded-blocks": ["warn"], "no-extend-native": ["warn"], "camelcase": ["warn"], "no-multi-spaces": ["error", { "ignoreEOLComments": true }], "space-before-function-paren": ["error", { "anonymous": "never", "named": "never", "asyncArrow": "always", }], "arrow-parens": "off", "prefer-promise-reject-errors": "off", "quotes": "off", "indent": "off", "no-constant-condition": "off", "no-async-promise-executor": "off", // We use a `logger` intermediary module "no-console": "error", }, overrides: [{ "files": ["src/**/*.ts"], "extends": ["matrix-org/ts"], "rules": { // While we're converting to ts we make heavy use of this "@typescript-eslint/no-explicit-any": "off", "quotes": "off", }, }], };
module.exports = { extends: ["matrix-org"], plugins: [ "babel", ], env: { browser: true, node: true, }, rules: { "no-var": ["warn"], "prefer-rest-params": ["warn"], "prefer-spread": ["warn"], "one-var": ["warn"], "padded-blocks": ["warn"], "no-extend-native": ["warn"], "camelcase": ["warn"], "no-multi-spaces": ["error", { "ignoreEOLComments": true }], "space-before-function-paren": ["error", { "anonymous": "never", "named": "never", "asyncArrow": "always", }], "arrow-parens": "off", "prefer-promise-reject-errors": "off", "quotes": "off", "indent": "off", "no-constant-condition": "off", "no-async-promise-executor": "off", // We use a `logger` intermediary module "no-console": "error", }, overrides: [{ "files": ["src/**/*.ts"], "extends": ["matrix-org/ts"], "rules": { // We're okay being explicit at the moment "@typescript-eslint/no-empty-interface": "off", // While we're converting to ts we make heavy use of this "@typescript-eslint/no-explicit-any": "off", "quotes": "off", }, }], };
Resolve linting errors after upgrades
Resolve linting errors after upgrades
JavaScript
apache-2.0
matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk
f3ab92fb8626916d7824409c9b514854d28ab51e
www/js/Controllers/nearby.js
www/js/Controllers/nearby.js
angular.module('gitphaser') .controller('NearbyCtrl', NearbyCtrl); // @controller NearbyCtrl // @params: $scope, $reactive // @route: /tab/nearby // // Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter' // Subscription to 'connections' is handled in the route resolve. Also // exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user // clicks on list item to see profile) function NearbyCtrl ($scope, $reactive, Notify, GeoLocate ){ $reactive(this).attach($scope); var self = this; // Slide constants bound to the GeoLocate directive // and other DOM events, trigger updates based on // whether we are looking at List || Map view. self.listSlide = 0 self.mapSlide = 1; self.slide = 0; // Services self.geolocate = GeoLocate; self.notify = Notify; self.helpers({ connections: function () { if (Meteor.userId()){ return Connections.find( {transmitter: Meteor.userId() } ); } } }); };
angular.module('gitphaser').controller('NearbyCtrl', NearbyCtrl); /** * Exposes Meteor mongo 'connections' to DOM, filtered against current user as 'transmitter' * Subscription to 'connections' is handled in the route resolve. Also * exposes GeoLocate service (for the maps view) and Notify service (to trigger notification when user * clicks on list item to see profile) * @controller NearbyCtrl * @route: /tab/nearby */ function NearbyCtrl ($scope, $reactive, Notify, GeoLocate ){ $reactive(this).attach($scope); var self = this; // Slide constants bound to the GeoLocate directive // and other DOM events, trigger updates based on // whether we are looking at List || Map view. self.listSlide = 0 self.mapSlide = 1; self.slide = 0; // Services self.geolocate = GeoLocate; self.notify = Notify; self.helpers({ connections: function () { if (Meteor.userId()){ return Connections.find( {transmitter: Meteor.userId() } ); } } }); };
Test push after changing local remote
Test push after changing local remote
JavaScript
mit
git-phaser/git-phaser,git-phaser/git-phaser,git-phaser/git-phaser,git-phaser/git-phaser
1883460122f4690d84f673ef083d23b95f3abcd5
app/student.front.js
app/student.front.js
const $answer = $('.answer') const {makeRichText} = require('./math-editor') const save = ($elem, async = true) => $.post({ url: '/save', data: {text: $elem.html(), answerId: $elem.attr('id')}, async }) function saveScreenshot(questionId) { return ({data, type, id}) => { return $.post({ type: 'POST', url: `/saveImg?answerId=${questionId}&id=${id}`, data: data, processData: false, contentType: type }).then(res => { console.log('heh', res) return res.url }) } } const richTextOptions = id => ({ screenshot: { saver: data => saveScreenshot(id)(data) } }) $answer.each((i, answer) => { makeRichText(answer, richTextOptions(answer.id)) $.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html)) }).on('keypress', e => { if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') { e.preventDefault() save($(e.target)) } })
const $answer = $('.answer') const {makeRichText} = require('./math-editor') const save = ($elem, async = true) => $.post({ url: '/save', data: {text: $elem.html(), answerId: $elem.attr('id')}, async }) function saveScreenshot(questionId) { return ({data, type, id}) => { return $.post({ type: 'POST', url: `/saveImg?answerId=${questionId}&id=${id}`, data: data, processData: false, contentType: type }).then(res => { console.log('heh', res) return res.url }) } } const richTextOptions = id => ({ screenshot: { saver: data => saveScreenshot(id)(data) } }) $answer.each((i, answer) => { makeRichText(answer, richTextOptions(answer.id)) $.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html)) }).on('keypress', e => { if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') { e.preventDefault() save($(e.target)) } }) $('#answer1').focus()
Set focus automatically to first field
Set focus automatically to first field
JavaScript
mit
digabi/rich-text-editor,digabi/rich-text-editor,digabi/rich-text-editor,digabi/math-editor,digabi/math-editor
7dfbb87add262139525d9981f6024a46bbc52190
src/jupyter_contrib_nbextensions/nbextensions/export_embedded/main.js
src/jupyter_contrib_nbextensions/nbextensions/export_embedded/main.js
// toggle display of all code cells' inputs define([ 'jquery', 'base/js/namespace', 'base/js/events' ], function( $, Jupyter, events ) { "use strict"; function initialize () { console.log("Embedded HTML Exporter loaded!"); } var load_ipython_extension = function() { var dwm = $("#download_menu") var downloadEntry = $('<li id="download_html_embed"><a href="#">HTML Embedded (.html)</a></li>') dwm.append(downloadEntry) downloadEntry.click(function () { Jupyter.menubar._nbconvert('html_embed', true); }); Jupyter.toolbar.add_buttons_group([{ id : 'export_embeddedhtml', label : 'Embedded HTML Export', icon : 'fa-save', callback : function() { Jupyter.menubar._nbconvert('html_embed', true); } }]); if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) { // notebook_loaded.Notebook event has already happened initialize(); } events.on('notebook_loaded.Notebook', initialize); }; return { load_ipython_extension : load_ipython_extension }; });
// toggle display of all code cells' inputs define([ 'jquery', 'base/js/namespace', 'base/js/events' ], function( $, Jupyter, events ) { "use strict"; function initialize () { } var load_ipython_extension = function() { /* Add an entry in the download menu */ var dwm = $("#download_menu") var downloadEntry = $('<li id="download_html_embed"><a href="#">HTML Embedded (.html)</a></li>') dwm.append(downloadEntry) downloadEntry.click(function () { Jupyter.menubar._nbconvert('html_embed', true); }); /* Add also a Button, currently disabled */ /* Jupyter.toolbar.add_buttons_group([{ id : 'export_embeddedhtml', label : 'Embedded HTML Export', icon : 'fa-save', callback : function() { Jupyter.menubar._nbconvert('html_embed', true); } }]); */ if (Jupyter.notebook !== undefined && Jupyter.notebook._fully_loaded) { // notebook_loaded.Notebook event has already happened initialize(); } events.on('notebook_loaded.Notebook', initialize); }; return { load_ipython_extension : load_ipython_extension }; });
Remove Button, only in Download Menu
Remove Button, only in Download Menu
JavaScript
bsd-3-clause
ipython-contrib/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,juhasch/IPython-notebook-extensions
ca0425c4149e8a3dd736abef6a13967d8d656f20
src/audits/UnfocusableElementsWithOnClick.js
src/audits/UnfocusableElementsWithOnClick.js
// Copyright 2012 Google Inc. // // 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 // // http://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. AuditRules.addRule({ name: 'unfocusableElementsWithOnClick', severity: Severity.Warning, opt_shouldRunInDevtools: true, relevantNodesSelector: function() { var potentialOnclickElements = document.querySelectorAll('span, div, img'); var unfocusableClickableElements = []; for (var i = 0; i < potentialOnclickElements.length; i++) { var element = potentialOnclickElements[i]; if (AccessibilityUtils.isElementOrAncestorHidden) continue; var eventListeners = getEventListeners(element); if ('click' in eventListeners) { unfocusableClickableElements.push(element); } } return unfocusableClickableElements; }, test: function(element) { return element.tabIndex == null; } });
// Copyright 2012 Google Inc. // // 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 // // http://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. AuditRules.addRule({ name: 'unfocusableElementsWithOnClick', severity: Severity.Warning, opt_shouldRunInDevtools: true, relevantNodesSelector: function() { var potentialOnclickElements = document.querySelectorAll('*'); var unfocusableClickableElements = []; for (var i = 0; i < potentialOnclickElements.length; i++) { var element = potentialOnclickElements[i]; if (AccessibilityUtils.isElementOrAncestorHidden) continue; var eventListeners = getEventListeners(element); if ('click' in eventListeners) { unfocusableClickableElements.push(element); } } return unfocusableClickableElements; }, test: function(element) { return element.tabIndex == null; } });
Check all elements, not just [span, div, img], for unfocusableElementsWithOnClick
Check all elements, not just [span, div, img], for unfocusableElementsWithOnClick
JavaScript
apache-2.0
japacible/accessibility-developer-tools-extension,modulexcite/accessibility-developer-tools,alice/accessibility-developer-tools,modulexcite/accessibility-developer-tools-extension,ckundo/accessibility-developer-tools,modulexcite/accessibility-developer-tools-extension,kublaj/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,seksanman/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools-extension,googlearchive/accessibility-developer-tools-extension,japacible/accessibility-developer-tools,Khan/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,alice/accessibility-developer-tools,garcialo/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,ricksbrown/accessibility-developer-tools,japacible/accessibility-developer-tools,ckundo/accessibility-developer-tools,japacible/accessibility-developer-tools,alice/accessibility-developer-tools,seksanman/accessibility-developer-tools,t9nf/accessibility-developer-tools,hmrc/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools,japacible/accessibility-developer-tools-extension,seksanman/accessibility-developer-tools,hmrc/accessibility-developer-tools,Khan/accessibility-developer-tools,kristapsmelderis/accessibility-developer-tools,pivotal-cf/accessibility-developer-tools,garcialo/accessibility-developer-tools,GabrielDuque/accessibility-developer-tools,Khan/accessibility-developer-tools,kristapsmelderis/accessibility-developer-tools,GoogleChrome/accessibility-developer-tools-extension,kublaj/accessibility-developer-tools,ckundo/accessibility-developer-tools,minorninth/accessibility-developer-tools,dylanb/accessibility-developer-tools-extension,modulexcite/accessibility-developer-tools,GabrielDuque/accessibility-developer-tools,hmrc/accessibility-developer-tools,t9nf/accessibility-developer-tools,modulexcite/accessibility-developer-tools,garcialo/accessibility-developer-tools,googlearchive/accessibility-developer-tools-extension,GabrielDuque/accessibility-developer-tools,minorninth/accessibility-developer-tools,t9nf/accessibility-developer-tools,kublaj/accessibility-developer-tools,dylanb/accessibility-developer-tools-extension,kristapsmelderis/accessibility-developer-tools,ricksbrown/accessibility-developer-tools
8f5dda30829b7439f0fc49d8e1fe86623980dc3b
dev/grunt/postcss.js
dev/grunt/postcss.js
module.exports = { options: { map: true, // inline sourcemaps processors: [ require('pixrem')(), // add fallbacks for rem units require('autoprefixer-core')({ // add vendor prefixes browsers: [ 'last 3 version', 'ie 8', 'ff 3.6', 'opera 11.1', 'ios 4', 'android 2.3' ] }), require('cssnano')() // minify the result ] }, dist: { src: '<%= destCSSDir %>' + '/*.css' } };
module.exports = { options: { map: true, // inline sourcemaps processors: [ require('pixrem')(), // add fallbacks for rem units require('autoprefixer-core')({ // add vendor prefixes browsers: [ 'last 3 version', 'ie 8', 'ff 3.6', 'opera 11.1', 'ios 4', 'android 2.3' ] }), require('cssnano')({ convertValues: false }) // minify the result ] }, dist: { src: '<%= destCSSDir %>' + '/*.css' } };
Disable not-safe PostCSS value conversions
Disable not-safe PostCSS value conversions
JavaScript
mit
ideus-team/html-framework,ideus-team/html-framework
6cdb0bf0cb4872dae918175851b1fec4341bfb97
violet/violet.js
violet/violet.js
#!/usr/bin/env node var ncp = require('ncp').ncp; var path = require('path'); require('yargs') .usage('$0 <cmd> [args]') .option('directory', { alias: 'd', describe: 'Provide the directory to install Violet to' }) .command('install', 'Install violet', {}, function (argv) { var directory = 'violet'; if (argv.directory != null) { directory = argv.directory; } ncp(path.resolve(__dirname, './source'), directory, function (err) { if (err) { return console.error(err); } console.log('Installed Violet!'); }); }) .help('help') .argv;
#!/usr/bin/env node var ncp = require('ncp').ncp; var path = require('path'); var fs = require('fs'); require('yargs') .usage('$0 <cmd> [args]') .option('directory', { alias: 'd', describe: 'Provide the directory to install Violet to' }) .command('install', 'Install Violet', {}, function (argv) { var directory = 'violet'; if (argv.directory != null) { directory = argv.directory; } install(directory); }) .command('update', 'Update Violet', {}, function (argv) { var directory = 'violet'; if (argv.directory != null) { directory = argv.directory; } deleteFolderRecursive(directory); install(directory); }) .help('help') .argv; function install(directory) { ncp(path.resolve(__dirname, './source'), directory, function (err) { if (err) { return console.error(err); } console.log('Installed Violet!'); }); } // thanks to http://www.geedew.com/remove-a-directory-that-is-not-empty-in-nodejs/ function deleteFolderRecursive(path) { if (fs.existsSync(path)) { fs.readdirSync(path).forEach(function (file, index) { var curPath = path + "/" + file; if (fs.lstatSync(curPath).isDirectory()) { // recurse deleteFolderRecursive(curPath); } else { // delete file fs.unlinkSync(curPath); } }); fs.rmdirSync(path); } };
Add update fucntion to CLI
Add update fucntion to CLI
JavaScript
mit
Lexteam/lexteam.github.io,Lexteam/lexteam.github.io,Lexteam/lexteam.github.io
482508f2927d05f2be0c58b20d7f9acd35606bc4
scripts/docs.js
scripts/docs.js
#!/usr/bin/env node var _ = require('lodash'); var docdown = require('docdown'); var fs = require('fs'); var path = require('path'); var srcPath = path.join(__dirname, '../src'); var outPath = path.join(__dirname, '../docs'); // Define which files to scan var sourceFiles = [ 'tree.js', 'treenode.js', 'treenodes.js' ]; // Create output directory if (!fs.existsSync(outPath)) { fs.mkdirSync(outPath); } _.each(sourceFiles, function(sourceFile) { var markdown = docdown({ title: '', toc: 'categories', path: path.join(srcPath, sourceFile), url: 'https://github.com/helion3/inspire-tree/blob/master/src/' + sourceFile }); var docName = sourceFile.split('/').pop().replace('.js', '.md'); // Write file fs.writeFile(path.join(outPath, docName), markdown, function(err) { if (err) { console.log('Error writing to file:'); console.log(err); return; } console.log('Wrote output for ' + sourceFile); }); });
#!/usr/bin/env node var _ = require('lodash'); var docdown = require('docdown'); var fs = require('fs'); var path = require('path'); var srcPath = path.join(__dirname, '../src'); var outPath = path.join(__dirname, '../docs'); // Define which files to scan var sourceFiles = [ 'tree.js', 'treenode.js', 'treenodes.js' ]; // Create output directory if (!fs.existsSync(outPath)) { fs.mkdirSync(outPath); } _.each(sourceFiles, function(sourceFile) { var markdown = docdown({ title: '', toc: 'categories', path: path.join(srcPath, sourceFile), style: 'github', url: 'https://github.com/helion3/inspire-tree/blob/master/src/' + sourceFile }); var docName = sourceFile.split('/').pop().replace('.js', '.md'); // Write file fs.writeFile(path.join(outPath, docName), markdown, function(err) { if (err) { console.log('Error writing to file:'); console.log(err); return; } console.log('Wrote output for ' + sourceFile); }); });
Set docdown style to github.
Set docdown style to github. [ci skip]
JavaScript
mit
helion3/inspire-tree,helion3/inspire-tree
70fab2cf5426def9114bdd40727f4a72593df9e4
src/core.js
src/core.js
(function(global) { 'use strict'; define([ ], function() { // $HEADER$ /** * This will be the <code>warmsea</code> namespace. * @namespace * @alias warmsea */ var w = _.extend({}, _); /** * The unmodified underlying underscore object. */ w._ = w.underscore = _; /** * The version of this WarmseaJS. * @type {string} */ w.VERSION = '$VERSION$'; /** * The global object of the executing environment. * @type {object} */ w.global = global; /** * Save the previous `warmsea`. */ var previousWarmsea = global.warmsea; /** * Return the current `warmsea` and restore the previous global one. * @return {warmsea} This warmsea object. */ w.noConflict = function() { global.warmsea = previousWarmsea; return this; }; /** * A function that throws an error with the message "Unimplemented". */ w.unimplemented = function() { w.error('Unimplemented'); }; /** * Throws an Error. * @method * @param {string} msg * @throws {Error} */ w.error = function(msg) { throw new Error(msg); }; // $FOOTER$ return w; }); })(this);
(function(global) { 'use strict'; define([ ], function() { // $HEADER$ /** * This will be the <code>warmsea</code> namespace. * @namespace * @alias warmsea */ var w = _.extend({}, _); /** * The unmodified underlying underscore object. */ w._ = w.underscore = _; /** * The version of this WarmseaJS. * @type {string} */ w.VERSION = '$VERSION$'; /** * The global object of the executing environment. * @type {object} */ w.global = global; /** * Save the previous `warmsea`. */ var previousWarmsea = global.warmsea; /** * Return the current `warmsea` and restore the previous global one. * @return {warmsea} This warmsea object. */ w.noConflict = function() { global.warmsea = previousWarmsea; return this; }; /** * A function that throws an error with the message "Unimplemented". */ w.unimplemented = function() { w.error('Unimplemented'); }; /** * Throws an Error. * @method * @param {string} msg * @throws {Error} */ w.error = function(msg) { if (w.isFunction(w.format)) { msg = w.format.apply(w, arguments); } throw new Error(msg); }; // $FOOTER$ return w; }); })(this);
Format support for w.error() if possible.
Format support for w.error() if possible.
JavaScript
mit
warmsea/WarmseaJS
a0bd12dab161141e958e5d437694a7b22283fe8f
routes/index.js
routes/index.js
/* * Module dependencies */ var app = module.parent.exports, Joiner = require('../libs/joiner').Joiner; /* * Middlewares */ function isAnotherFile (req, res, next) { var folder = req.params.version; if (folder === 'assets' || folder === 'vendor' || folder === 'test' || folder === 'libs') { next('route'); } else { next(); } }; function isView (req, res, next) { if (req.params.type === undefined) { res.render(req.params.version + '.html'); } else { next(); } }; /* * Views */ app.get('/:version/:type?/:min?', isAnotherFile, isView, function (req, res, next) { var name = req.params.version + req.params.type.toUpperCase(), min = ((req.params.min) ? true : false), joiner = new Joiner(); joiner.on('joined', function (data) { res.set('Content-Type', 'text/' + (req.params.type === 'js' ? 'javascript' : 'css')); res.send(data.raw); }); joiner.run(name, min); }); /* * Index */ app.get('/', function (req, res, next) { res.redirect('/ui') });
/* * Module dependencies */ var app = module.parent.exports, Joiner = require('../libs/joiner').Joiner; /* * Middlewares */ function isAnotherFile (req, res, next) { var folder = req.params.version; if (folder === 'assets' || folder === 'vendor' || folder === 'test' || folder === 'libs') { next('route'); } else { next(); } }; function isView (req, res, next) { if (req.params.type === undefined) { res.render(req.params.version + '.html'); } else { next(); } }; /* * Views */ app.get('/:version/:type?', isAnotherFile, isView, function (req, res, next) { var name = req.params.version + req.params.type.toUpperCase(), min = ((req.query.min) ? req.query.min : false), joiner = new Joiner(); joiner.on('joined', function (data) { res.set('Content-Type', 'text/' + (req.params.type === 'js' ? 'javascript' : 'css')); res.send(data.raw); }); joiner.run(name, min); }); /* * Index */ app.get('/', function (req, res, next) { res.redirect('/ui') });
Change the min feature to a parameter as ?min=true to get data form joiner.
Change the min feature to a parameter as ?min=true to get data form joiner.
JavaScript
mit
amireynoso/uxtest,vrleonel/ml-test,atma/chico,mercadolibre/chico,amireynoso/uxtest,vrleonel/chico,vrleonel/chico,vrleonel/ml-test,mercadolibre/chico,atma/chico
70f456cc5409b296cfe481c16614c6444f88b69b
lib/actions/clean-cache.js
lib/actions/clean-cache.js
'use babel'; import yarnExec from '../yarn/exec'; import reportError from '../report-error'; const cleanCache = async () => { const success = await yarnExec(null, 'cache', ['clean']); if (!success) { atom.notifications.addError( 'An error occurred whilst cleaning cache. See output for more information.', ); return; } atom.notifications.addSuccess('Global package cache has been cleaned'); }; const confirmation = async () => { atom.confirm({ message: 'Are you sure you want to clean the global Yarn cache?', detailedMessage: 'Cleaning your global package cache will force Yarn to download packages from the npm registry the next time a package is requested.', buttons: { 'Clean Cache': () => { cleanCache().catch(reportError); }, Cancel: null, }, }); }; export default confirmation;
'use babel'; import yarnExec from '../yarn/exec'; import reportError from '../report-error'; import addProgressNotification from '../add-progress-notification'; const cleanCache = async () => { let progress; const options = { onStart: () => { progress = addProgressNotification('Cleaning global package cache...'); }, }; const success = await yarnExec(null, 'cache', ['clean'], options); progress.dismiss(); if (!success) { atom.notifications.addError( 'An error occurred whilst cleaning global cache. See output for more information.', ); return; } atom.notifications.addSuccess('Global package cache has been cleaned'); }; const confirmation = async () => { atom.confirm({ message: 'Are you sure you want to clean the global Yarn cache?', detailedMessage: 'Cleaning your global package cache will force Yarn to download packages from the npm registry the next time a package is requested.', buttons: { 'Clean Cache': () => { cleanCache().catch(reportError); }, Cancel: null, }, }); }; export default confirmation;
Add progress notification to clean cache command
Add progress notification to clean cache command
JavaScript
mit
cbovis/atom-yarn
1c7c0d1635747f12b82c202155045958907ec0c6
tests/unit/src/defur.js
tests/unit/src/defur.js
(function() { var defur = require('../../../src/defur'); var assert = require('chai').assert; suite('defur:', function() { var services = null; setup(function() { services = {}; }); test('`defur` is a function', function() { assert.isFunction(defur); }); test('`defur` defers execution of definition', function() { defur('foo', services, function() { throw new Error('This should be deferred.'); }); assert.throws(function() { services.foo; }); }); test('`defur` creates the service only once', function() { defur('foo', services, function() { return {}; }); assert.strictEqual(services.foo, services.foo); }); test('`defur` works with multiple service containers', function() { var otherServices = {}; defur('foo', services, function() { return {}; }); defur('foo', otherServices, function() { return {}; }); assert.notEqual(services.foo, otherServices.foo); }); }); })();
(function() { var defur = require('../../../src/defur'); var assert = require('chai').assert; suite('defur:', function() { var services = null; setup(function() { services = {}; }); test('`defur` is a function', function() { assert.isFunction(defur); }); test('`defur` defers execution of definition', function() { defur('foo', services, function() { throw new Error('This should be deferred.'); }); assert.throws(function() { services.foo; }); }); test('`defur` creates the service only once', function() { defur('foo', services, function() { return {}; }); assert.strictEqual(services.foo, services.foo); }); test('`defur` services don\'t collide', function() { defur('foo', services, function() { return {}; }); defur('bar', services, function() { return {}; }); assert.notEqual(services.foo, services.bar); }); test('`defur` works with multiple service containers', function() { var otherServices = {}; defur('foo', services, function() { return {}; }); defur('foo', otherServices, function() { return {}; }); assert.notEqual(services.foo, otherServices.foo); }); }); })();
Add test to cover container collisions
Add test to cover container collisions
JavaScript
mit
adlawson/js-defur,adlawson/js-defur
c4e58fda577b4f7f9165a788df9204d2646d26a3
lib/ext/patch-ember-app.js
lib/ext/patch-ember-app.js
/** * Monkeypatches the EmberApp instance from Ember CLI to contain the hooks we * need to filter environment-specific initializers. Hopefully we can upstream * similar hooks to Ember CLI and eventually remove these patches. */ function patchEmberApp(emberApp) { // App was already patched if (emberApp.addonPreconcatTree) { return; } // Save off original implementation of the `concatFiles` hook var originalConcatFiles = emberApp.concatFiles; // Install method to invoke `preconcatTree` hook on each addon emberApp.addonPreconcatTree = addonPreconcatTree; // Install patched `concatFiles` method. This checks options passed to it // and, if it detects that it's a concat for the app tree, invokes our // preconcat hook. Afterwards, we invoke the original implementation to // return a tree concating the files. emberApp.concatFiles = function(tree, options) { if (options.annotation === 'Concat: App') { tree = this.addonPreconcatTree(tree); } return originalConcatFiles.call(this, tree, options); }; } function addonPreconcatTree(tree) { var workingTree = tree; this.project.addons.forEach(function(addon) { if (addon.preconcatTree) { workingTree = addon.preconcatTree(workingTree); } }); return workingTree; } module.exports = patchEmberApp;
/** * Monkeypatches the EmberApp instance from Ember CLI to contain the hooks we * need to filter environment-specific initializers. Hopefully we can upstream * similar hooks to Ember CLI and eventually remove these patches. */ function patchEmberApp(emberApp) { // App was already patched if (emberApp.addonPreconcatTree) { return; } // Save off original implementation of the `concatFiles` hook var originalConcatFiles = emberApp.concatFiles; // Install method to invoke `preconcatTree` hook on each addon emberApp.addonPreconcatTree = addonPreconcatTree; // Install patched `concatFiles` method. This checks options passed to it // and, if it detects that it's a concat for the app tree, invokes our // preconcat hook. Afterwards, we invoke the original implementation to // return a tree concating the files. emberApp.concatFiles = function(tree, options) { if (options.annotation === 'Concat: App') { tree = this.addonPreconcatTree(tree); } return originalConcatFiles.apply(this, arguments); }; } function addonPreconcatTree(tree) { var workingTree = tree; this.project.addons.forEach(function(addon) { if (addon.preconcatTree) { workingTree = addon.preconcatTree(workingTree); } }); return workingTree; } module.exports = patchEmberApp;
Fix deprecation warning in for using EmberApp.concatFiles
Fix deprecation warning in for using EmberApp.concatFiles
JavaScript
mit
tildeio/ember-cli-fastboot,rwjblue/ember-cli-fastboot,ember-fastboot/ember-cli-fastboot,kratiahuja/ember-cli-fastboot,ember-fastboot/ember-cli-fastboot,kratiahuja/ember-cli-fastboot,josemarluedke/ember-cli-fastboot,tildeio/ember-cli-fastboot,rwjblue/ember-cli-fastboot,josemarluedke/ember-cli-fastboot
520b14ea01edc333dff77bf0822729be2ae14d1d
step-capstone/src/Components/TravelObject.js
step-capstone/src/Components/TravelObject.js
import React from 'react' export default function TravelObject(props) { let content = null; switch(props.type) { case 'event': content = <div>Event!</div>; break; case 'flight': content = <div>Flight!</div> break; case 'hotel': content = <div>Hotel!</div> break; default: console.log("Invalid type"); break; } return ( <div> {content} <button onClick={() => console.log("editing")}>Edit</button> <button onClick={() => console.log("deleting")}>Delete</button> </div> ) }
import React from 'react' import Flight from './Flight' export default function TravelObject(props) { let content = null; switch(props.type) { case 'event': content = <div>Event!</div>; break; case 'flight': content = <Flight /> break; case 'hotel': content = <div>Hotel!</div> break; default: console.log("Invalid type"); break; } return ( <div> {content} <button onClick={() => console.log("editing")}>Edit</button> <button onClick={() => console.log("deleting")}>Delete</button> </div> ) }
Replace dummy code for flight case with flight component
Replace dummy code for flight case with flight component
JavaScript
apache-2.0
googleinterns/step98-2020,googleinterns/step98-2020
304b03a879b0b427214b90e7ae9f0d576876e954
app/javascript/app/utils/redux.js
app/javascript/app/utils/redux.js
import isFunction from 'lodash/isFunction'; import { createAction as CA, handleActions as handle } from 'redux-actions'; // matches action names with reducers and returns an object to // be used with handleActions // passes all state as a third argument export const bindActionsToReducers = (actions, reducerList, appState) => Object.keys(actions).reduce((result, k) => { const c = {}; const name = actions[k]; c[name] = (state, action) => reducerList.reduce((r, reducer) => { if (!reducer.hasOwnProperty(k) || !isFunction(reducer[k])) return r; return reducer[k](r, action, appState); }, state); return { ...result, ...c }; }, {}); export const handleActions = (key, actions, reducers, state) => handle(bindActionsToReducers(actions, [reducers], state), state[key] || {}); // our own actioncreattor that can handle thunks // fires the action as init // and leaves resolve/reject to the thunk creator export const createThunkAction = (name, thunkAction) => { if (!thunkAction) return CA(name); thunkAction.toString = () => name; return thunkAction; };
import isFunction from 'lodash/isFunction'; import { createAction as CA, handleActions as handle } from 'redux-actions'; // matches action names with reducers and returns an object to // be used with handleActions // passes all state as a third argument export const bindActionsToReducers = (actions, reducerList) => Object.keys(actions).reduce((result, k) => { const c = {}; const name = actions[k]; c[name] = (state, action) => reducerList.reduce((r, reducer) => { const hasProperty = Object.prototype.hasOwnProperty.call(reducer, k); if (!hasProperty || !isFunction(reducer[k])) return r; return reducer[k](r, action); }, state); return { ...result, ...c }; }, {}); export const handleActions = (key, actions, reducers, state) => handle(bindActionsToReducers(actions, [reducers], state), state[key] || {}); // our own actioncreattor that can handle thunks // fires the action as init // and leaves resolve/reject to the thunk creator export const createThunkAction = (name, thunkAction) => { if (!thunkAction) return CA(name); thunkAction.toString = () => name; // eslint-disable-line return thunkAction; };
Stop passing all store in each action
Stop passing all store in each action
JavaScript
mit
Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch
e3b80778bf188ac19ab4d698621864d52819085f
app/js/util/arethusa_generator.js
app/js/util/arethusa_generator.js
"use strict"; // Generators for Arethusa code for things such as // - useful directives function ArethusaGenerator() { this.panelTrigger = function panelTrigger(service, trsl, trslKey, template) { return { restrict: 'A', link: function(scope, element, attrs) { function toggle() { scope.$apply(service.toggle()); } var parent = element.parent(); trsl(trslKey, function(translation) { parent.attr('title', translation); }); element.bind('click', toggle); }, template: template }; }; } var arethusaGenerator = new ArethusaGenerator(); var aG = arethusaGenerator;
"use strict"; // Generators for Arethusa code for things such as // - useful directives function ArethusaGenerator() { this.panelTrigger = function panelTrigger(service, trsl, trslKey, template) { return { restrict: 'A', compile: function(element) { var parent = element.parent(); function updateTitle(translation) { parent.attr('title', translation); } return function link(scope, element, attrs) { function toggle() { scope.$apply(service.toggle()); } trsl(trslKey, updateTitle); element.bind('click', toggle); }; }, template: template }; }; } var arethusaGenerator = new ArethusaGenerator(); var aG = arethusaGenerator;
Refactor panel triggers for speed
Refactor panel triggers for speed
JavaScript
mit
latin-language-toolkit/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,Masoumeh/arethusa
d2f251b8a375ab011688d740113b8c09c79c5612
src/ex.js
src/ex.js
import _ from "lodash"; import jQuery from "jquery"; import moment from "moment"; import Config from "./config.js"; import DText from "./dtext.js"; import Tag from "./tag.js"; import UI from "./ui.js"; import "./danbooru-ex.css"; export default class EX { static get Config() { return Config; } static get DText() { return DText; } static get Tag() { return Tag; } static get UI() { return UI; } static search(url, search, { limit, page } = {}) { return $.getJSON(url, { search, limit: limit || 1000, page: page || 1 }); } static initialize() { EX.config = new Config(); EX.config.enableHeader && UI.Header.initialize(); EX.UI.initialize(); EX.UI.Artists.initialize(); EX.UI.Comments.initialize(); EX.UI.ForumPosts.initialize(); EX.UI.Pools.initialize(); EX.UI.Posts.initialize(); EX.UI.PostVersions.initialize(); EX.UI.WikiPages.initialize(); } } window.EX = EX; jQuery(function () { try { EX.initialize(); } catch(e) { $("footer").append(`<div class="ex-error">Danbooru EX error: ${e}</div>`); throw e; } });
import _ from "lodash"; import jQuery from "jquery"; import moment from "moment"; import Config from "./config.js"; import DText from "./dtext.js"; import Tag from "./tag.js"; import UI from "./ui.js"; import "./danbooru-ex.css"; export default class EX { static get Config() { return Config; } static get DText() { return DText; } static get Tag() { return Tag; } static get UI() { return UI; } static search(url, search, { limit, page } = {}) { return $.getJSON(url, { search, limit: limit || 1000, page: page || 1 }); } static initialize() { EX.config = new Config(); EX.config.enableHeader && UI.Header.initialize(); EX.UI.initialize(); EX.UI.Artists.initialize(); EX.UI.Comments.initialize(); EX.UI.ForumPosts.initialize(); EX.UI.Pools.initialize(); EX.UI.Posts.initialize(); EX.UI.PostVersions.initialize(); EX.UI.WikiPages.initialize(); } } window.EX = EX; window.moment = moment; jQuery(function () { try { EX.initialize(); } catch(e) { $("footer").append(`<div class="ex-error">Danbooru EX error: ${e}</div>`); throw e; } });
Make moment global for debugging.
[fix] Make moment global for debugging.
JavaScript
mit
evazion/danbooru-ex,evazion/danbooru-ex
0ae0be0b2a0124d19c73f3d1814d92470b1f4960
src/send.js
src/send.js
import { busy, scheduleRetry } from './actions'; import { JS_ERROR } from './constants'; import type { Config, OfflineAction, ResultAction } from './types'; const complete = ( action: ResultAction, success: boolean, payload: {} ): ResultAction => ({ ...action, payload, meta: { ...action.meta, success, completed: true } }); const send = (action: OfflineAction, dispatch, config: Config, retries = 0) => { const metadata = action.meta.offline; dispatch(busy(true)); return config .effect(metadata.effect, action) .then(result => { const commitAction = metadata.commit || config.defaultCommit; try { dispatch(complete(commitAction, true, result)); } catch (e) { dispatch(complete({ type: JS_ERROR, payload: e }, false)); } }) .catch(error => { const rollbackAction = metadata.rollback || config.defaultRollback; // discard if (config.discard(error, action, retries)) { dispatch(complete(rollbackAction, false, error)); return; } const delay = config.retry(action, retries); if (delay != null) { dispatch(scheduleRetry(delay)); return; } dispatch(complete(rollbackAction, false, error)); }); }; export default send;
import { busy, scheduleRetry } from './actions'; import { JS_ERROR } from './constants'; import type { Config, OfflineAction, ResultAction } from './types'; const complete = ( action: ResultAction, success: boolean, payload: {} ): ResultAction => ({ ...action, payload, meta: { ...action.meta, success, completed: true } }); const send = (action: OfflineAction, dispatch, config: Config, retries = 0) => { const metadata = action.meta.offline; dispatch(busy(true)); return config .effect(metadata.effect, action) .then(result => { const commitAction = metadata.commit || { ...config.defaultCommit, meta: { ...config.defaultCommit.meta, offlineAction: action } }; try { dispatch(complete(commitAction, true, result)); } catch (e) { dispatch(complete({ type: JS_ERROR, payload: e }, false)); } }) .catch(error => { const rollbackAction = metadata.rollback || { ...config.defaultRollback, meta: { ...config.defaultRollback.meta, offlineAction: action } }; // discard if (config.discard(error, action, retries)) { dispatch(complete(rollbackAction, false, error)); return; } const delay = config.retry(action, retries); if (delay != null) { dispatch(scheduleRetry(delay)); return; } dispatch(complete(rollbackAction, false, error)); }); }; export default send;
Add offline action to default commit and rollback actions
Add offline action to default commit and rollback actions
JavaScript
mit
redux-offline/redux-offline,jevakallio/redux-offline
7de0c1782ac690461693aa308364ac3aa996712a
tests/e2e/utils/activate-amp-and-set-mode.js
tests/e2e/utils/activate-amp-and-set-mode.js
/** * WordPress dependencies */ import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils'; /** * The allow list of AMP modes. * */ export const allowedAmpModes = { standard: 'standard', transitional: 'transitional', reader: 'disabled', }; /** * Activate AMP and set it to the correct mode. * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const activateAmpAndSetMode = async ( mode ) => { // Test to be sure that the passed mode is known. expect( Object.keys( allowedAmpModes ) ).toContain( mode ); // Active AMP and set the passed mode. await activatePlugin( 'amp' ); await visitAdminPage( 'admin.php', 'page=amp-options' ); await expect( page ).toClick( `#theme_support_${ allowedAmpModes[ mode ] }` ); await expect( page ).toClick( '#submit' ); await page.waitForSelector( '#setting-error-settings_updated' ); await expect( page ).toMatchElement( '#setting-error-settings_updated', { text: 'Settings saved.' } ); };
/** * WordPress dependencies */ import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils'; /** * The allow list of AMP modes. * */ export const allowedAmpModes = { standard: 'standard', transitional: 'transitional', reader: 'disabled', }; /** * Activate AMP and set it to the correct mode. * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const activateAmpAndSetMode = async ( mode ) => { await activatePlugin( 'amp' ); await setAMPMode( mode ); }; /** * Set AMP Mode * * @param {string} mode The mode to set AMP to. Possible value of standard, transitional or reader. */ export const setAMPMode = async ( mode ) => { // Test to be sure that the passed mode is known. expect( Object.keys( allowedAmpModes ) ).toContain( mode ); // Set the AMP mode await visitAdminPage( 'admin.php', 'page=amp-options' ); await expect( page ).toClick( `#theme_support_${ allowedAmpModes[ mode ] }` ); await expect( page ).toClick( '#submit' ); await page.waitForSelector( '#setting-error-settings_updated' ); await expect( page ).toMatchElement( '#setting-error-settings_updated', { text: 'Settings saved.' } ); };
Add helper to change AMP mode.
Add helper to change AMP mode.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
dc390d2733adb5c57866626125a04f1a6e9b5da3
js/cooldown.js
js/cooldown.js
var seconds_match = /^(\d)*s$/; function Cooldown(frames) { frames = frames || 10 if ($.type(frames) == "string") { var seconds = frames.match(seconds_match) if (seconds) { frames = seconds[1] * runtime.fps } else { frames = parseInt(frames) } } var total = frames var result = false this.set_result = function(new_result) { result = new_result } this.frame = function() { frames-- if (frames <= 0) return result return this } this.get_remaining = function() { return total - frames } this.get_pctdone = function() { return (total - frames) / total } }
var seconds_match = /^(\d)*s$/; function Cooldown(frames, inital_result) { frames = frames || 10 if ($.type(frames) == "string") { var seconds = frames.match(seconds_match) if (seconds) { frames = seconds[1] * runtime.fps } else { frames = parseInt(frames) } } var total = frames var result = false this.set_result = function(new_result) { result = new_result } if ($.isFunction(inital_result)) this.set_result(inital_result) this.frame = function() { frames-- if (frames <= 0) return result return this } this.reset = function() { frames = total } this.is_done = function() { return frames >= total } this.get_remaining = function() { return total - frames } this.get_pctdone = function() { return (total - frames) / total } }
Add a shortcut to set the result function in Cooldown
Add a shortcut to set the result function in Cooldown
JavaScript
artistic-2.0
atrodo/fission_engine,atrodo/fission_engine
1d6be34ff63350aa3e3c0cdeb163d653bec307dc
js/services.js
js/services.js
angular.module('services', []) .filter('file', function () { return function (input) { return input.split(' ').join('_').toLowerCase() } }) .factory('responsive', function () { var resizeTimer return { run: function (apply, main, input, output) { main(input, output) $(window).on('resize', function(e) { clearTimeout(resizeTimer) resizeTimer = setTimeout(function () { main(input, output) apply() }, 100) }) } } })
angular.module('services', []) .directive('done', ['$parse', function($parse) { return { restrict: 'A', link: function(scope, element, attrs) { var fn = $parse(attrs.done) if (scope.$last){ scope.done() } } } }]) .filter('file', function () { return function (input) { return input.split(' ').join('_').toLowerCase() } }) .filter('first', function () { return function (input) { var output = input.split(': ') return output[0] } }) .filter('second', function () { return function (input) { var output = input.split(': ') return output[1] } }) .filter('info', function () { return function (input) { return input.split(', ').join(',\ \ ') } }) .factory('responsive', function () { var resizeTimer return { run: function (apply, init, main, input, output) { init(main, input, output) $(window).on('resize', function(e) { window.requestAnimationFrame(function () { main(input, output) apply() }) }) } } })
Add filter/directives for about page
Add filter/directives for about page
JavaScript
mit
Cwejman/martina,Cwejman/martina
6594bafa373173d987271d51833bcbb45ea4cda1
js/settings.js
js/settings.js
var possibleStates = [ 'P,Pipeline', 'R,Request Evaluation', 'Rm,Requirements', 'C,Concept', 'D,Development', 'Dy,Deployment', 'L,Live' ]; var possible_colors = 4;
var possibleStates = [ 'B,Backlog', 'P,Pending ', 'Cs,Current Sprint', 'D,Doing', 'Bl,Blocked', 'Q,QA', 'L,Live' ]; var possible_colors = 4;
Set up more common Kanban columns
Set up more common Kanban columns
JavaScript
mit
rapsli/simple-kanban,rapsli/simple-kanban
a3aff6a41a08614ba68fb590aefbc6e2cb5067a4
routers/download/constants.js
routers/download/constants.js
const ALLOWED_CSV_FIELD_PATHS = [ 'ids.GB-CHC', 'ids.charityId', 'name', 'contact.email', 'contact.person', 'contact.postcode', 'contact.address', 'contact.geo.longitude', 'contact.geo.latitude', 'people.volunteers', 'people.employees', 'people.trustees', 'activities', 'website', 'income.annual', 'areaOfBenefit', 'causes', 'beneficiaries', 'operations', ] const FY_END_YEARS = [ 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, ] module.exports = { ALLOWED_CSV_FIELD_PATHS, FY_END_YEARS, }
const ALLOWED_CSV_FIELD_PATHS = [ 'ids.GB-CHC', 'ids.charityId', 'name', 'contact.address', 'contact.email', 'contact.geo.latitude', 'contact.geo.longitude', 'contact.person', 'contact.phone', 'contact.postcode', 'people.volunteers', 'people.employees', 'people.trustees', 'activities', 'website', 'income.annual', 'areaOfBenefit', 'causes', 'beneficiaries', 'operations', 'objectives', ] const FY_END_YEARS = [ 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, ] module.exports = { ALLOWED_CSV_FIELD_PATHS, FY_END_YEARS, }
Allow downloading objectives & phone
Allow downloading objectives & phone
JavaScript
mit
tithebarn/charity-base,tithebarn/open-charities,tythe-org/charity-base-api
3cd2d32ca72775777962a912fe539cbb540274b0
delay.safariextension/start.js
delay.safariextension/start.js
(function () { "use strict"; var settings, display; if (window !== window.top) { return; } safari.self.tab.dispatchMessage('getSettings'); safari.self.addEventListener('message', function (event) { if (event.name === 'settings') { settings = event.message; if (settings.blacklist.indexOf(window.location.hostname) !== -1) { display = document.documentElement.style.display; document.documentElement.style.display = 'none'; window.setTimeout(function () { document.documentElement.style.display = display; }, 1000 * (settings.delay - settings.jitter + (Math.random() * 2 * settings.jitter))); } } }, false); }());
(function () { "use strict"; var settings, visibility; if (window !== window.top) { return; } safari.self.tab.dispatchMessage('getSettings'); safari.self.addEventListener('message', function (event) { if (event.name === 'settings') { settings = event.message; if (settings.blacklist.indexOf(window.location.hostname) !== -1) { visibility = document.documentElement.style.visibility; document.documentElement.style.visibility = 'hidden'; window.setTimeout(function () { document.documentElement.style.visibility = visibility; }, 1000 * (settings.delay - settings.jitter + (Math.random() * 2 * settings.jitter))); } } }, false); }());
Switch from "display:none" to "visibility:hidden".
Switch from "display:none" to "visibility:hidden". That way the page layout won't be affected but it will still be hidden.
JavaScript
mit
tfausak/delay
cbd505bf2749c62d6baba3e9278a92143b1fc255
example/build.js
example/build.js
var thumbsup = require('../src/index'); thumbsup.build({ // the input folder // with all photos/videos input: 'example/media', // the output folder // for the thumbnails and static pages output: 'example/website', // website title // the first word will be in color title: 'Photo gallery', // main site color // for the title and links css: null, // size of the square thumbnails // in pixels thumbSize: 120, // size of the "fullscreen" view // in pixels largeSize: 400 });
var thumbsup = require('../src/index'); thumbsup.build({ // the input folder // with all photos/videos input: 'example/media', // the output folder // for the thumbnails and static pages output: '_site', // website title // the first word will be in color title: 'Photo gallery', // main site color // for the title and links css: null, // size of the square thumbnails // in pixels thumbSize: 120, // size of the "fullscreen" view // in pixels largeSize: 400 });
Build the example site into _site (published as Github pages)
Build the example site into _site (published as Github pages)
JavaScript
mit
kremlinkev/thumbsup,thumbsup/node-thumbsup,dravenst/thumbsup,rprieto/thumbsup,dravenst/thumbsup,thumbsup/thumbsup,kremlinkev/thumbsup,thumbsup/thumbsup,thumbsup/node-thumbsup,rprieto/thumbsup,thumbsup/node-thumbsup
c5b6ac00c1d05bc69f4dcbd9f999baf43421f0fe
tasks/styles.js
tasks/styles.js
'use strict'; var sass = require('gulp-sass'); var bourbon = require('node-bourbon'); var rev = require('gulp-rev'); var minify = require('gulp-minify-css'); /* compile sass with bourbon */ module.exports = function (stream) { return stream .pipe(sass({ includePaths: bourbon.includePaths })) .pipe(env.not('development', rev())) .pipe(env.not('development', minify())); };
'use strict'; var sass = require('gulp-sass'); var bourbon = require('node-bourbon'); var rev = require('gulp-rev'); var minify = require('gulp-minify-css'); var env = require('../utils/env'); var manifest = require('../utils/manifest'); /* compile sass with bourbon */ module.exports = function (stream) { return stream .pipe(sass({ includePaths: bourbon.includePaths })) .pipe(env.not('development', rev())) .pipe(env.not('development', manifest())) .pipe(env.not('development', minify())); };
Add CSS to asset manifest
Add CSS to asset manifest
JavaScript
mit
bendrucker/gulp-tasks
18264d202fb2a48c3f8952246708af1b5e941fbf
app/assets/javascripts/icons.js
app/assets/javascripts/icons.js
/* global gon */ $(document).ready(function() { // Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't // respect up/down key selections in a dropdown as a valid change() trigger $("#icon_dropdown").change(function() { setIconFromId($(this).val()); }); $("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); }); $('.gallery-minmax').click(function() { var elem = $(this); var id = elem.data('id'); if (elem.html().trim() === '-') { $('#gallery' + id).hide(); $('#gallery-tags-' + id).hide(); elem.html('+'); } else { $('#gallery' + id).show(); $('#gallery-tags-' + id).show(); elem.html('-'); } }); }); function setIconFromId(id) { $("#new_icon").attr('src', gon.gallery[id].url); $("#new_icon").attr('alt', gon.gallery[id].keyword); $("#new_icon").attr('title', gon.gallery[id].keyword); if (typeof gon.gallery[id].aliases !== "undefined") { var aliases = gon.gallery[id].aliases; if (aliases.length > 0) { $("#alias_dropdown").show().empty().append('<option value="">— No alias —</option>'); for (var i = 0; i < aliases.length; i++) { $("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name)); } } else { $("#alias_dropdown").hide().val(''); } } }
/* global gon */ $(document).ready(function() { // Bind both change() and keyup() in the icon keyword dropdown because Firefox doesn't // respect up/down key selections in a dropdown as a valid change() trigger $("#icon_dropdown").change(function() { setIconFromId($(this).val()); }); $("#icon_dropdown").keyup(function() { setIconFromId($(this).val()); }); }); function setIconFromId(id) { $("#new_icon").attr('src', gon.gallery[id].url); $("#new_icon").attr('alt', gon.gallery[id].keyword); $("#new_icon").attr('title', gon.gallery[id].keyword); if (typeof gon.gallery[id].aliases !== "undefined") { var aliases = gon.gallery[id].aliases; if (aliases.length > 0) { $("#alias_dropdown").show().empty().append('<option value="">— No alias —</option>'); for (var i = 0; i < aliases.length; i++) { $("#alias_dropdown").append($("<option>").attr({value: aliases[i].id}).append(aliases[i].name)); } } else { $("#alias_dropdown").hide().val(''); } } }
Remove dead duplicate code for gallery minmax
Remove dead duplicate code for gallery minmax
JavaScript
mit
Marri/glowfic,Marri/glowfic,Marri/glowfic,Marri/glowfic
bd223902c3d3f4bc07257ec4c49a540cfd654a95
test/feature.js
test/feature.js
var assert = require('assert'); var Feature = require('../feature'); describe('Feature', function () { describe('schema', function () { it('successfully creates a valid document'); it('fails at creating an invalid document'); }); describe('.search()', function () { it('performs an empty search, returning all commands', function (done) { Feature.search('', function (docs) { assert.equal(7, docs.length); done(); }); }); it('performs a case-insensitive search for a command', function (done) { Feature.search('git ADD', function (docs) { assert.equal(1, docs.length) done(); }); }); it('performs a search for a command that does not exist', function (done) { Feature.search('git yolo', function (docs) { assert.equal(0, docs.length); done(); }); }); }); });
var assert = require('assert'); var seeds = require('../seeds'); var Feature = require('../feature'); describe('Feature', function () { before(function (done) { seeds(done); }); describe('schema', function () { it('successfully creates a valid document'); it('fails at creating an invalid document'); }); describe('.search()', function () { it('performs an empty search, returning all commands', function (done) { Feature.search('', function (docs) { assert.equal(7, docs.length); done(); }); }); it('performs a case-insensitive search for a command', function (done) { Feature.search('git ADD', function (docs) { assert.equal(1, docs.length) done(); }); }); it('performs a search for a command that does not exist', function (done) { Feature.search('git yolo', function (docs) { assert.equal(0, docs.length); done(); }); }); }); });
Use the database seeds from the Feature spec
Use the database seeds from the Feature spec
JavaScript
mit
nickmccurdy/rose,nicolasmccurdy/rose,nicolasmccurdy/rose,nickmccurdy/rose
d70cfc735c3fdaf9c65c6bd6fa27f9ec6f9ea2de
test/package.js
test/package.js
import fs from 'fs'; import test from 'ava'; import pify from 'pify'; import index from '../'; test('Every rule is defined in index file', async t => { const files = await pify(fs.readdir, Promise)('../rules/'); const rules = files.filter(file => file.indexOf('.js') === file.length - 3); rules.forEach(file => { const name = file.slice(0, -3); t.truthy(index.rules[name], `'${name}' is not exported in 'index.js'`); t.truthy(index.configs.recommended.rules[`fp/${name}`], `'${name}' is not set in the recommended config`); }); t.is(Object.keys(index.rules).length, rules.length, 'There are more exported rules than rule files.'); });
import fs from 'fs'; import test from 'ava'; import pify from 'pify'; import index from '../'; test('every rule should defined in the index file and recommended settings', async t => { const files = await pify(fs.readdir, Promise)('../rules/'); const rules = files.filter(file => file.indexOf('.js') === file.length - 3); rules.forEach(file => { const name = file.slice(0, -3); t.truthy(index.rules[name], `'${name}' is not exported in 'index.js'`); t.truthy(index.configs.recommended.rules[`fp/${name}`], `'${name}' is not set in the recommended config`); }); t.is(Object.keys(index.rules).length, rules.length, 'There are more exported rules than rule files.'); }); test('no-var should be turned on in the recommended settings', async t => { t.true(index.configs.recommended.rules['no-var'] === 'error'); });
Add test to make sure `no-var` is in the recommended config
Add test to make sure `no-var` is in the recommended config
JavaScript
mit
eslint-plugin-cleanjs/eslint-plugin-cleanjs,jfmengels/eslint-plugin-fp
1012fb705859f61eb097f34a258050b837a593df
core/cb.project/parse/index.js
core/cb.project/parse/index.js
var path = require("path"); module.exports = { id: "parse", name: "Parse", sample: path.resolve(__dirname, "sample"), detector: path.resolve(__dirname, "detector.sh"), runner: [ { id: "run", script: path.resolve(__dirname, "run.sh") } ] };
var path = require("path"); module.exports = { id: "parse", name: "Parse", otherIds: ["mobile"], sample: path.resolve(__dirname, "sample"), detector: path.resolve(__dirname, "detector.sh"), runner: [ { id: "run", script: path.resolve(__dirname, "run.sh") } ] };
Add id of mobile stack to parse sample
Add id of mobile stack to parse sample
JavaScript
apache-2.0
kustomzone/codebox,CodeboxIDE/codebox,rodrigues-daniel/codebox,smallbal/codebox,ronoaldo/codebox,Ckai1991/codebox,lcamilo15/codebox,LogeshEswar/codebox,quietdog/codebox,Ckai1991/codebox,blubrackets/codebox,rajthilakmca/codebox,blubrackets/codebox,ronoaldo/codebox,nobutakaoshiro/codebox,smallbal/codebox,listepo/codebox,listepo/codebox,code-box/codebox,lcamilo15/codebox,ahmadassaf/Codebox,kustomzone/codebox,fly19890211/codebox,fly19890211/codebox,indykish/codebox,quietdog/codebox,indykish/codebox,etopian/codebox,CodeboxIDE/codebox,rodrigues-daniel/codebox,code-box/codebox,ahmadassaf/Codebox,nobutakaoshiro/codebox,etopian/codebox,LogeshEswar/codebox,rajthilakmca/codebox
c8fa6d7743e990f9b943ec045cada74403944d72
lib/webhook.js
lib/webhook.js
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const request = require('request') const colors = require('colors/safe') const logger = require('../lib/logger') const utils = require('../lib/utils') const os = require('os') const config = require('config') exports.notify = (challenge) => { request.post(process.env.SOLUTIONS_WEBHOOK, { json: { solution: { issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}`, challenge: challenge.key, evidence: null, issuedOn: new Date().toISOString() } } }, (error, res) => { if (error) { console.error(error) return } logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`) }) }
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const request = require('request') const colors = require('colors/safe') const logger = require('../lib/logger') const utils = require('../lib/utils') const os = require('os') exports.notify = (challenge) => { request.post(process.env.SOLUTIONS_WEBHOOK, { json: { solution: { issuer: `owasp_juiceshop-${utils.version()}@${os.hostname()}`, challenge: challenge.key, evidence: null, issuedOn: new Date().toISOString() } } }, (error, res) => { if (error) { console.error(error) return } logger.info(`Webhook ${colors.bold(process.env.SOLUTIONS_WEBHOOK)} notified about ${colors.cyan(challenge.key)} being solved: ${res.statusCode < 400 ? colors.green(res.statusCode) : colors.red(res.statusCode)}`) }) }
Remove unused config module import
Remove unused config module import
JavaScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
f182bb037d49003a42cc8fefa10d849b1145b15a
src/app/components/msp/application/personal-info/i18n/data/en/index.js
src/app/components/msp/application/personal-info/i18n/data/en/index.js
module.exports = { pageTitle: 'Tell us a bit about who is applying for health care coverage', addSpouseButton: 'Add Spouse/Common-Law Partner', addChildUnder19Button: 'Add Child (0-18)', addChild19To24Button: 'Add Child (19-24)', continueButton: 'Continue' }
module.exports = { pageTitle: 'Tell us a bit about who is applying for health care coverage', addSpouseButton: 'Add Spouse/Common-Law Partner', addChildUnder19Button: 'Add Child (0-18)', addChild19To24Button: 'Add Child (19-24) who is a full-time student', continueButton: 'Continue' }
Clarify student status of older children
Clarify student status of older children Re: MoH legal feedback
JavaScript
apache-2.0
bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP,bcgov/MyGovBC-MSP
62513397441fd0af5614a18e4cb6037479b744f2
models/User.js
models/User.js
'use strict'; var bcrypt = require('bcrypt'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; // export a mongoose model var userSchema = new Schema({ userName : String, passwordDigest : String }); userSchema.virtual('password').set(function(password) { var self = this; var saltPromise = new Promise(function saltExec(res, rej) { bcrypt.genSalt(16, function(err, salt) { if(err) { rej(err); return; } res(salt); }); }); var returnedPromise = saltPromise.then(function(salt) { return new Promise(function hashExec(res, rej) { bcrypt.hash(password, salt, function(err, digest) { if(err) { rej(err); return; } res(digest); }); }); }).then(function(digest) { self.passwordDigest = digest; }); return returnedPromise; }); module.exports = userSchema;
'use strict'; var bcrypt = require('bcrypt'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; // export a mongoose model var userSchema = new Schema({ userName : String, passwordDigest : String }); userSchema.methods.setPassword = function(password) { var self = this; var saltPromise = new Promise(function saltExec(res, rej) { bcrypt.genSalt(16, function(err, salt) { if(err) { rej(err); return; } res(salt); }); }); var returnedPromise = saltPromise.then(function(salt) { return new Promise(function hashExec(res, rej) { bcrypt.hash(password, salt, function(err, digest) { if(err) { rej(err); return; } res(digest); }); }); }).then(function(digest) { self.passwordDigest = digest; return self.save(); }); return returnedPromise; }; module.exports = userSchema;
Change virtual prop to an instance method
Change virtual prop to an instance method
JavaScript
mit
dhuddell/teachers-lounge-back-end
1810afeeeb0f678d6968f8849a1932a547e966eb
test/test_ss.js
test/test_ss.js
/*global seqJS:true */ (function() { /* ======== A Handy Little QUnit Reference ======== http://api.qunitjs.com/ Test methods: module(name, {[setup][ ,teardown]}) test(name, callback) expect(numberOfequalions) stop(increment) start(decrement) Test equalions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) throws(block, [expected], [message]) */ module('seqJS.ss'); test('Test ss', function(){ equal(seqJS.ss.predict('GGGAAATCC'), '.(((..)))', 'secondary structure incorrect'); }); }());
/*global seqJS:true */ (function() { /* ======== A Handy Little QUnit Reference ======== http://api.qunitjs.com/ Test methods: module(name, {[setup][ ,teardown]}) test(name, callback) expect(numberOfequalions) stop(increment) start(decrement) Test equalions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) throws(block, [expected], [message]) */ module('seqJS.ss'); test('Test ss', function(){ var s = new seqJS.Seq('GGGAAATCC', 'DNA'); equal(seqJS.ss.predict(s), '.(((..)))', 'secondary structure incorrect'); }); }());
Test passes a seqJS.Seq, not String
Test passes a seqJS.Seq, not String
JavaScript
mit
haydnKing/seqJS,haydnKing/seqJS
86b1e11b31c57bf51dd779c8ffc7e8ad5803de9a
client/src/views/member.js
client/src/views/member.js
_kiwi.view.Member = Backbone.View.extend({ tagName: "li", initialize: function (options) { this.model.bind('change', this.render, this); this.render(); }, render: function () { var $this = this.$el, prefix_css_class = (this.model.get('modes') || []).join(' '), max_prefix = (this.model.get('modes') || [])[0]; $this.attr('class', 'mode ' + prefix_css_class + ' member member-' + max_prefix); $this.html('<a class="nick"><span class="prefix prefix-' + max_prefix + '">' + this.model.get("prefix") + '</span>' + this.model.get("nick") + '</a>'); return this; } });
_kiwi.view.Member = Backbone.View.extend({ tagName: "li", initialize: function (options) { this.model.bind('change', this.render, this); this.render(); }, render: function () { var $this = this.$el, max_prefix = (this.model.get('modes') || [])[0]; $this.attr('class', 'member member-' + max_prefix); $this.html('<a class="nick"><span class="prefix prefix-' + max_prefix + '">' + this.model.get("prefix") + '</span>' + this.model.get("nick") + '</a>'); return this; } });
Remove old CSS classes (breaks stuff)
Remove old CSS classes (breaks stuff)
JavaScript
agpl-3.0
MDTech-us-MAN/KiwiIRC,MDTech-us-MAN/KiwiIRC,MDTech-us-MAN/KiwiIRC