commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
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
--- +++ @@ -35,7 +35,7 @@ _.object = _.zipObject; } - self.mapParams = { center: { latitude: 51.48, longitude: -2.5879 }, zoom: 12 }; + self.mapParams = { center: { latitude: 51.48, longitude: -2.53 }, zoom: 12 }; });
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
--- +++ @@ -30,7 +30,8 @@ lein: 'Lein', compiler: 'Compiler', crystal: 'Crystal', - osx_image: 'Xcode' + osx_image: 'Xcode', + r: 'R' }; configKeys = {
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
--- +++ @@ -22,7 +22,7 @@ for (var i = 0, len = arr.length; i < len; i++) { var item = arr[i] - if (!obj[item]) { + if (obj[item] !== 1) { obj[item] = 1 ret.push(item) }
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
--- +++ @@ -16,19 +16,22 @@ const {google} = require('googleapis'); const sampleClient = require('../sampleclient'); -const plus = google.plus({ +const people = google.people({ version: 'v1', auth: sampleClient.oAuth2Client, }); async function runSample() { - const res = await plus.people.get({userId: 'me'}); + // 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/plus.login', - 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ];
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
--- +++ @@ -24,8 +24,8 @@ // 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.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.");
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
--- +++ @@ -3,7 +3,7 @@ var client = new stomp.Client("localhost", 61613); client.subscribe("/queue/news", function(data){ - console.log('received: ' + data.body); + console.log('received: ' + JSON.stringify(data)); }); client.publish('/queue/news','hello');
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
--- +++ @@ -26,10 +26,10 @@ render() { return ( <div className="controls-component"> - <button id="rewind">Rewind</button> + <button id="previous">Previous</button> {this.renderStopButton()} {this.renderPlayButton()} - <button id="forward">Forward</button> + <button id="next">Next</button> </div> ); } @@ -38,7 +38,11 @@ ControlsComponent.displayName = 'ControlsComponent'; ControlsComponent.propTypes = { - isPlaying : React.PropTypes.bool.isRequired + isPlaying : React.PropTypes.bool.isRequired, + onPrevious : React.PropTypes.func, + onStop : React.PropTypes.func, + onPlay : React.PropTypes.func, + onNext : React.PropTypes.func }; ControlsComponent.defaultProps = {
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
--- +++ @@ -26,9 +26,7 @@ // 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); + 0, 0, 0, 0, false, false, false, false, 0, null); // dispatch click event to simulate download a.dispatchEvent(clickEvent);
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
--- +++ @@ -1,15 +1,15 @@ var questions = [ Q1 = { - question: "What does HTML means?", - answer: "HyperText Markup Language" + question: "What does HTML means?", + answer: "HyperText Markup Language" }, Q2 = { - question: "What does CSS means?", - answer: "Cascading Style Sheet" + 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" + 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" } ]; @@ -19,10 +19,9 @@ // Generate random number to display random QA set function createNum() { - questionNum = Math.floor(Math.random() * 3); + questionNum = Math.floor(Math.random() * 3); } createNum(); question.innerHTML = questions[questionNum].question; -
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
--- +++ @@ -27,11 +27,10 @@ } 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]; + var msg = e && (e.toString() || e.frameTrace || e.stack); + if (msg) { + msg = msg.split("\n", 1)[0]; } if (!msg) { msg = errorInfo.messages.join("\n");
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
--- +++ @@ -13,12 +13,7 @@ var lines = data.split('\n'); var categories = ['groups', 'teachers', 'rooms', 'other']; - var container = categories.map(function (item) { - return { - name : item, - data : [] - } - }); + var container = {}; lines.forEach(function (line) { if(!line.length) return; @@ -26,16 +21,14 @@ var data = line.split('=')[1]; var items = data.split(';'); - container[items[2] - 1].data.push({ - code : items[0], - name : items[1] - }); + container[items[0]] = { + name : items[1], + category : categories[items[2] - 1] + }; }); - container.forEach(function (item) { - fs.writeFile(item.name + '.json', JSON.stringify(item.data, null, '\t'), function (err) { - if(err) console.log(err); - }); + fs.writeFile('components.json', JSON.stringify(container, null, '\t'), function (err) { + if(err) console.log(err); }); console.log('Files are processing');
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
--- +++ @@ -16,7 +16,6 @@ includeComments: true, sourceMaps: true, - // cacheMode: "localStorage", implicitBundleDest: "[setHash].js",
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
--- +++ @@ -1,4 +1,6 @@ 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_') +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_')
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
--- +++ @@ -3,7 +3,10 @@ * @description Pass in options for RequireJS like paths, shims or the baseUrl */ require.config({ - paths: { } + paths: { }, + + // Append a date on each requested script to prevent caching issues. + urlArgs: 'bust=' + (new Date()).getDate() });
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
--- +++ @@ -13,7 +13,7 @@ module: module, dest: definition.dest, entry: isEntryPt, - includeRuntime: !!definition.entry && !definition.excludeRuntime + includeRuntime: isEntryPt && !definition.excludeRuntime }; }, { resolveAsset, loadAst });
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
--- +++ @@ -4,14 +4,15 @@ module.exports = function(symbl, flags, opts) { return function *remove() { - if (!this[symbl].id) { + 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); - - // TODO: remove all related posts return result; };
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
--- +++ @@ -1,8 +1,10 @@ +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 (!(typeof show === 'function' && !show(inputValue))) { + if (!(isFunction(show) && !show(inputValue) && (!isFunction(orm.filter) || orm.filter(inputValue)))) { const list = data[key]; retVal = retVal.concat(list); } @@ -10,8 +12,10 @@ } else { Object.keys(data) .forEach((key) => { - const list = data[key]; - retVal = retVal.concat(list); + if (!isFunction(orm.filter) || orm.filter(inputValue)) { + const list = data[key]; + retVal = retVal.concat(list); + } }); } return retVal;
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
--- +++ @@ -5,14 +5,10 @@ exports.name = 'ect'; exports.outputFormat = 'html'; exports.compile = function(str, options) { - if (!options) { - options = {}; - } - if (!options.root) { - options.root = { - 'page': str - }; - } + options = options || {}; + options.root = options.root || {}; + options.root.page = str; + var engine = ect(options); return function(locals) { return engine.render('page', locals);
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
--- +++ @@ -9,8 +9,9 @@ blueprintsPath: function() { return path.join(__dirname, 'blueprints'); }, + treeForStyles: function() { - var bourbonPath = path.join(this.app.bowerDirectory, 'bourbon', 'app'); + var bourbonPath = path.join(this.project.bowerDirectory, 'bourbon', 'app'); var bourbonTree = new Funnel(this.treeGenerator(bourbonPath), { srcDir: '/assets/stylesheets', destDir: '/app/styles'
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
--- +++ @@ -31,7 +31,7 @@ }; window.onscroll = function() { - scrollbar.style.display = element.getBoundingClientRect().height + offset.top < window.scrollY + window.innerHeight ? "none" : "block"; + scrollbar.style.display = element.getBoundingClientRect().height + offset.top <= window.scrollY + window.innerHeight ? "none" : "block"; scrollbar.scrollLeft = element.scrollLeft; }; };
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
--- +++ @@ -16,9 +16,16 @@ // HTTP API-type URL handling. Router.map(function() { - // Provide a trivial front page, to avoid the Iron Router default. + // Redirect the front page to the Sandstorm wiki. this.route('root', { - path: '/' + 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', {
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
--- +++ @@ -6,13 +6,18 @@ 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/dir/:directory_id', validateProjectAccess, projects.dirTree); + + router.get('/projects2/:project_id/files/:file_id', validateProjectAccess, files.get); return router; };
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
--- +++ @@ -1,6 +1,8 @@ +import sortObjByOnlyKey from "./sortObjByOnlyKey"; + // Count duplicate keys within an array // ------------------------------------------------------------ -module.exports = function(array) { +const groupByDuplicatesInArray = array => { if(array.length === 0) { return null; } @@ -8,5 +10,7 @@ array.forEach(function(x) { counts[x] = (counts[x] || 0) + 1; }); - return counts; + return sortObjByOnlyKey(counts); }; + +export default groupByDuplicatesInArray;
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
--- +++ @@ -1 +1,8 @@ // 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; +}
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
--- +++ @@ -3,14 +3,14 @@ const buble = require('buble'); class BrunchBuble { - constructor({ plugins: { buble } }) { - this.config = buble || {}; + constructor(config) { + this.config = config && config.plugins && config.plugins.buble || {}; } - compile({ data }) { + compile(file) { try { - const { code } = buble.transform(data, this.config); - return Promise.resolve(code); + const transform = buble.transform(file.data, this.config); + return Promise.resolve(transform.code); } catch (error) { return Promise.reject(error); }
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
--- +++ @@ -13,7 +13,7 @@ } CurrencyFormatter.prototype.format = function (value, options) { - var currency = data.find(c => c.code === options.code) || this.defaultCurrency; + var currency = data.find(function(c) { return c.code === options.code; }) || this.defaultCurrency; var symbolOnLeft = currency.symbolOnLeft; var spaceBetweenAmountAndSymbol = currency.spaceBetweenAmountAndSymbol; @@ -39,7 +39,7 @@ } CurrencyFormatter.prototype.findCurrency = function (currencyCode) { - return data.find(c => c.code === currencyCode); + return data.find(function(c) { return c.code === currencyCode; }); } module.exports = new CurrencyFormatter();
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
--- +++ @@ -10,7 +10,8 @@ return through.obj( function(file, enc, done) { try { - var src = ts2dart.translateFile(file.path); + 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);
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
--- +++ @@ -2,7 +2,11 @@ console.log('loading electron-updater-sample-plugin...') function plugin(context) { - console.log('loaded electron-updater-sample-plugin!') + 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
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
--- +++ @@ -11,10 +11,9 @@ return boards.map(({url, title}) => { let boardID = url.split('/').slice(-2)[0] - console.log(boardID) return { boardID, - description: `${url} - ${title}` + description: `/${boardID}/ - ${title}` } }); }
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
--- +++ @@ -14,9 +14,8 @@ throw new Error('MongoDB connection URI missing in environment') } -mongoose.set('useFindAndModify', false) - mongoose.connect(dbUrl, { + useFindAndModify: false, useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true
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
--- +++ @@ -1,5 +1,6 @@ var config = require('./config'), rest = require('./rest'), + apiUrl = require('./apiUrl'), projects = require('./projects'); module.exports.init = function () { @@ -23,6 +24,7 @@ } return { + 'apiUrl': apiUrl, 'projects': projects.projects, 'project': projects.project };
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
--- +++ @@ -6,15 +6,22 @@ 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; } -process.on('exit', () => { - graphDb.close(); -}); - -module.exports = graphDb;
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
--- +++ @@ -5,7 +5,8 @@ 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( + console.log('node') + module.exports = factory( require('./lib/Dice'), require('./lib/inventory'), require('./lib/modifiers'), @@ -14,6 +15,7 @@ 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]; }));
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
--- +++ @@ -3,89 +3,3 @@ 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)); -}
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
--- +++ @@ -1,9 +1,12 @@ 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 + pack: Packer.pack, + unpack: Packer.unpack, + execute: Executor.execute };
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
--- +++ @@ -1,18 +1,39 @@ var Connection = require('../lib/tedious').Connection; var Request = require('../lib/tedious').Request; -var options = {}; +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('192.168.1.210', 'test', 'test', options, - function(err, loggedIn) { +var connection = new Connection(config); + +connection.on('connection', function(err) { // If no error, then good to go... - executeStatement() + executeStatement(); } -) +); + +connection.on('debug', function(text) { + //console.log(text); + } +); function executeStatement() { - request = new Request("select 42, 'hello world'", function(err, rowCount) { - console.log(rowCount + ' rows returned'); + request = new Request("select 42, 'hello world'", function(err) { + connection.close(); }); request.on('row', function(columns) { @@ -25,5 +46,9 @@ }); }); + request.on('done', function(rowCount, more) { + console.log(rowCount + ' rows returned'); + }); + connection.execSql(request); }
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
--- +++ @@ -6,9 +6,9 @@ // parseInt : Int -> String -> Result Decode.Value Int const parseInt = F2((radix, string) => { try { - // radix values integer from 2-36 + // NOTE radix can be any integer from 2-36 const value = global.parseInt(string, radix) - // TODO check for value === NaN and Err in that case + if (isNaN(value)) return Err(new Error(`String cannot be converted to an integer: ${string}`)) return Ok(value) } catch (error) { return Err(error) } })
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
--- +++ @@ -28,7 +28,7 @@ $$('.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[0].getAttribute('class')).toBe('ng-scope ng-admin-column-created_at'); expect(inputs[1].getAttribute('class')).toBe('ng-scope ng-admin-column-body'); }); });
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
--- +++ @@ -8,7 +8,7 @@ query = URI.parseQuery(uri.query()); if (!uri.hasQuery(param)) { - throw new Error(`Parameter "${param}" missing from URL`); + return null; } if (type == 'int') {
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
--- +++ @@ -4,12 +4,24 @@ 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' + date_created: '2015-06-19T17:21:58.000Z', + date_updated: '2015-06-23T06:41:58.000Z' }), - knex('projects').where('id', 2) - .update({ - published_id: 1 + 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 + }) + ); + }); };
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
--- +++ @@ -16,6 +16,6 @@ assert.ok(document.querySelector('paper-button').shadowRoot, 'paper-button has shadowRoot'); - assert.equal(this.$('paper-button').attr('role'), 'button', + assert.equal($('paper-button').attr('role'), 'button', 'role is attached to button immediately'); });
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
--- +++ @@ -3,8 +3,8 @@ * * @module turf/featurecollection * @category helper - * @param {Feature} features input Features - * @returns {FeatureCollection} a FeatureCollection of input features + * @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'}),
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
--- +++ @@ -13,8 +13,9 @@ 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); + id = getIdFromUrl(url, /\/watch\?v=([A-Z0-9_-]+)/i); return id ? ['youtube', id] : null; }
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
--- +++ @@ -1,15 +1,9 @@ function Message(queue, message, headers, deliveryInfo) { // Crane uses slash ('/') separators rather than period ('.') - this.queue = deliveryInfo.queue.replace(/\./g, '/'); + this.topic = deliveryInfo.routingKey.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(); }
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
--- +++ @@ -11,7 +11,7 @@ ampSpectrum:TestData.VALID_AMPLITUDE_SPECTRUM, }); - assert.equal(en, 0.1511072674115075); + assert.approximately(en, 0.1511072674115075, 1e-15); done(); });
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
--- +++ @@ -10,7 +10,11 @@ marked.setOptions({ highlight: function (code, lang) { - return hljs.highlight(lang, code).value; + if (lang) { + return hljs.highlight(lang, code).value; + } else { + return hljs.highlightAuto(code).value; + } } });
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
--- +++ @@ -9,7 +9,7 @@ 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 + process.env.CHECK_SYNTACTIC_ERRORS ); function run (cancellationToken) {
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
--- +++ @@ -4,6 +4,8 @@ sass.render({ file: 'sass/matter.sass', + indentedSyntax: true, + outputStyle: 'expanded', }, function (renderError, result) { if (renderError) { console.log(renderError);
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
--- +++ @@ -12,7 +12,9 @@ // 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
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
--- +++ @@ -12,8 +12,12 @@ function isNaNConstant(subject) { - // There is not Number.isNaN in Node 0.6.x - return ('number' === typeof subject) && isNaN(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); + } }
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
--- +++ @@ -27,6 +27,7 @@ this.onRequest('ping', function(_, message) { message.response = 'pong' }) + this.request('ping') } request(name, data = {}) {
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
--- +++ @@ -1,6 +1,5 @@ import ClickOutsideMixin from './mixin'; import Component from '@ember/component'; -import { on } from '@ember/object/evented'; import { next, cancel } from '@ember/runloop'; import $ from 'jquery'; @@ -22,12 +21,13 @@ } }, - _attachClickOutsideHandler: on('didInsertElement', function() { + didInsertElement() { + this._super(...arguments); this._cancelOutsideListenerSetup = next(this, this.addClickOutsideListener); - }), + }, - _removeClickOutsideHandler: on('willDestroyElement', function() { + willDestroyElement() { cancel(this._cancelOutsideListerSetup); this.removeClickOutsideListener(); - }) + } });
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
--- +++ @@ -4,7 +4,7 @@ return []; } return stringValue.split('~').map(s => { - const m = s.match(/range_(\-?[0-9.]+)\-(\-?[0-9.]+)/); + const m = s.match(/range\-(\-?[0-9.]+)_(\-?[0-9.]+)/); if (!m) { return { start: 0, end: 1000 }; } @@ -16,6 +16,6 @@ return arrayValue.map(({ start, end }) => { const startStr = (start / 1000).toFixed(4); const endStr = (end / 1000).toFixed(4); - return `range_${startStr}-${endStr}`; + return `range-${startStr}_${endStr}`; }).join('~'); }
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
--- +++ @@ -13,7 +13,10 @@ const SESSION = { secret: 'goodbirbs', - cookie: { secure: false }, + cookie: { + secure: false, + maxAge: (1000 * 60 * 60 * 2) // two hours + }, saveUninitialized: true, resave: true };
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
--- +++ @@ -15,7 +15,7 @@ $("#mastervolslider").slider({ animate: true, - min : 0.0, max : 1.5, range : 'true', value : 1.0, step : 0.05, + 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(); } });
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
--- +++ @@ -9,7 +9,7 @@ var stream = new CTM.Stream( event.data.data ); stream.offset = event.data.offsets[ i ]; - files[ i ] = new CTM.File( stream ); + files[ i ] = new CTM.File( stream, [event.data.data.buffer] ); }
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
--- +++ @@ -9,11 +9,11 @@ <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> + <script src="/static/lib.min.js" /> </Fragment> );
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
--- +++ @@ -1,3 +1,14 @@ +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'; @@ -20,23 +31,13 @@ '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); + copyToClipboard(tabs[0].title); }); 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); + copyToClipboard(tabs[0].url); }); }); });
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
--- +++ @@ -19,7 +19,6 @@ var containerController = require('./containerController'), createContainerController = require('./createContainerController'), - instanceController = require('./instanceController'), instanceDetailController = require('./instanceDetailController'), instanceModel = require('./instanceModel'), instanceService = require('./instanceService'); @@ -30,7 +29,6 @@ // register module components instances.controller('containerController', containerController); instances.controller('createContainerController', createContainerController); -instances.controller('instanceController', instanceController); instances.controller('instanceDetailController', instanceDetailController); instances.factory('instanceService', instanceService);
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
--- +++ @@ -3,7 +3,7 @@ // Load our requirements const i18n = require('i18n'), path = require('path'), - logger = require('../log'); + logger = require(__base + 'libs/log'); // Variables let localeDir = path.resolve(__base + '../locales'); @@ -12,6 +12,7 @@ i18n.configure({ locales: require('./available-locales')(localeDir), defaultLocale: 'en', + objectNotation: true, directory: localeDir, syncFiles: true, autoReload: true,
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
--- +++ @@ -2,24 +2,24 @@ * Factory object for XMLHttpRequest */ function Request(debug) { - var XMLHttpRequest; + var XHR; switch (true) { - case typeof global.Titanium.Network.createHTTPClient != 'undefined': - XMLHttpRequest = global.Titanium.Network.createHTTPClient(); + case typeof global.Titanium != 'undefined' && typeof global.Titanium.Network.createHTTPClient != 'undefined': + XHR = global.Titanium.Network.createHTTPClient(); break; // CommonJS require case typeof require != 'undefined': - XMLHttpRequest = new require("xhr").XMLHttpRequest(); + XHR = new require("xhr").XMLHttpRequest(); break; case typeof global.XMLHttpRequest != 'undefined': - XMLHttpRequest = new global.XMLHttpRequest(); + XHR = new global.XMLHttpRequest(); break; } - return XMLHttpRequest; + return XHR; }
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
--- +++ @@ -1,18 +1,22 @@ -import Rx from 'rx'; import Cycle from '@cycle/core'; -import CycleDOM from '@cycle/dom'; +import {makeDOMDriver, h} from '@cycle/dom'; -function main() { +function main(drivers) { return { - DOM: Rx.Observable.interval(1000) - .map(i => CycleDOM.h( - 'h1', '' + i + ' seconds elapsed' - )) + 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: CycleDOM.makeDOMDriver('#app') + DOM: makeDOMDriver('#app') }; Cycle.run(main, drivers);
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
--- +++ @@ -22,7 +22,12 @@ return { width: width, height: height, - area: area + area: area, + topBound: 0, + rightBound: width - border, + leftBound: 0, + bottomBound: height - border + } };
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
--- +++ @@ -13,17 +13,13 @@ }); 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, ' '); }
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
--- +++ @@ -18,7 +18,7 @@ options: { livereload: true }, - files: ["*.css", "app.js", "lib/**/*.js", "*.html"], + files: ["*.css", "app.js", "helper.js", "lib/**/*.js", "*.html"], tasks: ["dev"] }, config: {
b56d78047b8865e382810b750abc61db381160b9
tasks/spritesheet.js
tasks/spritesheet.js
module.exports = function(grunt) {"use strict"; var Builder = require('../').Builder; grunt.registerMultiTask("spritesheet", "Compile images to sprite sheet", function() { var helpers = require('grunt-lib-contrib').init(grunt); var options = helpers.options(this); var done = this.async() grunt.verbose.writeflags(options, "Options"); // TODO: ditch this when grunt v0.4 is released this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target); var srcFiles; var images; grunt.util.async.forEachSeries(this.files, function(file, callback) { var builder; var dir = ''; //grunt.task.expand( './..' ); srcFiles = grunt.file.expandFiles(file.src); for(var i = 0; i < srcFiles.length; i++) { srcFiles[i] = dir + srcFiles[i]; } options.images = srcFiles; options.outputDirectory = dir + file.dest; builder = Builder.fromGruntTask(options); builder.build(callback); }, done); }); };
module.exports = function(grunt) {"use strict"; var Builder = require('../').Builder; grunt.registerMultiTask("spritesheet", "Compile images to sprite sheet", function() { var helpers = require('grunt-lib-contrib').init(grunt); var options = helpers.options(this); var done = this.async() grunt.verbose.writeflags(options, "Options"); // TODO: ditch this when grunt v0.4 is released this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target); var srcFiles; var images; grunt.util.async.forEachSeries(this.files, function(file, callback) { var builder; var dir = ''; //grunt.task.expand( './..' ); srcFiles = grunt.file.expand(file.src); for(var i = 0; i < srcFiles.length; i++) { srcFiles[i] = dir + srcFiles[i]; } options.images = srcFiles; options.outputDirectory = dir + file.dest; builder = Builder.fromGruntTask(options); builder.build(callback); }, done); }); };
Move from `expandFiles` to grunt 0.4's `expand` This largely fixes 0.4 compatibility for me
Move from `expandFiles` to grunt 0.4's `expand` This largely fixes 0.4 compatibility for me
JavaScript
mit
richardbutler/node-spritesheet
--- +++ @@ -20,7 +20,7 @@ var dir = ''; //grunt.task.expand( './..' ); - srcFiles = grunt.file.expandFiles(file.src); + srcFiles = grunt.file.expand(file.src); for(var i = 0; i < srcFiles.length; i++) { srcFiles[i] = dir + srcFiles[i];
fb7d7d4b2a4c4015c9193064dcb41a44df70c312
client/templates/posts/posts_list.js
client/templates/posts/posts_list.js
var postsData = [ { title: 'Introducing Telescope', url: 'http://sachagreif.com/introducing-telescope/' }, { title: 'Meteor', url: 'http://meteor.com' }, { title: 'The Meteor Book', url: 'http://themeteorbook.com' } ]; Template.postsList.helpers({ posts: function() { return Posts.find(); } });
var postsData = [ { title: 'Introducing Telescope', url: 'http://sachagreif.com/introducing-telescope/' }, { title: 'Meteor', url: 'http://meteor.com' }, { title: 'The Meteor Book', url: 'http://themeteorbook.com' } ]; Template.postsList.helpers({ posts: function() { return Posts.find({}, {sort: {submitted: -1}}); } });
Sort posts by submitted timestamp
Sort posts by submitted timestamp
JavaScript
mit
valgalin/microscope,valgalin/microscope
--- +++ @@ -15,6 +15,6 @@ Template.postsList.helpers({ posts: function() { - return Posts.find(); + return Posts.find({}, {sort: {submitted: -1}}); } });
c6f398add9622d5dd84b8347a4f85fa98da6c5ad
spec/import-notebook-spec.js
spec/import-notebook-spec.js
"use babel"; // const { dialog } = require("electron").remote; const { existsSync } = require("fs"); import { _loadNotebook } from "../lib/import-notebook"; import { waitAsync } from "./helpers/test-utils"; describe("Import notebook", () => { const sampleNotebook = require.resolve("./helpers/test-notebook.ipynb"); beforeEach( waitAsync(async () => { await atom.packages.activatePackage("language-python"); await _loadNotebook(sampleNotebook); }) ); it("Should import a notebook and convert it to a script", () => { const editor = atom.workspace.getActiveTextEditor(); const code = editor.getText(); expect(code.split("\n")).toEqual([ "# %%", "import pandas as pd", "# %%", "pd.util.testing.makeDataFrame()", "# %%", "" ]); }); });
"use babel"; // const { dialog } = require("electron").remote; const { existsSync } = require("fs"); const { EOL } = require("os"); import { _loadNotebook } from "../lib/import-notebook"; import { waitAsync } from "./helpers/test-utils"; describe("Import notebook", () => { const sampleNotebook = require.resolve("./helpers/test-notebook.ipynb"); beforeEach( waitAsync(async () => { await atom.packages.activatePackage("language-python"); await _loadNotebook(sampleNotebook); }) ); it("Should import a notebook and convert it to a script", () => { const editor = atom.workspace.getActiveTextEditor(); const code = editor.getText(); expect(code.split(EOL)).toEqual([ "# %%", "import pandas as pd", "# %%", "pd.util.testing.makeDataFrame()", "# %%", "" ]); }); });
Use platform EOL for newlines
Use platform EOL for newlines - Fixes test for Windows
JavaScript
mit
nteract/hydrogen,nteract/hydrogen
--- +++ @@ -2,6 +2,7 @@ // const { dialog } = require("electron").remote; const { existsSync } = require("fs"); +const { EOL } = require("os"); import { _loadNotebook } from "../lib/import-notebook"; import { waitAsync } from "./helpers/test-utils"; @@ -17,7 +18,7 @@ it("Should import a notebook and convert it to a script", () => { const editor = atom.workspace.getActiveTextEditor(); const code = editor.getText(); - expect(code.split("\n")).toEqual([ + expect(code.split(EOL)).toEqual([ "# %%", "import pandas as pd", "# %%",
a7f2519f6b94ead24084978a611c8f799abf760b
lib/handlers/PostHandler.js
lib/handlers/PostHandler.js
'use strict'; const BaseHandler = require('./BaseHandler'); const ERRORS = require('../constants').ERRORS; const EVENT_ENDPOINT_CREATED = require('../constants').EVENT_ENDPOINT_CREATED; class PostHandler extends BaseHandler { /** * Create a file in the DataStore. * * @param {object} req http.incomingMessage * @param {object} res http.ServerResponse * @return {function} */ send(req, res) { return this.store.create(req) .then((File) => { const url = `http://${req.headers.host}${this.store.path}/${File.id}`; this.emit(EVENT_ENDPOINT_CREATED, { url }); return super.send(res, 201, { Location: url }); }) .catch((error) => { console.warn('[PostHandler]', error); const status_code = error.status_code || ERRORS.UNKNOWN_ERROR.status_code; const body = error.body || `${ERRORS.UNKNOWN_ERROR.body}${error.message || ''}\n`; return super.send(res, status_code, {}, body); }); } } module.exports = PostHandler;
'use strict'; const BaseHandler = require('./BaseHandler'); const ERRORS = require('../constants').ERRORS; const EVENT_ENDPOINT_CREATED = require('../constants').EVENT_ENDPOINT_CREATED; class PostHandler extends BaseHandler { /** * Create a file in the DataStore. * * @param {object} req http.incomingMessage * @param {object} res http.ServerResponse * @return {function} */ send(req, res) { return this.store.create(req) .then((File) => { const url = `//${req.headers.host}${this.store.path}/${File.id}`; this.emit(EVENT_ENDPOINT_CREATED, { url }); return super.send(res, 201, { Location: url }); }) .catch((error) => { console.warn('[PostHandler]', error); const status_code = error.status_code || ERRORS.UNKNOWN_ERROR.status_code; const body = error.body || `${ERRORS.UNKNOWN_ERROR.body}${error.message || ''}\n`; return super.send(res, status_code, {}, body); }); } } module.exports = PostHandler;
Remove HTTP as part of POST handler response
Remove HTTP as part of POST handler response
JavaScript
mit
tus/tus-node-server
--- +++ @@ -15,7 +15,7 @@ send(req, res) { return this.store.create(req) .then((File) => { - const url = `http://${req.headers.host}${this.store.path}/${File.id}`; + const url = `//${req.headers.host}${this.store.path}/${File.id}`; this.emit(EVENT_ENDPOINT_CREATED, { url }); return super.send(res, 201, { Location: url }); })
d22e1cc72041a3453f7a54bfb989ca71bd76c96a
webpack.config.client.production.js
webpack.config.client.production.js
const webpack = require('webpack') const path = require('path') const Dotenv = require('dotenv-webpack') const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin') const WebpackChunkHash = require('webpack-chunk-hash') module.exports = { entry: { client: './src/client' }, target: 'web', module: { rules: [{ test: /\.jsx?$/, use: 'babel-loader', include: [ path.join(__dirname, 'src') ] }] }, resolve: { extensions: ['.json', '.js', '.jsx'], alias: { api: path.resolve(__dirname, 'src/api/') } }, plugins: [ new webpack.HashedModuleIdsPlugin(), new webpack.NoEmitOnErrorsPlugin() new webpack.ProvidePlugin({ fetch: 'isomorphic-fetch' }), new Dotenv({ path: './.env', safe: false }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function include(module) { return module.context && module.context.indexOf('node_modules') !== -1 } }), new webpack.optimize.CommonsChunkPlugin({ name: 'client.manifest', }), new WebpackChunkHash(), new ChunkManifestPlugin({ filename: 'client.chunk-manifest.json', manifestVariable: 'webpackManifest' }) ], output: { path: path.join(__dirname, 'dist'), publicPath: 'dist/', filename: '[name].[chunkhash].js', chunkFilename: '[name].[chunkhash].js' } }
const webpack = require('webpack') const path = require('path') const Dotenv = require('dotenv-webpack') const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin') const WebpackChunkHash = require('webpack-chunk-hash') module.exports = { entry: { client: './src/client' }, target: 'web', module: { rules: [{ test: /\.jsx?$/, use: 'babel-loader', include: [ path.join(__dirname, 'src') ] }] }, resolve: { extensions: ['.json', '.js', '.jsx'], alias: { api: path.resolve(__dirname, 'src/api/') } }, plugins: [ new webpack.HashedModuleIdsPlugin(), new webpack.NoEmitOnErrorsPlugin(), new webpack.ProvidePlugin({ fetch: 'isomorphic-fetch' }), new Dotenv({ path: './.env', safe: false }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function include(module) { return module.context && module.context.indexOf('node_modules') !== -1 } }), new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', }), new WebpackChunkHash(), new ChunkManifestPlugin({ filename: 'chunk-manifest.json', manifestVariable: 'webpackManifest' }) ], output: { path: path.join(__dirname, 'dist'), publicPath: 'dist/', filename: '[name].[chunkhash].js', chunkFilename: '[name].[chunkhash].js' } }
Fix syntax error, rename manifest
Fix syntax error, rename manifest
JavaScript
mit
madeagency/reactivity
--- +++ @@ -26,7 +26,7 @@ }, plugins: [ new webpack.HashedModuleIdsPlugin(), - new webpack.NoEmitOnErrorsPlugin() + new webpack.NoEmitOnErrorsPlugin(), new webpack.ProvidePlugin({ fetch: 'isomorphic-fetch' }), @@ -41,11 +41,11 @@ } }), new webpack.optimize.CommonsChunkPlugin({ - name: 'client.manifest', + name: 'manifest', }), new WebpackChunkHash(), new ChunkManifestPlugin({ - filename: 'client.chunk-manifest.json', + filename: 'chunk-manifest.json', manifestVariable: 'webpackManifest' }) ],
b331d9b5cb1ce6122737a4b1136f0ae83449d282
lib/info-iframe-receiver.js
lib/info-iframe-receiver.js
'use strict'; var inherits = require('inherits') , EventEmitter = require('events').EventEmitter , JSON3 = require('json3') , XHRLocalObject = require('./transport/sender/xhr-local') , InfoAjax = require('./info-ajax') ; function InfoReceiverIframe(transUrl, baseUrl) { var self = this; EventEmitter.call(this); this.ir = new InfoAjax(baseUrl, XHRLocalObject); this.ir.once('finish', function(info, rtt) { self.ir = null; self.emit('message', JSON3.stringify([info, rtt])); }); } inherits(InfoReceiverIframe, EventEmitter); InfoReceiverIframe.transportName = 'iframe-info-receiver'; InfoReceiverIframe.prototype.close = function() { if (this.ir) { this.ir.close(); this.ir = null; } this.removeAllListeners(); }; module.exports = InfoReceiverIframe;
'use strict'; var inherits = require('inherits') , EventEmitter = require('events').EventEmitter , JSON3 = require('json3') , XHRLocalObject = require('./transport/sender/xhr-local') , InfoAjax = require('./info-ajax') ; function InfoReceiverIframe(transUrl) { var self = this; EventEmitter.call(this); this.ir = new InfoAjax(transUrl, XHRLocalObject); this.ir.once('finish', function(info, rtt) { self.ir = null; self.emit('message', JSON3.stringify([info, rtt])); }); } inherits(InfoReceiverIframe, EventEmitter); InfoReceiverIframe.transportName = 'iframe-info-receiver'; InfoReceiverIframe.prototype.close = function() { if (this.ir) { this.ir.close(); this.ir = null; } this.removeAllListeners(); }; module.exports = InfoReceiverIframe;
Fix iframe info receiver using wrong url
Fix iframe info receiver using wrong url
JavaScript
mit
modulexcite/sockjs-client,the1sky/sockjs-client,bulentv/sockjs-client,webmechanicx/sockjs-client,vkorehov/sockjs-client,jmptrader/sockjs-client,JohnKossa/sockjs-client,sockjs/sockjs-client,woosoobar/sockjs-client,bulentv/sockjs-client,jmptrader/sockjs-client,reergymerej/sockjs-client,arusakov/sockjs-client,modulexcite/sockjs-client,sockjs/sockjs-client,sockjs/sockjs-client,woosoobar/sockjs-client,JohnKossa/sockjs-client,the1sky/sockjs-client,webmechanicx/sockjs-client,reergymerej/sockjs-client,vkorehov/sockjs-client,arusakov/sockjs-client
--- +++ @@ -7,11 +7,11 @@ , InfoAjax = require('./info-ajax') ; -function InfoReceiverIframe(transUrl, baseUrl) { +function InfoReceiverIframe(transUrl) { var self = this; EventEmitter.call(this); - this.ir = new InfoAjax(baseUrl, XHRLocalObject); + this.ir = new InfoAjax(transUrl, XHRLocalObject); this.ir.once('finish', function(info, rtt) { self.ir = null; self.emit('message', JSON3.stringify([info, rtt]));
97f8f233846493d5809dd63155fe156acb635c43
lib/assets/javascripts/views/shared/create_account_form.js
lib/assets/javascripts/views/shared/create_account_form.js
import ariatiseForm from '../../utils/ariatiseForm'; import { togglisePasswords } from '../../utils/passwordHelper'; import validateOrgSelection from '../shared/my_org'; import { isValidText } from '../../utils/isValidInputType'; $(() => { const options = { selector: '#create-account-form' }; ariatiseForm(options); togglisePasswords(options); $('#create_account_form').on('submit', (e) => { // Additional validation to force the user to choose an org or type something for other if (validateOrgSelection()) { $('#help-org').hide(); } else { e.preventDefault(); $('#help-org').show(); } }); });
import ariatiseForm from '../../utils/ariatiseForm'; import { togglisePasswords } from '../../utils/passwordHelper'; import { validateOrgSelection } from '../shared/my_org'; $(() => { const options = { selector: '#create-account-form' }; ariatiseForm(options); togglisePasswords(options); $('#create_account_form').on('submit', (e) => { // Additional validation to force the user to choose an org or type something for other if (validateOrgSelection()) { $('#help-org').hide(); } else { e.preventDefault(); $('#help-org').show(); } }); });
Fix lint issues in JS
Fix lint issues in JS
JavaScript
mit
CDLUC3/dmptool,DigitalCurationCentre/roadmap,DMPRoadmap/roadmap,DigitalCurationCentre/roadmap,CDLUC3/dmptool,DigitalCurationCentre/roadmap,CDLUC3/dmptool,CDLUC3/roadmap,CDLUC3/roadmap,DMPRoadmap/roadmap,CDLUC3/roadmap,CDLUC3/dmptool,DMPRoadmap/roadmap,CDLUC3/roadmap
--- +++ @@ -1,7 +1,6 @@ import ariatiseForm from '../../utils/ariatiseForm'; import { togglisePasswords } from '../../utils/passwordHelper'; -import validateOrgSelection from '../shared/my_org'; -import { isValidText } from '../../utils/isValidInputType'; +import { validateOrgSelection } from '../shared/my_org'; $(() => { const options = { selector: '#create-account-form' };
9263492051ac911f429e9585afce5568fe2eb8ff
app/scripts/app.js
app/scripts/app.js
'use strict'; angular .module('visualizerApp', [ 'ngRoute', 'angularFileUpload', 'angularMoment', 'angularPeity' ]) .config(function ($routeProvider) { $routeProvider .when('/', { redirectTo: '/read/' }) .when('/read/', { templateUrl: 'views/read.html', controller: 'ReadController', activetab: 'read' }) .when('/display/', { templateUrl: 'views/display.html', controller: 'DisplayController', activetab: 'display' }) .otherwise({ redirectTo: '/' }); }); angular.module('visualizerApp') .filter('limitToFrom', function() { return function(arr, offset, limit) { if (!angular.isArray(arr)) return arr; var start = offset; var end = start + limit; start = Math.max(Math.min(start, arr.length), 0); end = Math.max(Math.min(end, arr.length), 0); return arr.slice(start, end); }; }); jQuery.fn.peity.defaults.pie = { diameter: 16, fill: ['#ff9900', '#ffd592', '#fff4dd'] };
'use strict'; angular .module('visualizerApp', [ 'ngRoute', 'angularFileUpload', 'angularMoment', 'angularPeity' ]) .config(function ($routeProvider) { $routeProvider .when('/', { redirectTo: '/read/' }) .when('/read/', { templateUrl: 'views/read.html', controller: 'ReadController', activetab: 'read' }) .when('/display/', { templateUrl: 'views/display.html', controller: 'DisplayController', activetab: 'display' }) .when('/display/:owner/:repo/', { templateUrl: 'views/display.html', controller: 'DisplayController', activetab: 'display' }) .otherwise({ redirectTo: '/' }); }); angular.module('visualizerApp') .filter('limitToFrom', function() { return function(arr, offset, limit) { if (!angular.isArray(arr)) return arr; var start = offset; var end = start + limit; start = Math.max(Math.min(start, arr.length), 0); end = Math.max(Math.min(end, arr.length), 0); return arr.slice(start, end); }; }); jQuery.fn.peity.defaults.pie = { diameter: 16, fill: ['#ff9900', '#ffd592', '#fff4dd'] };
Add routing for specified repos
Add routing for specified repos
JavaScript
mit
PRioritizer/PRioritizer-visualizer,PRioritizer/PRioritizer-visualizer
--- +++ @@ -18,6 +18,11 @@ activetab: 'read' }) .when('/display/', { + templateUrl: 'views/display.html', + controller: 'DisplayController', + activetab: 'display' + }) + .when('/display/:owner/:repo/', { templateUrl: 'views/display.html', controller: 'DisplayController', activetab: 'display'
21d3e05ce05ee3d0e8eb2237c43335d8e4d12d8d
samples/fortytwo_test.js
samples/fortytwo_test.js
define(['chai', 'mocha', 'samples/fortytwo'], function(chai, mocha, fortytwo) { 'use strict'; var expect = chai.expect; describe('fortytwo', function() { it('should return fortytwo', function() { expect(fortytwo.fortytwo()).to.equal(42); }); }); });
define(['chai', 'mocha', 'samples/fortytwo'], function(chai, unusedMocha, fortytwo) { 'use strict'; var expect = chai.expect; describe('fortytwo', function() { it('should return fortytwo', function() { expect(fortytwo.fortytwo()).to.equal(42); }); }); });
Align the variables slightly differently.
Align the variables slightly differently.
JavaScript
mit
solventz/js
--- +++ @@ -1,4 +1,9 @@ -define(['chai', 'mocha', 'samples/fortytwo'], function(chai, mocha, fortytwo) { +define(['chai', + 'mocha', + 'samples/fortytwo'], + function(chai, + unusedMocha, + fortytwo) { 'use strict'; var expect = chai.expect; describe('fortytwo', function() {
07d28940c615563b434c7a982bd89c8fc9356f15
lib/event_bus/in_memory/receiver.js
lib/event_bus/in_memory/receiver.js
var inherit = require("../../inherit"); var CommonEventBusReceiver = require("../common/receiver"); var InMemoryEventBus; inherit(InMemoryEventBusReceiver, CommonEventBusReceiver); function InMemoryEventBusReceiver(options) { CommonEventBusReceiver.call(this, options); InMemoryEventBus = InMemoryEventBus || require("../in_memory"); } InMemoryEventBusReceiver.prototype.start = function (callback) { var self = this; self.queue = InMemoryEventBus.registerQueue({ name: self.queueName, logger: self.logger }); self.queue.registerHandler(function (event, callback) { self._handleEvent(event, callback); }); callback(); }; module.exports = InMemoryEventBusReceiver;
var inherit = require("../../inherit"); var CommonEventBusReceiver = require("../common/receiver"); var InMemoryEventBus; inherit(InMemoryEventBusReceiver, CommonEventBusReceiver); function InMemoryEventBusReceiver(options) { CommonEventBusReceiver.call(this, options); InMemoryEventBus = InMemoryEventBus || require("../in_memory"); } InMemoryEventBusReceiver.prototype.initialize = function (callback) { callback(); }; InMemoryEventBusReceiver.prototype.start = function (callback) { var self = this; self.queue = InMemoryEventBus.registerQueue({ name: self.queueName, logger: self.logger }); self.queue.registerHandler(function (event, callback) { self._handleEvent(event, callback); }); callback(); }; module.exports = InMemoryEventBusReceiver;
Add intiialize method to InMemoryEventBusReceiver
Add intiialize method to InMemoryEventBusReceiver
JavaScript
mit
jbpros/plutonium
--- +++ @@ -8,6 +8,10 @@ CommonEventBusReceiver.call(this, options); InMemoryEventBus = InMemoryEventBus || require("../in_memory"); } + +InMemoryEventBusReceiver.prototype.initialize = function (callback) { + callback(); +}; InMemoryEventBusReceiver.prototype.start = function (callback) { var self = this;
412c8f46f99efeb830bc5683fb238c0fb9990f18
generators/app/templates/src/__tools-jest._jest.config.js
generators/app/templates/src/__tools-jest._jest.config.js
// https://github.com/thymikee/jest-preset-angular#brief-explanation-of-config module.exports = { preset: 'jest-preset-angular', roots: ['src'], coverageDirectory: 'reports', setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'], moduleNameMapper: { '@app/(.*)': '<rootDir>/src/app/$1', '@env': '<rootDir>/src/environments/environment' }, // Do not ignore librairies such as ionic, ionic-native or bootstrap to transform them during unit testing. <% var excludedLibrairies = ['jest-test']; if (props.target.includes('cordova')) { excludedLibrairies.push('@ionic-native'); } if (props.ui === 'ionic') { excludedLibrairies.push('@ionic'); } if (props.ui === 'bootstrap') { excludedLibrairies.push('@ng-bootstrap'); } -%> transformIgnorePatterns: ['node_modules/(?!(<%- excludedLibrairies.join('|') %>))'] };
// https://github.com/thymikee/jest-preset-angular#brief-explanation-of-config module.exports = { preset: 'jest-preset-angular', roots: ['src'], coverageDirectory: 'reports', setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'], moduleNameMapper: { '@app/(.*)': '<rootDir>/src/app/$1', '@env': '<rootDir>/src/environments/environment' }, // Do not ignore librairies such as ionic, ionic-native or bootstrap to transform them during unit testing. <% const excludedLibrairies = ['jest-test'] if (props.target.includes('cordova')) { excludedLibrairies.push('@ionic-native'); } if (props.ui === 'ionic') { excludedLibrairies.push('@ionic'); } if (props.ui === 'bootstrap') { excludedLibrairies.push('@ng-bootstrap'); } -%> transformIgnorePatterns: ['node_modules/(?!(<%- excludedLibrairies.join('|') %>))'] };
Include libraries for transformation with Jest
Include libraries for transformation with Jest
JavaScript
mit
angular-starter-kit/generator-ngx-app,angular-starter-kit/generator-ngx-app,ngx-rocket/generator-ngx-rocket,ngx-rocket/generator-ngx-rocket,ngx-rocket/generator-ngx-rocket,ngx-rocket/generator-ngx-rocket,angular-starter-kit/generator-ngx-app,angular-starter-kit/generator-ngx-app
--- +++ @@ -9,11 +9,9 @@ '@env': '<rootDir>/src/environments/environment' }, // Do not ignore librairies such as ionic, ionic-native or bootstrap to transform them during unit testing. -<% - var excludedLibrairies = ['jest-test']; +<% const excludedLibrairies = ['jest-test'] if (props.target.includes('cordova')) { excludedLibrairies.push('@ionic-native'); } if (props.ui === 'ionic') { excludedLibrairies.push('@ionic'); } - if (props.ui === 'bootstrap') { excludedLibrairies.push('@ng-bootstrap'); } --%> + if (props.ui === 'bootstrap') { excludedLibrairies.push('@ng-bootstrap'); } -%> transformIgnorePatterns: ['node_modules/(?!(<%- excludedLibrairies.join('|') %>))'] };
181d2ce8bcffc566f3a3be9d7fca412195ed65f9
client/views/settings/users/enroll/autoform.js
client/views/settings/users/enroll/autoform.js
AutoForm.addHooks('usersEnrollForm', { onError (formType, error) { // Show the error to end user // TODO: add internationalization support for specefic error type(s) FlashMessages.sendError(`${error.error}: ${error.reason}`, { autoHide: false }); } });
AutoForm.addHooks('usersEnrollForm', { onError (formType, error) { // Show the error to end user // TODO: add internationalization support for specefic error type(s) // Make sure there is an error type, otherwise don't show error // to prevent 'unknown' or undefined error messages from triggering flash message if (error.error) { FlashMessages.sendError(`${error.error}: ${error.reason}`, { autoHide: false }); } } });
Make sure error type exists before flash message
Make sure error type exists before flash message
JavaScript
agpl-3.0
GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing
--- +++ @@ -2,6 +2,11 @@ onError (formType, error) { // Show the error to end user // TODO: add internationalization support for specefic error type(s) - FlashMessages.sendError(`${error.error}: ${error.reason}`, { autoHide: false }); + + // Make sure there is an error type, otherwise don't show error + // to prevent 'unknown' or undefined error messages from triggering flash message + if (error.error) { + FlashMessages.sendError(`${error.error}: ${error.reason}`, { autoHide: false }); + } } });
e05609d5ec95f804daf0e403647b98483abc4fb5
extensions/markdown/media/loading.js
extensions/markdown/media/loading.js
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check 'use strict'; (function () { const unloadedStyles = []; const onStyleLoadError = (event) => { const source = event.target.dataset.source; unloadedStyles.push(source); }; window.addEventListener('DOMContentLoaded', () => { for (const link of document.getElementsByClassName('code-user-style')) { if (link.dataset.source) { link.onerror = onStyleLoadError; } } }) window.addEventListener('load', () => { if (!unloadedStyles.length) { return; } const args = [unloadedStyles]; window.parent.postMessage({ command: 'did-click-link', data: `command:_markdown.onPreviewStyleLoadError?${encodeURIComponent(JSON.stringify(args))}` }, '*'); }); }());
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check 'use strict'; (function () { const unloadedStyles = []; const onStyleLoadError = (event) => { const source = event.target.dataset.source; unloadedStyles.push(source); }; window.addEventListener('DOMContentLoaded', () => { for (const link of document.getElementsByClassName('code-user-style')) { if (link.dataset.source) { link.onerror = onStyleLoadError; } } }) window.addEventListener('load', () => { if (!unloadedStyles.length) { return; } window.parent.postMessage({ command: '_markdown.onPreviewStyleLoadError', args: [unloadedStyles] }, '*'); }); }());
Fix markdown style load error
Fix markdown style load error
JavaScript
mit
microlv/vscode,landonepps/vscode,eamodio/vscode,eamodio/vscode,0xmohit/vscode,the-ress/vscode,landonepps/vscode,joaomoreno/vscode,0xmohit/vscode,0xmohit/vscode,rishii7/vscode,eamodio/vscode,0xmohit/vscode,microlv/vscode,landonepps/vscode,Microsoft/vscode,0xmohit/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,microlv/vscode,the-ress/vscode,microlv/vscode,microlv/vscode,rishii7/vscode,cleidigh/vscode,microsoft/vscode,the-ress/vscode,DustinCampbell/vscode,cleidigh/vscode,Microsoft/vscode,joaomoreno/vscode,rishii7/vscode,rishii7/vscode,joaomoreno/vscode,rishii7/vscode,cleidigh/vscode,joaomoreno/vscode,eamodio/vscode,Microsoft/vscode,joaomoreno/vscode,eamodio/vscode,rishii7/vscode,hoovercj/vscode,0xmohit/vscode,the-ress/vscode,DustinCampbell/vscode,the-ress/vscode,microsoft/vscode,eamodio/vscode,microsoft/vscode,hoovercj/vscode,DustinCampbell/vscode,microsoft/vscode,joaomoreno/vscode,cleidigh/vscode,hoovercj/vscode,mjbvz/vscode,hoovercj/vscode,mjbvz/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,DustinCampbell/vscode,joaomoreno/vscode,DustinCampbell/vscode,DustinCampbell/vscode,rishii7/vscode,Microsoft/vscode,0xmohit/vscode,hoovercj/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,DustinCampbell/vscode,hoovercj/vscode,cleidigh/vscode,landonepps/vscode,rishii7/vscode,Microsoft/vscode,cleidigh/vscode,hoovercj/vscode,rishii7/vscode,cleidigh/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,mjbvz/vscode,cleidigh/vscode,the-ress/vscode,mjbvz/vscode,the-ress/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,cleidigh/vscode,hoovercj/vscode,the-ress/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,microlv/vscode,Krzysztof-Cieslak/vscode,DustinCampbell/vscode,Microsoft/vscode,eamodio/vscode,joaomoreno/vscode,the-ress/vscode,mjbvz/vscode,cleidigh/vscode,the-ress/vscode,cleidigh/vscode,mjbvz/vscode,0xmohit/vscode,DustinCampbell/vscode,eamodio/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,joaomoreno/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,the-ress/vscode,the-ress/vscode,microsoft/vscode,eamodio/vscode,rishii7/vscode,0xmohit/vscode,landonepps/vscode,DustinCampbell/vscode,Krzysztof-Cieslak/vscode,cleidigh/vscode,Microsoft/vscode,microlv/vscode,Microsoft/vscode,microlv/vscode,mjbvz/vscode,microlv/vscode,DustinCampbell/vscode,hoovercj/vscode,Krzysztof-Cieslak/vscode,mjbvz/vscode,hoovercj/vscode,joaomoreno/vscode,mjbvz/vscode,cleidigh/vscode,microsoft/vscode,the-ress/vscode,eamodio/vscode,microsoft/vscode,landonepps/vscode,joaomoreno/vscode,landonepps/vscode,DustinCampbell/vscode,eamodio/vscode,microsoft/vscode,eamodio/vscode,joaomoreno/vscode,0xmohit/vscode,landonepps/vscode,microsoft/vscode,rishii7/vscode,0xmohit/vscode,mjbvz/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,hoovercj/vscode,joaomoreno/vscode,landonepps/vscode,mjbvz/vscode,rishii7/vscode,microlv/vscode,landonepps/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,Microsoft/vscode,eamodio/vscode,Microsoft/vscode,microsoft/vscode,hoovercj/vscode,cleidigh/vscode,landonepps/vscode,mjbvz/vscode,hoovercj/vscode,microsoft/vscode,Krzysztof-Cieslak/vscode,microlv/vscode,DustinCampbell/vscode,mjbvz/vscode,microlv/vscode,rishii7/vscode,Krzysztof-Cieslak/vscode,landonepps/vscode,microlv/vscode,DustinCampbell/vscode,landonepps/vscode,the-ress/vscode,Microsoft/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,microsoft/vscode,eamodio/vscode,0xmohit/vscode,joaomoreno/vscode,eamodio/vscode,hoovercj/vscode,cleidigh/vscode,rishii7/vscode,the-ress/vscode,joaomoreno/vscode,cleidigh/vscode,DustinCampbell/vscode,eamodio/vscode,landonepps/vscode,Microsoft/vscode,eamodio/vscode,joaomoreno/vscode,0xmohit/vscode,Microsoft/vscode,Krzysztof-Cieslak/vscode,Microsoft/vscode,rishii7/vscode,0xmohit/vscode,joaomoreno/vscode,Microsoft/vscode,Microsoft/vscode,mjbvz/vscode,hoovercj/vscode,0xmohit/vscode,0xmohit/vscode,microsoft/vscode,mjbvz/vscode,landonepps/vscode,rishii7/vscode,the-ress/vscode,hoovercj/vscode,mjbvz/vscode,hoovercj/vscode,cleidigh/vscode,0xmohit/vscode,microsoft/vscode,rishii7/vscode
--- +++ @@ -27,10 +27,9 @@ if (!unloadedStyles.length) { return; } - const args = [unloadedStyles]; window.parent.postMessage({ - command: 'did-click-link', - data: `command:_markdown.onPreviewStyleLoadError?${encodeURIComponent(JSON.stringify(args))}` + command: '_markdown.onPreviewStyleLoadError', + args: [unloadedStyles] }, '*'); }); }());
4227a56fe23fdd3c43128c4e86df4e532cd24993
__tests__/end-to-end/e2e-constants.js
__tests__/end-to-end/e2e-constants.js
export const ENTER_UNICODE = '\u000d'; export const SIMPLE_TEST_TIMEOUT = 10 * 1000; const NIGHTMARE_ACTION_TIMEOUT = (process.env.CIRCLECI ? 4 : 2) * 1000; export const NIGHTMARE_CONFIG = { waitTimeout: NIGHTMARE_ACTION_TIMEOUT, gotoTimeout: NIGHTMARE_ACTION_TIMEOUT, loadTimeout: NIGHTMARE_ACTION_TIMEOUT, executionTimeout: NIGHTMARE_ACTION_TIMEOUT, // This one decides whether nightmarejs actually opens a window for the browser it tests in show: process.env.ELECTRON_SHOW_DISPLAY === '1', };
export const ENTER_UNICODE = '\u000d'; export const SIMPLE_TEST_TIMEOUT = 10 * 1000; const NIGHTMARE_ACTION_TIMEOUT = (process.env.CIRCLECI ? 6 : 2) * 1000; export const NIGHTMARE_CONFIG = { waitTimeout: NIGHTMARE_ACTION_TIMEOUT, gotoTimeout: NIGHTMARE_ACTION_TIMEOUT, loadTimeout: NIGHTMARE_ACTION_TIMEOUT, executionTimeout: NIGHTMARE_ACTION_TIMEOUT, // This one decides whether nightmarejs actually opens a window for the browser it tests in show: process.env.ELECTRON_SHOW_DISPLAY === '1', };
Increase nightmare action timeout on CI for e2e tests
Increase nightmare action timeout on CI for e2e tests
JavaScript
mit
thegazelle-ad/gazelle-front-end,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-server,thegazelle-ad/gazelle-front-end,thegazelle-ad/gazelle-server
--- +++ @@ -1,6 +1,6 @@ export const ENTER_UNICODE = '\u000d'; export const SIMPLE_TEST_TIMEOUT = 10 * 1000; -const NIGHTMARE_ACTION_TIMEOUT = (process.env.CIRCLECI ? 4 : 2) * 1000; +const NIGHTMARE_ACTION_TIMEOUT = (process.env.CIRCLECI ? 6 : 2) * 1000; export const NIGHTMARE_CONFIG = { waitTimeout: NIGHTMARE_ACTION_TIMEOUT, gotoTimeout: NIGHTMARE_ACTION_TIMEOUT,
007d247a719af3e9149a915a33034742efb98c0c
src/components/stream-app.js
src/components/stream-app.js
'use strict'; var React = require('react'); var io = require('socket.io-client'); var TwitterStreamList = require('./stream-list'); var TwitterStreamApp = React.createClass({ getInitialState: function() { return { tweets: [] }; }, componentDidMount: function() { var socket = io(); socket.on('tweet', function(tweet) { var tweets = this.state.tweets.slice(); tweets.unshift(tweet); this.setState({ tweets: tweets }); }.bind(this)); }, render: function() { return ( <div className="TwitterStream"> <TwitterStreamList data={this.state.tweets}/> </div> ); } }); module.exports = TwitterStreamApp;
'use strict'; var React = require('react'); var io = require('socket.io-client'); var TwitterStreamList = require('./stream-list'); var TwitterStreamApp = React.createClass({ getInitialState: function() { return { tweets: [] }; }, onTweetReceived: function(tweet) { var tweets = this.state.tweets.slice(); tweets.unshift(tweet); this.setState({ tweets: tweets }); }, componentDidMount: function() { this.socket = io(); this.socket.on('tweet', this.onTweetReceived); }, this.setState({ tweets: tweets }); }.bind(this)); }, render: function() { return ( <div className="TwitterStream"> <TwitterStreamList data={this.state.tweets}/> </div> ); } }); module.exports = TwitterStreamApp;
Move setState logic on new tweet to component method
Move setState logic on new tweet to component method
JavaScript
mit
bjarneo/TwitterStream,bjarneo/TwitterStream
--- +++ @@ -11,13 +11,17 @@ }; }, + onTweetReceived: function(tweet) { + var tweets = this.state.tweets.slice(); + tweets.unshift(tweet); + this.setState({ tweets: tweets }); + }, + componentDidMount: function() { - var socket = io(); + this.socket = io(); - socket.on('tweet', function(tweet) { - var tweets = this.state.tweets.slice(); - - tweets.unshift(tweet); + this.socket.on('tweet', this.onTweetReceived); + }, this.setState({ tweets: tweets }); }.bind(this));
0334e6c0138bfef3b11c400d3da58633c8697257
library/CM/Page/Abstract.js
library/CM/Page/Abstract.js
/** * @class CM_Page_Abstract * @extends CM_Component_Abstract */ var CM_Page_Abstract = CM_Component_Abstract.extend({ /** @type String */ _class: 'CM_Page_Abstract', /** @type String[] */ _stateParams: [], /** @type String|Null */ _fragment: null, _ready: function() { this._fragment = window.location.pathname + window.location.search; // @todo routeToState CM_Component_Abstract.prototype._ready.call(this); }, /** * @returns {String|Null} */ getFragment: function() { return this._fragment; }, /** * @returns {String[]} */ getStateParams: function() { return this._stateParams; }, /** * @param {Object} state * @param {String} fragment */ routeToState: function(state, fragment) { this._fragment = fragment; this._changeState(state); }, /** * @param {Object} state */ _changeState: function(state) { } });
/** * @class CM_Page_Abstract * @extends CM_Component_Abstract */ var CM_Page_Abstract = CM_Component_Abstract.extend({ /** @type String */ _class: 'CM_Page_Abstract', /** @type String[] */ _stateParams: [], /** @type String|Null */ _fragment: null, _ready: function() { var location = window.location; var params = queryString.parse(location.search); var state = _.pick(params, _.intersection(_.keys(params), this.getStateParams())); this.routeToState(state, location.pathname + location.search); CM_Component_Abstract.prototype._ready.call(this); }, /** * @returns {String|Null} */ getFragment: function() { return this._fragment; }, /** * @returns {String[]} */ getStateParams: function() { return this._stateParams; }, /** * @param {Object} state * @param {String} fragment */ routeToState: function(state, fragment) { this._fragment = fragment; this._changeState(state); }, /** * @param {Object} state */ _changeState: function(state) { } });
Call "routeToState" on page's ready()
Call "routeToState" on page's ready()
JavaScript
mit
vogdb/cm,cargomedia/CM,mariansollmann/CM,vogdb/cm,njam/CM,christopheschwyzer/CM,njam/CM,tomaszdurka/CM,tomaszdurka/CM,mariansollmann/CM,alexispeter/CM,njam/CM,fauvel/CM,njam/CM,fvovan/CM,alexispeter/CM,zazabe/cm,fvovan/CM,vogdb/cm,zazabe/cm,christopheschwyzer/CM,fauvel/CM,zazabe/cm,alexispeter/CM,njam/CM,mariansollmann/CM,zazabe/cm,tomaszdurka/CM,tomaszdurka/CM,fauvel/CM,mariansollmann/CM,christopheschwyzer/CM,vogdb/cm,vogdb/cm,cargomedia/CM,cargomedia/CM,fvovan/CM,fauvel/CM,fauvel/CM,fvovan/CM,alexispeter/CM,cargomedia/CM,tomaszdurka/CM,christopheschwyzer/CM
--- +++ @@ -14,8 +14,10 @@ _fragment: null, _ready: function() { - this._fragment = window.location.pathname + window.location.search; - // @todo routeToState + var location = window.location; + var params = queryString.parse(location.search); + var state = _.pick(params, _.intersection(_.keys(params), this.getStateParams())); + this.routeToState(state, location.pathname + location.search); CM_Component_Abstract.prototype._ready.call(this); },
d192bf8fcb996c5d4d0a86e6fab2e0c4fac3bc8a
src/functions/run.js
src/functions/run.js
'use strict' const { addGenErrorHandler } = require('../errors') const { getParams } = require('./params') const { stringifyConfigFunc } = require('./tokenize') // Process config function, i.e. fires it and returns its value const runConfigFunc = function ({ configFunc, mInput, mInput: { serverParams }, params, }) { // If this is not config function, returns as is if (typeof configFunc !== 'function') { return configFunc } const paramsA = getParams(mInput, { params, serverParams, mutable: false }) return configFunc(paramsA) } const eRunConfigFunc = addGenErrorHandler(runConfigFunc, { message: ({ configFunc }) => `Function failed: '${stringifyConfigFunc({ configFunc })}'`, reason: 'CONFIG_RUNTIME', }) module.exports = { runConfigFunc: eRunConfigFunc, }
'use strict' const { addGenPbHandler } = require('../errors') const { getParams } = require('./params') const { stringifyConfigFunc } = require('./tokenize') // Process config function, i.e. fires it and returns its value const runConfigFunc = function ({ configFunc, mInput, mInput: { serverParams }, params, }) { // If this is not config function, returns as is if (typeof configFunc !== 'function') { return configFunc } const paramsA = getParams(mInput, { params, serverParams, mutable: false }) return configFunc(paramsA) } const eRunConfigFunc = addGenPbHandler(runConfigFunc, { message: ({ configFunc }) => `Function failed: '${stringifyConfigFunc({ configFunc })}'`, reason: 'CONFIG_RUNTIME', extra: ({ configFunc }) => ({ value: stringifyConfigFunc({ configFunc }) }), }) module.exports = { runConfigFunc: eRunConfigFunc, }
Improve error handling of config functions
Improve error handling of config functions
JavaScript
apache-2.0
autoserver-org/autoserver,autoserver-org/autoserver
--- +++ @@ -1,6 +1,6 @@ 'use strict' -const { addGenErrorHandler } = require('../errors') +const { addGenPbHandler } = require('../errors') const { getParams } = require('./params') const { stringifyConfigFunc } = require('./tokenize') @@ -20,10 +20,11 @@ return configFunc(paramsA) } -const eRunConfigFunc = addGenErrorHandler(runConfigFunc, { +const eRunConfigFunc = addGenPbHandler(runConfigFunc, { message: ({ configFunc }) => `Function failed: '${stringifyConfigFunc({ configFunc })}'`, reason: 'CONFIG_RUNTIME', + extra: ({ configFunc }) => ({ value: stringifyConfigFunc({ configFunc }) }), }) module.exports = {
f04c6bf92ee6e09bb2fa0b1686bfdc5fc8c98ffd
lighthouse-inline-images.js
lighthouse-inline-images.js
// ==UserScript== // @name Lighthouse Inline Image Attachments // @namespace headinsky.dk // @description Show image attachments for Lighthouse tickets inline // @include https://*.lighthouseapp.com/* // @require http://code.jquery.com/jquery-latest.js // ==/UserScript== var width = $("div#main div.attachments").width(); $("ul.attachment-list li.aimg a").each(function() { img = document.createElement('img'); img.setAttribute('src', this.getAttribute('href')); img.setAttribute('style','max-width: ' + (width-45) + 'px;'); this.replaceChild(img, this.firstChild); });
// ==UserScript== // @name Lighthouse Inline Image Attachments // @namespace headinsky.dk // @description Show image attachments for Lighthouse tickets inline // @include https://*.lighthouseapp.com/* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js // ==/UserScript== var width = $("div#main div.attachments").width(); $("ul.attachment-list li.aimg a").each(function() { img = document.createElement('img'); img.setAttribute('src', this.getAttribute('href')); img.setAttribute('style','max-width: ' + (width-45) + 'px;'); this.replaceChild(img, this.firstChild); });
Use optimized jQuery from Google APIs
Use optimized jQuery from Google APIs
JavaScript
mit
kasperg/lighthouse-inline-images
--- +++ @@ -3,7 +3,7 @@ // @namespace headinsky.dk // @description Show image attachments for Lighthouse tickets inline // @include https://*.lighthouseapp.com/* -// @require http://code.jquery.com/jquery-latest.js +// @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js // ==/UserScript== var width = $("div#main div.attachments").width();
7eca0341a136b75907c58287a8d16f625be85e31
src/http/pdf-http.js
src/http/pdf-http.js
const ex = require('../util/express'); const pdfCore = require('../core/pdf-core'); const getRender = ex.createRoute((req, res) => { const opts = { // TODO: add all params here }; return pdfCore.render(req.query) .then((data) => { res.set('content-type', 'application/pdf'); res.send(data); }); }); const postRender = ex.createRoute((req, res) => { return pdfCore.render(req.body) .then((data) => { res.set('content-type', 'application/pdf'); res.send(data); }); }); module.exports = { getRender, postRender };
const ex = require('../util/express'); const pdfCore = require('../core/pdf-core'); const getRender = ex.createRoute((req, res) => { const opts = { url: req.query.url, scrollPage: req.query.scrollPage, emulateScreenMedia: req.query.emulateScreenMedia, waitFor: req.query.waitFor, viewport: { width: req.query['viewport.width'], height: req.query['viewport.height'], deviceScaleFactor: req.query['viewport.deviceScaleFactor'], isMobile: req.query['viewport.isMobile'], hasTouch: req.query['viewport.hasTouch'], isLandscape: req.query['viewport.isLandscape'], }, goto: { timeout: req.query['goto.timeout'], waitUntil: req.query['goto.waitUntil'], networkIdleInflight: req.query['goto.networkIdleInflight'], networkIdleTimeout: req.query['goto.networkIdleTimeout'], }, pdf: { scale: req.query['pdf.scale'], displayHeaderFooter: req.query['pdf.displayHeaderFooter'], landscape: req.query['pdf.landscape'], pageRanges: req.query['pdf.pageRanges'], format: req.query['pdf.format'], width: req.query['pdf.width'], height: req.query['pdf.height'], margin: { top: req.query['pdf.margin.top'], right: req.query['pdf.margin.right'], bottom: req.query['pdf.margin.bottom'], left: req.query['pdf.margin.left'], }, printBackground: req.query['pdf.printBackground'], }, }; return pdfCore.render(opts) .then((data) => { res.set('content-type', 'application/pdf'); res.send(data); }); }); const postRender = ex.createRoute((req, res) => { return pdfCore.render(req.body) .then((data) => { res.set('content-type', 'application/pdf'); res.send(data); }); }); module.exports = { getRender, postRender };
Implement parameters for GET request
Implement parameters for GET request
JavaScript
mit
alvarcarto/url-to-pdf-api,alvarcarto/url-to-pdf-api
--- +++ @@ -3,10 +3,43 @@ const getRender = ex.createRoute((req, res) => { const opts = { - // TODO: add all params here + url: req.query.url, + scrollPage: req.query.scrollPage, + emulateScreenMedia: req.query.emulateScreenMedia, + waitFor: req.query.waitFor, + viewport: { + width: req.query['viewport.width'], + height: req.query['viewport.height'], + deviceScaleFactor: req.query['viewport.deviceScaleFactor'], + isMobile: req.query['viewport.isMobile'], + hasTouch: req.query['viewport.hasTouch'], + isLandscape: req.query['viewport.isLandscape'], + }, + goto: { + timeout: req.query['goto.timeout'], + waitUntil: req.query['goto.waitUntil'], + networkIdleInflight: req.query['goto.networkIdleInflight'], + networkIdleTimeout: req.query['goto.networkIdleTimeout'], + }, + pdf: { + scale: req.query['pdf.scale'], + displayHeaderFooter: req.query['pdf.displayHeaderFooter'], + landscape: req.query['pdf.landscape'], + pageRanges: req.query['pdf.pageRanges'], + format: req.query['pdf.format'], + width: req.query['pdf.width'], + height: req.query['pdf.height'], + margin: { + top: req.query['pdf.margin.top'], + right: req.query['pdf.margin.right'], + bottom: req.query['pdf.margin.bottom'], + left: req.query['pdf.margin.left'], + }, + printBackground: req.query['pdf.printBackground'], + }, }; - return pdfCore.render(req.query) + return pdfCore.render(opts) .then((data) => { res.set('content-type', 'application/pdf'); res.send(data);
f016db1ff759c47e602e0aaa0984bfbcd694438b
src/main/webapp/components/BuildSnapshotContainer.js
src/main/webapp/components/BuildSnapshotContainer.js
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; import {Wrapper} from "./Wrapper"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { const SOURCE = '/data'; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE).then(res => setData(res.json())); }, []); return ( <Wrapper> {data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)} </Wrapper> ); } );
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; import {Wrapper} from "./Wrapper"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { const SOURCE = '/data'; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE).then(res => setData(res.json())); }, []); return ( <Wrapper> {data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)} </Wrapper> ); } );
Add space between comment summary and @see
Add space between comment summary and @see
JavaScript
apache-2.0
googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020
--- +++ @@ -16,6 +16,7 @@ * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. + * * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => {
85af498cbc8f3bad4fc8d15e0332fe46cdbf7d73
js/components/module-container.js
js/components/module-container.js
(function(app) { 'use strict'; var jCore = require('jcore'); var helper = app.helper || require('../helper.js'); var Module = app.Module || require('./module.js'); var ModuleContainer = helper.inherits(function(props) { ModuleContainer.super_.call(this); this.modules = this.prop([]); this.element = this.prop(props.element); this.deleter = ModuleContainer.prototype.deleter.bind(this); }, jCore.Component); ModuleContainer.prototype.loadModule = function(props) { props.deleter = this.deleter; var module = new Module(props); this.modules().push(module); module.parentElement(this.element()); module.redraw(); return module.loadComponent().then(function() { return module; }); }; ModuleContainer.prototype.deleter = function(module) { var modules = this.modules(); var index = modules.indexOf(module); if (index === -1) return; modules.splice(index, 1); }; if (typeof module !== 'undefined' && module.exports) module.exports = ModuleContainer; else app.ModuleContainer = ModuleContainer; })(this.app || (this.app = {}));
(function(app) { 'use strict'; var jCore = require('jcore'); var helper = app.helper || require('../helper.js'); var Module = app.Module || require('./module.js'); var ModuleContainer = helper.inherits(function(props) { ModuleContainer.super_.call(this); this.modules = this.prop([]); this.element = this.prop(props.element); this.deleter = ModuleContainer.prototype.deleter.bind(this); }, jCore.Component); ModuleContainer.prototype.loadModule = function(props) { props.deleter = this.deleter; var module = new Module(props); this.modules().push(module); module.parentElement(this.element()); module.redraw(); return module.loadComponent().then(function() { return module; }); }; ModuleContainer.prototype.toFront = function(module) { var modules = this.modules(); var index = modules.indexOf(module); if (index === -1) return; modules.splice(index, 1); modules.push(module); }; ModuleContainer.prototype.deleter = function(module) { var modules = this.modules(); var index = modules.indexOf(module); if (index === -1) return; modules.splice(index, 1); }; if (typeof module !== 'undefined' && module.exports) module.exports = ModuleContainer; else app.ModuleContainer = ModuleContainer; })(this.app || (this.app = {}));
Add method to move a module on top of others
Add method to move a module on top of others
JavaScript
mit
ionstage/modular,ionstage/modular
--- +++ @@ -25,6 +25,17 @@ }); }; + ModuleContainer.prototype.toFront = function(module) { + var modules = this.modules(); + var index = modules.indexOf(module); + + if (index === -1) + return; + + modules.splice(index, 1); + modules.push(module); + }; + ModuleContainer.prototype.deleter = function(module) { var modules = this.modules(); var index = modules.indexOf(module);
2bf536eb1d383b479c0df0477cde3bd5ceb76290
keyhole/static/keyhole/js/main.js
keyhole/static/keyhole/js/main.js
(function($) { function init_editor(e) { var editor = $(e); var selector = editor.data('selector'); editor.cropit({ imageState: { src: editor.data('original-image') } }); $("body").on('click', '#' + selector + '_btn', function(e) { e.preventDefault(); e.stopPropagation(); // Move cropped image data to hidden input var imageData = editor.cropit('export'); $('#' + selector).val(imageData); return false; }); } $(document).ready(function() { var editors = $('.image-editor'); $.each(editors, function(index, value) { init_editor(value); }); }); })(django.jQuery);
(function($) { function init_editor(e) { var editor = $(e); var selector = editor.data('selector'); editor.cropit({ imageState: { src: editor.data('original-image') } }); $("form[class*='form'").submit(function( event ) { // Move cropped image data to hidden input var imageData = editor.cropit('export'); $('#' + selector).val(imageData); }); } $(document).ready(function() { var editors = $('.image-editor'); $.each(editors, function(index, value) { init_editor(value); }); }); })(django.jQuery);
Save cropped image on submit and not by clicking on the button.
Save cropped image on submit and not by clicking on the button.
JavaScript
mit
BontaVlad/DjangoKeyhole,BontaVlad/DjangoKeyhole
--- +++ @@ -8,13 +8,10 @@ } }); - $("body").on('click', '#' + selector + '_btn', function(e) { - e.preventDefault(); - e.stopPropagation(); - // Move cropped image data to hidden input - var imageData = editor.cropit('export'); - $('#' + selector).val(imageData); - return false; + $("form[class*='form'").submit(function( event ) { + // Move cropped image data to hidden input + var imageData = editor.cropit('export'); + $('#' + selector).val(imageData); }); } @@ -26,4 +23,3 @@ }); })(django.jQuery); -
cf248f613e7334acc46629787c1134aadc07801d
src/reducers/root.js
src/reducers/root.js
import { LOAD_PAGE, LOAD_PAGE_REQUEST } from '../actions/constants' const initialState = { page: 1, photos: [], loading: true } export default function (state = initialState, action) { switch (action.type) { case LOAD_PAGE_REQUEST: return Object.assign({}, state, { loading: true }) case LOAD_PAGE: return Object.assign({}, state, { page: action.payload.page, photos: action.payload.photos, loading: false }) default: return state } }
import { LOAD_PAGE, LOAD_PAGE_REQUEST } from '../actions/constants' const initialState = { page: 1, photos: [], loading: true } export default function (state = initialState, action) { switch (action.type) { case LOAD_PAGE_REQUEST: return { ...state, loading: true } case LOAD_PAGE: return { ...state, page: action.payload.page, photos: action.payload.photos, loading: false } default: return state } }
Use object spread operator instead of Object.assign
Use object spread operator instead of Object.assign
JavaScript
mit
stackia/unsplash-trending,stackia/unsplash-trending
--- +++ @@ -9,16 +9,18 @@ export default function (state = initialState, action) { switch (action.type) { case LOAD_PAGE_REQUEST: - return Object.assign({}, state, { + return { + ...state, loading: true - }) + } case LOAD_PAGE: - return Object.assign({}, state, { + return { + ...state, page: action.payload.page, photos: action.payload.photos, loading: false - }) + } default: return state
2af6a80603f3b17106fb11a15b02636d18540fc3
src/shared/config.js
src/shared/config.js
import { InjectionToken } from 'yabf' import { LOG_LEVEL } from '../services' export const OPTION_PATH_FILE_TOKEN = new InjectionToken() export const APP_LOG_LEVEL_TOKEN = new InjectionToken() export const APP_LOG_LEVEL = LOG_LEVEL.ALL
import { InjectionToken } from 'yabf' import { LOG_LEVEL } from '../services' export const OPTION_PATH_FILE_TOKEN = new InjectionToken() export const APP_LOG_LEVEL_TOKEN = new InjectionToken() export const APP_LOG_LEVEL = LOG_LEVEL.ERROR
Set log level to ERROR
Set log level to ERROR
JavaScript
apache-2.0
Mindsers/configfile
--- +++ @@ -5,4 +5,4 @@ export const OPTION_PATH_FILE_TOKEN = new InjectionToken() export const APP_LOG_LEVEL_TOKEN = new InjectionToken() -export const APP_LOG_LEVEL = LOG_LEVEL.ALL +export const APP_LOG_LEVEL = LOG_LEVEL.ERROR
e2695a633c0fef9ef0402ba765f4e7322574f324
language-command.js
language-command.js
var _ = require('lodash'); var os = require('os'); var path = require('path'); var crypto = require('crypto'); var commands = require('./commands.json'); /** * Look up the command for executing a file in any language. * * @param {String} language * @param {String} file * @param {String} args * @return {String} */ module.exports = function (language, file, args) { // Unsupported language. if (!commands[language]) { return; } // Render the language using EJS to enable support for inline JavaScript. return _.template(commands[language], { file: file, tmpdir: os.tmpdir(), tmpfile: path.join(os.tmpdir(), crypto.randomBytes(32).toString('hex')), dirname: path.dirname, extname: path.extname, basename: path.basename, type: os.type(), arch: os.arch(), platform: os.platform(), sep: path.sep, join: path.join, delimiter: path.delimiter, args: args }); };
var _ = require('lodash'); var os = require('os'); var path = require('path'); var crypto = require('crypto'); var commands = require('./commands.json'); /** * Look up the command for executing a file in any language. * * @param {String} language * @param {String} file * @param {Array} args * @return {String} */ module.exports = function (language, file, args) { // Unsupported language. if (!commands[language]) { return; } // Render the language using EJS to enable support for inline JavaScript. return _.template(commands[language], { file: file, tmpdir: os.tmpdir(), tmpfile: path.join(os.tmpdir(), crypto.randomBytes(32).toString('hex')), dirname: path.dirname, extname: path.extname, basename: path.basename, type: os.type(), arch: os.arch(), platform: os.platform(), sep: path.sep, join: path.join, delimiter: path.delimiter, args: Array.isArray(args) ? args.map(JSON.stringify).join(' ') : args }); };
Support an array of arguments.
Support an array of arguments.
JavaScript
mit
blakeembrey/node-language-command
--- +++ @@ -9,7 +9,7 @@ * * @param {String} language * @param {String} file - * @param {String} args + * @param {Array} args * @return {String} */ module.exports = function (language, file, args) { @@ -32,6 +32,6 @@ sep: path.sep, join: path.join, delimiter: path.delimiter, - args: args + args: Array.isArray(args) ? args.map(JSON.stringify).join(' ') : args }); };
65b836b5c005faba6335ce65cc31a95e0d74251d
app/assets/javascripts/map-overlay.js
app/assets/javascripts/map-overlay.js
(function($) { if (!$.cookie('first_time_visitor')) { $.cookie('first_time_visitor', true, { expires: 1000, path: '/' }); var $overlayWrapper = $('.overlay-wrapper'); $overlayWrapper.show(); setTimeout(function() { $overlayWrapper.addClass('in'); }, 0); $overlayWrapper.find('.close-btn, .go').click(function () { if ($.support.transition.end) { $overlayWrapper.one($.support.transition.end, function() { $overlayWrapper.hide(); }); } $overlayWrapper.removeClass('in'); }); } })(jQuery);
(function($) { if (!$.cookie('first_time_visitor')) { $.cookie('first_time_visitor', true, { expires: 1000, path: '/' }); var $overlayWrapper = $('.overlay-wrapper'); $overlayWrapper.show(); setTimeout(function() { $overlayWrapper.addClass('in'); }, 0); $overlayWrapper.find('.close-btn, .go').click(function () { if ($.support.transition && $.support.transition.end) { $overlayWrapper.one($.support.transition.end, function() { $overlayWrapper.hide(); }); } $overlayWrapper.removeClass('in'); }); } })(jQuery);
Fix missing transition variable in map overlay.
Fix missing transition variable in map overlay.
JavaScript
agpl-3.0
sozialhelden/wheelmap,sozialhelden/wheelmap,sozialhelden/wheelmap,sozialhelden/wheelmap,sozialhelden/wheelmap
--- +++ @@ -12,7 +12,7 @@ }, 0); $overlayWrapper.find('.close-btn, .go').click(function () { - if ($.support.transition.end) { + if ($.support.transition && $.support.transition.end) { $overlayWrapper.one($.support.transition.end, function() { $overlayWrapper.hide(); });
5b288f095f8b7ed76a9f8331f1c330119e8d9786
feeds.js
feeds.js
"use strict"; var BlogController = require('./controllers/blog'); var BloggerController = require('./controllers/blogger'); var RSS = require('rss'); exports.serveRoutes = function(router) { router.get('/main', function(req, res) { var mainFeed = new RSS({ title: "CS Blogs Main Feed", description: "All of the blog posts from bloggers on CSBlogs.com", feed_url: "http://feeds.csblogs.com/main", site_url: "http://csblogs.com", }); BlogController.getAllBlogs({}, function(blogs, error) { blogs.forEach(function(blog) { mainFeed.item({ title: blog.title, description: blog.summary, url: blog.link, guid: blog.link, author: "CS Blogs User", date: blog.pubDate }); }); }); res.header('Content-Type','application/rss+xml'); res.send(mainFeed.xml({indent: true})); }); };
"use strict"; var BlogController = require('./controllers/blog'); var BloggerController = require('./controllers/blogger'); var RSS = require('rss'); exports.serveRoutes = function(router) { router.get('/main', function(req, res) { var mainFeed = new RSS({ title: "CS Blogs Main Feed", description: "All of the blog posts from bloggers on CSBlogs.com", feed_url: "http://feeds.csblogs.com/main", site_url: "http://csblogs.com", }); BlogController.getAllBlogs({}, function(blogs, error) { blogs.forEach(function(blog) { mainFeed.item({ title: blog.title, description: blog.summary, url: blog.link, guid: blog.link, author: "CS Blogs User", date: blog.pubDate }); }); res.header('Content-Type','application/rss+xml'); res.send(mainFeed.xml({indent: true})); }); }); };
Fix for sending XML before async call returns
Fix for sending XML before async call returns
JavaScript
mit
robcrocombe/csblogs,csblogs/csblogs-web-app,csblogs/csblogs-web-app
--- +++ @@ -24,9 +24,9 @@ date: blog.pubDate }); }); + + res.header('Content-Type','application/rss+xml'); + res.send(mainFeed.xml({indent: true})); }); - - res.header('Content-Type','application/rss+xml'); - res.send(mainFeed.xml({indent: true})); }); };
b06898cf54a898a03817599f46c074e2c8901c73
lib/capabilities.js
lib/capabilities.js
import Oasis from "oasis"; import { services } from "conductor/services"; import { copy } from "conductor/lang"; import { a_indexOf } from "oasis/shims"; function ConductorCapabilities() { this.capabilities = [ 'xhr', 'metadata', 'render', 'data', 'lifecycle', 'height', 'nestedWiretapping' ]; this.services = copy(services); } ConductorCapabilities.prototype = { defaultCapabilities: function () { return this.capabilities; }, defaultServices: function () { return this.services; }, addDefaultCapability: function (capability, service) { if (!service) { service = Oasis.Service; } this.capabilities.push(capability); this.services[capability] = service; }, removeDefaultCapability: function (capability) { var index = a_indexOf.call(this.capabilities, capability); if (index) { return this.capabilities.splice(index, 1); } } }; export default ConductorCapabilities;
import Oasis from "oasis"; import { services } from "conductor/services"; import { copy } from "conductor/lang"; import { a_indexOf } from "oasis/shims"; function ConductorCapabilities() { this.capabilities = [ 'xhr', 'metadata', 'render', 'data', 'lifecycle', 'height', 'nestedWiretapping' ]; this.services = copy(services); } ConductorCapabilities.prototype = { defaultCapabilities: function () { return this.capabilities; }, defaultServices: function () { return this.services; }, addDefaultCapability: function (capability, service) { if (!service) { service = Oasis.Service; } this.capabilities.push(capability); this.services[capability] = service; }, removeDefaultCapability: function (capability) { var index = a_indexOf.call(this.capabilities, capability); if (index !== -1) { return this.capabilities.splice(index, 1); } } }; export default ConductorCapabilities;
Fix index check in `removeDefaultCapability`.
Fix index check in `removeDefaultCapability`.
JavaScript
mit
tildeio/conductor.js
--- +++ @@ -27,7 +27,7 @@ removeDefaultCapability: function (capability) { var index = a_indexOf.call(this.capabilities, capability); - if (index) { + if (index !== -1) { return this.capabilities.splice(index, 1); } }
5caf144cad6ef3362ebf15afb112cc8e62a142f5
Resources/Private/Javascripts/Modules/Module.js
Resources/Private/Javascripts/Modules/Module.js
/** * Defines a dummy module * * @module Modules/Module */ var App; /** * App * @param el * @constructor */ App = function(el) { 'use strict'; this.el = el; }; /** * Function used to to render the App * * @memberof module:Modules/Module * @returns {Object} the App itself. */ App.prototype.render = function() { 'use strict'; // Return false if not 'el' was set in the app. if(!this.el) { return false; } this.el.innerHTML = 'App is rendered properly!'; }; module.exports = App;
/** * Defines a dummy module * * @module Modules/Module */ var App; /** * App * @param el * @constructor */ App = function(el) { 'use strict'; this.el = el; }; /** * Function used to to render the App * * @memberof module:Modules/Module * @returns {Object} The App itself. */ App.prototype.render = function() { 'use strict'; // Return false if not 'el' was set in the app. if(!this.el) { return false; } this.el.innerHTML = 'App is rendered properly!'; return this; }; module.exports = App;
Make sure the example App modules render method returns the module
[TASK] Make sure the example App modules render method returns the module
JavaScript
mit
t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template
--- +++ @@ -21,7 +21,7 @@ * Function used to to render the App * * @memberof module:Modules/Module - * @returns {Object} the App itself. + * @returns {Object} The App itself. */ App.prototype.render = function() { 'use strict'; @@ -32,6 +32,8 @@ } this.el.innerHTML = 'App is rendered properly!'; + + return this; }; module.exports = App;
53374261765f24b58db7bc71337d9f7eb7900433
lib/cli/index.js
lib/cli/index.js
'use strict'; var path = require('path'); var program = require('commander'); var jsdoctest = require('../..'); var packageJson = require('../../package.json'); /** * The main command-line utility's entry point. * * @param {Array.<String>} The `process.argv` array. */ exports.run = function(argv) { program .usage('[FILES...]') .version(packageJson.version); program.parse(argv); if(program.args.length === 0) { program.displayUsage(); process.exit(1); } // Base test running case for(var i = 0, len = program.args.length; i < len; i++) { var fileName = program.args[i]; var failed = jsdoctest.run(path.join(process.cwd(), fileName)); if(failed) { exports._fail(new Error('Tests failed')); } else { console.log('Tests passed'); } } }; /** * Prints an error to stderr and exits. */ exports._fail = function fail(err) { console.error(err.message); process.exit(err.code || 1); };
'use strict'; var path = require('path'); var program = require('commander'); var jsdoctest = require('../..'); var packageJson = require('../../package.json'); /** * The main command-line utility's entry point. * * @param {Array.<String>} The `process.argv` array. */ exports.run = function(argv) { program .usage('[FILES...]') .version(packageJson.version); program.parse(argv); if(program.args.length === 0) { program.help(); } // Base test running case for(var i = 0, len = program.args.length; i < len; i++) { var fileName = program.args[i]; var failed = jsdoctest.run(path.join(process.cwd(), fileName)); if(failed) { exports._fail(new Error('Tests failed')); } else { console.log('Tests passed'); } } }; /** * Prints an error to stderr and exits. */ exports._fail = function fail(err) { console.error(err.message); process.exit(err.code || 1); };
Fix help message on wrong calls
Fix help message on wrong calls This fixes the display of usage information when the program is called without arguments.
JavaScript
mit
yamadapc/jsdoctest,yamadapc/jsdoctest
--- +++ @@ -19,8 +19,7 @@ program.parse(argv); if(program.args.length === 0) { - program.displayUsage(); - process.exit(1); + program.help(); } // Base test running case
1a149064f53560e72c3ff763683011e29e67604c
www/js/keyManager.js
www/js/keyManager.js
function displayKeys() { // Retrieve all keyPairs var sql = "select K.name from key K"; dbRetrieve(sql, [], function(res) { // Populate key list var html = '<hr>'; for (var i = 0; i < res.rows.length; ++i) { var keyName = res.rows.item(i).name; html += '<span onclick="showPubKey($(this).text());">' + keyName + '</span><br/><hr>'; } // Update GUI document.getElementById("key_list").innerHTML = html; }); } function showPubKey(keyName) { // Retrieve all keyPairs var sql = "select K.keyPair from key K where K.name = ?"; dbRetrieve(sql, [keyName.toString()], function(res) { if (res.rows.length === 1) { // Extract public key and create qr-code var key = buf2hex(cryptoJS.publicKey(hex2buf(res.rows.item(0).keyPair))); alert(key); cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, key, function (success) { alert('succes'); alert("Encode succes: " + success); }, function (fail) { alert('fail'); alert("Encoding failed: " + fail); } ); } }); }
function displayKeys() { // Retrieve all keyPairs var sql = "select K.name from key K"; dbRetrieve(sql, [], function(res) { // Populate key list var html = '<hr>'; for (var i = 0; i < 1; ++i) { var keyName = res.rows.item(i).name; html += '<button onclick="showPubKey(this.innerHTML);">' + keyName + '</button>'; } // Update GUI document.getElementById("key_list").innerHTML = html; }); } function showPubKey(keyName) { // Retrieve all keyPairs var sql = "select K.keyPair from key K where K.name = ?"; dbRetrieve(sql, [keyName.toString()], function(res) { if (res.rows.length === 1) { // Extract public key and create qr-code var key = buf2hex(cryptoJS.publicKey(hex2buf(res.rows.item(0).keyPair))); alert(key); cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, key, function (success) { alert('succes'); alert("Encode succes: " + success); }, function (fail) { alert('fail'); alert("Encoding failed: " + fail); } ); } }); }
Print key on click (try 5 - button)
Print key on click (try 5 - button)
JavaScript
agpl-3.0
lromerio/cothority-mobile,lromerio/cothority-mobile
--- +++ @@ -7,9 +7,9 @@ // Populate key list var html = '<hr>'; - for (var i = 0; i < res.rows.length; ++i) { + for (var i = 0; i < 1; ++i) { var keyName = res.rows.item(i).name; - html += '<span onclick="showPubKey($(this).text());">' + keyName + '</span><br/><hr>'; + html += '<button onclick="showPubKey(this.innerHTML);">' + keyName + '</button>'; } // Update GUI
7cf7979e06f0774f46d133e070887cb29957c9d5
index.js
index.js
"use strict"; // modified from https://github.com/es-shims/es6-shim var keys = Object.keys || require('object-keys'); var assignShim = function assign(target, source) { return keys(source).reduce(function (target, key) { target[key] = source[key]; return target; }, target); }; assignShim.shim = function shimObjectAssign() { if (!Object.assign) { Object.assign = assignShim; } return Object.assign || assignShim; }; module.exports = assignShim;
"use strict"; // modified from https://github.com/es-shims/es6-shim var keys = Object.keys || require('object-keys'); var assignShim = function assign(target, source) { var props = keys(source); for (var i = 0; i < props.length; ++i) { target[props[i]] = source[props[i]]; } return target; }; assignShim.shim = function shimObjectAssign() { if (!Object.assign) { Object.assign = assignShim; } return Object.assign || assignShim; }; module.exports = assignShim;
Use a for loop, because ES3 browsers don't have "reduce"
Use a for loop, because ES3 browsers don't have "reduce"
JavaScript
mit
ljharb/object.assign,es-shims/object.assign,reggi/object.assign
--- +++ @@ -4,10 +4,11 @@ var keys = Object.keys || require('object-keys'); var assignShim = function assign(target, source) { - return keys(source).reduce(function (target, key) { - target[key] = source[key]; - return target; - }, target); + var props = keys(source); + for (var i = 0; i < props.length; ++i) { + target[props[i]] = source[props[i]]; + } + return target; }; assignShim.shim = function shimObjectAssign() {
c72a5d2988107208b2a344df2b55656f81ca545d
index.js
index.js
'use strict'; var mote = require('mote'); exports.name = 'mote'; exports.outputFormat = 'html'; exports.compile = function (str, options) { return mote.compile(str); };
'use strict'; var mote = require('mote'); exports.name = 'mote'; exports.outputFormat = 'html'; exports.compile = mote.compile;
Make compile use mote's compile
refactor(~): Make compile use mote's compile
JavaScript
mit
jstransformers/jstransformer-mote
--- +++ @@ -5,6 +5,4 @@ exports.name = 'mote'; exports.outputFormat = 'html'; -exports.compile = function (str, options) { - return mote.compile(str); -}; +exports.compile = mote.compile;
73d5d2b89ef60ffc1035e2a3787ae86c5f360725
index.js
index.js
/** * Copyright (c) 2016, Christopher Ramírez * All rights reserved. * * This source code is licensed under the MIT license. */ 'use strict' const validIdNumberRegExp = /^(\d{3})[ -]?(\d{6})[ -]?(\d{4}\S{1})$/ class NicaraguanId { constructor(number) { this.fullName = undefined this.birthPlace = undefined this.birthDate = undefined this.validSince = undefined this.validThrough = undefined this.setNewNumber(number) } checkNumber(number) { if (!validIdNumberRegExp.test(number)) { throw `${number} is an invalid nicaraguan ID number.` } } setNewNumber(number) { this.checkNumber(number) let [_, cityId, birthDigits, consecutive] = validIdNumberRegExp.exec(number) this.number = number this.cityId = cityId this.birthDigits = birthDigits this.consecutive = consecutive this.birthDate = dateFromSixIntDigits(this.birthDigits) } } function dateFromSixIntDigits(sixIntDigits) { const dateFormat = /^(\d{2})(\d{2})(\d{2})$/ let [_, day, month, year] = dateFormat.exec(this.birthDigits) return new Date(parseInt(year), parseInt(month) -1, parseInt(day)) } module.exports.NicaraguanId = NicaraguanId
/** * Copyright (c) 2016, Christopher Ramírez * All rights reserved. * * This source code is licensed under the MIT license. */ 'use strict' const validIdNumberRegExp = /^(\d{3})[ -]?(\d{6})[ -]?(\d{4}\S{1})$/ class NicaraguanId { constructor(number) { this.fullName = undefined this.birthPlace = undefined this.birthDate = undefined this.validSince = undefined this.validThrough = undefined this.setNewNumber(number) } setNewNumber(number) { this.checkNumber(number) let [_, cityId, birthDigits, consecutive] = validIdNumberRegExp.exec(number) this.number = number this.cityId = cityId this.birthDigits = birthDigits this.consecutive = consecutive this.birthDate = dateFromSixIntDigits(this.birthDigits) } checkNumber(number) { if (!validIdNumberRegExp.test(number)) { throw `${number} is an invalid nicaraguan ID number.` } } } function dateFromSixIntDigits(sixIntDigits) { const dateFormat = /^(\d{2})(\d{2})(\d{2})$/ let [_, day, month, year] = dateFormat.exec(this.birthDigits) return new Date(parseInt(year), parseInt(month) -1, parseInt(day)) } module.exports.NicaraguanId = NicaraguanId
Move checkNumber function to the buttom of class implementation.
Move checkNumber function to the buttom of class implementation.
JavaScript
mit
christopher-ramirez/nic-id
--- +++ @@ -19,12 +19,6 @@ this.setNewNumber(number) } - checkNumber(number) { - if (!validIdNumberRegExp.test(number)) { - throw `${number} is an invalid nicaraguan ID number.` - } - } - setNewNumber(number) { this.checkNumber(number) @@ -35,6 +29,12 @@ this.consecutive = consecutive this.birthDate = dateFromSixIntDigits(this.birthDigits) } + + checkNumber(number) { + if (!validIdNumberRegExp.test(number)) { + throw `${number} is an invalid nicaraguan ID number.` + } + } } function dateFromSixIntDigits(sixIntDigits) {
a16f274a861655f73ad07adff88196540aacd698
emoji.js
emoji.js
Emoji = {}; Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/'; Emoji.convert = function (str) { if (typeof str !== 'string') { return ''; } return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) { var imgName = match.slice(1, -1), path = Emoji.baseImagePath + imgName + '.png'; return '<img class="emoji" alt="' + match + '" src="' + path + '"/>'; }); }; // borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js if (Package.templating) { var Template = Package.templating.Template; var Blaze = Package.blaze.Blaze; // implied by `templating` var HTML = Package.htmljs.HTML; // implied by `blaze` Blaze.Template.registerHelper('emoji', new Template('emoji', function () { var view = this, content = ''; if (view.templateContentBlock) { // this is for the block usage eg: {{#emoji}}:smile:{{/emoji}} content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING); } else { // this is for the direct usage eg: {{> emoji ':blush:'}} content = view.parentView.dataVar.get(); } return HTML.Raw(Emoji.convert(content)); })); }
Emoji = {}; Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/'; Emoji.convert = function (str) { if (typeof str !== 'string') { return ''; } return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) { var imgName = match.slice(1, -1), path = Emoji.baseImagePath + imgName + '.png'; return '<img class="emoji" alt="' + match + '" src="' + path + '" draggable="false" />'; }); }; // borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js if (Package.templating) { var Template = Package.templating.Template; var Blaze = Package.blaze.Blaze; // implied by `templating` var HTML = Package.htmljs.HTML; // implied by `blaze` Blaze.Template.registerHelper('emoji', new Template('emoji', function () { var view = this, content = ''; if (view.templateContentBlock) { // this is for the block usage eg: {{#emoji}}:smile:{{/emoji}} content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING); } else { // this is for the direct usage eg: {{> emoji ':blush:'}} content = view.parentView.dataVar.get(); } return HTML.Raw(Emoji.convert(content)); })); }
Add draggable attr to <img>s and set it to false
Add draggable attr to <img>s and set it to false
JavaScript
mit
dmfrancisco/meteor-twemoji
--- +++ @@ -10,7 +10,7 @@ return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) { var imgName = match.slice(1, -1), path = Emoji.baseImagePath + imgName + '.png'; - return '<img class="emoji" alt="' + match + '" src="' + path + '"/>'; + return '<img class="emoji" alt="' + match + '" src="' + path + '" draggable="false" />'; }); };