commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
1dc21a911253f9485a71963701355a226b8a71e5
test/load-json-spec.js
test/load-json-spec.js
/* global require, describe, it */ import assert from 'assert'; var urlPrefix = 'http://katas.tddbin.com/katas/es6/language/'; var katasUrl = urlPrefix + '__grouped__.json'; var GroupedKata = require('../src/grouped-kata.js'); describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { function onSuccess(groupedKatas) { assert.ok(groupedKatas); done(); } new GroupedKata(katasUrl).load(function() {}, onSuccess); }); describe('on error, call error callback and the error passed', function() { it('invalid JSON', function(done) { function onError(err) { assert.ok(err); done(); } var invalidUrl = urlPrefix; new GroupedKata(invalidUrl).load(onError); }); it('for invalid data', function(done) { function onError(err) { assert.ok(err); done(); } var invalidData = urlPrefix + '__all__.json'; new GroupedKata(invalidData).load(onError); }); }); });
/* global describe, it */ import assert from 'assert'; const urlPrefix = 'http://katas.tddbin.com/katas/es6/language'; const katasUrl = `${urlPrefix}/__grouped__.json`; import GroupedKata from '../src/grouped-kata.js'; describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { function onSuccess(groupedKatas) { assert.ok(groupedKatas); done(); } new GroupedKata(katasUrl).load(() => {}, onSuccess); }); describe('on error, call error callback and the error passed', function() { it('invalid JSON', function(done) { function onError(err) { assert.ok(err); done(); } var invalidUrl = urlPrefix; new GroupedKata(invalidUrl).load(onError); }); it('for invalid data', function(done) { function onError(err) { assert.ok(err); done(); } var invalidData = `${urlPrefix}/__all__.json`; new GroupedKata(invalidData).load(onError); }); }); });
Use ES6 in the tests.
Use ES6 in the tests.
JavaScript
mit
wolframkriesing/es6-react-workshop,wolframkriesing/es6-react-workshop
33afa5699718ca8afcf7ffcda01e17af214da5bd
app/router.js
app/router.js
import Ember from 'ember'; import config from './config/environment'; var Router = Ember.Router.extend({ location: config.locationType }); Router.map(function() { this.route('lists', function() { this.route('show', {path: 'list/:id'}); }); this.route('top50'); this.route('movies', {path: '/'}, function() { this.route('show', {path: '/movie/:id'}); }); }); export default Router;
import Ember from 'ember'; import config from './config/environment'; var Router = Ember.Router.extend({ location: config.locationType }); Router.map(function() { this.route('lists', function() { this.route('show', {path: ':id'}); }); this.route('top50'); this.route('movies', {path: '/'}, function() { this.route('show', {path: '/movie/:id'}); }); }); export default Router;
Fix up route for single list
Fix up route for single list
JavaScript
mit
sabarasaba/moviezio-client,sabarasaba/moviezio-client,sabarasaba/moviez.city-client,sabarasaba/moviez.city-client,sabarasaba/moviezio-client,sabarasaba/moviez.city-client,sabarasaba/moviezio-client,sabarasaba/moviezio-client,sabarasaba/moviezio-client,sabarasaba/moviez.city-client,sabarasaba/moviez.city-client,sabarasaba/moviez.city-client
08b0f2604942a6b48eedf05a0f1a7e1573ad4699
main.js
main.js
/* * grunt-util-options * https://github.com/mikaelkaron/grunt-util-process * * Copyright (c) 2013 Mikael Karon * Licensed under the MIT license. */ module.exports = function(grunt) { "use strict"; var _ = grunt.util._; var _property = require("grunt-util-property")(grunt); return function (properties) { var me = this; var name = me.name; var target = me.target; _.each(_.rest(arguments), function (key) { _property.call(properties, key, _.find([ grunt.option([ name, target, key ].join(".")), grunt.option([ name, key ].join(".")), grunt.option(key), properties[key] ], function (value) { return !_.isUndefined(value); })); }); return properties; }; }
/* * grunt-util-options * https://github.com/mikaelkaron/grunt-util-process * * Copyright (c) 2013 Mikael Karon * Licensed under the MIT license. */ module.exports = function(grunt) { "use strict"; var _ = grunt.util._; var _property = require("grunt-util-property")(grunt); return function (properties) { var me = this; var name = me.name; var target = me.target; _.each(_.tail(arguments), function (key) { _property.call(properties, key, _.find([ grunt.option([ name, target, key ].join(".")), grunt.option([ name, key ].join(".")), grunt.option(key), properties[key] ], function (value) { return !_.isUndefined(value); })); }); return properties; }; }
Add support for lodash 4.x (Found in Grunt 1.x) * Changed lodash `rest` usage to tail. * Note this still supports lodash 3.x as tail was an alias for the original rest. Both 3.x and 4.x tail do the same thing.
Add support for lodash 4.x (Found in Grunt 1.x) * Changed lodash `rest` usage to tail. * Note this still supports lodash 3.x as tail was an alias for the original rest. Both 3.x and 4.x tail do the same thing.
JavaScript
mit
mikaelkaron/grunt-util-options
fd3e37f287d48df7185f8655dab37894ffafaae6
main.js
main.js
import ExamplePluginComponent from "./components/ExamplePluginComponent"; var PluginHelper = global.MarathonUIPluginAPI.PluginHelper; PluginHelper.registerMe("examplePlugin-0.0.1"); PluginHelper.injectComponent(ExamplePluginComponent, "SIDEBAR_BOTTOM");
import ExamplePluginComponent from "./components/ExamplePluginComponent"; var MarathonUIPluginAPI = global.MarathonUIPluginAPI; var PluginHelper = MarathonUIPluginAPI.PluginHelper; var PluginMountPoints = MarathonUIPluginAPI.PluginMountPoints; PluginHelper.registerMe("examplePlugin-0.0.1"); PluginHelper.injectComponent(ExamplePluginComponent, PluginMountPoints.SIDEBAR_BOTTOM);
Introduce read-only but extensible mount points file
Introduce read-only but extensible mount points file
JavaScript
apache-2.0
mesosphere/marathon-ui-example-plugin
87cb50db1913fccaee9e06f4eef8ab16d8564488
popup.js
popup.js
document.addEventListener('DOMContentLoaded', function () { display('Searching...'); }); function display(msg) { var el = document.body; el.innerHTML = msg; } chrome.runtime.getBackgroundPage(displayMessages); function displayMessages(backgroundPage) { var html = '<ul>'; html += backgroundPage.services.map(function (service) { return '<li class="service">' + service.name + '<span class="host">' + service.host + ':' + service.port + '</span>' '</li>'; }).join(''); html += '</ul>'; display(html); var items = Array.prototype.slice.call(document.getElementsByTagName('li')), uiPage = chrome.extension.getURL("ui.html"); items.forEach(function(li) { li.addEventListener('click', function() { chrome.tabs.create({url: uiPage}); }); }); }
document.addEventListener('DOMContentLoaded', function () { display('Searching...'); }); function display(msg) { var el = document.body; el.innerHTML = msg; } chrome.runtime.getBackgroundPage(displayMessages); function displayMessages(backgroundPage) { var html = '<ul>'; html += backgroundPage.services.map(function (service) { return '<li class="service">' + service.host + '<span class="host">' + service.address + ':' + service.port + '</span>' '</li>'; }).join(''); html += '</ul>'; display(html); var items = Array.prototype.slice.call(document.getElementsByTagName('li')), uiPage = chrome.extension.getURL("ui.html"); items.forEach(function(li) { li.addEventListener('click', function() { chrome.tabs.create({url: uiPage}); }); }); }
Change name to match new service instance object
Change name to match new service instance object
JavaScript
apache-2.0
mediascape/discovery-extension,mediascape/discovery-extension
06164aff052d6922f1506398dc60a7dde78a9f98
resolve-cache.js
resolve-cache.js
'use strict'; const _ = require('lodash'); const tests = { db: (value) => { const keys = ['query', 'connect', 'begin']; return keys.every((key) => _.has(value, key)); }, }; const ok = require('ok')(tests); const previous = []; module.exports = (obj) => { const result = obj ? previous.find((item) => _.isEqual(item, obj)) : _.last(previous); if (result) { return result; } else { const errors = ok(obj); if (errors.length) { throw new Error(`Configuration is invalid: ${errors.join(', ')}`); } if (obj) { previous.push(obj); } return obj; } };
'use strict'; const _ = require('lodash'); const tests = { db: (value) => { const keys = ['query', 'connect', 'begin']; return keys.every((key) => _.has(value, key)); }, }; const ok = require('ok')(tests); const previous = []; module.exports = (obj) => { let result; if (obj) { result = previous.find((item) => _.isEqual(item, obj)); } if (result) { return result; } else { const errors = ok(obj); if (errors.length) { throw new Error(`Configuration is invalid: ${errors.join(', ')}`); } if (obj) { previous.push(obj); } return obj; } };
Remove ability to get last memoize result by passing falsy argument
Remove ability to get last memoize result by passing falsy argument
JavaScript
mit
thebitmill/midwest-membership-services
ba70aba5132157e1ec43264a2cc5257ba0ba880c
src/client/app/states/manage/cms/cms.state.js
src/client/app/states/manage/cms/cms.state.js
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper, navigationHelper) { routerHelper.configureStates(getStates()); navigationHelper.navItems(navItems()); navigationHelper.sidebarItems(sidebarItems()); } function getStates() { return { 'manage.cms': { url: '/cms', redirectTo: 'manage.cms.list', template: '<ui-view></ui-view>' } }; } function navItems() { return {}; } function sidebarItems() { return { 'manage.cms': { type: 'state', state: 'manage.cms', label: 'CMS', order: 10 } }; } })();
(function() { 'use strict'; angular.module('app.states') .run(appRun); /** @ngInject */ function appRun(routerHelper, navigationHelper) { routerHelper.configureStates(getStates()); navigationHelper.navItems(navItems()); navigationHelper.sidebarItems(sidebarItems()); } function getStates() { return { 'manage.cms': { url: '/cms', redirectTo: 'manage.cms.list', template: '<ui-view></ui-view>' } }; } function navItems() { return {}; } function sidebarItems() { return { 'manage.cms': { type: 'state', state: 'manage.cms', label: 'Pages', order: 10 } }; } })();
Rename CMS label to Pages
Rename CMS label to Pages
JavaScript
apache-2.0
stackus/api,sreekantch/JellyFish,mafernando/api,sonejah21/api,AllenBW/api,stackus/api,projectjellyfish/api,AllenBW/api,mafernando/api,boozallen/projectjellyfish,projectjellyfish/api,boozallen/projectjellyfish,stackus/api,sonejah21/api,AllenBW/api,sreekantch/JellyFish,sonejah21/api,sreekantch/JellyFish,boozallen/projectjellyfish,projectjellyfish/api,mafernando/api,boozallen/projectjellyfish
69454caa8503cb7cfa7366d569ed16cd9bf4caa8
app/configureStore.js
app/configureStore.js
import { createStore, applyMiddleware } from 'redux' import logger from 'redux-logger' import thunk from 'redux-thunk' import oaaChat from './reducers' const configureStore = () => { const store = createStore( oaaChat, applyMiddleware(thunk, logger())) return store } export default configureStore
import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import oaaChat from './reducers' const configureStore = () => { const store = createStore( oaaChat, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), applyMiddleware(thunk)) return store } export default configureStore
Remove redux-logger and setup redux devtools
Remove redux-logger and setup redux devtools
JavaScript
mit
danielzy95/oaa-chat,danielzy95/oaa-chat
f7d6d3ff62ac6de0022e4b014ac5b04096758d48
src/db/migrations/20161005172637_init_demo.js
src/db/migrations/20161005172637_init_demo.js
export async function up(knex) { await knex.schema.createTable('Resource', (table) => { table.uuid('id').notNullable().primary() table.string('name', 32).notNullable() table.string('mime', 32) table.string('md5') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) await knex.schema.createTable('Content', (table) => { table.increments() table.uuid('resourceId').notNullable().references('Resource.id') table.string('name', 32) table.string('title', 255) table.text('description') table.json('data') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) } export async function down(knex) { await knex.schema.dropTableIfExists('Content') await knex.schema.dropTableIfExists('Resource') }
export async function up(knex) { await knex.schema.createTable('Resource', (table) => { table.uuid('id').notNullable().primary() table.string('name', 32).notNullable() table.string('mime', 32) table.string('md5') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) await knex.schema.createTable('Content', (table) => { table.increments() table.uuid('resourceId').notNullable().references('Resource.id') table.string('name', 32).notNullable() table.string('title', 255) table.text('description') table.json('data') table.integer('status').notNullable() table.bigInteger('createdAt') table.bigInteger('updatedAt') }) } export async function down(knex) { await knex.schema.dropTableIfExists('Content') await knex.schema.dropTableIfExists('Resource') }
Tweak Content name to be not nullable
Tweak Content name to be not nullable
JavaScript
mit
thangntt2/chatbot_api_hapi,vietthang/hapi-boilerplate
fcbaeb4705d02858f59c1142f77117e953c4db96
app/libs/locale/available-locales.js
app/libs/locale/available-locales.js
'use strict'; // Load our requirements const glob = require('glob'), path = require('path'), logger = require('../log'); // Build a list of the available locale files in a given directory module.exports = function(dir) { // Variables let available = []; // Run through the installed locales and add to array to be loaded glob.sync(path.join(dir, '/*.json')).forEach((file) => { // Get the shortname for the file let lang = path.basename(file, '.json'); // Add to our object logger.debug('Found the "%s" locale.', lang); available.push(lang); }); return available; };
'use strict'; // Load our requirements const glob = require('glob'), path = require('path'), logger = require(__base + 'libs/log'); // Build a list of the available locale files in a given directory module.exports = function(dir) { // Variables let available = ['en']; // Run through the installed locales and add to array to be loaded glob.sync(path.join(dir, '/*.json')).forEach((file) => { // Get the shortname for the file let lang = path.basename(file, '.json'); // Ignore english if ( lang !== 'en' ) { available.push(lang); } }); return available; };
Update available locales to prioritise english
Update available locales to prioritise english
JavaScript
apache-2.0
transmutejs/core
27ea2b2e1951431b0f6bae742d7c3babf5053bc1
jest.config.js
jest.config.js
module.exports = { verbose: !!process.env.VERBOSE, moduleNameMapper: { testHelpers: '<rootDir>/testHelpers/index.js', }, setupTestFrameworkScriptFile: '<rootDir>/testHelpers/setup.js', testResultsProcessor: './node_modules/jest-junit', testPathIgnorePatterns: ['/node_modules/'], testEnvironment: 'node', }
module.exports = { verbose: !!process.env.VERBOSE, moduleNameMapper: { testHelpers: '<rootDir>/testHelpers/index.js', }, setupTestFrameworkScriptFile: '<rootDir>/testHelpers/setup.js', testResultsProcessor: './node_modules/jest-junit', testPathIgnorePatterns: ['/node_modules/'], testEnvironment: 'node', bail: true, }
Configure tests to fail fast
Configure tests to fail fast
JavaScript
mit
tulios/kafkajs,tulios/kafkajs,tulios/kafkajs,tulios/kafkajs
fd6dd6bbe2220181202535eb6df9715bf78cf956
js/agency.js
js/agency.js
/*! * Start Bootstrap - Agnecy Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top' }) // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); });
/*! * Start Bootstrap - Agnecy Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top' }) // Event tracking for google analytics // inspired by http://cutroni.com/blog/2012/02/21/advanced-content-tracking-with-google-analytics-part-1/ var timer = 0; var callBackTime = 700; var debugTracker = false; var startTime = new Date().getTime(); var currentItem = ""; function trackLocation() { var currentTime = new Date().getTime(); var timeToScroll = Math.round((currentTime - startTime) / 1000); if(!debugTracker) { ga('send', { 'hitType': 'event', 'eventCategory': 'Navigation', 'eventAction': '#'+currentItem, 'eventValue': timeToScroll }); } else { console.log("You have viewed: #" + currentItem + " (" + timeToScroll + " sec.)"); } // determine current location currentItem = $(".nav li.active > a").text(); // reset duration startTime = currentTime; } $('body').on('activate.bs.scrollspy', function () { // Use a buffer so we don't call track location too often (high speed scroll) if (timer) clearTimeout(timer); timer = setTimeout(trackLocation, callBackTime); }) window.onbeforeunload = function() { trackLocation(); return null; } // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); });
Add event tracking to google analytics
Add event tracking to google analytics
JavaScript
apache-2.0
tibotiber/greeny,tibotiber/greeny,tibotiber/greeny
4fd824256e18f986f2cbd3c54cb1b9019cc1918e
index.js
index.js
var pkg = require(process.cwd() + '/package.json'); var intrepidjsVersion = pkg.version; // Dummy index, only shows intrepidjs-cli version console.log(intrepidjsVersion);
var pkg = require(__dirname + '/package.json'); var intrepidjsVersion = pkg.version; // Dummy index, only shows intrepidjs-cli version console.log(intrepidjsVersion);
Use __dirname instead of process.cwd
Use __dirname instead of process.cwd process.cwd refers to the directory in which file was executed, not the directory in which it lives
JavaScript
mit
wtelecom/intrepidjs-cli
2f747d79f542577e5cf60d18b9fbf8eea82070da
index.js
index.js
'use strict'; module.exports = { name: 'Ember CLI ic-ajax', init: function(name) { this.treePaths['vendor'] = 'node_modules'; }, included: function(app) { var options = this.app.options.icAjaxOptions || {enabled: true}; if (options.enabled) { this.app.import('vendor/ic-ajax/dist/named-amd/main.js', { exports: { 'ic-ajax': [ 'default', 'defineFixture', 'lookupFixture', 'raw', 'request', ] } }); } } };
'use strict'; module.exports = { name: 'Ember CLI ic-ajax', init: function(name) { this.treePaths['vendor'] = require.resolve('ic-ajax').replace('ic-ajax/dist/cjs/main.js', ''); }, included: function(app) { var options = this.app.options.icAjaxOptions || {enabled: true}; if (options.enabled) { this.app.import('vendor/ic-ajax/dist/named-amd/main.js', { exports: { 'ic-ajax': [ 'default', 'defineFixture', 'lookupFixture', 'raw', 'request', ] } }); } } };
Revert "Revert "resolve ala node_module resolution algorithim (NPM v3 support);""
Revert "Revert "resolve ala node_module resolution algorithim (NPM v3 support);"" This reverts commit 2aeb7307e81c8052b2fb6021bf4ab10ca433abce.
JavaScript
mit
rwjblue/ember-cli-ic-ajax,tsing80/ember-cli-ic-ajax,stefanpenner/ember-cli-ic-ajax,taras/ember-cli-ic-ajax
cb0ebc4c7ca492ed3c1144777643468ef0db054e
index.js
index.js
import postcss from 'postcss'; const postcssFlexibility = postcss.plugin('postcss-flexibility', () => css => { css.walkRules(rule => { const isDisabled = rule.some(({prop, text}) => prop === '-js-display' || text === 'flexibility-disable' || text === '! flexibility-disable' ); if (!isDisabled) { rule.walkDecls('display', decl => { const {value} = decl; if (value === 'flex') { decl.cloneBefore({prop: '-js-display'}); } }); } }); }); export default postcssFlexibility;
import postcss from 'postcss'; const postcssFlexibility = postcss.plugin('postcss-flexibility', () => css => { css.walkRules(rule => { const isDisabled = rule.some(({prop, text = ''}) => prop === '-js-display' || text.endsWith('flexibility-disable') ); if (!isDisabled) { rule.walkDecls('display', decl => { const {value} = decl; if (value === 'flex') { decl.cloneBefore({prop: '-js-display'}); } }); } }); }); export default postcssFlexibility;
Change check to use endsWith for supporting loud comments
Change check to use endsWith for supporting loud comments
JavaScript
mit
7rulnik/postcss-flexibility
98ded26910a319a9bfb7b9ce5cbece57254bbb31
index.js
index.js
$(document).ready(function() { $("#trcAge").slider({ id: "trcAge" }); $("#trcAge").on("slide", function(slideEvt) { console.log("Age range selected", slideEvt.value); $("#trcAgeSelection").text(slideEvt.value.join(" - ")); }); });
$(document).ready(function() { $("#trcAge").slider({ id: "trcAge" }); $("#trcAge").on("slide", function(slideEvt) { // console.log("Age range selected", slideEvt.value); $("#trcAgeSelection").text(slideEvt.value.join(" - ")); }); });
Undo console log (was a demo of git)
Undo console log (was a demo of git)
JavaScript
agpl-3.0
6System7/cep,6System7/cep
933ee47b1f2cf923f4937ebb8297cef49c3390f8
index.js
index.js
#!/usr/bin/env node const express = require('express'); const fileExists = require('file-exists'); const bodyParser = require('body-parser'); const fs = require('fs'); const { port = 8123 } = require('minimist')(process.argv.slice(2)); const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.get('*', (req, res) => { const filePath = req.get('X-Requested-File-Path'); if (!filePath) { return res.status(500).send('Server did not provide file path'); } if (!fileExists(filePath)) { return res.status(500).send('Cannot find such file on the server'); } try { require(filePath)(req, res); // eslint-disable-line global-require } catch (e) { return res.status(500).send(`<pre>${e.stack}</pre>`); } const watcher = fs.watch(filePath, (eventType) => { if (eventType === 'change') { delete require.cache[require.resolve(filePath)]; watcher.close(); } }); return undefined; }); app.listen(port, () => { console.log(`node-direct listening on port ${port}!`); });
#!/usr/bin/env node const express = require('express'); const fileExists = require('file-exists'); const bodyParser = require('body-parser'); const fs = require('fs'); const { port = 8123 } = require('minimist')(process.argv.slice(2)); const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.get('*', (req, res) => { const filePath = req.get('X-Requested-File-Path'); if (!filePath) { return res.status(500).send('Server did not provide file path'); } if (!fileExists(filePath)) { return res.status(404).send('Cannot find such file on the server'); } try { require(filePath)(req, res); // eslint-disable-line global-require } catch (e) { return res.status(500).send(`<pre>${e.stack}</pre>`); } const watcher = fs.watch(filePath, (eventType) => { if (eventType === 'change') { delete require.cache[require.resolve(filePath)]; watcher.close(); } }); return undefined; }); app.listen(port, () => { console.log(`node-direct listening on port ${port}!`); });
Use 404 instead of 500 when a file is not found
fix: Use 404 instead of 500 when a file is not found
JavaScript
mit
finom/node-direct,finom/node-direct
a2172115022e7658573428d9ddf9b094f9c6d1b5
index.js
index.js
module.exports = isPromise; function isPromise(obj) { return obj && typeof obj.then === 'function'; }
module.exports = isPromise; function isPromise(obj) { return obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; }
Make the test a bit more strict
Make the test a bit more strict
JavaScript
mit
floatdrop/is-promise,then/is-promise,then/is-promise
edbc6e8931c9c2777520c0ccf0a3d74b8f75ebf6
index.js
index.js
const Discord = require('discord.js'); const client = new Discord.Client(); const config = require("./config.json"); client.on('ready', () => { console.log("I am ready!"); // client.channels.get('spam').send("Soup is ready!") }); client.on('message', (message) => { if (!message.content.startsWith(config.prefix) || message.author.bot) return; let msg = message.content.slice(config.prefix.length); if (msg.startsWith('ping')) { message.reply('pong'); } if (msg.startsWith('echo')) { if (msg.length > 5) { message.channel.send(msg.slice(5)); } else { message.channel.send("Please provide valid text to echo!"); } } if (msg.startsWith('die')) { message.channel.send("Shutting down..."); client.destroy((err) => { console.log(err); }); } }); client.on('disconnected', () => { console.log("Disconnected!"); process.exit(0); }); client.login(config.token);
const Discord = require('discord.js'); const client = new Discord.Client(); const config = require("./config.json"); client.on('ready', () => { console.log("I am ready!"); }); client.on('message', (message) => { if (!message.content.startsWith(config.prefix) || message.author.bot) return; // Ignore messages not // starting with your prefix let msg = message.content.slice(config.prefix.length); if (msg.startsWith('ping')) { message.reply('pong'); } if (msg.startsWith('echo')) { if (msg.length > 5 && msg[4] === ' ') { // If msg starts with 'echo ' message.channel.send(msg.slice(5)); // Echo the rest of msg. } else { message.channel.send("Please provide valid text to echo!"); } } if (msg.startsWith('die')) { message.channel.send("Shutting down..."); client.destroy((err) => { console.log(err); }); } }); client.on('disconnected', () => { console.log("Disconnected!"); process.exit(0); }); client.login(config.token);
Add some comments and refine echo command
Add some comments and refine echo command
JavaScript
mit
Rafer45/soup
e1e5840e921465d0454213cb455aca4661bcf715
index.js
index.js
var Q = require('q'); /** * Chai-Mugshot Plugin * * @param mugshot - Mugshot instance * @param testRunnerCtx - Context of the test runner where the assertions are * done */ module.exports = function(mugshot, testRunnerCtx) { return function(chai) { var Assertion = chai.Assertion; function composeMessage(message) { var standardMessage = 'expected baseline and screenshot of #{act}'; return { affirmative: standardMessage + ' to ' + message, negative: standardMessage + ' to not ' + message }; } function mugshotProperty(name, message) { var msg = composeMessage(message); Assertion.addProperty(name, function() { var captureItem = this._obj; var deferred = Q.defer(); var _this = this; mugshot.test(captureItem, function(error, result) { if (error) { deferred.reject(error); } else { if (testRunnerCtx !== undefined) { testRunnerCtx.result = result; } try { _this.assert(result.isEqual, msg.affirmative, msg.negative); deferred.resolve(); } catch (error) { deferred.reject(error); } } }); return deferred.promise; }); } mugshotProperty('identical', 'be identical'); } };
/** * Chai-Mugshot Plugin * * @param mugshot - Mugshot instance * @param testRunnerCtx - Context of the test runner where the assertions are * done */ module.exports = function(mugshot, testRunnerCtx) { return function(chai) { var Assertion = chai.Assertion; function composeMessage(message) { var standardMessage = 'expected baseline and screenshot of #{act}'; return { affirmative: standardMessage + ' to ' + message, negative: standardMessage + ' to not ' + message }; } function mugshotProperty(name, message) { var msg = composeMessage(message); Assertion.addProperty(name, function() { var _this = this, captureItem = this._obj, promise, resolve, reject; promise = new Promise(function(res, rej) { resolve = res; reject = rej; }); mugshot.test(captureItem, function(error, result) { if (error) { reject(error); } else { if (testRunnerCtx !== undefined) { testRunnerCtx.result = result; } try { _this.assert(result.isEqual, msg.affirmative, msg.negative); resolve(); } catch (error) { reject(error); } } }); return promise; }); } mugshotProperty('identical', 'be identical'); } };
Replace q with native Promises
Replace q with native Promises
JavaScript
mit
uberVU/chai-mugshot,uberVU/chai-mugshot
bc3e85aafc3fa1095169153661093d3f012424e2
node_modules/hotCoreStoreRegistry/lib/hotCoreStoreRegistry.js
node_modules/hotCoreStoreRegistry/lib/hotCoreStoreRegistry.js
"use strict"; /*! * Module dependencies. */ var dummy , hotplate = require('hotplate') ; exports.getAllStores = hotplate.cachable( function( done ){ var res = { stores: {}, collections: {}, }; hotplate.hotEvents.emit( 'stores', function( err, results){ results.forEach( function( element ) { element.result.forEach( function( Store ){ try { var store = new Store(); } catch ( e ){ hotplate.log("AN ERROR HAPPENED WHILE INSTANCING A STORE: " ); hotplate.log( e ); hotplate.log( element ); hotplate.log( Store ); } // If the store was created (no exception thrown...) if( store ){ // Add the module to the store registry res.stores[ store.storeName ] = { Store: Store, storeObject: store }; // Add the module to the collection registry if( store.collectionName ){ res.collections[ store.collectionName ] = res.collections[ store.collectionName ] || []; res.collections[ store.collectionName ].push( { Store: Store, storeObject: store } ); } } }); }); done( null, res ); }); });
"use strict"; /*! * Module dependencies. */ var dummy , hotplate = require('hotplate') ; exports.getAllStores = hotplate.cachable( function( done ){ var res = { stores: {}, collections: {}, }; hotplate.hotEvents.emit( 'stores', function( err, results){ results.forEach( function( element ) { Object.keys( element.result ).forEach( function( k ){ var Store = element.result[ k ]; try { var store = new Store(); } catch ( e ){ hotplate.log("AN ERROR HAPPENED WHILE INSTANCING A STORE: " ); hotplate.log( e ); hotplate.log( element ); hotplate.log( Store ); } // If the store was created (no exception thrown...) if( store ){ // Add the module to the store registry res.stores[ store.storeName ] = { Store: Store, storeObject: store }; // Add the module to the collection registry if( store.collectionName ){ res.collections[ store.collectionName ] = res.collections[ store.collectionName ] || []; res.collections[ store.collectionName ].push( { Store: Store, storeObject: store } ); } } }); }); done( null, res ); }); });
Change way in which storeRegistry expects stores to be returned, it's now a hash
Change way in which storeRegistry expects stores to be returned, it's now a hash
JavaScript
mit
shelsonjava/hotplate,mercmobily/hotplate,mercmobily/hotplate,shelsonjava/hotplate
9235990779b1098df387e534656a921107732818
src/mw-menu/directives/mw_menu_top_entries.js
src/mw-menu/directives/mw_menu_top_entries.js
angular.module('mwUI.Menu') .directive('mwMenuTopEntries', function ($rootScope, $timeout) { return { scope: { menu: '=mwMenuTopEntries', right: '=' }, transclude: true, templateUrl: 'uikit/mw-menu/directives/templates/mw_menu_top_entries.html', controller: function ($scope) { var menu = $scope.menu || new mwUI.Menu.MwMenu(); this.getMenu = function () { return menu; }; }, link: function (scope, el, attrs, ctrl) { scope.entries = ctrl.getMenu(); scope.unCollapse = function () { var collapseEl = el.find('.navbar-collapse'); if (collapseEl.hasClass('in')) { collapseEl.collapse('hide'); } }; $rootScope.$on('$locationChangeSuccess', function () { scope.unCollapse(); }); scope.$on('mw-menu:triggerReorder', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); scope.$on('mw-menu:triggerResort', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:resort'); scope.entries.sort(); }); })); scope.entries.on('add remove reset', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); } }; });
angular.module('mwUI.Menu') .directive('mwMenuTopEntries', function ($rootScope, $timeout) { return { scope: { menu: '=mwMenuTopEntries', right: '=' }, transclude: true, templateUrl: 'uikit/mw-menu/directives/templates/mw_menu_top_entries.html', controller: function ($scope) { var menu = $scope.menu || new mwUI.Menu.MwMenu(); this.getMenu = function () { return menu; }; }, link: function (scope, el, attrs, ctrl) { scope.entries = ctrl.getMenu(); scope.$on('mw-menu:triggerReorder', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); scope.$on('mw-menu:triggerResort', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:resort'); scope.entries.sort(); }); })); scope.entries.on('add remove reset', _.throttle(function () { $timeout(function () { scope.$broadcast('mw-menu:reorder'); }); })); } }; });
Move close functionality on location change into mwMenuTopBar
Move close functionality on location change into mwMenuTopBar
JavaScript
apache-2.0
mwaylabs/uikit,mwaylabs/uikit,mwaylabs/uikit
b9c96cfc73b6e0adcb7b747c40ac40c74995ea7f
eslint-rules/no-primitive-constructors.js
eslint-rules/no-primitive-constructors.js
/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; module.exports = function(context) { function check(node) { const name = node.callee.name; let msg = null; switch (name) { case 'Boolean': msg = 'To cast a value to a boolean, use double negation: !!value'; break; case 'String': msg = 'To cast a value to a string, concat it with the empty string: \'\' + value'; break; } if (msg) { context.report(node, `Do not use the ${name} constructor. ${msg}`); } } return { CallExpression: check, NewExpression: check, }; };
/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; module.exports = function(context) { function report(node, name, msg) { context.report(node, `Do not use the ${name} constructor. ${msg}`); } function check(node) { const name = node.callee.name; switch (name) { case 'Boolean': report( node, name, 'To cast a value to a boolean, use double negation: !!value' ); break; case 'String': report( node, name, 'To cast a value to a string, concat it with the empty string ' + '(unless it\'s a symbol, which have different semantics): ' + '\'\' + value' ); break; } } return { CallExpression: check, NewExpression: check, }; };
Add caveat about symbols to string error message
Add caveat about symbols to string error message
JavaScript
bsd-3-clause
acdlite/react,apaatsio/react,jorrit/react,krasimir/react,jordanpapaleo/react,mosoft521/react,facebook/react,jameszhan/react,yungsters/react,STRML/react,AlmeroSteyn/react,glenjamin/react,tomocchino/react,Simek/react,trueadm/react,jzmq/react,TheBlasfem/react,silvestrijonathan/react,joecritch/react,yiminghe/react,prometheansacrifice/react,shergin/react,jzmq/react,sekiyaeiji/react,STRML/react,quip/react,wmydz1/react,ArunTesco/react,ArunTesco/react,Simek/react,camsong/react,terminatorheart/react,aickin/react,pyitphyoaung/react,ArunTesco/react,facebook/react,silvestrijonathan/react,yiminghe/react,AlmeroSteyn/react,glenjamin/react,quip/react,cpojer/react,chicoxyzzy/react,kaushik94/react,rickbeerendonk/react,acdlite/react,prometheansacrifice/react,TheBlasfem/react,camsong/react,silvestrijonathan/react,yungsters/react,rricard/react,yungsters/react,flarnie/react,yangshun/react,rickbeerendonk/react,jquense/react,syranide/react,VioletLife/react,anushreesubramani/react,jorrit/react,joecritch/react,jordanpapaleo/react,rickbeerendonk/react,glenjamin/react,roth1002/react,edvinerikson/react,jameszhan/react,wmydz1/react,roth1002/react,jdlehman/react,anushreesubramani/react,yangshun/react,edvinerikson/react,AlmeroSteyn/react,AlmeroSteyn/react,jzmq/react,cpojer/react,chicoxyzzy/react,billfeller/react,AlmeroSteyn/react,apaatsio/react,terminatorheart/react,yiminghe/react,leexiaosi/react,STRML/react,maxschmeling/react,mosoft521/react,roth1002/react,Simek/react,empyrical/react,joecritch/react,shergin/react,kaushik94/react,mhhegazy/react,jdlehman/react,nhunzaker/react,roth1002/react,jzmq/react,mosoft521/react,prometheansacrifice/react,mjackson/react,kaushik94/react,rickbeerendonk/react,cpojer/react,Simek/react,acdlite/react,nhunzaker/react,mhhegazy/react,AlmeroSteyn/react,jquense/react,silvestrijonathan/react,silvestrijonathan/react,yungsters/react,joecritch/react,dilidili/react,kaushik94/react,anushreesubramani/react,chenglou/react,ericyang321/react,mhhegazy/react,jzmq/react,jdlehman/react,tomocchino/react,STRML/react,facebook/react,dilidili/react,yiminghe/react,acdlite/react,aickin/react,TheBlasfem/react,dilidili/react,krasimir/react,jordanpapaleo/react,mjackson/react,TheBlasfem/react,yiminghe/react,aickin/react,ericyang321/react,yungsters/react,brigand/react,jzmq/react,chenglou/react,mhhegazy/react,jameszhan/react,cpojer/react,cpojer/react,mjackson/react,brigand/react,shergin/react,jquense/react,anushreesubramani/react,brigand/react,jordanpapaleo/react,pyitphyoaung/react,pyitphyoaung/react,edvinerikson/react,jdlehman/react,roth1002/react,jorrit/react,kaushik94/react,jdlehman/react,glenjamin/react,tomocchino/react,TheBlasfem/react,pyitphyoaung/react,acdlite/react,maxschmeling/react,jordanpapaleo/react,maxschmeling/react,krasimir/react,rricard/react,AlmeroSteyn/react,mhhegazy/react,kaushik94/react,jzmq/react,billfeller/react,joecritch/react,leexiaosi/react,krasimir/react,STRML/react,prometheansacrifice/react,ericyang321/react,trueadm/react,trueadm/react,aickin/react,shergin/react,Simek/react,ericyang321/react,facebook/react,billfeller/react,maxschmeling/react,pyitphyoaung/react,apaatsio/react,VioletLife/react,camsong/react,terminatorheart/react,anushreesubramani/react,silvestrijonathan/react,jquense/react,tomocchino/react,chenglou/react,yiminghe/react,empyrical/react,chenglou/react,yiminghe/react,yangshun/react,aickin/react,facebook/react,nhunzaker/react,prometheansacrifice/react,maxschmeling/react,glenjamin/react,flarnie/react,rricard/react,joecritch/react,prometheansacrifice/react,quip/react,billfeller/react,edvinerikson/react,syranide/react,STRML/react,yangshun/react,aickin/react,jorrit/react,camsong/react,terminatorheart/react,billfeller/react,dilidili/react,ericyang321/react,maxschmeling/react,facebook/react,trueadm/react,nhunzaker/react,VioletLife/react,jameszhan/react,chicoxyzzy/react,mhhegazy/react,brigand/react,empyrical/react,acdlite/react,anushreesubramani/react,yangshun/react,kaushik94/react,jquense/react,apaatsio/react,dilidili/react,quip/react,tomocchino/react,empyrical/react,jdlehman/react,syranide/react,mosoft521/react,cpojer/react,sekiyaeiji/react,jameszhan/react,krasimir/react,prometheansacrifice/react,roth1002/react,shergin/react,krasimir/react,yangshun/react,jorrit/react,trueadm/react,edvinerikson/react,apaatsio/react,TheBlasfem/react,wmydz1/react,mhhegazy/react,flarnie/react,jordanpapaleo/react,leexiaosi/react,pyitphyoaung/react,anushreesubramani/react,mjackson/react,dilidili/react,Simek/react,tomocchino/react,chicoxyzzy/react,VioletLife/react,quip/react,rricard/react,ericyang321/react,quip/react,mosoft521/react,brigand/react,edvinerikson/react,yungsters/react,jameszhan/react,glenjamin/react,sekiyaeiji/react,brigand/react,apaatsio/react,brigand/react,VioletLife/react,mosoft521/react,flarnie/react,rickbeerendonk/react,mjackson/react,mjackson/react,mosoft521/react,cpojer/react,flipactual/react,empyrical/react,wmydz1/react,trueadm/react,dilidili/react,jquense/react,roth1002/react,edvinerikson/react,chicoxyzzy/react,rickbeerendonk/react,wmydz1/react,Simek/react,flipactual/react,chicoxyzzy/react,apaatsio/react,shergin/react,camsong/react,jameszhan/react,chenglou/react,empyrical/react,yungsters/react,mjackson/react,camsong/react,nhunzaker/react,chenglou/react,wmydz1/react,glenjamin/react,flipactual/react,VioletLife/react,jorrit/react,shergin/react,jorrit/react,silvestrijonathan/react,krasimir/react,ericyang321/react,joecritch/react,wmydz1/react,empyrical/react,chenglou/react,billfeller/react,aickin/react,jdlehman/react,nhunzaker/react,VioletLife/react,yangshun/react,rricard/react,rricard/react,rickbeerendonk/react,maxschmeling/react,flarnie/react,quip/react,camsong/react,terminatorheart/react,chicoxyzzy/react,nhunzaker/react,trueadm/react,acdlite/react,pyitphyoaung/react,STRML/react,flarnie/react,facebook/react,jquense/react,syranide/react,jordanpapaleo/react,billfeller/react,tomocchino/react,terminatorheart/react,flarnie/react
8aa85b90cbffc79fdc54ba1aac070d7fb2a8dccb
public/controllers/main.routes.js
public/controllers/main.routes.js
'use strict'; angular.module('StudentApp').config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider.when('/studentPage', { templateUrl: 'views/student/student.list.html', controller: 'StudentController' }).when('/comments/:id', { templateUrl: 'views/comment/comments.list.html', controller: 'CommentsController' }).when('/stockPage', { templateUrl: 'views/Stock/StockManagment.html', controller: 'StockController' }).when('/orderPage', { templateUrl: 'views/Stock/OrderManagment.html', controller: 'OrderController' }).otherwise({ redirectTo: '/' }); $locationProvider.html5Mode(true); }]);
'use strict'; angular.module('StudentApp').config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { $routeProvider.when('/studentPage', { templateUrl: 'views/student/student.list.html', controller: 'StudentController' }).when('/comments/:id', { templateUrl: 'views/comment/comments.list.html', controller: 'CommentsController' }).when('/stockPage', { templateUrl: 'views/Stock/StockManagment.html', controller: 'StockController' }).when('/orderPage', { templateUrl: 'views/Stock/OrderManagment.html', controller: 'OrderController' }).when('/customerPage', { templateUrl: 'views/Customer/Customer.html', controller: 'CustomerController' }).otherwise({ redirectTo: '/' }); $locationProvider.html5Mode(true); }]);
Add relevant Customer section changes to main.router.js
Add relevant Customer section changes to main.router.js
JavaScript
mit
scoobygroup/IWEX,scoobygroup/IWEX
c11d0b3d616fb1d03cdbf0453dcdc5cb39ac122a
lib/node_modules/@stdlib/types/ndarray/ctor/lib/getnd.js
lib/node_modules/@stdlib/types/ndarray/ctor/lib/getnd.js
'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; // FUNCTIONS // /** * Returns an array element. * * @private * @param {...integer} idx - indices * @throws {TypeError} provided indices must be integer valued * @throws {RangeError} index exceeds array dimensions * @returns {*} array element */ function get() { /* eslint-disable no-invalid-this */ var len; var idx; var i; // TODO: support index modes len = arguments.length; idx = this._offset; for ( i = 0; i < len; i++ ) { if ( !isInteger( arguments[ i ] ) ) { throw new TypeError( 'invalid input argument. Indices must be integer valued. Argument: '+i+'. Value: `'+arguments[i]+'`.' ); } idx += this._strides[ i ] * arguments[ i ]; } return this._buffer[ idx ]; } // end FUNCTION get() // EXPORTS // module.exports = get;
'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; var getIndex = require( './get_index.js' ); // FUNCTIONS // /** * Returns an array element. * * @private * @param {...integer} idx - indices * @throws {TypeError} provided indices must be integer valued * @throws {RangeError} index exceeds array dimensions * @returns {*} array element */ function get() { /* eslint-disable no-invalid-this */ var len; var idx; var ind; var i; len = arguments.length; idx = this._offset; for ( i = 0; i < len; i++ ) { if ( !isInteger( arguments[ i ] ) ) { throw new TypeError( 'invalid input argument. Indices must be integer valued. Argument: '+i+'. Value: `'+arguments[i]+'`.' ); } ind = getIndex( arguments[ i ], this._shape[ i ], this._mode ); idx += this._strides[ i ] * ind; } return this._buffer[ idx ]; } // end FUNCTION get() // EXPORTS // module.exports = get;
Add support for an index mode
Add support for an index mode
JavaScript
apache-2.0
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
2d1bd23a872645053b8e19bdf8b656b8ca872c4b
index.js
index.js
require('babel/register'); require('dotenv').load(); var startServer = require('./app'); var port = process.env['PORT'] || 3000; startServer(port);
require('babel/register'); if (process.env.NODE_ENV !== 'production') { require('dotenv').load(); } var startServer = require('./app'); var port = process.env.PORT || 3000; startServer(port);
Handle case where dotenv is not included in production.
Handle case where dotenv is not included in production.
JavaScript
mit
keokilee/hitraffic-api,hitraffic/api-server
3321cc95a521445a1ad1a2f70c057acb583ac71e
solutions.digamma.damas.ui/src/components/layouts/app-page.js
solutions.digamma.damas.ui/src/components/layouts/app-page.js
import Vue from "vue" export default { name: 'AppPage', props: { layout: { type: String, required: true, validator: [].includes.bind(["standard", "empty"]) } }, created() { let component = components[this.layout] if (!Vue.options.components[component.name]) { Vue.component( component.name, component, ); } this.$parent.$emit('update:layout', component); }, render(h) { return this.$slots.default ? this.$slots.default[0] : h(); }, } const components = { "standard": () => import("./layout-standard"), "empty": () => import("./layout-empty") }
import Vue from "vue" export default { name: 'AppPage', props: { layout: { type: String, required: true, validator: [].includes.bind(["standard", "empty"]) } }, created() { let component = components[this.layout] if (!Vue.options.components[component.name]) { Vue.component( component.name, component, ); } if (this.$parent.layout !== component) { this.$parent.$emit('update:layout', component); } }, render(h) { return this.$slots.default ? this.$slots.default[0] : h(); }, } const components = { "standard": () => import("./layout-standard"), "empty": () => import("./layout-empty") }
Add identity gard before firing layout change
Add identity gard before firing layout change
JavaScript
mit
digammas/damas,digammas/damas,digammas/damas,digammas/damas
77174ca4c0e6e663ed9fb1cd5ef74d3ae7ec865c
index.js
index.js
"use strict"; var _ = require("lodash"); var HTTP_STATUS_CODES = require("http").STATUS_CODES; var request = require("request"); var url = require("url"); function LamernewsAPI(root) { this.root = root; return this; } LamernewsAPI.prototype.getNews = function getNews(options, callback) { var defaults = { count: 30, start: 0, type: "latest" }; var signature; if (!callback && typeof options === "function") { callback = options; options = {}; } options = _.defaults(options || {}, defaults); signature = ["getnews", options.type, options.start, options.count]; this.query(signature.join("/"), callback); return this; }; LamernewsAPI.prototype.query = function query(signature, callback) { if (!this.root) { throw new Error("No API root specified"); } request(url.resolve(this.root, signature), function(err, res, body) { var status; if (err) { return callback(err); } status = res.statusCode; if (status !== 200) { err = new Error(HTTP_STATUS_CODES[status]); err.code = status; return callback(err); } try { body = JSON.parse(body); } catch (err) { callback(err); } callback(null, body); }); }; module.exports = LamernewsAPI;
"use strict"; var _ = require("lodash"); var HTTP_STATUS_CODES = require("http").STATUS_CODES; var request = require("request"); var url = require("url"); function LamernewsAPI(root) { this.root = root; return this; } LamernewsAPI.prototype = { getNews: function getNews(options, callback) { var defaults = { count: 30, start: 0, type: "latest" }; var signature; if (!callback && typeof options === "function") { callback = options; options = {}; } options = _.defaults(options || {}, defaults); signature = ["getnews", options.type, options.start, options.count]; this.query(signature.join("/"), callback); return this; }, query: function query(signature, callback) { if (!this.root) { throw new Error("No API root specified"); } request(url.resolve(this.root, signature), function(err, res, body) { var status; if (err) { return callback(err); } status = res.statusCode; if (status !== 200) { err = new Error(HTTP_STATUS_CODES[status]); err.code = status; return callback(err); } try { body = JSON.parse(body); } catch (err) { callback(err); } callback(null, body); }); } }; module.exports = LamernewsAPI;
Refactor method definitions on prototype to be more DRY
Refactor method definitions on prototype to be more DRY
JavaScript
mit
sbruchmann/lamernews-api
5e4c5c4d4ecc1698c5adddb31a2378df0e78ec22
index.js
index.js
/** * espower-source - Power Assert instrumentor from source to source. * * https://github.com/twada/espower-source * * Copyright (c) 2014 Takuto Wada * Licensed under the MIT license. * https://github.com/twada/espower-source/blob/master/MIT-LICENSE.txt */ var espower = require('espower'), esprima = require('esprima'), escodegen = require('escodegen'), merge = require('lodash.merge'), convert = require('convert-source-map'); function espowerSourceToSource(jsCode, filepath, options) { 'use strict'; var jsAst, espowerOptions, modifiedAst, escodegenOutput, code, map; jsAst = esprima.parse(jsCode, {tolerant: true, loc: true, tokens: true, raw: true, source: filepath}); espowerOptions = merge(merge(espower.defaultOptions(), options), { destructive: true, path: filepath }); modifiedAst = espower(jsAst, espowerOptions); escodegenOutput = escodegen.generate(modifiedAst, { sourceMap: true, sourceMapWithCode: true }); code = escodegenOutput.code; // Generated source code map = convert.fromJSON(escodegenOutput.map.toString()); map.sourcemap.sourcesContent = [jsCode]; return code + '\n' + map.toComment() + '\n'; } module.exports = espowerSourceToSource;
/** * espower-source - Power Assert instrumentor from source to source. * * https://github.com/twada/espower-source * * Copyright (c) 2014 Takuto Wada * Licensed under the MIT license. * https://github.com/twada/espower-source/blob/master/MIT-LICENSE.txt */ var espower = require('espower'), esprima = require('esprima'), escodegen = require('escodegen'), merge = require('lodash.merge'), convert = require('convert-source-map'); function espowerSource(jsCode, filepath, options) { 'use strict'; var jsAst, espowerOptions, modifiedAst, escodegenOutput, code, map; jsAst = esprima.parse(jsCode, {tolerant: true, loc: true, tokens: true, raw: true, source: filepath}); espowerOptions = merge(merge(espower.defaultOptions(), options), { destructive: true, path: filepath }); modifiedAst = espower(jsAst, espowerOptions); escodegenOutput = escodegen.generate(modifiedAst, { sourceMap: true, sourceMapWithCode: true }); code = escodegenOutput.code; // Generated source code map = convert.fromJSON(escodegenOutput.map.toString()); map.sourcemap.sourcesContent = [jsCode]; return code + '\n' + map.toComment() + '\n'; } module.exports = espowerSource;
Change exposed function name to espowerSource
Change exposed function name to espowerSource
JavaScript
mit
power-assert-js/espower-source
2083f66c81315589377d6c2a174d45c5d32ff564
index.js
index.js
'use strict' var window = require('global/window') var Struct = require('observ-struct') var Observ = require('observ') var minimumViewport = require('minimum-viewport') var orientation = require('screen-orientation') var MOBILE_WIDTH = 640 var device = Struct({ mobile: Observ(false), orientation: Observ(null) }) module.exports = device if (window.addEventListener) { window.addEventListener('resize', onResize) onResize() } function onResize () { device.mobile.set(minimumViewport({x: MOBILE_WIDTH})) device.orientation.set(orientation().direction) }
'use strict' var window = require('global/window') var Struct = require('observ-struct') var Observ = require('observ') var minimumViewport = require('minimum-viewport') var orientation = require('screen-orientation') var MOBILE_WIDTH = 840 var device = Struct({ mobile: Observ(false), orientation: Observ(null) }) module.exports = device if (window.addEventListener) { window.addEventListener('resize', onResize) onResize() } function onResize () { device.mobile.set(minimumViewport({x: MOBILE_WIDTH})) device.orientation.set(orientation().direction) }
Update mobile width to 840 px
Update mobile width to 840 px
JavaScript
mit
bendrucker/observ-mobile
be9edb357e5ec2ae7cf99723018d5decbe154ccf
index.js
index.js
'use strict'; var MarkdownIt = require('markdown-it'); exports.name = 'markdown-it'; exports.outputFormat = 'html'; exports.render = function (str, options) { var md = MarkdownIt(options); return md.render(str); };
'use strict'; var MarkdownIt = require('markdown-it'); exports.name = 'markdown-it'; exports.outputFormat = 'xml'; exports.render = function (str, options) { var md = MarkdownIt(options); return md.render(str); };
Mark output format as XML
Mark output format as XML
JavaScript
mit
jstransformers/jstransformer-markdown-it,jstransformers/jstransformer-markdown-it
24ae87eca54f0baa1a379c21cac17fcc3c70f10c
index.js
index.js
function Fs() {} Fs.prototype = require('fs') var fs = new Fs() , Promise = require('promise') module.exports = exports = fs for (var key in fs) if (!(typeof fs[key] != 'function' || key.match(/Sync$/) || key.match(/^[A-Z]/) || key.match(/^create/) || key.match(/^(un)?watch/) )) fs[key] = Promise.denodeify(fs[key])
var fs = Object.create(require('fs')) var Promise = require('promise') module.exports = exports = fs for (var key in fs) if (!(typeof fs[key] != 'function' || key.match(/Sync$/) || key.match(/^[A-Z]/) || key.match(/^create/) || key.match(/^(un)?watch/) )) fs[key] = Promise.denodeify(fs[key])
Use multiple var statements and `Object.create`
Use multiple var statements and `Object.create`
JavaScript
mit
then/fs
3c8494b2151178eb169947e7da0775521e1c2bfd
index.js
index.js
/* eslint-env node */ "use strict"; module.exports = { name: "ember-component-attributes", setupPreprocessorRegistry(type, registry) { registry.add("htmlbars-ast-plugin", { name: "attributes-expression", plugin: require("./lib/attributes-expression-transform"), baseDir: function() { return __dirname; } }); } };
/* eslint-env node */ "use strict"; module.exports = { name: "ember-component-attributes", setupPreprocessorRegistry(type, registry) { registry.add("htmlbars-ast-plugin", { name: "attributes-expression", plugin: require("./lib/attributes-expression-transform"), baseDir: function() { return __dirname; } }); }, included() { this.import('vendor/ember-component-attributes/index.js'); }, treeForVendor(rawVendorTree) { let babelAddon = this.addons.find(addon => addon.name === 'ember-cli-babel'); let transpiledVendorTree = babelAddon.transpileTree(rawVendorTree, { 'ember-cli-babel': { compileModules: false } }); return transpiledVendorTree; }, };
Add `treeForVendor` and `included` hook implementations.
Add `treeForVendor` and `included` hook implementations.
JavaScript
mit
mmun/ember-component-attributes,mmun/ember-component-attributes
9dcd369bcd7529f8c925d82a73111df72fbdd433
index.js
index.js
/** * @jsx React.DOM */ var React = require('react'); var Pdf = React.createClass({ getInitialState: function() { return {}; }, componentDidMount: function() { var self = this; PDFJS.getDocument(this.props.file).then(function(pdf) { pdf.getPage(self.props.page).then(function(page) { self.setState({pdfPage: page, pdf: pdf}); }); }); }, componentWillReceiveProps: function(newProps) { var self = this; if (newProps.page) { self.state.pdf.getPage(newProps.page).then(function(page) { self.setState({pdfPage: page, pageId: newProps.page}); }); } this.setState({ pdfPage: null }); }, render: function() { var self = this; this.state.pdfPage && setTimeout(function() { var canvas = self.getDOMNode(), context = canvas.getContext('2d'), scale = 1.0, viewport = self.state.pdfPage.getViewport(scale); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; self.state.pdfPage.render(renderContext); }); return this.state.pdfPage ? <canvas></canvas> : <div>Loading pdf..</div>; } }); module.exports = Pdf;
/** * @jsx React.DOM */ var React = require('react'); var Pdf = React.createClass({ getInitialState: function() { return {}; }, componentDidMount: function() { var self = this; PDFJS.getDocument(this.props.file).then(function(pdf) { pdf.getPage(self.props.page).then(function(page) { self.setState({pdfPage: page, pdf: pdf}); }); }); }, componentWillReceiveProps: function(newProps) { var self = this; if (newProps.page) { self.state.pdf.getPage(newProps.page).then(function(page) { self.setState({pdfPage: page, pageId: newProps.page}); }); } this.setState({ pdfPage: null }); }, getDefaultProps: function() { return {page: 1}; }, render: function() { var self = this; this.state.pdfPage && setTimeout(function() { var canvas = self.getDOMNode(), context = canvas.getContext('2d'), scale = 1.0, viewport = self.state.pdfPage.getViewport(scale); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; self.state.pdfPage.render(renderContext); }); return this.state.pdfPage ? <canvas></canvas> : <div>Loading pdf..</div>; } }); module.exports = Pdf;
Add default prop for page
Add default prop for page
JavaScript
mit
nnarhinen/react-pdf,wojtekmaj/react-pdf,BartVanHoutte-ADING/react-pdf,BartVanHoutte-ADING/react-pdf,BartVanHoutte-ADING/react-pdf,suancarloj/react-pdf,peergradeio/react-pdf,wojtekmaj/react-pdf,wojtekmaj/react-pdf,peergradeio/react-pdf,suancarloj/react-pdf,nnarhinen/react-pdf,suancarloj/react-pdf
6e8d2a2f6587b964d2ded8149898728686a282bf
public/app/controllers/mvUserListController.js
public/app/controllers/mvUserListController.js
angular.module('app').controller('mvUserListController', function ($scope, mvUser) { $scope.users = mvUser.query(); $scope.sortOptions = [{ value: "username", text: "Sort by username" }, { value: "registrationDate", text: "Sort by registration date" }, { value: "role", text: "Sort by role" }]; $scope.sortOrder = { selected: $scope.sortOptions[0].value }; });
angular.module('app').controller('mvUserListController', function ($scope, mvUser) { $scope.users = mvUser.query(); $scope.sortOptions = [{ value: "username", text: "Sort by username" }, { value: "- registrationDate", text: "Sort by registration date" }, { value: "- role", text: "Sort by role" }]; $scope.sortOrder = { selected: $scope.sortOptions[0].value }; });
Fix ordering on user list page
Fix ordering on user list page
JavaScript
mit
BenjaminBini/dilemme,BenjaminBini/dilemme
6a02cfd389b3633637eff9a2d7d29a2271681c74
src/app/controllers/MapController.js
src/app/controllers/MapController.js
(function(){ angular .module('app') .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider.configure({ // key: 'your api key', v: '3.20', //defaults to latest 3.X anyhow libraries: 'weather,geometry,visualization' }); }) .controller('MapController', [ '$state', 'uiGmapGoogleMapApi', 'sitesService', MapController ]); function MapController($state, uiGmapGoogleMapApi, sitesService) { self = this; sitesService .loadAllItems() .then(function(siteData) { self.siteData = [].concat(siteData); console.log(self.siteData); }); uiGmapGoogleMapApi.then(function(maps) { //small hack to fix issues with older lodash version. to be resolved in future if( typeof _.contains === 'undefined' ) { _.contains = _.includes; } if( typeof _.object === 'undefined' ) { _.object = _.zipObject; } self.mapParams = { center: { latitude: 51.48, longitude: -2.5879 }, zoom: 12 }; }); self.goToSite = function (shortcode) { $state.go('home.site', {shortcode: shortcode}); }; } })();
(function(){ angular .module('app') .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider.configure({ // key: 'your api key', v: '3.20', //defaults to latest 3.X anyhow libraries: 'weather,geometry,visualization' }); }) .controller('MapController', [ '$state', 'uiGmapGoogleMapApi', 'sitesService', MapController ]); function MapController($state, uiGmapGoogleMapApi, sitesService) { self = this; sitesService .loadAllItems() .then(function(siteData) { self.siteData = [].concat(siteData); console.log(self.siteData); }); uiGmapGoogleMapApi.then(function(maps) { //small hack to fix issues with older lodash version. to be resolved in future if( typeof _.contains === 'undefined' ) { _.contains = _.includes; } if( typeof _.object === 'undefined' ) { _.object = _.zipObject; } self.mapParams = { center: { latitude: 51.48, longitude: -2.53 }, zoom: 12 }; }); self.goToSite = function (shortcode) { $state.go('home.site', {shortcode: shortcode}); }; } })();
Move starting location a little so Wick Sports Ground is visible
Map: Move starting location a little so Wick Sports Ground is visible
JavaScript
mit
spiraledgeuk/bec,spiraledgeuk/bec,spiraledgeuk/bec
546a6787123156b39c9b7ac7c518e09edeaf9512
app/utils/keys-map.js
app/utils/keys-map.js
import Ember from 'ember'; var configKeys, configKeysMap, languageConfigKeys; languageConfigKeys = { go: 'Go', php: 'PHP', node_js: 'Node.js', perl: 'Perl', perl6: 'Perl6', python: 'Python', scala: 'Scala', smalltalk: 'Smalltalk', ruby: 'Ruby', d: 'D', julia: 'Julia', csharp: 'C#', mono: 'Mono', dart: 'Dart', elixir: 'Elixir', ghc: 'GHC', haxe: 'Haxe', jdk: 'JDK', rvm: 'Ruby', otp_release: 'OTP Release', rust: 'Rust', c: 'C', cpp: 'C++', clojure: 'Clojure', lein: 'Lein', compiler: 'Compiler', crystal: 'Crystal', osx_image: 'Xcode' }; configKeys = { env: 'ENV', gemfile: 'Gemfile', xcode_sdk: 'Xcode SDK', xcode_scheme: 'Xcode Scheme', compiler: 'Compiler', os: 'OS' }; configKeysMap = Ember.merge(configKeys, languageConfigKeys); export default configKeysMap; export { languageConfigKeys, configKeys };
import Ember from 'ember'; var configKeys, configKeysMap, languageConfigKeys; languageConfigKeys = { go: 'Go', php: 'PHP', node_js: 'Node.js', perl: 'Perl', perl6: 'Perl6', python: 'Python', scala: 'Scala', smalltalk: 'Smalltalk', ruby: 'Ruby', d: 'D', julia: 'Julia', csharp: 'C#', mono: 'Mono', dart: 'Dart', elixir: 'Elixir', ghc: 'GHC', haxe: 'Haxe', jdk: 'JDK', rvm: 'Ruby', otp_release: 'OTP Release', rust: 'Rust', c: 'C', cpp: 'C++', clojure: 'Clojure', lein: 'Lein', compiler: 'Compiler', crystal: 'Crystal', osx_image: 'Xcode', r: 'R' }; configKeys = { env: 'ENV', gemfile: 'Gemfile', xcode_sdk: 'Xcode SDK', xcode_scheme: 'Xcode Scheme', compiler: 'Compiler', os: 'OS' }; configKeysMap = Ember.merge(configKeys, languageConfigKeys); export default configKeysMap; export { languageConfigKeys, configKeys };
Add R language key for matrix column
Add R language key for matrix column
JavaScript
mit
fauxton/travis-web,fotinakis/travis-web,fotinakis/travis-web,travis-ci/travis-web,fotinakis/travis-web,travis-ci/travis-web,fauxton/travis-web,fotinakis/travis-web,fauxton/travis-web,travis-ci/travis-web,fauxton/travis-web,travis-ci/travis-web
804cdee7fa3af228d67e99d618f161fb4aafd1d2
src/util-lang.js
src/util-lang.js
/** * util-lang.js - The minimal language enhancement */ var hasOwnProperty = {}.hasOwnProperty function hasOwn(obj, prop) { return hasOwnProperty.call(obj, prop) } function isFunction(obj) { return typeof obj === "function" } var isArray = Array.isArray || function(obj) { return obj instanceof Array } function unique(arr) { var obj = {} var ret = [] for (var i = 0, len = arr.length; i < len; i++) { var item = arr[i] if (!obj[item]) { obj[item] = 1 ret.push(item) } } return ret }
/** * util-lang.js - The minimal language enhancement */ var hasOwnProperty = {}.hasOwnProperty function hasOwn(obj, prop) { return hasOwnProperty.call(obj, prop) } function isFunction(obj) { return typeof obj === "function" } var isArray = Array.isArray || function(obj) { return obj instanceof Array } function unique(arr) { var obj = {} var ret = [] for (var i = 0, len = arr.length; i < len; i++) { var item = arr[i] if (obj[item] !== 1) { obj[item] = 1 ret.push(item) } } return ret }
Fix a bug for unique
Fix a bug for unique
JavaScript
mit
chinakids/seajs,uestcNaldo/seajs,baiduoduo/seajs,eleanors/SeaJS,angelLYK/seajs,evilemon/seajs,zwh6611/seajs,PUSEN/seajs,AlvinWei1024/seajs,yern/seajs,yuhualingfeng/seajs,13693100472/seajs,moccen/seajs,121595113/seajs,ysxlinux/seajs,MrZhengliang/seajs,sheldonzf/seajs,twoubt/seajs,yuhualingfeng/seajs,Gatsbyy/seajs,JeffLi1993/seajs,jishichang/seajs,hbdrawn/seajs,uestcNaldo/seajs,treejames/seajs,LzhElite/seajs,lovelykobe/seajs,kuier/seajs,jishichang/seajs,mosoft521/seajs,jishichang/seajs,seajs/seajs,miusuncle/seajs,miusuncle/seajs,tonny-zhang/seajs,lianggaolin/seajs,wenber/seajs,longze/seajs,AlvinWei1024/seajs,LzhElite/seajs,coolyhx/seajs,Gatsbyy/seajs,judastree/seajs,lee-my/seajs,lee-my/seajs,liupeng110112/seajs,PUSEN/seajs,sheldonzf/seajs,zaoli/seajs,LzhElite/seajs,hbdrawn/seajs,evilemon/seajs,baiduoduo/seajs,PUSEN/seajs,chinakids/seajs,ysxlinux/seajs,twoubt/seajs,liupeng110112/seajs,moccen/seajs,judastree/seajs,yern/seajs,imcys/seajs,tonny-zhang/seajs,longze/seajs,seajs/seajs,wenber/seajs,eleanors/SeaJS,coolyhx/seajs,Lyfme/seajs,JeffLi1993/seajs,seajs/seajs,tonny-zhang/seajs,twoubt/seajs,lianggaolin/seajs,angelLYK/seajs,baiduoduo/seajs,imcys/seajs,lee-my/seajs,Gatsbyy/seajs,kuier/seajs,mosoft521/seajs,kaijiemo/seajs,MrZhengliang/seajs,judastree/seajs,kaijiemo/seajs,yuhualingfeng/seajs,FrankElean/SeaJS,coolyhx/seajs,lianggaolin/seajs,mosoft521/seajs,ysxlinux/seajs,evilemon/seajs,FrankElean/SeaJS,moccen/seajs,angelLYK/seajs,treejames/seajs,miusuncle/seajs,kuier/seajs,FrankElean/SeaJS,lovelykobe/seajs,zwh6611/seajs,Lyfme/seajs,MrZhengliang/seajs,13693100472/seajs,yern/seajs,eleanors/SeaJS,zaoli/seajs,imcys/seajs,zwh6611/seajs,AlvinWei1024/seajs,sheldonzf/seajs,121595113/seajs,JeffLi1993/seajs,zaoli/seajs,Lyfme/seajs,liupeng110112/seajs,wenber/seajs,longze/seajs,treejames/seajs,kaijiemo/seajs,uestcNaldo/seajs,lovelykobe/seajs
275f8ce0c77ca79c32359d8780849684ed44bedb
samples/people/me.js
samples/people/me.js
// Copyright 2016, 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. 'use strict'; const {google} = require('googleapis'); const sampleClient = require('../sampleclient'); const plus = google.plus({ version: 'v1', auth: sampleClient.oAuth2Client, }); async function runSample() { const res = await plus.people.get({userId: 'me'}); console.log(res.data); } const scopes = [ 'https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ]; if (module === require.main) { sampleClient .authenticate(scopes) .then(runSample) .catch(console.error); }
// Copyright 2016, 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. 'use strict'; const {google} = require('googleapis'); const sampleClient = require('../sampleclient'); const people = google.people({ version: 'v1', auth: sampleClient.oAuth2Client, }); async function runSample() { // See documentation of personFields at // https://developers.google.com/people/api/rest/v1/people/get const res = await people.people.get({ resourceName: 'people/me', personFields: 'emailAddresses,names,photos', }); console.log(res.data); } const scopes = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ]; if (module === require.main) { sampleClient .authenticate(scopes) .then(runSample) .catch(console.error); }
Use people API instead of plus API
Use people API instead of plus API Use people API instead of plus API The plus API is being deprecated. This updates the sample code to use the people API instead. Fixes #1600. - [x] Tests and linter pass - [x] Code coverage does not decrease (if any source code was changed) - [x] Appropriate docs were updated (if necessary) #1601 automerged by dpebot
JavaScript
apache-2.0
googleapis/google-api-nodejs-client,stems/google-api-nodejs-client,stems/google-api-nodejs-client,stems/google-api-nodejs-client,stems/google-api-nodejs-client,stems/google-api-nodejs-client,googleapis/google-api-nodejs-client,googleapis/google-api-nodejs-client
4bd41b1aa225ac4d30d68e5e93a82f9062ad0488
test.js
test.js
var Office365ConnectorHook = require("./index.js"), winston = require('winston'), Logger = winston.Logger, Console = winston.transports.Console, hookUrl = process.env.HOOK_URL; if (!hookUrl) { console.warn("No process.env.HOOK_URL set. Please set it to your Connector Webhook URL before running this test."); process.exit(); } var logger = new Logger({ transports: [ new Console({}), new Office365ConnectorHook({ "hookUrl": hookUrl, "colors": { "debug": "FFFFFF" } }) ] }); // will be sent to both console and channel logger.log('debug', 'Starting tests...'); logger.info('This is a test log from Winston.'); logger.info('This text appears in card body.', { title: 'You can send card titles too!' }); logger.info('# Seriously!?\n > This is cool!', { title: 'You can use Markdown in error messages.' }); logger.warn('Warning! An error test coming up!'); try { throw new Error("Everything's alright, just testing error logging."); } catch (err) { logger.error(err.message, err); }
var Office365ConnectorHook = require("./index.js"), winston = require('winston'), Logger = winston.Logger, Console = winston.transports.Console, hookUrl = process.env.HOOK_URL; if (!hookUrl) { console.warn("No process.env.HOOK_URL set. Please set it to your Connector Webhook URL before running this test."); process.exit(); } var logger = new Logger({ transports: [ new Console({}), new Office365ConnectorHook({ "hookUrl": hookUrl, "colors": { "debug": "FFFFFF" } }) ] }); // will be sent to both console and channel logger.log('debug', 'Starting tests...'); logger.info('This is a test log from Winston.'); logger.info('This text appears in card body.', { title: 'My puny title' }); logger.info('# Seriously!?\n > This is cool!', { title: 'You can use Markdown in messages.' }); logger.warn('Warning! An error test coming up!'); try { throw new Error("Everything's alright, just testing error logging."); } catch (err) { logger.error(err.message, err); }
Change error message per readme.
Change error message per readme.
JavaScript
mit
SukantGujar/winston-office365-connector-hook
b88c06ce00120abbfef8ea8fb2dfae8fe89f7160
test.js
test.js
var sys = require("sys"), stomp = require("./stomp"); var client = new stomp.Client("localhost", 61613); client.subscribe("/queue/news", function(data){ console.log('received: ' + data.body); }); client.publish('/queue/news','hello'); var repl = require('repl').start( 'stomp-test> ' ); repl.context.client = client;
var sys = require("sys"), stomp = require("./stomp"); var client = new stomp.Client("localhost", 61613); client.subscribe("/queue/news", function(data){ console.log('received: ' + JSON.stringify(data)); }); client.publish('/queue/news','hello'); var repl = require('repl').start( 'stomp-test> ' ); repl.context.client = client;
Test program now emits JSON strings of messages, not just message bodies
Test program now emits JSON strings of messages, not just message bodies
JavaScript
agpl-3.0
jbalonso/node-stomp-server
86b3bd06d76d8ea3806acaf397cda97bff202127
src/components/ControlsComponent.js
src/components/ControlsComponent.js
'use strict'; import React from 'react'; require('styles//Controls.scss'); class ControlsComponent extends React.Component { renderStopButton() { if (this.props.isPlaying) { return <button id="stop">Stop</button> } return <button id="stop" style={{display: 'none'}}>Stop</button> } renderPlayButton() { if (this.props.isPlaying) { return <button id="play" style={{display: 'none'}}>Play</button> } return <button id="play">Play</button> } render() { return ( <div className="controls-component"> <button id="rewind">Rewind</button> {this.renderStopButton()} {this.renderPlayButton()} <button id="forward">Forward</button> </div> ); } } ControlsComponent.displayName = 'ControlsComponent'; ControlsComponent.propTypes = { isPlaying : React.PropTypes.bool.isRequired }; ControlsComponent.defaultProps = { isPlaying : true }; export default ControlsComponent;
'use strict'; import React from 'react'; require('styles//Controls.scss'); class ControlsComponent extends React.Component { renderStopButton() { if (this.props.isPlaying) { return <button id="stop">Stop</button> } return <button id="stop" style={{display: 'none'}}>Stop</button> } renderPlayButton() { if (this.props.isPlaying) { return <button id="play" style={{display: 'none'}}>Play</button> } return <button id="play">Play</button> } render() { return ( <div className="controls-component"> <button id="previous">Previous</button> {this.renderStopButton()} {this.renderPlayButton()} <button id="next">Next</button> </div> ); } } ControlsComponent.displayName = 'ControlsComponent'; ControlsComponent.propTypes = { isPlaying : React.PropTypes.bool.isRequired, onPrevious : React.PropTypes.func, onStop : React.PropTypes.func, onPlay : React.PropTypes.func, onNext : React.PropTypes.func }; ControlsComponent.defaultProps = { isPlaying : true }; export default ControlsComponent;
Add props for the action trigger
Add props for the action trigger
JavaScript
mit
C3-TKO/junkan,C3-TKO/junkan,C3-TKO/gaiyo,C3-TKO/gaiyo
41bd5bdd133e5b6d74b76b454d1a5681ffb90201
js/file.js
js/file.js
var save = (function() { "use strict"; // saveAs from https://gist.github.com/MrSwitch/3552985 var saveAs = window.saveAs || (window.navigator.msSaveBlob ? function (b, n) { return window.navigator.msSaveBlob(b, n); } : false) || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs || (function () { // URL's window.URL = window.URL || window.webkitURL; if (!window.URL) { return false; } return function (blob, name) { var url = URL.createObjectURL(blob); // Test for download link support if ("download" in document.createElement('a')) { var a = document.createElement('a'); a.setAttribute('href', url); a.setAttribute('download', name); // Create Click event var clickEvent = document.createEvent("MouseEvent"); clickEvent.initMouseEvent("click", true, true, window, 0, event.screenX, event.screenY, event.clientX, event.clientY, event.ctrlKey, event.altKey, event.shiftKey, event.metaKey, 0, null); // dispatch click event to simulate download a.dispatchEvent(clickEvent); } else { // fallover, open resource in new tab. window.open(url, '_blank', ''); } }; })(); function save (text, fileName) { var blob = new Blob([text], { type: 'text/plain' }); saveAs(blob, fileName || 'subtitle.srt'); } return save; })();
var save = (function() { "use strict"; // saveAs from https://gist.github.com/MrSwitch/3552985 var saveAs = window.saveAs || (window.navigator.msSaveBlob ? function (b, n) { return window.navigator.msSaveBlob(b, n); } : false) || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs || (function () { // URL's window.URL = window.URL || window.webkitURL; if (!window.URL) { return false; } return function (blob, name) { var url = URL.createObjectURL(blob); // Test for download link support if ("download" in document.createElement('a')) { var a = document.createElement('a'); a.setAttribute('href', url); a.setAttribute('download', name); // Create Click event var clickEvent = document.createEvent("MouseEvent"); clickEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); // dispatch click event to simulate download a.dispatchEvent(clickEvent); } else { // fallover, open resource in new tab. window.open(url, '_blank', ''); } }; })(); function save (text, fileName) { var blob = new Blob([text], { type: 'text/plain' }); saveAs(blob, fileName || 'subtitle.srt'); } return save; })();
Fix ReferenceError in saveAs polyfill
Fix ReferenceError in saveAs polyfill
JavaScript
mit
JMPerez/linkedin-to-json-resume,JMPerez/linkedin-to-json-resume
e2235a00a2a5e375b1b2bacbf190bdc328445bd9
js/main.js
js/main.js
var questions = [ Q1 = { question: "What does HTML means?", answer: "HyperText Markup Language" }, Q2 = { question: "What does CSS means?", answer: "Cascading Style Sheet" }, Q3 = { question: "Why the \"C\" in CSS, is called Cascading?", answer: "When CSS rules are duplicated, the rule to be use is chosen by <em>cascading</em> down from more general rules to the specific rule required" } ]; var question = document.getElementById('question'); var questionNum = 0; // Generate random number to display random QA set function createNum() { questionNum = Math.floor(Math.random() * 3); } createNum(); question.innerHTML = questions[questionNum].question;
var questions = [ Q1 = { question: "What does HTML means?", answer: "HyperText Markup Language" }, Q2 = { question: "What does CSS means?", answer: "Cascading Style Sheet" }, Q3 = { question: "Why the \"C\" in CSS, is called Cascading?", answer: "When CSS rules are duplicated, the rule to be use is chosen by <em>cascading</em> down from more general rules to the specific rule required" } ]; var question = document.getElementById('question'); var questionNum = 0; // Generate random number to display random QA set function createNum() { questionNum = Math.floor(Math.random() * 3); } createNum(); question.innerHTML = questions[questionNum].question;
Increase indention by 2 spaces
Increase indention by 2 spaces
JavaScript
mit
vinescarlan/FlashCards,vinescarlan/FlashCards
a185960250cf95592867d23c402f033eafbba88a
src/js/viewmodels/message-dialog.js
src/js/viewmodels/message-dialog.js
/* * Copyright 2015 Vivliostyle Inc. * * This file is part of Vivliostyle UI. * * Vivliostyle UI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vivliostyle UI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Vivliostyle UI. If not, see <http://www.gnu.org/licenses/>. */ import ko from "knockout"; function MessageDialog(queue) { this.list = queue; this.visible = ko.pureComputed(function() { return queue().length > 0; }); } MessageDialog.prototype.getDisplayMessage = function(errorInfo) { var msg; var e = errorInfo.error; var stack = e && (e.frameTrace || e.stack || e.toString()); if (stack) { msg = stack.split("\n", 1)[0]; } if (!msg) { msg = errorInfo.messages.join("\n"); } return msg; }; export default MessageDialog;
/* * Copyright 2015 Vivliostyle Inc. * * This file is part of Vivliostyle UI. * * Vivliostyle UI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Vivliostyle UI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Vivliostyle UI. If not, see <http://www.gnu.org/licenses/>. */ import ko from "knockout"; function MessageDialog(queue) { this.list = queue; this.visible = ko.pureComputed(function() { return queue().length > 0; }); } MessageDialog.prototype.getDisplayMessage = function(errorInfo) { var e = errorInfo.error; var msg = e && (e.toString() || e.frameTrace || e.stack); if (msg) { msg = msg.split("\n", 1)[0]; } if (!msg) { msg = errorInfo.messages.join("\n"); } return msg; }; export default MessageDialog;
Use `Error.toString` for a displayed message whenever possible
Use `Error.toString` for a displayed message whenever possible
JavaScript
agpl-3.0
vivliostyle/vivliostyle.js,vivliostyle/vivliostyle.js,vivliostyle/vivliostyle.js,vivliostyle/vivliostyle-ui,vivliostyle/vivliostyle.js,vivliostyle/vivliostyle-ui,vivliostyle/vivliostyle-ui,vivliostyle/vivliostyle-ui
acda2674e43657112a621ad9b78527828ed3a60d
data/componentData.js
data/componentData.js
/** * Transfer component data from .mxt to json */ var fs = require('fs'); var path = require('path'); var componentDataPath = './componentdata.tmp'; fs.readFile(componentDataPath, { encoding : 'utf-8' }, function (err, data) { if(err) return console.log(err); var lines = data.split('\n'); var categories = ['groups', 'teachers', 'rooms', 'other']; var container = categories.map(function (item) { return { name : item, data : [] } }); lines.forEach(function (line) { if(!line.length) return; var data = line.split('=')[1]; var items = data.split(';'); container[items[2] - 1].data.push({ code : items[0], name : items[1] }); }); container.forEach(function (item) { fs.writeFile(item.name + '.json', JSON.stringify(item.data, null, '\t'), function (err) { if(err) console.log(err); }); }); console.log('Files are processing'); });
/** * Transfer component data from .mxt to json */ var fs = require('fs'); var path = require('path'); var componentDataPath = './componentdata.tmp'; fs.readFile(componentDataPath, { encoding : 'utf-8' }, function (err, data) { if(err) return console.log(err); var lines = data.split('\n'); var categories = ['groups', 'teachers', 'rooms', 'other']; var container = {}; lines.forEach(function (line) { if(!line.length) return; var data = line.split('=')[1]; var items = data.split(';'); container[items[0]] = { name : items[1], category : categories[items[2] - 1] }; }); fs.writeFile('components.json', JSON.stringify(container, null, '\t'), function (err) { if(err) console.log(err); }); console.log('Files are processing'); });
Use a better structure for components
Use a better structure for components
JavaScript
mit
lukkari/sync,lukkari/sync
cf183c2065926aeb8011e5bf6b1e472e53290dcf
example/build.js
example/build.js
var path = require("path"); var Interlock = require(".."); var ilk = new Interlock({ srcRoot: __dirname, destRoot: path.join(__dirname, "dist"), entry: { "./app/entry-a.js": "entry-a.bundle.js", "./app/entry-b.js": { dest: "entry-b.bundle.js" } }, split: { "./app/shared/lib-a.js": "[setHash].js" }, includeComments: true, sourceMaps: true, // cacheMode: "localStorage", implicitBundleDest: "[setHash].js", plugins: [] }); ilk.watch(true).observe(function (buildEvent) { var patchModules = buildEvent.patchModules; var compilation = buildEvent.compilation; if (patchModules) { const paths = patchModules.map(function (module) { return module.path; }); console.log("the following modules have been updated:", paths); } if (compilation) { console.log("a new compilation has completed"); } }); // ilk.build();
var path = require("path"); var Interlock = require(".."); var ilk = new Interlock({ srcRoot: __dirname, destRoot: path.join(__dirname, "dist"), entry: { "./app/entry-a.js": "entry-a.bundle.js", "./app/entry-b.js": { dest: "entry-b.bundle.js" } }, split: { "./app/shared/lib-a.js": "[setHash].js" }, includeComments: true, sourceMaps: true, implicitBundleDest: "[setHash].js", plugins: [] }); ilk.watch(true).observe(function (buildEvent) { var patchModules = buildEvent.patchModules; var compilation = buildEvent.compilation; if (patchModules) { const paths = patchModules.map(function (module) { return module.path; }); console.log("the following modules have been updated:", paths); } if (compilation) { console.log("a new compilation has completed"); } }); // ilk.build();
Remove `cacheMode` top-level property - this will be accomplished through plugin.
Remove `cacheMode` top-level property - this will be accomplished through plugin.
JavaScript
mit
interlockjs/interlock,interlockjs/interlock
22342e24bbdf38a287dc91bf5dcd1778bc364a01
src/containers/Invite/services/inviteAction.js
src/containers/Invite/services/inviteAction.js
import { callController } from '../../../util/apiConnection' export const acceptThesis = token => callController(`/invite/thesis/${token}`, 'INVITE_ACCEPT_THESIS_') export const acceptRole = token => callController(`/invite/role/${token}`, 'INVITE_ACCEPT_ROLE_')
import { callController } from '../../../util/apiConnection' const prefix = process.env.NODE_ENV === 'development' ? '' : '../..' export const acceptThesis = token => callController(`${prefix}/invite/thesis/${token}`, 'INVITE_ACCEPT_THESIS_') export const acceptRole = token => callController(`${prefix}/invite/role/${token}`, 'INVITE_ACCEPT_ROLE_')
Fix thesis invite on staging.
Fix thesis invite on staging.
JavaScript
mit
OhtuGrappa2/front-grappa2,OhtuGrappa2/front-grappa2
13f5e45e847231f1597a2e751b87c1f98d9f17e7
Resources/Public/Javascripts/Main.js
Resources/Public/Javascripts/Main.js
/** * RequireJS configuration * @description Pass in options for RequireJS like paths, shims or the baseUrl */ require.config({ paths: { } }); /** * RequireJS calls * @description Call the needed AMD modules. */ require(['Modules/Main'], function(MainFn) { new MainFn; });
/** * RequireJS configuration * @description Pass in options for RequireJS like paths, shims or the baseUrl */ require.config({ paths: { }, // Append a date on each requested script to prevent caching issues. urlArgs: 'bust=' + (new Date()).getDate() }); /** * RequireJS calls * @description Call the needed AMD modules. */ require(['Modules/Main'], function(MainFn) { new MainFn; });
Append a date on each requested requireJS module to prevent caching issues
[TASK] Append a date on each requested requireJS module to prevent caching issues
JavaScript
mit
t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template
c12248d8dc4962ed56de67eed74d4a2fcc43338a
lib/compile/bundles/bootstrap.js
lib/compile/bundles/bootstrap.js
import most from "most"; import * as Pluggable from "../../pluggable"; import resolveAsset from "../modules/resolve"; import loadAst from "../modules/load-ast"; import { entries } from "../../util"; const bootstrapBundle = Pluggable.sync(function bootstrapBundle (srcPath, definition, isEntryPt) { const asset = this.resolveAsset(srcPath); const module = this.loadAst(asset); return { module: module, dest: definition.dest, entry: isEntryPt, includeRuntime: !!definition.entry && !definition.excludeRuntime }; }, { resolveAsset, loadAst }); function bootstrapBundles (entryPointDefs, splitPointDefs) { const entryPointBundles = most.generate(entries, entryPointDefs) .map(([srcPath, bundleDef]) => this.bootstrapBundle(srcPath, bundleDef, true)); const splitPointBundles = most.generate(entries, splitPointDefs) .map(([srcPath, splitDef]) => this.bootstrapBundle(srcPath, splitDef, false)); return most.merge(entryPointBundles, splitPointBundles); } export default Pluggable.stream(bootstrapBundles, { bootstrapBundle });
import most from "most"; import * as Pluggable from "../../pluggable"; import resolveAsset from "../modules/resolve"; import loadAst from "../modules/load-ast"; import { entries } from "../../util"; const bootstrapBundle = Pluggable.sync(function bootstrapBundle (srcPath, definition, isEntryPt) { const asset = this.resolveAsset(srcPath); const module = this.loadAst(asset); return { module: module, dest: definition.dest, entry: isEntryPt, includeRuntime: isEntryPt && !definition.excludeRuntime }; }, { resolveAsset, loadAst }); function bootstrapBundles (entryPointDefs, splitPointDefs) { const entryPointBundles = most.generate(entries, entryPointDefs) .map(([srcPath, bundleDef]) => this.bootstrapBundle(srcPath, bundleDef, true)); const splitPointBundles = most.generate(entries, splitPointDefs) .map(([srcPath, splitDef]) => this.bootstrapBundle(srcPath, splitDef, false)); return most.merge(entryPointBundles, splitPointBundles); } export default Pluggable.stream(bootstrapBundles, { bootstrapBundle });
Fix runtime inclusion after API changes.
Fix runtime inclusion after API changes.
JavaScript
mit
interlockjs/interlock,interlockjs/interlock
407b68dadadd3609d1eb6110d24ff465686bb3fa
lib/yamb/proto/methods/remove.js
lib/yamb/proto/methods/remove.js
"use strict"; // yamb.prototype.remove() module.exports = function(symbl, flags, opts) { return function *remove() { if (!this[symbl].id) { // TODO: fix error message throw new Error('This is a new object'); } let result = yield opts.storage.removeById(this.id); // TODO: remove all related posts return result; }; };
"use strict"; // yamb.prototype.remove() module.exports = function(symbl, flags, opts) { return function *remove() { if (!this.id) { // TODO: fix error message throw new Error('This is a new object'); } let oid = '' + this.id; yield opts.storage.update({related: oid}, {$pull: {related: oid}}); let result = yield opts.storage.removeById(this.id); return result; }; };
Remove related link if yamb deleted
Remove related link if yamb deleted
JavaScript
mit
yamb/yamb
0323861f7315467b7fd143e1d2e831b62034d479
src/react-chayns-personfinder/utils/getList.js
src/react-chayns-personfinder/utils/getList.js
export default function getList(data, orm, inputValue) { let retVal = []; if (Array.isArray(orm.groups)) { orm.groups.forEach(({ key, show }) => { if (!(typeof show === 'function' && !show(inputValue))) { const list = data[key]; retVal = retVal.concat(list); } }); } else { Object.keys(data) .forEach((key) => { const list = data[key]; retVal = retVal.concat(list); }); } return retVal; }
import { isFunction } from '../../utils/is'; export default function getList(data, orm, inputValue) { let retVal = []; if (Array.isArray(orm.groups)) { orm.groups.forEach(({ key, show }) => { if (!(isFunction(show) && !show(inputValue) && (!isFunction(orm.filter) || orm.filter(inputValue)))) { const list = data[key]; retVal = retVal.concat(list); } }); } else { Object.keys(data) .forEach((key) => { if (!isFunction(orm.filter) || orm.filter(inputValue)) { const list = data[key]; retVal = retVal.concat(list); } }); } return retVal; }
Fix bug that personFinder used unfiltered list
:bug: Fix bug that personFinder used unfiltered list
JavaScript
mit
TobitSoftware/chayns-components,TobitSoftware/chayns-components,TobitSoftware/chayns-components
f891afa4f3c6bc12b5c39b10241801e4935f7eca
index.js
index.js
'use strict'; var ect = require('ect'); exports.name = 'ect'; exports.outputFormat = 'html'; exports.compile = function(str, options) { if (!options) { options = {}; } if (!options.root) { options.root = { 'page': str }; } var engine = ect(options); return function(locals) { return engine.render('page', locals); }; };
'use strict'; var ect = require('ect'); exports.name = 'ect'; exports.outputFormat = 'html'; exports.compile = function(str, options) { options = options || {}; options.root = options.root || {}; options.root.page = str; var engine = ect(options); return function(locals) { return engine.render('page', locals); }; };
Fix the if statement syntax
Fix the if statement syntax
JavaScript
mit
jstransformers/jstransformer-ect,jstransformers/jstransformer-ect
19fdb1188e0d50e7fdfdba28d1731ca94bca59fb
index.js
index.js
/* jshint node: true */ 'use strict'; var path = require('path'); var Funnel = require('broccoli-funnel'); module.exports = { name: 'ember-cli-bourbon', blueprintsPath: function() { return path.join(__dirname, 'blueprints'); }, treeForStyles: function() { var bourbonPath = path.join(this.app.bowerDirectory, 'bourbon', 'app'); var bourbonTree = new Funnel(this.treeGenerator(bourbonPath), { srcDir: '/assets/stylesheets', destDir: '/app/styles' }); return bourbonTree; } };
/* jshint node: true */ 'use strict'; var path = require('path'); var Funnel = require('broccoli-funnel'); module.exports = { name: 'ember-cli-bourbon', blueprintsPath: function() { return path.join(__dirname, 'blueprints'); }, treeForStyles: function() { var bourbonPath = path.join(this.project.bowerDirectory, 'bourbon', 'app'); var bourbonTree = new Funnel(this.treeGenerator(bourbonPath), { srcDir: '/assets/stylesheets', destDir: '/app/styles' }); return bourbonTree; } };
Allow add-on to be nested.
Allow add-on to be nested.
JavaScript
mit
yapplabs/ember-cli-bourbon,joedaniels29/ember-cli-bourbon,joedaniels29/ember-cli-bourbon,yapplabs/ember-cli-bourbon
9a20daf6d339eac4491f11da4424b49291289c7c
index.js
index.js
var globalOffset = require("global-offset"); module.exports = function(element) { var offset = globalOffset(element), scrollbar = document.createElement("div"), inner = document.createElement("div"); element.style.overflowX = "scroll"; element.parentNode.insertBefore(scrollbar, element); scrollbar.style.backgroundColor = "transparent"; scrollbar.style.position = "fixed"; scrollbar.style.bottom = 0; scrollbar.style.left = offset.left + "px"; scrollbar.style.height = "20px"; scrollbar.style.width = element.getBoundingClientRect().width + "px"; scrollbar.style.overflowX = "scroll"; scrollbar.style.overflowY = "hidden"; scrollbar.appendChild(inner); inner.style.width = element.children[0].getBoundingClientRect().width + "px"; inner.style.height = "1px"; scrollbar.onscroll = function() { element.scrollLeft = scrollbar.scrollLeft; }; element.onscroll = function() { scrollbar.scrollLeft = element.scrollLeft; }; window.onscroll = function() { scrollbar.style.display = element.getBoundingClientRect().height + offset.top < window.scrollY + window.innerHeight ? "none" : "block"; scrollbar.scrollLeft = element.scrollLeft; }; };
var globalOffset = require("global-offset"); module.exports = function(element) { var offset = globalOffset(element), scrollbar = document.createElement("div"), inner = document.createElement("div"); element.style.overflowX = "scroll"; element.parentNode.insertBefore(scrollbar, element); scrollbar.style.backgroundColor = "transparent"; scrollbar.style.position = "fixed"; scrollbar.style.bottom = 0; scrollbar.style.left = offset.left + "px"; scrollbar.style.height = "20px"; scrollbar.style.width = element.getBoundingClientRect().width + "px"; scrollbar.style.overflowX = "scroll"; scrollbar.style.overflowY = "hidden"; scrollbar.appendChild(inner); inner.style.width = element.children[0].getBoundingClientRect().width + "px"; inner.style.height = "1px"; scrollbar.onscroll = function() { element.scrollLeft = scrollbar.scrollLeft; }; element.onscroll = function() { scrollbar.scrollLeft = element.scrollLeft; }; window.onscroll = function() { scrollbar.style.display = element.getBoundingClientRect().height + offset.top <= window.scrollY + window.innerHeight ? "none" : "block"; scrollbar.scrollLeft = element.scrollLeft; }; };
Hide scrollbar when scroll reaches the bottom of the page
Hide scrollbar when scroll reaches the bottom of the page
JavaScript
mit
cvermeul/floating-horizontal-scrollbar
f5ee0cd3d94bf8a51b752d40d0d67dccf7e3524b
sandcats/sandcats.js
sandcats/sandcats.js
if (Meteor.isServer) { Meteor.startup(function () { // Validate that the config file contains the data we need. validateSettings(); // Create our DNS zone for PowerDNS, if necessary. mysqlQuery = createWrappedQuery(); createDomainIfNeeded(mysqlQuery); // Bind handlers for UDP-based client ping system. startListeningForUdpPings(); }); } // Always route all URLs, though we carefully set where: 'server' for // HTTP API-type URL handling. Router.map(function() { // Provide a trivial front page, to avoid the Iron Router default. this.route('root', { path: '/' }); this.route('register', { path: '/register', where: 'server', action: function() { doRegister(this.request, this.response); } }); this.route('sendrecoverytoken', { path: '/sendrecoverytoken', where: 'server', action: function() { doSendRecoveryToken(this.request, this.response); } }); this.route('recover', { path: '/recover', where: 'server', action: function() { doRecover(this.request, this.response); } }); this.route('update', { path: '/update', where: 'server', action: function() { doUpdate(this.request, this.response); } }); });
if (Meteor.isServer) { Meteor.startup(function () { // Validate that the config file contains the data we need. validateSettings(); // Create our DNS zone for PowerDNS, if necessary. mysqlQuery = createWrappedQuery(); createDomainIfNeeded(mysqlQuery); // Bind handlers for UDP-based client ping system. startListeningForUdpPings(); }); } // Always route all URLs, though we carefully set where: 'server' for // HTTP API-type URL handling. Router.map(function() { // Redirect the front page to the Sandstorm wiki. this.route('root', { path: '/', where: 'server', action: function() { this.response.writeHead(302, { 'Location': 'https://github.com/sandstorm-io/sandstorm/wiki/Sandcats-dynamic-DNS' }); this.response.end(); } }); this.route('register', { path: '/register', where: 'server', action: function() { doRegister(this.request, this.response); } }); this.route('sendrecoverytoken', { path: '/sendrecoverytoken', where: 'server', action: function() { doSendRecoveryToken(this.request, this.response); } }); this.route('recover', { path: '/recover', where: 'server', action: function() { doRecover(this.request, this.response); } }); this.route('update', { path: '/update', where: 'server', action: function() { doUpdate(this.request, this.response); } }); });
Make front page redirect to wiki
Make front page redirect to wiki
JavaScript
apache-2.0
sandstorm-io/sandcats,sandstorm-io/sandcats,sandstorm-io/sandcats,sandstorm-io/sandcats
c666013ca38766fc1d1fb2e3d149a820c406df63
backend/server/resources/projects-routes.js
backend/server/resources/projects-routes.js
module.exports = function(model) { 'use strict'; let validateProjectAccess = require('./project-access')(model.access); let schema = require('.././schema')(model); let router = require('koa-router')(); let projects = require('./projects')(model.projects); let samples = require('./samples')(model.samples, schema); let processes = require('./processes')(model.processes, schema); router.get('/projects2', projects.all); router.post('/projects2/:project_id/processes', validateProjectAccess, processes.create); router.post('/projects2/:project_id/samples', validateProjectAccess, samples.create); router.put('/projects2/:project_id/samples/:sample_id', validateProjectAccess, samples.update); router.get('/projects2/:project_id/dir/:directory_id', validateProjectAccess, projects.dirTree); return router; };
module.exports = function(model) { 'use strict'; let validateProjectAccess = require('./project-access')(model.access); let schema = require('.././schema')(model); let router = require('koa-router')(); let projects = require('./projects')(model.projects); let samples = require('./samples')(model.samples, schema); let files = require('./files')(model.files); let processes = require('./processes')(model.processes, schema); router.get('/projects2', projects.all); router.get('/projects2/:project_id/dir/:directory_id', validateProjectAccess, projects.dirTree); router.post('/projects2/:project_id/processes', validateProjectAccess, processes.create); router.post('/projects2/:project_id/samples', validateProjectAccess, samples.create); router.put('/projects2/:project_id/samples/:sample_id', validateProjectAccess, samples.update); router.get('/projects2/:project_id/files/:file_id', validateProjectAccess, files.get); return router; };
Add REST call for files.
Add REST call for files.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
845478266066fe205560ae442bb7a38388884d9e
backend/helpers/groupByDuplicatesInArray.js
backend/helpers/groupByDuplicatesInArray.js
// Count duplicate keys within an array // ------------------------------------------------------------ module.exports = function(array) { if(array.length === 0) { return null; } var counts = {}; array.forEach(function(x) { counts[x] = (counts[x] || 0) + 1; }); return counts; };
import sortObjByOnlyKey from "./sortObjByOnlyKey"; // Count duplicate keys within an array // ------------------------------------------------------------ const groupByDuplicatesInArray = array => { if(array.length === 0) { return null; } var counts = {}; array.forEach(function(x) { counts[x] = (counts[x] || 0) + 1; }); return sortObjByOnlyKey(counts); }; export default groupByDuplicatesInArray;
Sort object by keys to avoid problems with 'addEmptyDays' util
:bug: Sort object by keys to avoid problems with 'addEmptyDays' util
JavaScript
mit
dreamyguy/gitinsight,dreamyguy/gitinsight,dreamyguy/gitinsight
00642cb34569c9ca324b11637b83ea53f5c34216
binary-search-tree.js
binary-search-tree.js
// Program that creates a binary search tree: each node has up to two children, and all left descendants of a node is less than or equal to the node and all right descendants are greater than the node
// Program that creates a binary search tree: each node has up to two children, and all left descendants of a node is less than or equal to the node and all right descendants are greater than the node // create node function Node(val) { this.value = val; this.left = null; this.right = null; }
Create node in binary search tree program
Create node in binary search tree program
JavaScript
mit
derekmpham/interview-prep,derekmpham/interview-prep
397836570354391affaaee1dd222dd3e5caaa14f
index.js
index.js
'use strict'; const buble = require('buble'); class BrunchBuble { constructor({ plugins: { buble } }) { this.config = buble || {}; } compile({ data }) { try { const { code } = buble.transform(data, this.config); return Promise.resolve(code); } catch (error) { return Promise.reject(error); } } } BrunchBuble.prototype.brunchPlugin = true; BrunchBuble.prototype.type = 'javascript'; BrunchBuble.prototype.extension = 'js'; BrunchBuble.prototype.pattern = /\.js$/; module.exports = BrunchBuble;
'use strict'; const buble = require('buble'); class BrunchBuble { constructor(config) { this.config = config && config.plugins && config.plugins.buble || {}; } compile(file) { try { const transform = buble.transform(file.data, this.config); return Promise.resolve(transform.code); } catch (error) { return Promise.reject(error); } } } BrunchBuble.prototype.brunchPlugin = true; BrunchBuble.prototype.type = 'javascript'; BrunchBuble.prototype.extension = 'js'; BrunchBuble.prototype.pattern = /\.js$/; module.exports = BrunchBuble;
Improve the compatibility with older versions of node
Improve the compatibility with older versions of node
JavaScript
mit
aMarCruz/buble-brunch
c94b93e87e1364fab1f232995d3d8b2ebb64b241
index.js
index.js
var data = require('./data'); var accounting = require('accounting'); var CurrencyFormatter = function() { this.defaultCurrency = { symbol: '', thousandsSeparator: ',', decimalSeparator: '.', symbolOnLeft: true, spaceBetweenAmountAndSymbol: false, decimalDigits: 2 } } CurrencyFormatter.prototype.format = function (value, options) { var currency = data.find(c => c.code === options.code) || this.defaultCurrency; var symbolOnLeft = currency.symbolOnLeft; var spaceBetweenAmountAndSymbol = currency.spaceBetweenAmountAndSymbol; var format = ""; if (symbolOnLeft) { format = spaceBetweenAmountAndSymbol ? "%s %v" : "%s%v" } else { format = spaceBetweenAmountAndSymbol ? "%v %s" : "%v%s" } return accounting.formatMoney(value, { symbol: options.symbol || currency.symbol, decimal: options.decimal || currency.decimalSeparator, thousand: options.thousand || currency.thousandsSeparator, precision: options.precision || currency.decimalDigits, format: options.format || format }) } CurrencyFormatter.prototype.findCurrency = function (currencyCode) { return data.find(c => c.code === currencyCode); } module.exports = new CurrencyFormatter();
var data = require('./data'); var accounting = require('accounting'); var CurrencyFormatter = function() { this.defaultCurrency = { symbol: '', thousandsSeparator: ',', decimalSeparator: '.', symbolOnLeft: true, spaceBetweenAmountAndSymbol: false, decimalDigits: 2 } } CurrencyFormatter.prototype.format = function (value, options) { var currency = data.find(function(c) { return c.code === options.code; }) || this.defaultCurrency; var symbolOnLeft = currency.symbolOnLeft; var spaceBetweenAmountAndSymbol = currency.spaceBetweenAmountAndSymbol; var format = ""; if (symbolOnLeft) { format = spaceBetweenAmountAndSymbol ? "%s %v" : "%s%v" } else { format = spaceBetweenAmountAndSymbol ? "%v %s" : "%v%s" } return accounting.formatMoney(value, { symbol: options.symbol || currency.symbol, decimal: options.decimal || currency.decimalSeparator, thousand: options.thousand || currency.thousandsSeparator, precision: options.precision || currency.decimalDigits, format: options.format || format }) } CurrencyFormatter.prototype.findCurrency = function (currencyCode) { return data.find(function(c) { return c.code === currencyCode; }); } module.exports = new CurrencyFormatter();
Use ES5 functions instead of arrow functions
Use ES5 functions instead of arrow functions
JavaScript
mit
smirzaei/currency-formatter,enVolt/currency-formatter
6eb15445636e3dcb1901edf9b32aab3216651365
index.js
index.js
var chalk = require('chalk'); var gutil = require('gulp-util'); var spawn = require('gulp-spawn'); var through = require('through2'); var ts2dart = require('ts2dart'); var which = require('which'); exports.transpile = function() { var hadErrors = false; return through.obj( function(file, enc, done) { try { var src = ts2dart.translateFile(file.path); file.contents = new Buffer(src); file.path = file.path.replace(/.[tj]s$/, '.dart'); done(null, file); } catch (e) { hadErrors = true; if (e.name === 'TS2DartError') { // Sort of expected, log only the message. gutil.log(chalk.red(e.message)); } else { // Log the entire stack trace. gutil.log(chalk.red(e.stack)); } done(null, null); } }, function finished(done) { if (hadErrors) { gutil.log(chalk.red('ts2dart transpilation failed.')); throw new Error('ts2dart transpilation failed.'); } else { gutil.log(chalk.green('ts2dart transpilation succeeded.')); } done(); }); }; exports.format = function() { return spawn({cmd: which.sync('dartfmt')}); };
var chalk = require('chalk'); var gutil = require('gulp-util'); var spawn = require('gulp-spawn'); var through = require('through2'); var ts2dart = require('ts2dart'); var which = require('which'); exports.transpile = function() { var hadErrors = false; return through.obj( function(file, enc, done) { try { var transpiler = new ts2dart.Transpiler(/* failFast */ false, /* generateLibrary */ true); var src = transpiler.translateFile(file.path, file.relative); file.contents = new Buffer(src); file.path = file.path.replace(/.[tj]s$/, '.dart'); done(null, file); } catch (e) { hadErrors = true; if (e.name === 'TS2DartError') { // Sort of expected, log only the message. gutil.log(chalk.red(e.message)); } else { // Log the entire stack trace. gutil.log(chalk.red(e.stack)); } done(null, null); } }, function finished(done) { if (hadErrors) { gutil.log(chalk.red('ts2dart transpilation failed.')); throw new Error('ts2dart transpilation failed.'); } else { gutil.log(chalk.green('ts2dart transpilation succeeded.')); } done(); }); }; exports.format = function() { return spawn({cmd: which.sync('dartfmt')}); };
Adjust to ts2dart change of filename handling.
Adjust to ts2dart change of filename handling.
JavaScript
apache-2.0
dart-archive/gulp-ts2dart,dart-archive/gulp-ts2dart
4bca760f4b165dc66de6057f9ea9f4ae40773927
index.js
index.js
console.log('loading electron-updater-sample-plugin...') function plugin(context) { console.log('loaded electron-updater-sample-plugin!') } module.exports = plugin
console.log('loading electron-updater-sample-plugin...') function plugin(context) { var d = context.document var ul = d.getElementById('plugins') var li = d.createElement('li') li.innerHTML = 'electron-updater-sample-plugin' ul.appendChild(li) } module.exports = plugin
Add to the sample apps ul
Add to the sample apps ul
JavaScript
mit
EvolveLabs/electron-updater-sample-plugin
d4af65ae7a3c7228ab96396522fe8c21f2f67331
src/server/services/redditParser.js
src/server/services/redditParser.js
import fs from 'fs' export function parseBoardList(boardList) { // console.log(JSON.stringify(boardList)) try { boardList.data.children } catch (e) { log.error(`Bad reddit data returned => ${e}`) } const boards = boardList.data.children.map(board => board.data) // thanks, reddit! return boards.map(({url, title}) => { let boardID = url.split('/').slice(-2)[0] console.log(boardID) return { boardID, description: `${url} - ${title}` } }); }
import fs from 'fs' export function parseBoardList(boardList) { // console.log(JSON.stringify(boardList)) try { boardList.data.children } catch (e) { log.error(`Bad reddit data returned => ${e}`) } const boards = boardList.data.children.map(board => board.data) // thanks, reddit! return boards.map(({url, title}) => { let boardID = url.split('/').slice(-2)[0] return { boardID, description: `/${boardID}/ - ${title}` } }); }
Remove '/r/' from reddit board list
Remove '/r/' from reddit board list
JavaScript
mit
AdamSalma/Lurka,AdamSalma/Lurka
04f89b16a80b44e2d9fa247ef5f98a76d27efb69
functions/api.js
functions/api.js
'use strict' const mongoose = require('mongoose') const { ApolloServer } = require('apollo-server-lambda') const { UnsignedIntResolver, UnsignedIntTypeDefinition, DateTimeResolver, DateTimeTypeDefinition } = require('graphql-scalars') const isAuthenticated = require('../src/utils/isAuthenticated') const isDemoMode = require('../src/utils/isDemoMode') const createDate = require('../src/utils/createDate') const dbUrl = process.env.ACKEE_MONGODB || process.env.MONGODB_URI if (dbUrl == null) { throw new Error('MongoDB connection URI missing in environment') } mongoose.set('useFindAndModify', false) mongoose.connect(dbUrl, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true }) const apolloServer = new ApolloServer({ introspection: false, playground: false, debug: false, // formatError: handleGraphError, typeDefs: [ UnsignedIntTypeDefinition, DateTimeTypeDefinition, require('../src/types') ], resolvers: { UnsignedInt: UnsignedIntResolver, DateTime: DateTimeResolver, ...require('../src/resolvers') }, context: async (integrationContext) => ({ isDemoMode, isAuthenticated: await isAuthenticated(integrationContext.event.headers['authorization']), dateDetails: createDate(integrationContext.event.headers['time-zone']), req: integrationContext.req }) }) exports.handler = apolloServer.createHandler()
'use strict' const mongoose = require('mongoose') const { ApolloServer } = require('apollo-server-lambda') const { UnsignedIntResolver, UnsignedIntTypeDefinition, DateTimeResolver, DateTimeTypeDefinition } = require('graphql-scalars') const isAuthenticated = require('../src/utils/isAuthenticated') const isDemoMode = require('../src/utils/isDemoMode') const createDate = require('../src/utils/createDate') const dbUrl = process.env.ACKEE_MONGODB || process.env.MONGODB_URI if (dbUrl == null) { throw new Error('MongoDB connection URI missing in environment') } mongoose.connect(dbUrl, { useFindAndModify: false, useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true }) const apolloServer = new ApolloServer({ introspection: false, playground: false, debug: false, // formatError: handleGraphError, typeDefs: [ UnsignedIntTypeDefinition, DateTimeTypeDefinition, require('../src/types') ], resolvers: { UnsignedInt: UnsignedIntResolver, DateTime: DateTimeResolver, ...require('../src/resolvers') }, context: async (integrationContext) => ({ isDemoMode, isAuthenticated: await isAuthenticated(integrationContext.event.headers['authorization']), dateDetails: createDate(integrationContext.event.headers['time-zone']), req: integrationContext.req }) }) exports.handler = apolloServer.createHandler()
Set options in connect (serverless)
Set options in connect (serverless)
JavaScript
mit
electerious/Ackee
d1fe3fe748b9ca8c640f785c6f3779451cdbde68
index.js
index.js
var config = require('./config'), rest = require('./rest'), projects = require('./projects'); module.exports.init = function () { /** * Load config variables as environment variables */ for (envVar in config) { if (config.hasOwnProperty(envVar)) { process.env[envVar] = config[envVar]; } } /** * If the app is in testing mode, then set the api url * and api key from the defined testing api url and key */ if (config['ENVIRONMENT'] === 'testing') { process.env['API_URL'] = config['TESTING_API_URL']; process.env['API_KEY'] = config['TESTING_API_KEY']; } return { 'projects': projects.projects, 'project': projects.project }; };
var config = require('./config'), rest = require('./rest'), apiUrl = require('./apiUrl'), projects = require('./projects'); module.exports.init = function () { /** * Load config variables as environment variables */ for (envVar in config) { if (config.hasOwnProperty(envVar)) { process.env[envVar] = config[envVar]; } } /** * If the app is in testing mode, then set the api url * and api key from the defined testing api url and key */ if (config['ENVIRONMENT'] === 'testing') { process.env['API_URL'] = config['TESTING_API_URL']; process.env['API_KEY'] = config['TESTING_API_KEY']; } return { 'apiUrl': apiUrl, 'projects': projects.projects, 'project': projects.project }; };
Load new apiUrl module in ac module base
Load new apiUrl module in ac module base
JavaScript
mit
mediasuitenz/node-activecollab
406218069f7083816acee50367f7ca88fb4355c5
server/db/graphDb.js
server/db/graphDb.js
if (process.env.NODE_ENV !== 'production') require('../../secrets'); const neo4j = require('neo4j-driver').v1; if (process.env.NODE_ENV === 'production') { const graphDb = neo4j.driver( process.env.GRAPHENEDB_BOLT_URL, neo4j.auth.basic(process.env.GRAPHENEDB_BOLT_USER, process.env.GRAPHENEDB_BOLT_PASSWORD) ); } else { const graphDb = neo4j.driver( process.env.NEO4j_BOLT_URL, neo4j.auth.basic(process.env.NEO4j_BOLT_USER, process.env.NEO4j_BOLT_PASSWORD) ); } process.on('exit', () => { graphDb.close(); }); module.exports = graphDb;
if (process.env.NODE_ENV !== 'production') require('../../secrets'); const neo4j = require('neo4j-driver').v1; if (process.env.NODE_ENV === 'production') { const graphDb = neo4j.driver( process.env.GRAPHENEDB_BOLT_URL, neo4j.auth.basic(process.env.GRAPHENEDB_BOLT_USER, process.env.GRAPHENEDB_BOLT_PASSWORD) ); process.on('exit', () => { graphDb.close(); }); module.exports = graphDb; } else { const graphDb = neo4j.driver( process.env.NEO4j_BOLT_URL, neo4j.auth.basic(process.env.NEO4j_BOLT_USER, process.env.NEO4j_BOLT_PASSWORD) ); process.on('exit', () => { graphDb.close(); }); module.exports = graphDb; }
Debug deployment and setting of node env variables
Debug deployment and setting of node env variables
JavaScript
mit
wordupapp/wordup,wordupapp/wordup
d92b18cddf1a23fbbf2edf6e6cf0ca57d374d3e5
index.js
index.js
(function (root, factory) { 'use strict'; /* global define, module, require */ if (typeof define === 'function' && define.amd) { // AMD define(['./lib/Dice', './lib/inventory', './lib/modifiers', './lib/ProtoTree', './lib/random', './lib/requirements'], factory); } else if (typeof exports === 'object') { // Node, browserify and alike module.exports = factory.apply( require('./lib/Dice'), require('./lib/inventory'), require('./lib/modifiers'), require('./lib/ProtoTree'), require('./lib/random'), require('./lib/requirements') ); } else { // Browser globals (root is window) var modules = ['Dice', 'inventory', 'modifiers', 'ProtoTree', 'random', 'requirements']; root.rpgTools = (root.rpgTools || {}); root.rpgTools = factory.apply(null, modules.map(function (module) { return root.rpgTools[module]; })); } }(this, function (Dice, inventory, modifiers, ProtoTree, random, requirements) { 'use strict'; var exports = { Dice: Dice, inventory: inventory, modifiers: modifiers, ProtoTree: ProtoTree, random: random, requirements: requirements }; return exports; }));
(function (root, factory) { 'use strict'; /* global define, module, require */ if (typeof define === 'function' && define.amd) { // AMD define(['./lib/Dice', './lib/inventory', './lib/modifiers', './lib/ProtoTree', './lib/random', './lib/requirements'], factory); } else if (typeof exports === 'object') { // Node, browserify and alike console.log('node') module.exports = factory( require('./lib/Dice'), require('./lib/inventory'), require('./lib/modifiers'), require('./lib/ProtoTree'), require('./lib/random'), require('./lib/requirements') ); } else { // Browser globals (root is window) console.log('browser') var modules = ['Dice', 'inventory', 'modifiers', 'ProtoTree', 'random', 'requirements']; root.rpgTools = (root.rpgTools || {}); root.rpgTools = factory.apply(null, modules.map(function (module) { return root.rpgTools[module]; })); } }(this, function (Dice, inventory, modifiers, ProtoTree, random, requirements) { 'use strict'; var exports = { Dice: Dice, inventory: inventory, modifiers: modifiers, ProtoTree: ProtoTree, random: random, requirements: requirements }; return exports; }));
Fix incorrect import of modules n commonjs env
Fix incorrect import of modules n commonjs env
JavaScript
mit
hogart/rpg-tools
485849e4d89287c4a0ac21f23e82bd9c22cfe3e5
querylang/index.js
querylang/index.js
import query from './query.pegjs'; export function parseToAst (string) { return query.parse(string); } const opfunc = { '<=': function (x, y) { return x <= y; }, '<': function (x, y) { return x < y; }, '>=': function (x, y) { return x >= y; }, '>': function (x, y) { return x > y; }, '=': function (x, y) { return x === y; }, '!=': function (x, y) { return x !== y; } }; function checker (ast, include) { return function (row) { const data = row[ast.operands[0]]; for (let i = 0; i < ast.operands[1].length; i++) { if (data === ast.operands[1][i]) { return include; } } return !include; }; } export function astToFunction (ast) { switch (ast.operator) { case 'or': return function (row) { const f1 = astToFunction(ast.operands[0]); const f2 = astToFunction(ast.operands[1]); return f1(row) || f2(row); }; case 'and': return function (row) { const f1 = astToFunction(ast.operands[0]); const f2 = astToFunction(ast.operands[1]); return f1(row) && f2(row); }; case 'not': return function (row) { const f = astToFunction(ast.operands); return !f(row); }; case 'in': return checker(ast, true); case 'not in': return checker(ast, false); case '<=': case '<': case '>=': case '>': case '=': case '!=': return function (row) { const data = row[ast.operands[0]]; return opfunc[ast.operator](data, ast.operands[1]); }; } } export function parseToFunction (string) { return astToFunction(parseToAst(string)); }
import query from './query.pegjs'; export function parseToAst (string) { return query.parse(string); }
Remove astToFunction from JavaScript code
Remove astToFunction from JavaScript code
JavaScript
apache-2.0
ronichoudhury-work/resonantlab,ronichoudhury-work/resonantlab,ronichoudhury-work/resonantlab,ronichoudhury-work/resonantlab
4bddfa56144fd2302ef80c3d41d86d329140ea8c
index.js
index.js
let Scanner = require('./lib/scanner.js'); let Parser = require('./lib/parser.js'); let Packer = require('./lib/packer.js'); module.exports = { scan: Scanner.scan, parse: Parser.parse, pack: Packer.pack };
let Scanner = require('./lib/scanner.js'); let Parser = require('./lib/parser.js'); let Packer = require('./lib/packer.js'); let Executor = require('./lib/executor.js'); module.exports = { scan: Scanner.scan, parse: Parser.parse, pack: Packer.pack, unpack: Packer.unpack, execute: Executor.execute };
Add unpack() to the public interface
Add unpack() to the public interface
JavaScript
mit
cranbee/template,cranbee/template
2da38edb4540a35be74e74c66a13b0c2ca79bc1c
examples/minimal.js
examples/minimal.js
var Connection = require('../lib/tedious').Connection; var Request = require('../lib/tedious').Request; var options = {}; var connection = new Connection('192.168.1.210', 'test', 'test', options, function(err, loggedIn) { // If no error, then good to go... executeStatement() } ) function executeStatement() { request = new Request("select 42, 'hello world'", function(err, rowCount) { console.log(rowCount + ' rows returned'); }); request.on('row', function(columns) { columns.forEach(function(column) { if (column.isNull) { console.log('NULL'); } else { console.log(column.value); } }); }); connection.execSql(request); }
var Connection = require('../lib/tedious').Connection; var Request = require('../lib/tedious').Request; var config = { server: '192.168.1.210', userName: 'test', password: 'test' /* ,options: { debug: { packet: true, data: true, payload: true, token: false, log: true } } */ }; var connection = new Connection(config); connection.on('connection', function(err) { // If no error, then good to go... executeStatement(); } ); connection.on('debug', function(text) { //console.log(text); } ); function executeStatement() { request = new Request("select 42, 'hello world'", function(err) { connection.close(); }); request.on('row', function(columns) { columns.forEach(function(column) { if (column.isNull) { console.log('NULL'); } else { console.log(column.value); } }); }); request.on('done', function(rowCount, more) { console.log(rowCount + ' rows returned'); }); connection.execSql(request); }
Change example code to use new API.
Change example code to use new API.
JavaScript
mit
tediousjs/tedious,tediousjs/tedious,LeanKit-Labs/tedious,pekim/tedious,arthurschreiber/tedious,spanditcaa/tedious,Sage-ERP-X3/tedious
13e72c4b5b4b5f57ef517baefbc28f019e00d026
src/Native/Global.js
src/Native/Global.js
const _elm_node$core$Native_Global = function () { const Err = _elm_lang$core$Result$Err const Ok = _elm_lang$core$Result$Ok // parseInt : Int -> String -> Result Decode.Value Int const parseInt = F2((radix, string) => { try { // radix values integer from 2-36 const value = global.parseInt(string, radix) // TODO check for value === NaN and Err in that case return Ok(value) } catch (error) { return Err(error) } }) const exports = { parseInt } return exports }()
const _elm_node$core$Native_Global = function () { const Err = _elm_lang$core$Result$Err const Ok = _elm_lang$core$Result$Ok // parseInt : Int -> String -> Result Decode.Value Int const parseInt = F2((radix, string) => { try { // NOTE radix can be any integer from 2-36 const value = global.parseInt(string, radix) if (isNaN(value)) return Err(new Error(`String cannot be converted to an integer: ${string}`)) return Ok(value) } catch (error) { return Err(error) } }) const exports = { parseInt } return exports }()
Add check for NaN in parseInt native code.
Add check for NaN in parseInt native code.
JavaScript
unlicense
elm-node/core
14ee18829254fabd2c56dbd58f70a444ebec09ce
src/javascripts/test/e2e/ShowViewSpec.js
src/javascripts/test/e2e/ShowViewSpec.js
/*global describe,it,expect,$$,element,browser,by*/ describe('ShowView', function () { 'use strict'; var hasToLoad = true; beforeEach(function() { if (hasToLoad) { browser.get(browser.baseUrl + '#/posts/show/1'); hasToLoad = false; } }); describe('ChoiceField', function() { it('should render as a label when choices is an array', function () { $$('.ng-admin-field-category').then(function (fields) { expect(fields[0].getText()).toBe('Tech'); }); }); it('should render as a label when choices is a function', function () { $$('.ng-admin-field-subcategory').then(function (fields) { expect(fields[0].getText()).toBe('Computers'); }); }); }); describe('ReferencedListField', function() { it('should render as a datagrid', function () { $$('.ng-admin-field-comments th').then(function (inputs) { expect(inputs.length).toBe(2); expect(inputs[0].getAttribute('class')).toBe('ng-scope ng-admin-column-id'); expect(inputs[1].getAttribute('class')).toBe('ng-scope ng-admin-column-body'); }); }); }); });
/*global describe,it,expect,$$,element,browser,by*/ describe('ShowView', function () { 'use strict'; var hasToLoad = true; beforeEach(function() { if (hasToLoad) { browser.get(browser.baseUrl + '#/posts/show/1'); hasToLoad = false; } }); describe('ChoiceField', function() { it('should render as a label when choices is an array', function () { $$('.ng-admin-field-category').then(function (fields) { expect(fields[0].getText()).toBe('Tech'); }); }); it('should render as a label when choices is a function', function () { $$('.ng-admin-field-subcategory').then(function (fields) { expect(fields[0].getText()).toBe('Computers'); }); }); }); describe('ReferencedListField', function() { it('should render as a datagrid', function () { $$('.ng-admin-field-comments th').then(function (inputs) { expect(inputs.length).toBe(2); expect(inputs[0].getAttribute('class')).toBe('ng-scope ng-admin-column-created_at'); expect(inputs[1].getAttribute('class')).toBe('ng-scope ng-admin-column-body'); }); }); }); });
Fix e2e tests for ShowView
Fix e2e tests for ShowView
JavaScript
mit
jainpiyush111/ng-admin,rifer/ng-admin,SebLours/ng-admin,gxr1028/ng-admin,heliodor/ng-admin,arturbrasil/ng-admin,ronal2do/ng-admin,jainpiyush111/ng-admin,thachp/ng-admin,AgustinCroce/ng-admin,bericonsulting/ng-admin,Benew/ng-admin,rao1219/ng-admin,maninga/ng-admin,vasiakorobkin/ng-admin,manuelnaranjo/ng-admin,VincentBel/ng-admin,eBoutik/ng-admin,AgustinCroce/ng-admin,ronal2do/ng-admin,zealot09/ng-admin,heliodor/ng-admin,spfjr/ng-admin,baytelman/ng-admin,jainpiyush111/ng-admin,vasiakorobkin/ng-admin,Benew/ng-admin,ulrobix/ng-admin,marmelab/ng-admin,spfjr/ng-admin,janusnic/ng-admin,manekinekko/ng-admin,VincentBel/ng-admin,marmelab/ng-admin,zealot09/ng-admin,ahgittin/ng-admin,baytelman/ng-admin,ahgittin/ng-admin,eBoutik/ng-admin,shekhardesigner/ng-admin,thachp/ng-admin,rao1219/ng-admin,manekinekko/ng-admin,gxr1028/ng-admin,arturbrasil/ng-admin,rifer/ng-admin,shekhardesigner/ng-admin,SebLours/ng-admin,LuckeyHomes/ng-admin,maninga/ng-admin,ulrobix/ng-admin,LuckeyHomes/ng-admin,marmelab/ng-admin,janusnic/ng-admin,LuckeyHomes/ng-admin,manuelnaranjo/ng-admin,jainpiyush111/ng-admin,bericonsulting/ng-admin,ulrobix/ng-admin,eBoutik/ng-admin
91da0f03a2cebcd09ce3e6a72a4cbad9f899f0b3
_js/utils/get-url-parameter.js
_js/utils/get-url-parameter.js
import URI from 'urijs'; /** * Return a URL parameter. */ const getUrlParameter = function(url, param, type) { const uri = new URI(url), query = URI.parseQuery(uri.query()); if (!uri.hasQuery(param)) { throw new Error(`Parameter "${param}" missing from URL`); } if (type == 'int') { if (isNaN(parseInt(query[param]))) { throw new Error(`Parameter "${param}" must be an integer`); } return parseInt(query[param]); } return query[param]; }; export default getUrlParameter;
import URI from 'urijs'; /** * Return a URL parameter. */ const getUrlParameter = function(url, param, type) { const uri = new URI(url), query = URI.parseQuery(uri.query()); if (!uri.hasQuery(param)) { return null; } if (type == 'int') { if (isNaN(parseInt(query[param]))) { throw new Error(`Parameter "${param}" must be an integer`); } return parseInt(query[param]); } return query[param]; }; export default getUrlParameter;
Return null of param not found
Return null of param not found
JavaScript
mit
alexandermendes/tei-viewer,alexandermendes/tei-viewer,alexandermendes/tei-viewer
d72da7c135bbf9441e22b1a54a6e30f169872004
seeds/4_publishedProjects.js
seeds/4_publishedProjects.js
exports.seed = function(knex, Promise) { return Promise.join( knex('publishedProjects').insert({ title: 'sinatra-contrib', tags: 'ruby, sinatra, community, utilities', description: 'Hydrogen atoms Sea of Tranquility are creatures of the cosmos shores of the cosmic ocean.', date_created: '2015-06-03T16:21:58.000Z', date_updated: '2015-06-03T16:41:58.000Z' }), knex('projects').where('id', 2) .update({ published_id: 1 }) ); };
exports.seed = function(knex, Promise) { return Promise.join( knex('publishedProjects').insert({ title: 'sinatra-contrib', tags: 'ruby, sinatra, community, utilities', description: 'Hydrogen atoms Sea of Tranquility are creatures of the cosmos shores of the cosmic ocean.', date_created: '2015-06-19T17:21:58.000Z', date_updated: '2015-06-23T06:41:58.000Z' }), knex('publishedProjects').insert({ title: 'spacecats-API', tags: 'sinatra, api, REST, server, ruby', description: 'Venture a very small stage in a vast cosmic arena Euclid billions upon billions!' }) ).then(function() { return Promise.join( knex('projects').where('id', 2) .update({ published_id: 1 }), knex('projects').where('id', 1) .update({ published_id: 2 }) ); }); };
Fix race condition between updating project before creating corresponding published project
Fix race condition between updating project before creating corresponding published project
JavaScript
mpl-2.0
mozilla/publish.webmaker.org,sedge/publish.webmaker.org,mozilla/publish.webmaker.org,Pomax/publish.webmaker.org,Pomax/publish.webmaker.org,sedge/publish.webmaker.org,sedge/publish.webmaker.org,mozilla/publish.webmaker.org,Pomax/publish.webmaker.org
57ba2daa4091aa2660564eb92fc131929a6b0bc1
tests/integration/shadow-dom-test.js
tests/integration/shadow-dom-test.js
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('foo-bar', 'Integration | Polymer | Shadow DOM', { integration: true }); test('Uses native Shadow DOM if available', function(assert) { if (!window.Polymer.Settings.nativeShadow) { return assert.expect(0); } assert.expect(2); this.render(hbs`<paper-button></paper-button>`); assert.ok(document.querySelector('paper-button').shadowRoot, 'paper-button has shadowRoot'); assert.equal(this.$('paper-button').attr('role'), 'button', 'role is attached to button immediately'); });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('foo-bar', 'Integration | Polymer | Shadow DOM', { integration: true }); test('Uses native Shadow DOM if available', function(assert) { if (!window.Polymer.Settings.nativeShadow) { return assert.expect(0); } assert.expect(2); this.render(hbs`<paper-button></paper-button>`); assert.ok(document.querySelector('paper-button').shadowRoot, 'paper-button has shadowRoot'); assert.equal($('paper-button').attr('role'), 'button', 'role is attached to button immediately'); });
Fix jquery scope once again, in integration test 🔨
Fix jquery scope once again, in integration test 🔨 For some reason ember 2.9.0 and above has some serious problems with the previously used scope. This should fix a broken build.
JavaScript
mit
dunnkers/ember-polymer,dunnkers/ember-polymer
3f9c0f33d1848a1b28c202868a0f58a257232d0a
index.js
index.js
/** * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection} * * @module turf/featurecollection * @category helper * @param {Feature} features input Features * @returns {FeatureCollection} a FeatureCollection of input features * @example * var features = [ * turf.point([-75.343, 39.984], {name: 'Location A'}), * turf.point([-75.833, 39.284], {name: 'Location B'}), * turf.point([-75.534, 39.123], {name: 'Location C'}) * ]; * * var fc = turf.featurecollection(features); * * //=fc */ module.exports = function(features){ return { type: "FeatureCollection", features: features }; };
/** * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection} * * @module turf/featurecollection * @category helper * @param {Feature<(Point|LineString|Polygon)>} features input features * @returns {FeatureCollection<(Point|LineString|Polygon)>} a FeatureCollection of input features * @example * var features = [ * turf.point([-75.343, 39.984], {name: 'Location A'}), * turf.point([-75.833, 39.284], {name: 'Location B'}), * turf.point([-75.534, 39.123], {name: 'Location C'}) * ]; * * var fc = turf.featurecollection(features); * * //=fc */ module.exports = function(features){ return { type: "FeatureCollection", features: features }; };
Switch doc to closure compiler templating
Switch doc to closure compiler templating
JavaScript
mit
Turfjs/turf-featurecollection
1334e33b73f465803b96d847b61f743cdabf566f
lib/utils.js
lib/utils.js
/** * Helper functions */ 'use strict'; module.exports = { parseVideoUrl(url) { function getIdFromUrl(url, re) { let matches = url.match(re); return (matches && matches[1]) || null; } let id; // https://www.youtube.com/watch?v=24X9FpeSASY if (url.indexOf('youtube.com/') > -1) { id = getIdFromUrl(url, /\/watch\?v=([A-Z0-9]+)/i); return id ? ['youtube', id] : null; } // https://vimeo.com/27986705 if (url.indexOf('vimeo.com/') > -1) { id = getIdFromUrl(url, /\/([0-9]+)/); return id ? ['vimeo', id] : null; } return null; } };
/** * Helper functions */ 'use strict'; module.exports = { parseVideoUrl(url) { function getIdFromUrl(url, re) { let matches = url.match(re); return (matches && matches[1]) || null; } let id; // https://www.youtube.com/watch?v=24X9FpeSASY // http://stackoverflow.com/questions/5830387/how-to-find-all-youtube-video-ids-in-a-string-using-a-regex/5831191#5831191 if (url.indexOf('youtube.com/') > -1) { id = getIdFromUrl(url, /\/watch\?v=([A-Z0-9_-]+)/i); return id ? ['youtube', id] : null; } // https://vimeo.com/27986705 if (url.indexOf('vimeo.com/') > -1) { id = getIdFromUrl(url, /\/([0-9]+)/); return id ? ['vimeo', id] : null; } return null; } };
Allow underscores and hyphens in Youtube video ID
Allow underscores and hyphens in Youtube video ID Fixes #122
JavaScript
bsd-2-clause
macbre/nodemw
554ceb2837c9f71f6454b34a75769fa05ecb25d2
lib/message.js
lib/message.js
function Message(queue, message, headers, deliveryInfo) { // Crane uses slash ('/') separators rather than period ('.') this.queue = deliveryInfo.queue.replace(/\./g, '/'); this.headers = {}; if (deliveryInfo.contentType) { headers['content-type'] = deliveryInfo.contentType; } this.body = message; this._amqp = { queue: queue }; } Message.prototype.ack = function() { this._amqp.queue.shift(); } module.exports = Message;
function Message(queue, message, headers, deliveryInfo) { // Crane uses slash ('/') separators rather than period ('.') this.topic = deliveryInfo.routingKey.replace(/\./g, '/'); this.headers = {}; if (deliveryInfo.contentType) { headers['content-type'] = deliveryInfo.contentType; } this.body = message; } module.exports = Message;
Set topic based on routing key.
Set topic based on routing key.
JavaScript
mit
jaredhanson/antenna-amqp
4c3d453b2c880b9d7773f9c15184401b78a03092
test/extractors/spectralKurtosis.js
test/extractors/spectralKurtosis.js
var chai = require('chai'); var assert = chai.assert; var TestData = require('../TestData'); // Setup var spectralKurtosis = require('../../dist/node/extractors/spectralKurtosis'); describe('spectralKurtosis', function () { it('should return correct Spectral Kurtosis value', function (done) { var en = spectralKurtosis({ ampSpectrum:TestData.VALID_AMPLITUDE_SPECTRUM, }); assert.equal(en, 0.1511072674115075); done(); }); it('should throw an error when passed an empty object', function (done) { try { var en = spectralKurtosis({}); } catch (e) { done(); } }); it('should throw an error when not passed anything', function (done) { try { var en = spectralKurtosis(); } catch (e) { done(); } }); it('should throw an error when passed something invalid', function (done) { try { var en = spectralKurtosis({ signal:'not a signal' }); } catch (e) { done(); } }); });
var chai = require('chai'); var assert = chai.assert; var TestData = require('../TestData'); // Setup var spectralKurtosis = require('../../dist/node/extractors/spectralKurtosis'); describe('spectralKurtosis', function () { it('should return correct Spectral Kurtosis value', function (done) { var en = spectralKurtosis({ ampSpectrum:TestData.VALID_AMPLITUDE_SPECTRUM, }); assert.approximately(en, 0.1511072674115075, 1e-15); done(); }); it('should throw an error when passed an empty object', function (done) { try { var en = spectralKurtosis({}); } catch (e) { done(); } }); it('should throw an error when not passed anything', function (done) { try { var en = spectralKurtosis(); } catch (e) { done(); } }); it('should throw an error when passed something invalid', function (done) { try { var en = spectralKurtosis({ signal:'not a signal' }); } catch (e) { done(); } }); });
Modify test for approximate equality
Modify test for approximate equality A change in Node 12 means that the test value we were previously using differs from the new result by `2.7755575615628914e-17`.
JavaScript
mit
meyda/meyda,hughrawlinson/meyda,meyda/meyda,meyda/meyda
3cbf626c27f8cfd777b99265f5f2f9f356466943
client/app/scripts/filters.js
client/app/scripts/filters.js
/*global Showdown */ 'use strict'; angular.module('memoFilters', []) .filter('markdown', function ($sce) { // var converter = new Showdown.converter({ extensions: ['github', 'youtube'] }); var marked = window.marked; var hljs = window.hljs; marked.setOptions({ highlight: function (code, lang) { return hljs.highlight(lang, code).value; } }); return function (input) { if (!input) { return null; } // console.log(input); // return $sce.trustAsHtml(converter.makeHtml(input)); return $sce.trustAsHtml(marked(input)); }; });
/*global Showdown */ 'use strict'; angular.module('memoFilters', []) .filter('markdown', function ($sce) { // var converter = new Showdown.converter({ extensions: ['github', 'youtube'] }); var marked = window.marked; var hljs = window.hljs; marked.setOptions({ highlight: function (code, lang) { if (lang) { return hljs.highlight(lang, code).value; } else { return hljs.highlightAuto(code).value; } } }); return function (input) { if (!input) { return null; } // console.log(input); // return $sce.trustAsHtml(converter.makeHtml(input)); return $sce.trustAsHtml(marked(input)); }; });
Fix an issue to show code without language option
Fix an issue to show code without language option
JavaScript
mit
eqot/memo
a8689937a9f202e5efd4a003435fd6e3652ef72c
lib/service.js
lib/service.js
var ts = require('typescript'); var process = require('process'); var IncrementalChecker = require('./IncrementalChecker'); var CancellationToken = require('./CancellationToken'); var checker = new IncrementalChecker( process.env.TSCONFIG, process.env.TSLINT === '' ? false : process.env.TSLINT, process.env.WATCH === '' ? [] : process.env.WATCH.split('|'), parseInt(process.env.WORK_NUMBER, 10), parseInt(process.env.WORK_DIVISION, 10), process.env.CHECK_SYNTACTIC_ERRORS === '' ? false : process.env.CHECK_SYNTACTIC_ERRORS ); function run (cancellationToken) { var diagnostics = []; var lints = []; checker.nextIteration(); try { diagnostics = checker.getDiagnostics(cancellationToken); if (checker.hasLinter()) { lints = checker.getLints(cancellationToken); } } catch (error) { if (error instanceof ts.OperationCanceledException) { return; } throw error; } if (!cancellationToken.isCancellationRequested()) { try { process.send({ diagnostics: diagnostics, lints: lints }); } catch (e) { // channel closed... process.exit(); } } } process.on('message', function (message) { run(CancellationToken.createFromJSON(message)); }); process.on('SIGINT', function () { process.exit(); });
var ts = require('typescript'); var process = require('process'); var IncrementalChecker = require('./IncrementalChecker'); var CancellationToken = require('./CancellationToken'); var checker = new IncrementalChecker( process.env.TSCONFIG, process.env.TSLINT === '' ? false : process.env.TSLINT, process.env.WATCH === '' ? [] : process.env.WATCH.split('|'), parseInt(process.env.WORK_NUMBER, 10), parseInt(process.env.WORK_DIVISION, 10), process.env.CHECK_SYNTACTIC_ERRORS ); function run (cancellationToken) { var diagnostics = []; var lints = []; checker.nextIteration(); try { diagnostics = checker.getDiagnostics(cancellationToken); if (checker.hasLinter()) { lints = checker.getLints(cancellationToken); } } catch (error) { if (error instanceof ts.OperationCanceledException) { return; } throw error; } if (!cancellationToken.isCancellationRequested()) { try { process.send({ diagnostics: diagnostics, lints: lints }); } catch (e) { // channel closed... process.exit(); } } } process.on('message', function (message) { run(CancellationToken.createFromJSON(message)); }); process.on('SIGINT', function () { process.exit(); });
Simplify pass through of CHECK_SYNTACTIC_ERRORS
Simplify pass through of CHECK_SYNTACTIC_ERRORS
JavaScript
mit
Realytics/fork-ts-checker-webpack-plugin,Realytics/fork-ts-checker-webpack-plugin
9acb0f7396da889dab0182cd22ba2d7f91883c82
build.js
build.js
let fs = require('fs'); let mkdirp = require('mkdirp'); let sass = require('node-sass'); sass.render({ file: 'sass/matter.sass', }, function (renderError, result) { if (renderError) { console.log(renderError); } else { mkdirp('dist/css', function (mkdirError) { if (mkdirError) { console.log(mkdirError); } else { fs.writeFile('dist/css/matter.css', result.css, function (writeError) { if (writeError) { console.log(writeError); } else { console.log('dist/css/matter.css generated!'); } }); } }); } });
let fs = require('fs'); let mkdirp = require('mkdirp'); let sass = require('node-sass'); sass.render({ file: 'sass/matter.sass', indentedSyntax: true, outputStyle: 'expanded', }, function (renderError, result) { if (renderError) { console.log(renderError); } else { mkdirp('dist/css', function (mkdirError) { if (mkdirError) { console.log(mkdirError); } else { fs.writeFile('dist/css/matter.css', result.css, function (writeError) { if (writeError) { console.log(writeError); } else { console.log('dist/css/matter.css generated!'); } }); } }); } });
Use expanded style in rendered css
Use expanded style in rendered css
JavaScript
mit
yusent/matter,yusent/matter
2251a3d504b511aebd3107c8a7c94da14cbbea1a
config/environment.js
config/environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'smallprint', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'smallprint', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, contentSecurityPolicy: { 'style-src': "'self' 'unsafe-inline'", }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
Stop console error about content security policy
Stop console error about content security policy
JavaScript
mit
Br3nda/priv-o-matic,OPCNZ/priv-o-matic,Br3nda/priv-o-matic,OPCNZ/priv-o-matic
0fef1857715cc92e6f8f58576b039b39f2ff1038
lib/assert-paranoid-equal/utilities.js
lib/assert-paranoid-equal/utilities.js
'use strict'; function isNothing(subject) { return (undefined === subject) || (null === subject); } function isObject(subject) { return ('object' === typeof subject) && (null !== subject); } function isNaNConstant(subject) { // There is not Number.isNaN in Node 0.6.x return ('number' === typeof subject) && isNaN(subject); } function isInstanceOf(constructor /*, subjects... */) { var index, length = arguments.length; if (length < 2) { return false; } for (index = 1; index < length; index += 1) { if (!(arguments[index] instanceof constructor)) { return false; } } return true; } function collectKeys(subject, include, exclude) { var result = Object.getOwnPropertyNames(subject); if (!isNothing(include)) { include.forEach(function (key) { if (0 > result.indexOf(key)) { result.push(key); } }); } if (!isNothing(exclude)) { result = result.filter(function (key) { return 0 > exclude.indexOf(key); }); } return result; } module.exports.isNothing = isNothing; module.exports.isObject = isObject; module.exports.isNaNConstant = isNaNConstant; module.exports.isInstanceOf = isInstanceOf; module.exports.collectKeys = collectKeys;
'use strict'; function isNothing(subject) { return (undefined === subject) || (null === subject); } function isObject(subject) { return ('object' === typeof subject) && (null !== subject); } function isNaNConstant(subject) { if (undefined !== Number.isNaN) { return Number.isNaN(subject); } else { // There is no Number.isNaN in Node 0.6.x return ('number' === typeof subject) && isNaN(subject); } } function isInstanceOf(constructor /*, subjects... */) { var index, length = arguments.length; if (length < 2) { return false; } for (index = 1; index < length; index += 1) { if (!(arguments[index] instanceof constructor)) { return false; } } return true; } function collectKeys(subject, include, exclude) { var result = Object.getOwnPropertyNames(subject); if (!isNothing(include)) { include.forEach(function (key) { if (0 > result.indexOf(key)) { result.push(key); } }); } if (!isNothing(exclude)) { result = result.filter(function (key) { return 0 > exclude.indexOf(key); }); } return result; } module.exports.isNothing = isNothing; module.exports.isObject = isObject; module.exports.isNaNConstant = isNaNConstant; module.exports.isInstanceOf = isInstanceOf; module.exports.collectKeys = collectKeys;
Use `Number.isNaN` when it's available.
Use `Number.isNaN` when it's available.
JavaScript
mit
dervus/assert-paranoid-equal
9c01da3c20f726f78308381e484f4c9b53396dae
src/exchange-main.js
src/exchange-main.js
'use babel' import {Disposable, CompositeDisposable} from 'sb-event-kit' import Communication from 'sb-communication' class Exchange { constructor(worker) { this.worker = worker this.port = worker.port || worker this.communication = new Communication() this.subscriptions = new CompositeDisposable() this.subscriptions.add(this.communication) const callback = message => { this.communication.parseMessage(message.data) } this.port.addEventListener('message', callback) this.subscriptions.add(new Disposable(() => { this.port.removeEventListener('message', callback) })) this.communication.onShouldSend(message => { this.port.postMessage(message) }) this.onRequest('ping', function(_, message) { message.response = 'pong' }) } request(name, data = {}) { return this.communication.request(name, data) } onRequest(name, callback) { return this.communication.onRequest(name, callback) } terminate() { if (this.worker.terminate) { this.worker.terminate() } else { this.port.close() } this.dispose() } dispose() { this.subscriptions.dispose() } static create(filePath) { return new Exchange(new Worker(filePath)) } static createShared(filePath) { const worker = new SharedWorker(filePath) const exchange = new Exchange(worker) worker.port.start() return exchange } } module.exports = Exchange
'use babel' import {Disposable, CompositeDisposable} from 'sb-event-kit' import Communication from 'sb-communication' class Exchange { constructor(worker) { this.worker = worker this.port = worker.port || worker this.communication = new Communication() this.subscriptions = new CompositeDisposable() this.subscriptions.add(this.communication) const callback = message => { this.communication.parseMessage(message.data) } this.port.addEventListener('message', callback) this.subscriptions.add(new Disposable(() => { this.port.removeEventListener('message', callback) })) this.communication.onShouldSend(message => { this.port.postMessage(message) }) this.onRequest('ping', function(_, message) { message.response = 'pong' }) this.request('ping') } request(name, data = {}) { return this.communication.request(name, data) } onRequest(name, callback) { return this.communication.onRequest(name, callback) } terminate() { if (this.worker.terminate) { this.worker.terminate() } else { this.port.close() } this.dispose() } dispose() { this.subscriptions.dispose() } static create(filePath) { return new Exchange(new Worker(filePath)) } static createShared(filePath) { const worker = new SharedWorker(filePath) const exchange = new Exchange(worker) worker.port.start() return exchange } } module.exports = Exchange
Send a ping on worker init This fixes non-shared workers
:bug: Send a ping on worker init This fixes non-shared workers
JavaScript
mit
steelbrain/Worker-Exchange,steelbrain/Worker-Exchange
14b277eb296e9cc90f8d70fc82e07128f432adb2
addon/component.js
addon/component.js
import ClickOutsideMixin from './mixin'; import Component from '@ember/component'; import { on } from '@ember/object/evented'; import { next, cancel } from '@ember/runloop'; import $ from 'jquery'; export default Component.extend(ClickOutsideMixin, { clickOutside(e) { if (this.isDestroying || this.isDestroyed) { return; } const exceptSelector = this.get('except-selector'); if (exceptSelector && $(e.target).closest(exceptSelector).length > 0) { return; } let action = this.get('action'); if (typeof action !== 'undefined') { action(e); } }, _attachClickOutsideHandler: on('didInsertElement', function() { this._cancelOutsideListenerSetup = next(this, this.addClickOutsideListener); }), _removeClickOutsideHandler: on('willDestroyElement', function() { cancel(this._cancelOutsideListerSetup); this.removeClickOutsideListener(); }) });
import ClickOutsideMixin from './mixin'; import Component from '@ember/component'; import { next, cancel } from '@ember/runloop'; import $ from 'jquery'; export default Component.extend(ClickOutsideMixin, { clickOutside(e) { if (this.isDestroying || this.isDestroyed) { return; } const exceptSelector = this.get('except-selector'); if (exceptSelector && $(e.target).closest(exceptSelector).length > 0) { return; } let action = this.get('action'); if (typeof action !== 'undefined') { action(e); } }, didInsertElement() { this._super(...arguments); this._cancelOutsideListenerSetup = next(this, this.addClickOutsideListener); }, willDestroyElement() { cancel(this._cancelOutsideListerSetup); this.removeClickOutsideListener(); } });
Fix lifecycle events to satisfy recommendations
Fix lifecycle events to satisfy recommendations
JavaScript
mit
zeppelin/ember-click-outside,zeppelin/ember-click-outside
041b0b6ef81cb86443f6cdf9a2001c1b1d9b3d01
src/range-filters.js
src/range-filters.js
export function parseRangeFilters(stringValue = '') { if (!stringValue) { return []; } return stringValue.split('~').map(s => { const m = s.match(/range_(\-?[0-9.]+)\-(\-?[0-9.]+)/); if (!m) { return { start: 0, end: 1000 }; } return { start: m[1] * 1000, end: m[2] * 1000 }; }); } export function stringifyRangeFilters(arrayValue = []) { return arrayValue.map(({ start, end }) => { const startStr = (start / 1000).toFixed(4); const endStr = (end / 1000).toFixed(4); return `range_${startStr}-${endStr}`; }).join('~'); }
export function parseRangeFilters(stringValue = '') { if (!stringValue) { return []; } return stringValue.split('~').map(s => { const m = s.match(/range\-(\-?[0-9.]+)_(\-?[0-9.]+)/); if (!m) { return { start: 0, end: 1000 }; } return { start: m[1] * 1000, end: m[2] * 1000 }; }); } export function stringifyRangeFilters(arrayValue = []) { return arrayValue.map(({ start, end }) => { const startStr = (start / 1000).toFixed(4); const endStr = (end / 1000).toFixed(4); return `range-${startStr}_${endStr}`; }).join('~'); }
Use range-start_end instead of range_start-end in the URL. Looks a little better to me.
Use range-start_end instead of range_start-end in the URL. Looks a little better to me.
JavaScript
mpl-2.0
squarewave/bhr.html,squarewave/bhr.html,mstange/cleopatra,mstange/cleopatra,devtools-html/perf.html,devtools-html/perf.html
f547c16a9648ad15265283ed856352b73aadc69d
src/server/server.js
src/server/server.js
const express = require('express'); const cors = require('cors'); const session = require('express-session'); const bodyParser = require('body-parser'); const authMiddleware = require('./authMiddleware'); const auth = require('./controllers/auth'); const documents = require('./controllers/documents'); const deadlines = require('./controllers/deadlines'); const app = express(); const PORT_NUMBER = 8081; const SESSION = { secret: 'goodbirbs', cookie: { secure: false }, saveUninitialized: true, resave: true }; const CORS_CONFIG = { credentials: true, origin: 'http://localhost:3000' }; // Middleware app.use(session(SESSION)); app.use(bodyParser.json()); app.use(authMiddleware); // Routes app.use('/auth', cors(CORS_CONFIG), auth); app.use('/documents', cors(CORS_CONFIG), documents); app.use('/deadlines', cors(CORS_CONFIG), deadlines); const server = app.listen(PORT_NUMBER, () => { const { port } = server.address(); console.log(`Marketplace Managed API listening to port ${port}`); }); module.exports = server;
const express = require('express'); const cors = require('cors'); const session = require('express-session'); const bodyParser = require('body-parser'); const authMiddleware = require('./authMiddleware'); const auth = require('./controllers/auth'); const documents = require('./controllers/documents'); const deadlines = require('./controllers/deadlines'); const app = express(); const PORT_NUMBER = 8081; const SESSION = { secret: 'goodbirbs', cookie: { secure: false, maxAge: (1000 * 60 * 60 * 2) // two hours }, saveUninitialized: true, resave: true }; const CORS_CONFIG = { credentials: true, origin: 'http://localhost:3000' }; // Middleware app.use(session(SESSION)); app.use(bodyParser.json()); app.use(authMiddleware); // Routes app.use('/auth', cors(CORS_CONFIG), auth); app.use('/documents', cors(CORS_CONFIG), documents); app.use('/deadlines', cors(CORS_CONFIG), deadlines); const server = app.listen(PORT_NUMBER, () => { const { port } = server.address(); console.log(`Marketplace Managed API listening to port ${port}`); }); module.exports = server;
Set maxAge of two hours on session cookie
Set maxAge of two hours on session cookie
JavaScript
mit
ShevaDas/exhibitor-management,ShevaDas/exhibitor-management
f849dd852b5872008ea81338ab8a09c2263cf4b0
src/static/player.js
src/static/player.js
$(document).ready(function() { var sendingVol = false; var volChange = false; function send_slider_volume() { if (sendingVol || !volChange) return; var curVol = $("#mastervolslider").slider( "option", "value"); sendingVol = true; volChange = false; $('#mastervolval').text(Math.round(curVol * 100).toString() + '%'); // console.log("Sending volume " + curVol.toString()); $.ajax({ url: "../control/volume?level=" + curVol.toString(), type: 'POST' }).complete(function() { sendingVol = false; send_slider_volume(); }); } $("#mastervolslider").slider({ animate: true, min : 0.0, max : 1.5, range : 'true', value : 1.0, step : 0.05, slide : function(event, ui) { volChange = true; send_slider_volume(); }, change : function(event, ui) { volChange = true; send_slider_volume(); } }); $("#play").click(function() { $.ajax({ url: "../control/play", type: 'POST' }); }); $("#pause").click(function() { $.ajax({ url: "../control/pause" , type: 'POST'}); }); $("#next").click(function() { $.ajax({ url: "../control/next" , type: 'POST'}); }); });
$(document).ready(function() { var sendingVol = false; var volChange = false; function send_slider_volume() { if (sendingVol || !volChange) return; var curVol = $("#mastervolslider").slider( "option", "value"); sendingVol = true; volChange = false; $('#mastervolval').text(Math.round(curVol * 100).toString() + '%'); // console.log("Sending volume " + curVol.toString()); $.ajax({ url: "../control/volume?level=" + curVol.toString(), type: 'POST' }).complete(function() { sendingVol = false; send_slider_volume(); }); } $("#mastervolslider").slider({ animate: true, min : 0.0, max : 1.5, range : 'true', value : 1.0, step : 0.01, slide : function(event, ui) { volChange = true; send_slider_volume(); }, change : function(event, ui) { volChange = true; send_slider_volume(); } }); $("#play").click(function() { $.ajax({ url: "../control/play", type: 'POST' }); }); $("#pause").click(function() { $.ajax({ url: "../control/pause" , type: 'POST'}); }); $("#next").click(function() { $.ajax({ url: "../control/next" , type: 'POST'}); }); });
Make the volume control finer grained.
Make the volume control finer grained.
JavaScript
lgpl-2.1
thaytan/aurena,thaytan/aurena,thaytan/aurena,thaytan/aurena,thaytan/aurena,thaytan/aurena
522e0af7990d6bcf5ccc25880f3f3e186f935a5a
examples/js/loaders/ctm/CTMWorker.js
examples/js/loaders/ctm/CTMWorker.js
importScripts( "lzma.js", "ctm.js" ); self.onmessage = function( event ) { var files = []; for ( var i = 0; i < event.data.offsets.length; i ++ ) { var stream = new CTM.Stream( event.data.data ); stream.offset = event.data.offsets[ i ]; files[ i ] = new CTM.File( stream ); } self.postMessage( files ); self.close(); };
importScripts( "lzma.js", "ctm.js" ); self.onmessage = function( event ) { var files = []; for ( var i = 0; i < event.data.offsets.length; i ++ ) { var stream = new CTM.Stream( event.data.data ); stream.offset = event.data.offsets[ i ]; files[ i ] = new CTM.File( stream, [event.data.data.buffer] ); } self.postMessage( files ); self.close(); };
Optimize sending data from worker
Optimize sending data from worker When transferable list is specified, postingMessage to worker doesn't copy data. Since ctm.js references original data, we can specify original stream to be transferred back to the main thread.
JavaScript
mit
nhalloran/three.js,jostschmithals/three.js,ondys/three.js,zhoushijie163/three.js,Hectate/three.js,ValtoLibraries/ThreeJS,nhalloran/three.js,06wj/three.js,Aldrien-/three.js,ngokevin/three.js,sherousee/three.js,colombod/three.js,mese79/three.js,fanzhanggoogle/three.js,gero3/three.js,WestLangley/three.js,satori99/three.js,sttz/three.js,TristanVALCKE/three.js,TristanVALCKE/three.js,fanzhanggoogle/three.js,framelab/three.js,Hectate/three.js,shanmugamss/three.js-modified,mhoangvslev/data-visualizer,Aldrien-/three.js,satori99/three.js,googlecreativelab/three.js,jeffgoku/three.js,Hectate/three.js,brianchirls/three.js,amakaroff82/three.js,nhalloran/three.js,fraguada/three.js,opensim-org/three.js,ondys/three.js,Ludobaka/three.js,Samsung-Blue/three.js,daoshengmu/three.js,spite/three.js,ngokevin/three-dev,brianchirls/three.js,gero3/three.js,SpinVR/three.js,ValtoLibraries/ThreeJS,jostschmithals/three.js,shinate/three.js,Aldrien-/three.js,fanzhanggoogle/three.js,daoshengmu/three.js,xundaokeji/three.js,Samsy/three.js,makc/three.js.fork,shanmugamss/three.js-modified,Ludobaka/three.js,xundaokeji/three.js,looeee/three.js,brianchirls/three.js,Amritesh/three.js,sasha240100/three.js,QingchaoHu/three.js,jeffgoku/three.js,Samsung-Blue/three.js,RemusMar/three.js,satori99/three.js,jpweeks/three.js,amakaroff82/three.js,mhoangvslev/data-visualizer,googlecreativelab/three.js,carlosanunes/three.js,ngokevin/three-dev,Ludobaka/three.js,Samsy/three.js,spite/three.js,stanford-gfx/three.js,Astrak/three.js,donmccurdy/three.js,RemusMar/three.js,framelab/three.js,spite/three.js,fyoudine/three.js,shinate/three.js,ngokevin/three-dev,fyoudine/three.js,shinate/three.js,brianchirls/three.js,sasha240100/three.js,arodic/three.js,jostschmithals/three.js,googlecreativelab/three.js,fraguada/three.js,spite/three.js,jostschmithals/three.js,looeee/three.js,sttz/three.js,Mugen87/three.js,Ludobaka/three.js,colombod/three.js,QingchaoHu/three.js,jostschmithals/three.js,Amritesh/three.js,RemusMar/three.js,mhoangvslev/data-visualizer,jostschmithals/three.js,daoshengmu/three.js,fraguada/three.js,xundaokeji/three.js,fanzhanggoogle/three.js,pailhead/three.js,colombod/three.js,RemusMar/three.js,ondys/three.js,TristanVALCKE/three.js,jee7/three.js,TristanVALCKE/three.js,matgr1/three.js,rfm1201/rfm.three.js,jee7/three.js,nhalloran/three.js,matgr1/three.js,ndebeiss/three.js,mhoangvslev/data-visualizer,amakaroff82/three.js,kaisalmen/three.js,TristanVALCKE/three.js,aardgoose/three.js,daoshengmu/three.js,RemusMar/three.js,colombod/three.js,Itee/three.js,ValtoLibraries/ThreeJS,jpweeks/three.js,googlecreativelab/three.js,hsimpson/three.js,ngokevin/three.js,stanford-gfx/three.js,Astrak/three.js,matgr1/three.js,ndebeiss/three.js,sasha240100/three.js,mese79/three.js,matgr1/three.js,Ludobaka/three.js,fanzhanggoogle/three.js,googlecreativelab/three.js,carlosanunes/three.js,Samsung-Blue/three.js,zhoushijie163/three.js,nhalloran/three.js,fraguada/three.js,Liuer/three.js,ndebeiss/three.js,arodic/three.js,Liuer/three.js,sherousee/three.js,fanzhanggoogle/three.js,sasha240100/three.js,amakaroff82/three.js,amakaroff82/three.js,Astrak/three.js,pailhead/three.js,RemusMar/three.js,shinate/three.js,aardgoose/three.js,Hectate/three.js,Astrak/three.js,Amritesh/three.js,satori99/three.js,Samsy/three.js,Astrak/three.js,ondys/three.js,Samsy/three.js,06wj/three.js,jeffgoku/three.js,arodic/three.js,brianchirls/three.js,mhoangvslev/data-visualizer,ngokevin/three.js,shanmugamss/three.js-modified,ngokevin/three.js,shinate/three.js,colombod/three.js,hsimpson/three.js,greggman/three.js,nhalloran/three.js,carlosanunes/three.js,jee7/three.js,jeffgoku/three.js,fernandojsg/three.js,jeffgoku/three.js,Samsy/three.js,arodic/three.js,Samsung-Blue/three.js,fernandojsg/three.js,shanmugamss/three.js-modified,amakaroff82/three.js,sherousee/three.js,sasha240100/three.js,sasha240100/three.js,jeffgoku/three.js,makc/three.js.fork,xundaokeji/three.js,mhoangvslev/data-visualizer,cadenasgmbh/three.js,ondys/three.js,fraguada/three.js,shanmugamss/three.js-modified,xundaokeji/three.js,ndebeiss/three.js,fraguada/three.js,framelab/three.js,satori99/three.js,WestLangley/three.js,Hectate/three.js,matgr1/three.js,kaisalmen/three.js,Samsung-Blue/three.js,Ludobaka/three.js,cadenasgmbh/three.js,greggman/three.js,arodic/three.js,spite/three.js,daoshengmu/three.js,spite/three.js,Aldrien-/three.js,carlosanunes/three.js,mese79/three.js,Hectate/three.js,donmccurdy/three.js,ValtoLibraries/ThreeJS,ndebeiss/three.js,ondys/three.js,Samsung-Blue/three.js,brianchirls/three.js,daoshengmu/three.js,julapy/three.js,ngokevin/three-dev,julapy/three.js,fernandojsg/three.js,Mugen87/three.js,ngokevin/three.js,Aldrien-/three.js,Aldrien-/three.js,shanmugamss/three.js-modified,xundaokeji/three.js,Astrak/three.js,hsimpson/three.js,julapy/three.js,carlosanunes/three.js,shinate/three.js,ngokevin/three-dev,rfm1201/rfm.three.js,mese79/three.js,TristanVALCKE/three.js,pailhead/three.js,SpinVR/three.js,colombod/three.js,satori99/three.js,Samsy/three.js,ValtoLibraries/ThreeJS,mese79/three.js,mrdoob/three.js,matgr1/three.js,ngokevin/three.js,rfm1201/rfm.three.js,mese79/three.js,Itee/three.js,ValtoLibraries/ThreeJS,mrdoob/three.js,carlosanunes/three.js,opensim-org/three.js,Mugen87/three.js,ndebeiss/three.js,arodic/three.js,ngokevin/three-dev,googlecreativelab/three.js
fba051054a620955435c0d4e7cf7ad1d53a77e53
pages/index.js
pages/index.js
import React, { Fragment } from 'react'; import Head from 'next/head'; import { Header, RaffleContainer } from '../components'; export default () => ( <Fragment> <Head> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>meetup-raffle</title> <link rel="stylesheet" href="/static/tachyons.min.css" /> <script src="/static/lib.min.js" /> </Head> <main className="sans-serif near-black"> <Header /> <RaffleContainer /> </main> </Fragment> );
import React, { Fragment } from 'react'; import Head from 'next/head'; import { Header, RaffleContainer } from '../components'; export default () => ( <Fragment> <Head> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>meetup-raffle</title> <link rel="stylesheet" href="/static/tachyons.min.css" /> </Head> <main className="sans-serif near-black"> <Header /> <RaffleContainer /> </main> <script src="/static/lib.min.js" /> </Fragment> );
Move script tag below content
Move script tag below content
JavaScript
mit
wKovacs64/meetup-raffle,wKovacs64/meetup-raffle
b3122ca59cef75447df5de3aeefc85f95dfc4073
popup.js
popup.js
window.addEventListener('load', function(){ 'use strict'; // Get elements var title = document.getElementById('page_title'); var url = document.getElementById('page_url'); var copyTitle = document.getElementById('copy_title'); var copyUrl = document.getElementById('copy_url'); // Get tab info chrome.tabs.query({ active: true }, function(tabs){ 'use strict'; // Show title and url title.innerHTML = tabs[0].title; url.innerHTML = tabs[0].url; // Add click listener to copy button copyTitle.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard var textArea = document.createElement('textarea'); document.body.appendChild(textArea); textArea.value = tabs[0].title; textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); }); copyUrl.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard var textArea = document.createElement('textarea'); document.body.appendChild(textArea); textArea.value = tabs[0].url; textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); }); }); });
function copyToClipboard(str){ 'use strict'; var textArea = document.createElement('textarea'); document.body.appendChild(textArea); textArea.value = str; textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); } window.addEventListener('load', function(){ 'use strict'; // Get elements var title = document.getElementById('page_title'); var url = document.getElementById('page_url'); var copyTitle = document.getElementById('copy_title'); var copyUrl = document.getElementById('copy_url'); // Get tab info chrome.tabs.query({ active: true }, function(tabs){ 'use strict'; // Show title and url title.innerHTML = tabs[0].title; url.innerHTML = tabs[0].url; // Add click listener to copy button copyTitle.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard copyToClipboard(tabs[0].title); }); copyUrl.addEventListener('click', function(){ 'use strict'; // Copy title to clipboard copyToClipboard(tabs[0].url); }); }); });
Split copy part to a function
Split copy part to a function
JavaScript
mit
Roadagain/TitleViewer,Roadagain/TitleViewer
f1d9bb6de06a201c0fee83d1c536fffbe2070016
app/js/instances/init.js
app/js/instances/init.js
/* * Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller * * 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. */ // instances/init.js // Handles discovery and display of Docker host instances var containerController = require('./containerController'), createContainerController = require('./createContainerController'), instanceController = require('./instanceController'), instanceDetailController = require('./instanceDetailController'), instanceModel = require('./instanceModel'), instanceService = require('./instanceService'); // init angular module var instances = angular.module('lighthouse.instances', []); // register module components instances.controller('containerController', containerController); instances.controller('createContainerController', createContainerController); instances.controller('instanceController', instanceController); instances.controller('instanceDetailController', instanceDetailController); instances.factory('instanceService', instanceService); instances.store('instanceModel', instanceModel); module.exports = instances;
/* * Copyright 2015 Caleb Brose, Chris Fogerty, Rob Sheehy, Zach Taylor, Nick Miller * * 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. */ // instances/init.js // Handles discovery and display of Docker host instances var containerController = require('./containerController'), createContainerController = require('./createContainerController'), instanceDetailController = require('./instanceDetailController'), instanceModel = require('./instanceModel'), instanceService = require('./instanceService'); // init angular module var instances = angular.module('lighthouse.instances', []); // register module components instances.controller('containerController', containerController); instances.controller('createContainerController', createContainerController); instances.controller('instanceDetailController', instanceDetailController); instances.factory('instanceService', instanceService); instances.store('instanceModel', instanceModel); module.exports = instances;
Fix bug introduced in merge
Fix bug introduced in merge
JavaScript
apache-2.0
lighthouse/harbor,lighthouse/harbor
7d88dec0afcbdbf15262e06a3bb8f59980e51251
app/libs/locale/index.js
app/libs/locale/index.js
'use strict'; // Load our requirements const i18n = require('i18n'), path = require('path'), logger = require('../log'); // Variables let localeDir = path.resolve(__base + '../locales'); // Configure the localization engine i18n.configure({ locales: require('./available-locales')(localeDir), defaultLocale: 'en', directory: localeDir, syncFiles: true, autoReload: true, register: global, api: { '__': 'lang', '__n': 'plural' } }); // Export for future use module.exports = i18n;
'use strict'; // Load our requirements const i18n = require('i18n'), path = require('path'), logger = require(__base + 'libs/log'); // Variables let localeDir = path.resolve(__base + '../locales'); // Configure the localization engine i18n.configure({ locales: require('./available-locales')(localeDir), defaultLocale: 'en', objectNotation: true, directory: localeDir, syncFiles: true, autoReload: true, register: global, api: { '__': 'lang', '__n': 'plural' } }); // Export for future use module.exports = i18n;
Update locale to use object notation
Update locale to use object notation
JavaScript
apache-2.0
transmutejs/core
74d57eb7613cef4fe6c998cf5c9ea7f86f22bf72
src/OAuth/Request.js
src/OAuth/Request.js
/** * Factory object for XMLHttpRequest */ function Request(debug) { var XMLHttpRequest; switch (true) { case typeof global.Titanium.Network.createHTTPClient != 'undefined': XMLHttpRequest = global.Titanium.Network.createHTTPClient(); break; // CommonJS require case typeof require != 'undefined': XMLHttpRequest = new require("xhr").XMLHttpRequest(); break; case typeof global.XMLHttpRequest != 'undefined': XMLHttpRequest = new global.XMLHttpRequest(); break; } return XMLHttpRequest; }
/** * Factory object for XMLHttpRequest */ function Request(debug) { var XHR; switch (true) { case typeof global.Titanium != 'undefined' && typeof global.Titanium.Network.createHTTPClient != 'undefined': XHR = global.Titanium.Network.createHTTPClient(); break; // CommonJS require case typeof require != 'undefined': XHR = new require("xhr").XMLHttpRequest(); break; case typeof global.XMLHttpRequest != 'undefined': XHR = new global.XMLHttpRequest(); break; } return XHR; }
Rename to XHR to avoid clashes, added extra check for Titanium object first
Rename to XHR to avoid clashes, added extra check for Titanium object first
JavaScript
mit
bytespider/jsOAuth,bytespider/jsOAuth,cklatik/jsOAuth,cklatik/jsOAuth,maxogden/jsOAuth,aoman89757/jsOAuth,aoman89757/jsOAuth
ef6b9a827c9f5af6018e08d69cc1cf4491d52386
frontend/src/app.js
frontend/src/app.js
import Rx from 'rx'; import Cycle from '@cycle/core'; import CycleDOM from '@cycle/dom'; function main() { return { DOM: Rx.Observable.interval(1000) .map(i => CycleDOM.h( 'h1', '' + i + ' seconds elapsed' )) }; } let drivers = { DOM: CycleDOM.makeDOMDriver('#app') }; Cycle.run(main, drivers);
import Cycle from '@cycle/core'; import {makeDOMDriver, h} from '@cycle/dom'; function main(drivers) { return { DOM: drivers.DOM.select('input').events('click') .map(ev => ev.target.checked) .startWith(false) .map(toggled => h('label', [ h('input', {type: 'checkbox'}), 'Toggle me', h('p', toggled ? 'ON' : 'off') ]) ) }; } let drivers = { DOM: makeDOMDriver('#app') }; Cycle.run(main, drivers);
Remove Rx as a direct dependency
Remove Rx as a direct dependency
JavaScript
mit
blakelapierre/cyclebox,blakelapierre/base-cyclejs,blakelapierre/cyclebox,blakelapierre/cyclebox,blakelapierre/base-cyclejs
243050586e55033f74debae5f2eac4ad17931161
myapp/public/javascripts/game-board.js
myapp/public/javascripts/game-board.js
/** * game-board.js * * Maintain game board object properties */ // Alias our game board var gameBoard = game.objs.board; /** * Main game board factory * * @returns {object} */ var getGameBoard = function() { var gameBoard = document.getElementById('game-board'); var width = gameBoard.width.baseVal.value; var height = gameBoard.height.baseVal.value; var border = 10; var area = (width - border) * (height - border); return { width: width, height: height, area: area } }; // Get game board gameBoard = getGameBoard();
/** * game-board.js * * Maintain game board object properties */ // Alias our game board var gameBoard = game.objs.board; /** * Main game board factory * * @returns {object} */ var getGameBoard = function() { var gameBoard = document.getElementById('game-board'); var width = gameBoard.width.baseVal.value; var height = gameBoard.height.baseVal.value; var border = 10; var area = (width - border) * (height - border); return { width: width, height: height, area: area, topBound: 0, rightBound: width - border, leftBound: 0, bottomBound: height - border } }; // Get game board gameBoard = getGameBoard();
Add boundaries to game board
Add boundaries to game board
JavaScript
mit
gabrielliwerant/SquareEatsSquare,gabrielliwerant/SquareEatsSquare
03653efc0acbf51875a78c3647d4ed6676052e1f
javascript/word-count/word-count.js
javascript/word-count/word-count.js
// super ugly but I'm tired var Words = function() {}; Words.prototype.count = function(input) { var wordArray = normalize(input.replace(/[\n\t]/g, ' ').trim()).split(' '); var result = {}; toLower(wordArray).forEach(function(item) { if (result[item] && Number.isInteger(result[item])) result[item] += 1; else result[item] = 1; }); function toLower(array) { console.log(array); for (var i = 0; i < array.length; i++) { array[i] = array[i].toLowerCase(); } console.log(array); return array; } function normalize(string) { console.log(string); console.log(string.replace(/\s+/g, ' ')); return string.replace(/\s+/g, ' '); } return result; } module.exports = Words;
// super ugly but I'm tired var Words = function() {}; Words.prototype.count = function(input) { var wordArray = normalize(input.replace(/[\n\t]/g, ' ').trim()).split(' '); var result = {}; toLower(wordArray).forEach(function(item) { if (result[item] && Number.isInteger(result[item])) result[item] += 1; else result[item] = 1; }); function toLower(array) { for (var i = 0; i < array.length; i++) { array[i] = array[i].toLowerCase(); } return array; } function normalize(string) { return string.replace(/\s+/g, ' '); } return result; } module.exports = Words;
Solve Word Count in JS
Solve Word Count in JS
JavaScript
mit
parkertm/exercism
109101b6d6fc7131a41f9f4ffd24305c1d5d1c09
tasks/development.js
tasks/development.js
module.exports = function (grunt) { grunt.config.merge({ connect: { server: { options: { base: { path: 'build', options: { index: 'index.html' } }, livereload: true } } }, watch: { sources: { options: { livereload: true }, files: ["*.css", "app.js", "lib/**/*.js", "*.html"], tasks: ["dev"] }, config: { options: { reload: true }, files: ["Gruntfile.js", "tasks/*.js"], tasks: [] } } }); grunt.loadNpmTasks("grunt-contrib-connect"); grunt.loadNpmTasks("grunt-contrib-watch"); };
module.exports = function (grunt) { grunt.config.merge({ connect: { server: { options: { base: { path: 'build', options: { index: 'index.html' } }, livereload: true } } }, watch: { sources: { options: { livereload: true }, files: ["*.css", "app.js", "helper.js", "lib/**/*.js", "*.html"], tasks: ["dev"] }, config: { options: { reload: true }, files: ["Gruntfile.js", "tasks/*.js"], tasks: [] } } }); grunt.loadNpmTasks("grunt-contrib-connect"); grunt.loadNpmTasks("grunt-contrib-watch"); };
Add helper.js to grunt watch
[TASK] Add helper.js to grunt watch
JavaScript
agpl-3.0
Freifunk-Troisdorf/meshviewer,FreifunkMD/Meshviewer,hopglass/ffrgb-meshviewer,Freifunk-Rhein-Neckar/meshviewer,rubo77/meshviewer-1,rubo77/meshviewer-1,Freifunk-Troisdorf/meshviewer,FreifunkBremen/meshviewer-ffrgb,freifunkMUC/meshviewer,Freifunk-Rhein-Neckar/meshviewer,xf-/meshviewer-1,FreifunkMD/Meshviewer,hopglass/ffrgb-meshviewer,Freifunk-Rhein-Neckar/meshviewer,ffrgb/meshviewer,FreifunkBremen/meshviewer-ffrgb,xf-/meshviewer-1,ffrgb/meshviewer,freifunkMUC/meshviewer