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
6801efd2f61d99e55042e06984c17ccca921fea1
web/static/js/app.js
web/static/js/app.js
import "phoenix_html" import $ from "jquery"; import * as BS from "./battle_snake" const BattleSnake = Object.assign(window.BattleSnake, BS); window.BattleSnake = BattleSnake; if ($("#board-viewer")) { const gameId = window.BattleSnake.gameId; window.BattleSnake.BoardViewer.init(gameId); }
import "phoenix_html" import $ from "jquery"; import * as BS from "./battle_snake" const BattleSnake = Object.assign(window.BattleSnake, BS); window.BattleSnake = BattleSnake; if ($("#board-viewer").length) { const gameId = window.BattleSnake.gameId; window.BattleSnake.BoardViewer.init(gameId); }
Fix issue with js conditional
Fix issue with js conditional Was not properly testing if there was any results, causing the js to be evaluated on every page.
JavaScript
agpl-3.0
Dkendal/battle_snake,Dkendal/battle_snake,Dkendal/battle_snake,Dkendal/battle_snake,Dkendal/battle_snake
--- +++ @@ -5,7 +5,7 @@ const BattleSnake = Object.assign(window.BattleSnake, BS); window.BattleSnake = BattleSnake; -if ($("#board-viewer")) { +if ($("#board-viewer").length) { const gameId = window.BattleSnake.gameId; window.BattleSnake.BoardViewer.init(gameId); }
eb7727d2922f4eda310318b119fb435bfcfdc00c
common/modules/template100Handler.js
common/modules/template100Handler.js
module.exports = { inputValidator: function (fileInfo, callback) { }, mergeDataWithTemplate: function(data, template, callback) { } }
module.exports = { inputValidator: function (dataInput, callback) { if (dataInput) if (dataInput.header && dataInput.time && dataInput.holding && dataInput.subtitle) return callback(null) return callback(new Error('Input Validation for Dynamic Template Handler 100 Failed')) }, mergeDataWithTemplate: function(data, template, callback) { const cheerio = require('cheerio') const $ = cheerio.load(template) $('FL_Header').text(data.header) $('FL_Holding').text(data.holding) $('FL_Time').text(data.time) $('FL_Subtitle').text(data.subtitle) return callback(null, $.html()) } }
Implement Input Validator and Merge Data for Template100 Handler
Implement Input Validator and Merge Data for Template100 Handler
JavaScript
mit
Flieral/Announcer-Service-LB,Flieral/Announcer-Service-LB
--- +++ @@ -1,9 +1,18 @@ module.exports = { - inputValidator: function (fileInfo, callback) { - + inputValidator: function (dataInput, callback) { + if (dataInput) + if (dataInput.header && dataInput.time && dataInput.holding && dataInput.subtitle) + return callback(null) + return callback(new Error('Input Validation for Dynamic Template Handler 100 Failed')) }, mergeDataWithTemplate: function(data, template, callback) { - + const cheerio = require('cheerio') + const $ = cheerio.load(template) + $('FL_Header').text(data.header) + $('FL_Holding').text(data.holding) + $('FL_Time').text(data.time) + $('FL_Subtitle').text(data.subtitle) + return callback(null, $.html()) } }
ccc000a58a8c25fdbc5566e7f4bb61b62269078c
lib/control/util/index.js
lib/control/util/index.js
'use strict'; const STATUS_CODES = require('./status-codes'); const Handlers = { allowed(methods) { return (req, res) => { res.set('Allow', methods); res.status(STATUS_CODES.METHOD_NOT_ALLOWED); res.end(); } } }; const Err = (err, req, res, next) => { res.status(500); res.json({error: err.message}); }; module.exports = { Handlers, Err };
'use strict'; const STATUS_CODES = require('./status-codes'); const Handlers = { allowed(methods) { return (req, res) => { res.set('Allow', methods); res.status(STATUS_CODES.METHOD_NOT_ALLOWED); res.end(); } } }; const Err = (err, req, res, next) => { const error = { error: { name: err.name, message: err.message } }; const statusCode = err.statusCode || STATUS_CODES.BAD_REQUEST; // Include response headers if it's a HTTP error if (err.response) { error.error.headers = err.response.headers; } res.status(statusCode); res.json(error); }; module.exports = { Handlers, Err };
Add additional formatting to error handling.
Add additional formatting to error handling.
JavaScript
mit
rapid7/tokend,rapid7/tokend,rapid7/tokend
--- +++ @@ -12,8 +12,21 @@ }; const Err = (err, req, res, next) => { - res.status(500); - res.json({error: err.message}); + const error = { + error: { + name: err.name, + message: err.message + } + }; + const statusCode = err.statusCode || STATUS_CODES.BAD_REQUEST; + + // Include response headers if it's a HTTP error + if (err.response) { + error.error.headers = err.response.headers; + } + + res.status(statusCode); + res.json(error); }; module.exports = {
ee759f8b085a754b07f89e31f44a169cb5a23a03
src/framework/common/source-map-support/browser.js
src/framework/common/source-map-support/browser.js
// TODO remove this split between browser & node once the package does it on its own. import 'source-map-support/browser-source-map-support'; sourceMapSupport.install(); // eslint-disable-line no-undef
// TODO remove this split between browser & node once the package does it on its own. // TODO Current version is broken https://github.com/evanw/node-source-map-support/issues/173 // import 'source-map-support/browser-source-map-support'; // // sourceMapSupport.install(); // eslint-disable-line no-undef
Disable source-map-support until it is compatible with webpack again
fix: Disable source-map-support until it is compatible with webpack again
JavaScript
mit
foobarhq/reworkjs,reworkjs/reworkjs,reworkjs/reworkjs,reworkjs/reworkjs,foobarhq/reworkjs
--- +++ @@ -1,5 +1,6 @@ // TODO remove this split between browser & node once the package does it on its own. -import 'source-map-support/browser-source-map-support'; - -sourceMapSupport.install(); // eslint-disable-line no-undef +// TODO Current version is broken https://github.com/evanw/node-source-map-support/issues/173 +// import 'source-map-support/browser-source-map-support'; +// +// sourceMapSupport.install(); // eslint-disable-line no-undef
2deaf95cde707b5b85616f9f3d0167f7af47eed4
src/js/components/single-response-format-editor.js
src/js/components/single-response-format-editor.js
import React, { PropTypes } from 'react' import CodeListSelector from './code-list-selector' import VisHintPicker from './vis-hint-picker' import { updateSingle, newCodeListSingle } from '../actions/response-format' import { connect } from 'react-redux' function SingleResponseFormatEditor( { id, qrId, format: { codeListReference, visHint }, updateSingle, newCodeListSingle, locale }) { return ( <div> <CodeListSelector id={codeListReference} select={codeListReference => updateSingle(id, { codeListReference })} create={() => newCodeListSingle(id, qrId)} locale={locale} /> <VisHintPicker visHint={visHint} locale={locale} select={visHint => updateSingle(id, { visHint})}/> </div> ) } const mapStateToProps = state => ({ qrId: state.appState.questionnaire }) const mapDispatchToProps = { updateSingle, newCodeListSingle } SingleResponseFormatEditor.propTypes = { id: PropTypes.string.isRequired, /** * Id of the current questionnaire */ qrId: PropTypes.string.isRequired, format: PropTypes.object.isRequired, locale: PropTypes.object.isRequired, updateSingle: PropTypes.func.isRequired, newCodeListSingle: PropTypes.func.isRequired } export default connect(mapStateToProps, mapDispatchToProps)(SingleResponseFormatEditor)
import React, { PropTypes } from 'react' import CodeListSelector from './code-list-selector' import VisHintPicker from './vis-hint-picker' import { updateSingle, newCodeListSingle } from '../actions/response-format' import { connect } from 'react-redux' function SingleResponseFormatEditor( { id, qrId, format: { codeListReference, visHint }, updateSingle, newCodeListSingle, locale }) { return ( <div> <CodeListSelector id={codeListReference} title={locale.selectCl} select={codeListReference => updateSingle(id, { codeListReference })} create={() => newCodeListSingle(id, qrId)} locale={locale} /> <VisHintPicker visHint={visHint} locale={locale} select={visHint => updateSingle(id, { visHint})}/> </div> ) } const mapStateToProps = state => ({ qrId: state.appState.questionnaire }) const mapDispatchToProps = { updateSingle, newCodeListSingle } SingleResponseFormatEditor.propTypes = { id: PropTypes.string.isRequired, /** * Id of the current questionnaire */ qrId: PropTypes.string.isRequired, format: PropTypes.object.isRequired, locale: PropTypes.object.isRequired, updateSingle: PropTypes.func.isRequired, newCodeListSingle: PropTypes.func.isRequired } export default connect(mapStateToProps, mapDispatchToProps)(SingleResponseFormatEditor)
Add title for code list selection within single response
Add title for code list selection within single response
JavaScript
mit
InseeFr/Pogues,InseeFr/Pogues,Zenika/Pogues,InseeFr/Pogues,Zenika/Pogues,Zenika/Pogues
--- +++ @@ -15,6 +15,7 @@ <div> <CodeListSelector id={codeListReference} + title={locale.selectCl} select={codeListReference => updateSingle(id, { codeListReference })} create={() => newCodeListSingle(id, qrId)} locale={locale} />
f4b155043a40d690c95323821147b20ff8e007a1
src/moonstone-samples/lib/ScrollerHorizontalSample.js
src/moonstone-samples/lib/ScrollerHorizontalSample.js
var kind = require('enyo/kind'), Img = require('enyo/Image'), Repeater = require('enyo/Repeater'); var Divider = require('moonstone/Divider'), Item = require('moonstone/Item'), Scroller = require('moonstone/Scroller'); module.exports = kind({ name: 'moon.sample.ScrollerHorizontalSample', classes: 'moon enyo-unselectable enyo-fit', components: [ {kind: Divider, content: 'Horizontal Scroller'}, {kind: Scroller, vertical: 'hidden', spotlight: 'container', style: 'white-space: nowrap;', components: [ {kind: Repeater, count: '50', components: [ {kind: Item, classes: 'moon-scroller-sample-item enyo', style: 'display:inline-block;', components: [ {kind: Img, src: '@../images/enyo-icon.png'} ]} ]} ]} ] });
var kind = require('enyo/kind'), Img = require('enyo/Image'), Repeater = require('enyo/Repeater'); var Divider = require('moonstone/Divider'), Item = require('moonstone/Item'), Scroller = require('moonstone/Scroller'); module.exports = kind({ name: 'moon.sample.ScrollerHorizontalSample', classes: 'moon enyo-unselectable enyo-fit', components: [ {kind: Divider, content: 'Horizontal Scroller'}, {kind: Scroller, vertical: 'hidden', spotlight: 'container', style: 'white-space: nowrap;', components: [ {kind: Repeater, count: '50', components: [ {kind: Item, classes: 'moon-scroller-sample-item enyo', style: 'display:inline-block;', components: [ {kind: Img, src: 'moonstone/images/enyo-icon.png'} ]} ]} ]} ] });
Fix path to library image asset.
ENYO-1948: Fix path to library image asset. Enyo-DCO-1.1-Signed-off-by: Aaron Tam <aaron.tam@lge.com>
JavaScript
apache-2.0
enyojs/enyo-strawman
--- +++ @@ -16,7 +16,7 @@ {kind: Scroller, vertical: 'hidden', spotlight: 'container', style: 'white-space: nowrap;', components: [ {kind: Repeater, count: '50', components: [ {kind: Item, classes: 'moon-scroller-sample-item enyo', style: 'display:inline-block;', components: [ - {kind: Img, src: '@../images/enyo-icon.png'} + {kind: Img, src: 'moonstone/images/enyo-icon.png'} ]} ]} ]}
789de4ae409cd528c220fce54fab7adc8dae93c2
example/redux/src/modules/forms/index.js
example/redux/src/modules/forms/index.js
/* @flow */ import { Map, fromJS } from 'immutable'; const REGISTER_FORM = 'redux-example/forms/REGISTER_FORM'; const UNREGISTER_FORM = 'redux-example/forms/UNREGISTER_FORM'; const UPDATE_FORM = 'redux-example/forms/UPDATE_FORM'; const initialState = Map({}); /* ************************************************************************** * Reducer * *************************************************************************/ export default function reducer(state = initialState, action) { const { type, payload } = action; switch (type) { case REGISTER_FORM: const initialValues = payload.initialValues ? fromJS(payload.initialValues) : Map({}); return state.set(payload.id, fromJS({ initialValues, currentValues: initialValues, })); case UNREGISTER_FORM: return state.delete(payload); case UPDATE_FORM: return state.setIn(payload.keypath, payload.value); default: return state; } } /* ************************************************************************** * Action Creators * *************************************************************************/ /** * type initialForm = { id: string, initialValues: Object | Map } */ export function registerForm(initialForm) { return { type: REGISTER_FORM, payload: initialForm, }; } /** * type update = { keypath: string[], value: string | number | boolean } */ export function updateForm(update) { return { type: UPDATE_FORM, payload: update, }; }
/* @flow */ import { Map, fromJS } from 'immutable'; const REGISTER_FORM = 'redux-example/forms/REGISTER_FORM'; const UNREGISTER_FORM = 'redux-example/forms/UNREGISTER_FORM'; const UPDATE_FORM = 'redux-example/forms/UPDATE_FORM'; const initialState = Map({}); /* ************************************************************************** * Reducer * *************************************************************************/ export default function reducer(state = initialState, action) { const { type, payload } = action; switch (type) { case REGISTER_FORM: const initialValues = payload.initialValues ? fromJS(payload.initialValues) : Map({}); return state.set(payload.id, fromJS({ initialValues, currentValues: initialValues, })); case UNREGISTER_FORM: return state.delete(payload); case UPDATE_FORM: return state.setIn(payload.keypath, payload.value); default: return state; } } /* ************************************************************************** * Action Creators * *************************************************************************/ /** * type initialForm = { id: string, initialValues: Object | Map } */ export function registerForm(initialForm) { return { type: REGISTER_FORM, payload: initialForm, }; } /** * type formId: string */ export function unregisterForm(formId) { return { type: REGISTER_FORM, payload: formId, }; } /** * type update = { keypath: string[], value: string | number | boolean } */ export function updateForm(update) { return { type: UPDATE_FORM, payload: update, }; }
Add unregister form action creator
Add unregister form action creator
JavaScript
mit
iansinnott/react-static-webpack-plugin,iansinnott/react-static-webpack-plugin
--- +++ @@ -47,6 +47,16 @@ } /** + * type formId: string + */ +export function unregisterForm(formId) { + return { + type: REGISTER_FORM, + payload: formId, + }; +} + +/** * type update = { keypath: string[], value: string | number | boolean } */ export function updateForm(update) {
ada2b9c9152edc91f6199c43b6d8838ba8026f98
server/models/locations.js
server/models/locations.js
const mongoose = require('mongoose') const { Schema } = mongoose const locationSchema = new Schema({ address: { type: String, unique: true, required: true }, rating: Number, reviews: [{rating: Number, content: String, userId: String}], photos: [], description: String, loc: { type: [Number], index: { type: '2dsphere' } } }) const Location = mongoose.model('Location', locationSchema) module.exports = Location
const mongoose = require('mongoose') const { Schema } = mongoose const locationSchema = new Schema({ address: { type: String, unique: true, required: true }, rating: { type: Number, default: 0 }, reviews: [{rating: Number, content: String, userId: String}], photos: [], description: String, loc: { type: [Number], index: { type: '2dsphere' } } }) const Location = mongoose.model('Location', locationSchema) module.exports = Location
Adjust location model to have default rating of 0
Adjust location model to have default rating of 0
JavaScript
mit
JabroniZambonis/pLot
--- +++ @@ -3,7 +3,7 @@ const locationSchema = new Schema({ address: { type: String, unique: true, required: true }, - rating: Number, + rating: { type: Number, default: 0 }, reviews: [{rating: Number, content: String, userId: String}], photos: [], description: String,
528675ccbd0ea2cb182152c2efdd284c81c2b5ce
src/scripts/feature/dateTime/dateTimeController.js
src/scripts/feature/dateTime/dateTimeController.js
(function() { 'use strict'; angular.module('app.feature.dateTime').controller('DateTimeController', [ '$scope', '$interval', function($scope, $interval) { $interval(function() { $scope.dateTime = Date.now(); }, 1000); } ]); })();
(function() { 'use strict'; angular.module('app.feature.dateTime').controller('DateTimeController', [ '$scope', '$interval', function($scope, $interval) { // Set the current date and time on startup $scope.dateTime = Date.now(); // And afterwards every second in an endless loop $interval(function() { $scope.dateTime = Date.now(); }, 1000); } ]); })();
Set current date and time before starting the interval service
Set current date and time before starting the interval service - The interval service does not start immediately, instead it waits the configured amount of time before it runs the code that is declared inside the callback function.
JavaScript
mit
molehillrocker/mm-website,molehillrocker/mm-website
--- +++ @@ -4,6 +4,9 @@ angular.module('app.feature.dateTime').controller('DateTimeController', [ '$scope', '$interval', function($scope, $interval) { + // Set the current date and time on startup + $scope.dateTime = Date.now(); + // And afterwards every second in an endless loop $interval(function() { $scope.dateTime = Date.now(); }, 1000);
eb4366ca475f12871ad6be067433aa8011704224
lib/libra2/app/assets/javascripts/remove_download_link.js
lib/libra2/app/assets/javascripts/remove_download_link.js
(function() { "use strict"; function initPage() { // The thumbnail images on the show page are links, but the links aren't correct, so remove the links. // The html looks something like the following, but it varies depending on the type of media it is: // <a target="_new" title="Download the full-sized PDF" href="/downloads/xxxxxxxxxx"> // <figure> // <img class="img-responsive" alt="Download the full-sized PDF of zzzzzzzzzz.pdf" src="/downloads/xxxxxxxxxx?file=thumbnail"> // <figcaption>Download the full-sized PDF</figcaption> // </figure> // </a> var downloadArea = $('.thesis-thumbnail'); if (downloadArea.length > 0) {// If we are on the show page. var links = downloadArea.find("a"); links.removeAttr("href"); links.removeAttr("title"); links.removeAttr("target"); var captions = downloadArea.find("figcaption"); captions.remove(); } } $(window).bind('page:change', function() { initPage(); }); })();
(function() { "use strict"; function initPage() { // The thumbnail images on the show page are links, but the links aren't correct, so remove the links. // The html looks something like the following, but it varies depending on the type of media it is: // <a target="_new" title="Download the full-sized PDF" href="/downloads/xxxxxxxxxx"> // <figure> // <img class="img-responsive" alt="Download the full-sized PDF of zzzzzzzzzz.pdf" src="/downloads/xxxxxxxxxx?file=thumbnail"> // <figcaption>Download the full-sized PDF</figcaption> // </figure> // </a> var downloadArea = $('.thesis-thumbnail'); if (downloadArea.length > 0) {// If we are on the show page. var links = downloadArea.find("a"); links.removeAttr("href"); links.removeAttr("title"); links.removeAttr("target"); var captions = downloadArea.find("figcaption"); captions.remove(); var img = downloadArea.find("img"); if (img.length > 0) { var alt = img.attr("alt"); alt = alt.replace(/Download/, ""); img.attr("alt", alt); } } } $(window).bind('page:change', function() { initPage(); }); })();
Remove the word "download" from the thumbnail alt text.
Remove the word "download" from the thumbnail alt text.
JavaScript
apache-2.0
uvalib/Libra2,uvalib/Libra2,uvalib/Libra2,uvalib/Libra2,uvalib/Libra2
--- +++ @@ -18,6 +18,12 @@ links.removeAttr("target"); var captions = downloadArea.find("figcaption"); captions.remove(); + var img = downloadArea.find("img"); + if (img.length > 0) { + var alt = img.attr("alt"); + alt = alt.replace(/Download/, ""); + img.attr("alt", alt); + } } }
093005bfd926fdae42706e0554ad1a985196d9d7
lib/template/fs-loader.js
lib/template/fs-loader.js
var _ = require('lodash'); var fs = require('fs'); var path = require('path'); var nunjucks = require('nunjucks'); /* Nunjucks loader similar to FileSystemLoader, but avoid infinite looping */ var Loader = nunjucks.Loader.extend({ init: function(searchPaths) { this.searchPaths = searchPaths.map(path.normalize); }, getSource: function(fullpath) { fullpath = this.resolve(null, fullpath); if(!fullpath) { return null; } return { src: fs.readFileSync(fullpath, 'utf-8'), path: fullpath, noCache: true }; }, resolve: function(from, to) { var resultFolder = _.find(this.searchPaths, function(basePath) { var p = path.resolve(basePath, to); return ( p.indexOf(basePath) === 0 && p != from && fs.existsSync(p) ); }); return path.resolve(resultFolder, to); } }); module.exports = Loader;
var _ = require('lodash'); var fs = require('fs'); var path = require('path'); var nunjucks = require('nunjucks'); /* Nunjucks loader similar to FileSystemLoader, but avoid infinite looping */ function isRelative(filename) { return (filename.indexOf('./') === 0 || filename.indexOf('../') === 0); } var Loader = nunjucks.Loader.extend({ init: function(searchPaths) { this.searchPaths = searchPaths.map(path.normalize); }, getSource: function(fullpath) { if (!fullpath) return null; fullpath = this.resolve(null, fullpath); if(!fullpath) { return null; } return { src: fs.readFileSync(fullpath, 'utf-8'), path: fullpath, noCache: true }; }, // We handle absolute paths ourselves in ".resolve" isRelative: function() { return true; }, resolve: function(from, to) { // Relative template like "./test.html" if (isRelative(to) && from) { return path.resolve(path.dirname(from), to); } // Absolute template to resolve in root folder var resultFolder = _.find(this.searchPaths, function(basePath) { var p = path.resolve(basePath, to); return ( p.indexOf(basePath) === 0 && p != from && fs.existsSync(p) ); }); if (!resultFolder) return null; return path.resolve(resultFolder, to); } }); module.exports = Loader;
Fix FSLoader for relative paths
Fix FSLoader for relative paths
JavaScript
apache-2.0
tshoper/gitbook,strawluffy/gitbook,gencer/gitbook,tshoper/gitbook,GitbookIO/gitbook,ryanswanson/gitbook,gencer/gitbook
--- +++ @@ -7,12 +7,18 @@ Nunjucks loader similar to FileSystemLoader, but avoid infinite looping */ +function isRelative(filename) { + return (filename.indexOf('./') === 0 || filename.indexOf('../') === 0); +} + var Loader = nunjucks.Loader.extend({ init: function(searchPaths) { this.searchPaths = searchPaths.map(path.normalize); }, getSource: function(fullpath) { + if (!fullpath) return null; + fullpath = this.resolve(null, fullpath); if(!fullpath) { @@ -26,7 +32,18 @@ }; }, + // We handle absolute paths ourselves in ".resolve" + isRelative: function() { + return true; + }, + resolve: function(from, to) { + // Relative template like "./test.html" + if (isRelative(to) && from) { + return path.resolve(path.dirname(from), to); + } + + // Absolute template to resolve in root folder var resultFolder = _.find(this.searchPaths, function(basePath) { var p = path.resolve(basePath, to); @@ -36,7 +53,7 @@ && fs.existsSync(p) ); }); - + if (!resultFolder) return null; return path.resolve(resultFolder, to); } });
28ea49920beb7ad6ed4e3c3a9552fa6dabf931e7
client/app/js/crypto/main.js
client/app/js/crypto/main.js
angular.module('GLBrowserCrypto', []) .factory('glbcProofOfWork', ['$q', function($q) { // proofOfWork return the answer to the proof of work // { [challenge string] -> [ answer index] } var str2Uint8Array = function(str) { var result = new Uint8Array(str.length); for (var i = 0; i < str.length; i++) { result[i] = str.charCodeAt(i); } return result; }; var getWebCrypto = function() { if (typeof window !== 'undefined') { if (window.crypto) { return window.crypto.subtle || window.crypto.webkitSubtle; } if (window.msCrypto) { return window.msCrypto.subtle; } } }; return { proofOfWork: function(str) { var deferred = $q.defer(); var work = function(i) { var hashme = str2Uint8Array(str + i); var damnIE = getWebCrypto().digest({name: "SHA-256"}, hashme); var xxx = function (hash) { hash = new Uint8Array(hash); if (hash[31] === 0) { deferred.resolve(i); } else { work(i + 1); } } if (damnIE.then !== undefined) { damnIE.then(xxx); } else { damnIE.oncomplete = function(r) { xxx(r.target.result); }; } } work(0); return deferred.promise; } }; }]);
angular.module('GLBrowserCrypto', []) .factory('glbcProofOfWork', ['$q', function($q) { // proofOfWork return the answer to the proof of work // { [challenge string] -> [ answer index] } var str2Uint8Array = function(str) { var result = new Uint8Array(str.length); for (var i = 0; i < str.length; i++) { result[i] = str.charCodeAt(i); } return result; }; var getWebCrypto = function() { if (typeof window !== 'undefined') { if (window.crypto) { return window.crypto.subtle || window.crypto.webkitSubtle; } if (window.msCrypto) { return window.msCrypto.subtle; } } }; return { proofOfWork: function(str) { var deferred = $q.defer(); var i; var xxx = function (hash) { hash = new Uint8Array(hash); if (hash[31] === 0) { deferred.resolve(i); } else { i += 1; work(); } } var work = function() { var hashme = str2Uint8Array(str + i); var damnIE = getWebCrypto().digest({name: "SHA-256"}, hashme); if (damnIE.then !== undefined) { damnIE.then(xxx); } else { damnIE.oncomplete = function(r) { xxx(r.target.result); }; } } work(); return deferred.promise; } }; }]);
Remove function definition from proof of work recursion
Remove function definition from proof of work recursion
JavaScript
agpl-3.0
vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks,vodkina/GlobaLeaks
--- +++ @@ -25,18 +25,21 @@ proofOfWork: function(str) { var deferred = $q.defer(); - var work = function(i) { + var i; + + var xxx = function (hash) { + hash = new Uint8Array(hash); + if (hash[31] === 0) { + deferred.resolve(i); + } else { + i += 1; + work(); + } + } + + var work = function() { var hashme = str2Uint8Array(str + i); var damnIE = getWebCrypto().digest({name: "SHA-256"}, hashme); - - var xxx = function (hash) { - hash = new Uint8Array(hash); - if (hash[31] === 0) { - deferred.resolve(i); - } else { - work(i + 1); - } - } if (damnIE.then !== undefined) { damnIE.then(xxx); @@ -45,7 +48,7 @@ } } - work(0); + work(); return deferred.promise; }
bb76872376d5b5c74b83035a054dbd479ad861a7
public/app/config.js
public/app/config.js
angular.module('config', []) .constant('API_URL', 'http://cloakmd.azurewebsites.net/api');
angular.module('config', []) .constant('API_URL', 'https://cloakmd.azurewebsites.net/api');
Set API endpoint to https
Set API endpoint to https
JavaScript
mit
ymukavozchyk/cloakmd,ymukavozchyk/cloakmd
--- +++ @@ -1,2 +1,2 @@ angular.module('config', []) -.constant('API_URL', 'http://cloakmd.azurewebsites.net/api'); +.constant('API_URL', 'https://cloakmd.azurewebsites.net/api');
376e79a26e4e3c3886168d6e7bf3f2b2653a0162
app/assets/javascripts/form.js
app/assets/javascripts/form.js
$(document).ready(function() { $('.search').on('click', function() { $.post( '/grant_gateway/search', $('#search-form').serialize(), function(data) { for (var i = 0; i < data.length; i++) { $('.results').append("<a href='" + data[i].link + "' class='media-links'><div class='media'><div class='media-body'><h5 class='media-heading'>" + data[i].name + "</h5><i class='fa fa-arrow-circle-o-right'></i><br/><p>" + data[i].description + "</p></div></div></a>") }; }); }); });
$(document).ready(function() { $('.search').on('click', function() { $.post( '/grant_gateway/search', $('#search-form').serialize(), function(data) { $('.results').empty() for (var i = 0; i < data.length; i++) { $('.results').append("<a href='" + data[i].link + "' class='media-links'><div class='media'><div class='media-body'><h5 class='media-heading'>" + data[i].name + "</h5><i class='fa fa-arrow-circle-o-right'></i><br/><p>" + data[i].description + "</p></div></div></a>") }; }); }); });
Clear results before loading new results
Clear results before loading new results
JavaScript
mit
tonysuaus/projectz,tonysuaus/projectz
--- +++ @@ -2,6 +2,7 @@ $('.search').on('click', function() { $.post( '/grant_gateway/search', $('#search-form').serialize(), function(data) { + $('.results').empty() for (var i = 0; i < data.length; i++) { $('.results').append("<a href='" + data[i].link + "' class='media-links'><div class='media'><div class='media-body'><h5 class='media-heading'>" + data[i].name + "</h5><i class='fa fa-arrow-circle-o-right'></i><br/><p>" + data[i].description + "</p></div></div></a>") };
b55a6f35084d0291d004e64a2b6b2ae68f08f4ad
snippet.js
snippet.js
// MIT license, see: https://github.com/tjcrowder/simple-snippets-console/blob/master/LICENSE var snippet = { version: "1.0", // Writes out the given text in a monospaced paragraph tag, escaping // & and < so they aren't rendered as HTML. log: function(msg) { if (Object.prototype.toString.call(msg) === "[object Array]") { msg = msg.join(); } else if (typeof object === "object") { msg = msg === null ? "null" : JSON.stringify(msg); } document.body.insertAdjacentHTML( 'beforeend', '<p style="font-family: monospace; margin: 2px 0 2px 0">' + msg.replace(/&/g, '&amp;').replace(/</g, '&lt;') + '</p>' ); }, // Writes out the given HTML at the end of the body, // exactly as-is logHTML: function(html) { document.body.insertAdjacentHTML("beforeend", html); } };
// MIT license, see: https://github.com/tjcrowder/simple-snippets-console/blob/master/LICENSE var snippet = { version: "1.1", // Writes out the given text in a monospaced paragraph tag, escaping // & and < so they aren't rendered as HTML. log: function(msg, tag) { var elm = document.createElement(tag || "p"); elm.style.fontFamily = "monospace"; elm.style.margin = "2px 0 2px 0"; if (Object.prototype.toString.call(msg) === "[object Array]") { msg = msg.join(); } else if (typeof object === "object") { msg = msg === null ? "null" : JSON.stringify(msg); } elm.innerHTML = msg.replace(/&/g, '&amp;').replace(/</g, '&lt;'); document.body.appendChild(elm); }, // Writes out the given HTML at the end of the body, // exactly as-is logHTML: function(html) { document.body.insertAdjacentHTML("beforeend", html); } };
Add the ability to specify a tag
Add the ability to specify a tag
JavaScript
mit
tjcrowder/simple-snippets-console,tjcrowder/simple-snippets-console
--- +++ @@ -1,21 +1,20 @@ // MIT license, see: https://github.com/tjcrowder/simple-snippets-console/blob/master/LICENSE var snippet = { - version: "1.0", + version: "1.1", // Writes out the given text in a monospaced paragraph tag, escaping // & and < so they aren't rendered as HTML. - log: function(msg) { + log: function(msg, tag) { + var elm = document.createElement(tag || "p"); + elm.style.fontFamily = "monospace"; + elm.style.margin = "2px 0 2px 0"; if (Object.prototype.toString.call(msg) === "[object Array]") { msg = msg.join(); } else if (typeof object === "object") { msg = msg === null ? "null" : JSON.stringify(msg); } - document.body.insertAdjacentHTML( - 'beforeend', - '<p style="font-family: monospace; margin: 2px 0 2px 0">' + - msg.replace(/&/g, '&amp;').replace(/</g, '&lt;') + - '</p>' - ); + elm.innerHTML = msg.replace(/&/g, '&amp;').replace(/</g, '&lt;'); + document.body.appendChild(elm); }, // Writes out the given HTML at the end of the body,
3ad0835f36c87cdbb6e66528177e1a1413d0c113
test/integration/test/integration-mocha-setup.js
test/integration/test/integration-mocha-setup.js
const chai = require('chai') const chaiAsPromised = require('chai-as-promised') const td = require('testdouble') const tdChai = require('testdouble-chai') chai.use(chaiAsPromised) chai.use(tdChai(td)) chai.config.includeStack = true chai.config.showDiff = false global.expect = chai.expect // if any unhandled rejections happen in promises, treat them as fatal errors process.on('unhandledRejection', function(err) { throw err }) // if there are any PropType warnings from React, treat them as fatal errors const realLogger = console.error console.error = function error(...args) { const msg = args.join(' ') if (~msg.indexOf('Failed prop type')) { throw new Error(msg) } else { return realLogger(...args) } }
const chai = require('chai') const chaiAsPromised = require('chai-as-promised') const td = require('testdouble') const tdChai = require('testdouble-chai') chai.use(chaiAsPromised) chai.use(tdChai(td)) chai.config.includeStack = true chai.config.showDiff = false global.expect = chai.expect // if any unhandled rejections happen in promises, treat them as fatal errors process.on('unhandledRejection', function(err) { throw err })
Fix build error on node v4
Fix build error on node v4
JavaScript
mit
mwolson/jazzdom
--- +++ @@ -14,14 +14,3 @@ process.on('unhandledRejection', function(err) { throw err }) - -// if there are any PropType warnings from React, treat them as fatal errors -const realLogger = console.error -console.error = function error(...args) { - const msg = args.join(' ') - if (~msg.indexOf('Failed prop type')) { - throw new Error(msg) - } else { - return realLogger(...args) - } -}
76c08bcda29127a7e06c41c979854930217d36af
config/webpack-dev-server.config.js
config/webpack-dev-server.config.js
const path = require('path'); module.exports = { entry: [ path.resolve(process.cwd(), 'src/theme/assets/main-critical.js'), path.resolve(process.cwd(), 'src/theme/assets/main.js') ], output: { publicPath: 'http://localhost:8080/_assets/', filename: '[name].js', chunkFilename: '[id].js' }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader?importLoaders=1&minimize=true', 'postcss-loader' ] }, { test: /\.(gif|png|jpe?g|svg)(\?.+)?$/, use: ['url-loader'] }, { test: /\.(eot|ttf|woff|woff2)(\?.+)?$/, use: ['url-loader'] } ] }, devtool: 'eval', devServer: { publicPath: 'http://localhost:8080/_assets/' } };
const path = require('path'); module.exports = { entry: [ path.resolve(process.cwd(), 'src/theme/assets/main-critical.js'), path.resolve(process.cwd(), 'src/theme/assets/main.js') ], output: { publicPath: 'http://localhost:8080/_assets/', filename: '[name].js', chunkFilename: '[id].js' }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader?importLoaders=1&minimize=true', 'postcss-loader' ] }, { test: /\.(gif|png|jpe?g|svg)(\?.+)?$/, use: ['url-loader'] }, { test: /\.(eot|ttf|woff|woff2)(\?.+)?$/, use: ['url-loader'] } ] }, devtool: 'eval', devServer: { publicPath: 'http://localhost:8080/_assets/', headers: { 'Access-Control-Allow-Origin': '*' } } };
Add cors headers to dev server responses
Add cors headers to dev server responses
JavaScript
mit
jsor-labs/website,jsor-labs/website
--- +++ @@ -32,6 +32,9 @@ }, devtool: 'eval', devServer: { - publicPath: 'http://localhost:8080/_assets/' + publicPath: 'http://localhost:8080/_assets/', + headers: { + 'Access-Control-Allow-Origin': '*' + } } };
0c41049a189c2a69b6d9ecfa3f1e00470623efd4
packages/lingui-conf/src/index.js
packages/lingui-conf/src/index.js
const path = require('path') const pkgConf = require('pkg-conf') const { validate } = require('jest-validate') function replaceRootDir (conf, rootDir) { const replace = s => s.replace('<rootDir>', rootDir) ;['srcPathDirs', 'srcPathIgnorePatterns', 'localeDir'] .forEach(key => { const value = conf[key] if (!value) { } else if (typeof value === 'string') { conf[key] = replace(value) } else if (value.length) { conf[key] = value.map(replace) } }) conf.rootDir = rootDir return conf } const defaults = { localeDir: './locale', fallbackLanguage: '', srcPathDirs: ['<rootDir>'], srcPathIgnorePatterns: ['/node_modules/'], format: 'json-lingui', rootDir: '.' } const configValidation = { exampleConfig: defaults, comment: `See https://l.lingui.io/ref-lingui-conf for a list of valid options` } function getConfig () { const raw = pkgConf.sync('lingui', { defaults, skipOnFalse: true }) validate(raw, configValidation) const rootDir = path.dirname(pkgConf.filepath(raw)) return replaceRootDir(raw, rootDir) } export default getConfig export { replaceRootDir }
const path = require('path') const pkgConf = require('pkg-conf') const { validate } = require('jest-validate') function replaceRootDir (conf, rootDir) { const replace = s => s.replace('<rootDir>', rootDir) ;['srcPathDirs', 'srcPathIgnorePatterns', 'localeDir'] .forEach(key => { const value = conf[key] if (!value) { } else if (typeof value === 'string') { conf[key] = replace(value) } else if (value.length) { conf[key] = value.map(replace) } }) conf.rootDir = rootDir return conf } const defaults = { localeDir: './locale', fallbackLanguage: '', srcPathDirs: ['<rootDir>'], srcPathIgnorePatterns: ['/node_modules/'], format: 'lingui', rootDir: '.' } const configValidation = { exampleConfig: defaults, comment: `See https://l.lingui.io/ref-lingui-conf for a list of valid options` } function getConfig () { const raw = pkgConf.sync('lingui', { defaults, skipOnFalse: true }) validate(raw, configValidation) const rootDir = path.dirname(pkgConf.filepath(raw)) return replaceRootDir(raw, rootDir) } export default getConfig export { replaceRootDir }
Change the default value for format
feat: Change the default value for format
JavaScript
mit
lingui/js-lingui,lingui/js-lingui
--- +++ @@ -26,7 +26,7 @@ fallbackLanguage: '', srcPathDirs: ['<rootDir>'], srcPathIgnorePatterns: ['/node_modules/'], - format: 'json-lingui', + format: 'lingui', rootDir: '.' }
16cb0348dab24ef26c98b4992aa2d04f73f4d525
components/ClickableImage.js
components/ClickableImage.js
import React, { Component } from 'react'; import { TouchableOpacity, Image, View } from 'react-native'; import styles from './styles/ClickableImageStyle'; import PropTypes from 'prop-types'; import { StackNagivator } from 'react-navigation'; import FadeInView from '../animations/FadeInView'; export default class ClickableImage extends Component { static propTypes = { onPress: PropTypes.func, text: PropTypes.object, children: PropTypes.object, navigation: PropTypes.object } render() { return ( <View> <FadeInView> <TouchableOpacity style={styles.touchableSize} activeOpacity={.85} onPress={this.props.onPress}> <Image style={styles.image} source={this.props.text} /> </TouchableOpacity> </FadeInView> </View> ) } }
import React, { Component } from 'react'; import { TouchableOpacity, Image, View } from 'react-native'; // import styles from './styles/ClickableImageStyle'; import PropTypes from 'prop-types'; import { StackNagivator } from 'react-navigation'; import FadeInView from '../animations/FadeInView'; export default class ClickableImage extends Component { static propTypes = { onPress: PropTypes.func, text: PropTypes.object, children: PropTypes.object, navigation: PropTypes.object, imageStyle: Image.propTypes.style, touchStyle: View.propTypes.style } render() { return ( <View> <FadeInView> <TouchableOpacity style={this.props.touchStyle} activeOpacity={.85} onPress={this.props.onPress}> <Image style={this.props.imageStyle} source={this.props.text} /> </TouchableOpacity> </FadeInView> </View> ) } }
Change clickableimage to allow it to take styles when a new component is called elsewhere
Change clickableimage to allow it to take styles when a new component is called elsewhere
JavaScript
mit
fridl8/cold-bacon-client,fridl8/cold-bacon-client,fridl8/cold-bacon-client
--- +++ @@ -1,6 +1,6 @@ import React, { Component } from 'react'; import { TouchableOpacity, Image, View } from 'react-native'; -import styles from './styles/ClickableImageStyle'; +// import styles from './styles/ClickableImageStyle'; import PropTypes from 'prop-types'; import { StackNagivator } from 'react-navigation'; import FadeInView from '../animations/FadeInView'; @@ -10,15 +10,17 @@ onPress: PropTypes.func, text: PropTypes.object, children: PropTypes.object, - navigation: PropTypes.object + navigation: PropTypes.object, + imageStyle: Image.propTypes.style, + touchStyle: View.propTypes.style } render() { return ( <View> <FadeInView> - <TouchableOpacity style={styles.touchableSize} activeOpacity={.85} onPress={this.props.onPress}> - <Image style={styles.image} source={this.props.text} /> + <TouchableOpacity style={this.props.touchStyle} activeOpacity={.85} onPress={this.props.onPress}> + <Image style={this.props.imageStyle} source={this.props.text} /> </TouchableOpacity> </FadeInView> </View>
17b8376c523ea0e537abb91760fd25d866a3abfd
app/scripts/login.babel.js
app/scripts/login.babel.js
/** * * Meet-Up Event Planner * Copyright 2015 Justin Varghese John All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License * */ /* eslint-env browser */ 'use strict'; var firebase = new Firebase("https://meet-up-event-planner.firebaseio.com"); let emailInput = document.querySelector('input[name="email"]'); let passwordInput = document.querySelector('input[name="password"]'); let submit = document.querySelector('button[type="submit"]'); submit.onclick = function() { event.preventDefault(); firebase.authWithPassword({ email : emailInput.value, password : passwordInput.value }, function(error, authData) { if (error) { console.log("Login Failed!", error); } else { console.log("Authenticated successfully with payload:", authData); } }); };
/** * * Meet-Up Event Planner * Copyright 2015 Justin Varghese John All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License * */ /* eslint-env browser */ 'use strict'; var firebase = new Firebase("https://meet-up-event-planner.firebaseio.com"); let emailInput = document.querySelector('input[name="email"]'); let passwordInput = document.querySelector('input[name="password"]'); let submit = document.querySelector('button[type="submit"]'); submit.onclick = function() { event.preventDefault(); firebase.authWithPassword({ email : emailInput.value, password : passwordInput.value }, function(error, authData) { if (error) { console.log("Login Failed!", error); } else { console.log("Authenticated successfully with payload:", authData); window.location.href = '/create-event.html'; } }); };
Add redirect after successful login
Add redirect after successful login
JavaScript
apache-2.0
johnjv/meet-up-event-planner,johnjv/meet-up-event-planner
--- +++ @@ -37,6 +37,7 @@ console.log("Login Failed!", error); } else { console.log("Authenticated successfully with payload:", authData); + window.location.href = '/create-event.html'; } }); };
fb5275af0191c5ec9532f21c19f400b9798fba2f
angular-stomp.js
angular-stomp.js
/* * Copyright: 2012, V. Glenn Tarcea * MIT License Applies */ angular.module('AngularStomp', []). factory('ngstomp', function($rootScope) { Stomp.WebSocketClass = SockJS; var stompClient = Stomp.client('http://localhost:15674/stomp'); return { subscribe: function(queue, callback) { stompClient.subscribe(queue, function() { var args = arguments; $rootScope.$apply(function() { callback(args[0]); }) }) }, send: function(queue, headers, data) { stompClient.send(queue, headers, data); }, connect: function(user, password, on_connect, on_error, vhost) { stompClient.connect(user, password, function(frame) { $rootScope.$apply(function() { on_connect.apply(stompClient, frame); }) }, function(frame) { $rootScope.$apply(function() { on_error.apply(stompClient, frame); }) }, vhost); }, disconnect: function(callback) { stompClient.disconnect(function() { var args = arguments; $rootScope.$apply(function() { callback.apply(args); }) }) } } // function NGStomp(url, socketClass) { // Stomp.WebSocketClass = socketClass; // var stompClient = Stomp.client(url); // } });
/* * Copyright: 2012, V. Glenn Tarcea * MIT License Applies */ angular.module('AngularStomp', []). factory('ngstomp', function($rootScope) { Stomp.WebSocketClass = SockJS; var stompClient = {}; function NGStomp(url) { this.stompClient = Stomp.client(url); } NGStomp.prototype.subscribe = function(queue, callback) { this.stompClient.subscribe(queue, function() { var args = arguments; $rootScope.$apply(function() { callback(args[0]); }) }) } NGStomp.prototype.send = function(queue, headers, data) { this.stompClient.send(queue, headers, data); } NGStomp.prototype.connect = function(user, password, on_connect, on_error, vhost) { this.stompClient.connect(user, password, function(frame) { $rootScope.$apply(function() { on_connect.apply(stompClient, frame); }) }, function(frame) { $rootScope.$apply(function() { on_error.apply(stompClient, frame); }) }, vhost); } NGStomp.prototype.disconnect = function(callback) { this.stompClient.disconnect(function() { var args = arguments; $rootScope.$apply(function() { callback.apply(args); }) }) } return function(url) { return new NGStomp(url); } });
Update to allow the url to be passed into a constructor for the service (the service returns a constructor).
Update to allow the url to be passed into a constructor for the service (the service returns a constructor).
JavaScript
apache-2.0
davinkevin/AngularStompDK
--- +++ @@ -6,49 +6,49 @@ angular.module('AngularStomp', []). factory('ngstomp', function($rootScope) { Stomp.WebSocketClass = SockJS; - var stompClient = Stomp.client('http://localhost:15674/stomp'); + var stompClient = {}; - return { - subscribe: function(queue, callback) { - stompClient.subscribe(queue, function() { - var args = arguments; - $rootScope.$apply(function() { - callback(args[0]); - }) - }) - }, - - send: function(queue, headers, data) { - stompClient.send(queue, headers, data); - }, - - connect: function(user, password, on_connect, on_error, vhost) { - stompClient.connect(user, password, - function(frame) { - $rootScope.$apply(function() { - on_connect.apply(stompClient, frame); - }) - }, - function(frame) { - $rootScope.$apply(function() { - on_error.apply(stompClient, frame); - }) - }, vhost); - }, - - disconnect: function(callback) { - stompClient.disconnect(function() { - var args = arguments; - $rootScope.$apply(function() { - callback.apply(args); - }) - }) - } + function NGStomp(url) { + this.stompClient = Stomp.client(url); } -// function NGStomp(url, socketClass) { -// Stomp.WebSocketClass = socketClass; -// var stompClient = Stomp.client(url); -// } + NGStomp.prototype.subscribe = function(queue, callback) { + this.stompClient.subscribe(queue, function() { + var args = arguments; + $rootScope.$apply(function() { + callback(args[0]); + }) + }) + } + NGStomp.prototype.send = function(queue, headers, data) { + this.stompClient.send(queue, headers, data); + } + + NGStomp.prototype.connect = function(user, password, on_connect, on_error, vhost) { + this.stompClient.connect(user, password, + function(frame) { + $rootScope.$apply(function() { + on_connect.apply(stompClient, frame); + }) + }, + function(frame) { + $rootScope.$apply(function() { + on_error.apply(stompClient, frame); + }) + }, vhost); + } + + NGStomp.prototype.disconnect = function(callback) { + this.stompClient.disconnect(function() { + var args = arguments; + $rootScope.$apply(function() { + callback.apply(args); + }) + }) + } + + return function(url) { + return new NGStomp(url); + } });
cbc42df4304d209f788fb9edc2688ee538c7470e
assets/js/ads.js
assets/js/ads.js
/** * This file is intended to detect active ad blocker. * * Ad blockers block URLs containing the word "ads" including this file. * If the file does load, `googlesitekit.canAdsRun` is set to true. */ global.googlesitekit = global.googlesitekit || {}; global.googlesitekit.canAdsRun = true; // Ensure that this flag does not get wiped at a later stage during pageload. document.addEventListener( 'DOMContentLoaded', function() { global.googlesitekit.canAdsRun = true; } );
/** * This file is intended to detect active ad blocker. * * Ad blockers block URLs containing the word "ads" including this file. * If the file does load, `googlesitekit.canAdsRun` is set to true. */ if ( global.googlesitekit === undefined ) { global.googlesitekit = {}; } global.googlesitekit.canAdsRun = true; // Ensure that this flag does not get wiped at a later stage during pageload. document.addEventListener( 'DOMContentLoaded', function() { global.googlesitekit.canAdsRun = true; } );
Tidy up check for Site Kit global.
Tidy up check for Site Kit global.
JavaScript
apache-2.0
google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp
--- +++ @@ -5,7 +5,10 @@ * If the file does load, `googlesitekit.canAdsRun` is set to true. */ -global.googlesitekit = global.googlesitekit || {}; +if ( global.googlesitekit === undefined ) { + global.googlesitekit = {}; +} + global.googlesitekit.canAdsRun = true; // Ensure that this flag does not get wiped at a later stage during pageload.
aaaaa76705e996cad798ec0d964b78434a87e621
spec/dev/scheduler.spec.js
spec/dev/scheduler.spec.js
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. const Scheduler = require("../../lib/scheduler"); const fsWatcher = require("../../lib/fs-watcher"); const MockInspector = require("../mock/file-tree-inspector"); const Ticker = require("../mock/ticker"); let scheduler = null; let ticker = null; let fakeFS = null; describe("in a mocked environment", () => { beforeEach(() => { let mockObj = MockInspector(); ticker = Ticker(); fakeFS = mockObj.fs; scheduler = Scheduler( {"watcher": fsWatcher({"tick": ticker.tick, "inspector": mockObj.inspector})}); }); it("does nothing when given nothing", done => { scheduler({}).then(() => { done(); }, error => { expect(error).toBe("not an error"); done(); }); }); });
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. const Scheduler = require("../../lib/scheduler"); const fsWatcher = require("../../lib/fs-watcher"); const MockInspector = require("../mock/file-tree-inspector"); const Ticker = require("../mock/ticker"); let scheduler = null; let ticker = null; let fakeFS = null; let taskSpy = function(find) { let task = {}; task.pwd = ""; task.events = []; task.find = () => new Promise(function(resolve, reject) { resolve(find()); }); task.move = files => new Promise(function(resolve, reject) { task.events.push(["move", files]); }); task.run = wd => new Promise(function(resolve, reject) { task.events.push(["run", wd]); }); return task; }; describe("in a mocked environment", () => { beforeEach(() => { let mockObj = MockInspector(); ticker = Ticker(); fakeFS = mockObj.fs; scheduler = Scheduler( {"watcher": fsWatcher({"tick": ticker.tick, "inspector": mockObj.inspector})}); }); it("does nothing when given nothing", done => { scheduler({}).then(() => { done(); }, error => { expect(error).toBe("not an error"); done(); }); }); });
Create untested (so far) task spy
:art: Create untested (so far) task spy
JavaScript
bsd-3-clause
daaang/awful-mess
--- +++ @@ -10,6 +10,27 @@ let scheduler = null; let ticker = null; let fakeFS = null; + +let taskSpy = function(find) { + let task = {}; + + task.pwd = ""; + task.events = []; + + task.find = () => new Promise(function(resolve, reject) { + resolve(find()); + }); + + task.move = files => new Promise(function(resolve, reject) { + task.events.push(["move", files]); + }); + + task.run = wd => new Promise(function(resolve, reject) { + task.events.push(["run", wd]); + }); + + return task; +}; describe("in a mocked environment", () => { beforeEach(() => {
abfcaf9e91eb8ca9976d6c7055bbca4086a9c5b2
Gruntfile.js
Gruntfile.js
// Configuration module.exports = function(grunt) { // Initialize config grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), }); // Load required tasks from submodules grunt.loadTasks('grunt'); // Default grunt.registerTask('default', [ 'connect', 'localtunnel', 'watch' ]); // Testing grunt.registerTask('test', [ 'htmlhint', 'jshint', 'scsslint' ]); // Staging grunt.registerTask('stage', [ 'clean:deploy', 'fontello:build', 'assemble:stage', 'copy:stage', 'concat', 'sass:deploy', 'autoprefixer:deploy', 'uglify', 'imagemin:deploy', 'svgmin:deploy', 'modernizr', 'hashres:deploy' ]); // Deployment grunt.registerTask('deploy', [ 'clean:deploy', 'fontello:build', 'assemble:deploy', 'copy:deploy', 'concat', 'sass:deploy', 'autoprefixer:deploy', 'uglify', 'imagemin:deploy', 'svgmin:deploy', 'modernizr', 'hashres:deploy' ]); };
// Configuration module.exports = function(grunt) { // Initialize config grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), }); // Load required tasks from submodules grunt.loadTasks('grunt'); // Default task grunt.registerTask('default', ['dev']); // Development grunt.registerTask('dev', [ 'connect', 'localtunnel', 'watch' ]); // Testing grunt.registerTask('test', [ 'htmlhint', 'jshint', 'scsslint' ]); // Staging grunt.registerTask('stage', [ 'clean:deploy', 'fontello:build', 'assemble:stage', 'copy:stage', 'concat', 'sass:deploy', 'autoprefixer:deploy', 'uglify', 'imagemin:deploy', 'svgmin:deploy', 'modernizr', 'hashres:deploy' ]); // Deployment grunt.registerTask('deploy', [ 'clean:deploy', 'fontello:build', 'assemble:deploy', 'copy:deploy', 'concat', 'sass:deploy', 'autoprefixer:deploy', 'uglify', 'imagemin:deploy', 'svgmin:deploy', 'modernizr', 'hashres:deploy' ]); };
Make it easier to change the default Grunt task
Make it easier to change the default Grunt task
JavaScript
mit
yellowled/yl-bp,yellowled/yl-bp
--- +++ @@ -8,8 +8,11 @@ // Load required tasks from submodules grunt.loadTasks('grunt'); - // Default - grunt.registerTask('default', [ + // Default task + grunt.registerTask('default', ['dev']); + + // Development + grunt.registerTask('dev', [ 'connect', 'localtunnel', 'watch'
e5f5593a922593bf8333c4704e35546c4a57b1c2
Gruntfile.js
Gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ movePackageTo: process.env["JOB_NAME"] ? "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package" : "build", jobName: process.env["JOB_NAME"] || "local", buildNumber: process.env["BUILD_NUMBER"] || "non-ci", destinationFolder: process.env["JOB_NAME"] ? "<%= movePackageTo %>\\<%= jobName %>\\<%= grunt.template.today('yyyy-mm-dd') %> #<%= buildNumber %>" : "<%= movePackageTo %>", compress: { main: { options: { archive: "<%= destinationFolder %>\\Telerik AppBuilder.zip" }, files: [ { src: ["**/*.{py,pyd,so}", "*.{sublime-keymap,sublime-menu,sublime-settings}", "LICENSE"] } ] } }, clean: { src: ["**/*.pyc"] } }); grunt.loadNpmTasks("grunt-contrib-compress"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.registerTask("default", "compress:main"); }
module.exports = function(grunt) { grunt.initConfig({ copyPackageTo: "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package", movePackageTo: process.env["JOB_NAME"] ? "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package" : "build", jobName: process.env["JOB_NAME"] || "local", buildNumber: process.env["BUILD_NUMBER"] || "non-ci", destinationFolder: process.env["JOB_NAME"] ? "<%= movePackageTo %>\\<%= jobName %>\\<%= grunt.template.today('yyyy-mm-dd') %> #<%= buildNumber %>" : "<%= movePackageTo %>", compress: { main: { options: { archive: "<%= destinationFolder %>\\Telerik AppBuilder.zip" }, files: [ { src: ["**/*.{py,pyd,so}", "*.{sublime-keymap,sublime-menu,sublime-settings}", "LICENSE"] } ] } }, copy: { package_to_qa_drop_folder: { src: "*.zip", dest: "<%= copyPackageTo %>/<%= jobName %>/Telerik AppBuilder.zip" } }, clean: { src: ["**/*.pyc"] } }); grunt.loadNpmTasks("grunt-contrib-compress"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.registerTask("default", "compress:main"); }
Copy built package to QA Folder
Copy built package to QA Folder
JavaScript
apache-2.0
Icenium/appbuilder-sublime-package,dimitardanailov/appbuilder-sublime-package,dimitardanailov/appbuilder-sublime-package,Icenium/appbuilder-sublime-package
--- +++ @@ -1,5 +1,7 @@ module.exports = function(grunt) { grunt.initConfig({ + copyPackageTo: "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package", + movePackageTo: process.env["JOB_NAME"] ? "\\\\telerik.com\\Resources\\BlackDragon\\Builds\\appbuilder-sublime-package" : "build", jobName: process.env["JOB_NAME"] || "local", buildNumber: process.env["BUILD_NUMBER"] || "non-ci", @@ -15,6 +17,13 @@ ] } }, + + copy: { + package_to_qa_drop_folder: { + src: "*.zip", + dest: "<%= copyPackageTo %>/<%= jobName %>/Telerik AppBuilder.zip" + } + }, clean: { src: ["**/*.pyc"]
3c999cf0f30d4638f59e57be1be8c5bac38be989
api/getPlayer.js
api/getPlayer.js
//http://stats.nba.com/media/players/230x185/201939.png module.exports = (dispatch) => { dispatch({type: 'RECEIVE_PLAYER_INFO', payload: { name: "Klay Thompson", team: "Golden State Warriors", ppg: 21.9, apg: 3.5, rpg: 4.2, image: "http://stats.nba.com/media/players/230x185/201939.png" }}) }
//http://stats.nba.com/media/players/230x185/201939.png module.exports = (dispatch) => { dispatch({type: 'RECEIVE_PLAYER_INFO', payload: { name: "Klay Thompson", team: "Golden State Warriors", ppg: 21.9, apg: 3.5, rpg: 4.2, image: "http://stats.nba.com/media/players/230x185/202691.png" }}) }
Change sample url so image is actually Klay Thompson lol
Change sample url so image is actually Klay Thompson lol
JavaScript
mit
michael-lowe-nz/NBA-battles,michael-lowe-nz/NBA-battles
--- +++ @@ -7,6 +7,6 @@ ppg: 21.9, apg: 3.5, rpg: 4.2, - image: "http://stats.nba.com/media/players/230x185/201939.png" + image: "http://stats.nba.com/media/players/230x185/202691.png" }}) }
71ef5ba237e6fa75eca9b64877faba452fbcd973
Gruntfile.js
Gruntfile.js
/* * grunt-check-pages * https://github.com/DavidAnson/grunt-check-pages * * Copyright (c) 2014 David Anson * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration grunt.initConfig({ // Linting jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', 'test/*.js' ], options: { jshintrc: '.jshintrc' } }, // Unit tests nodeunit: { tests: ['test/*_test.js'] } }); // Load this plugin's task grunt.loadTasks('tasks'); // Load required plugins grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Default: Test and lint grunt.registerTask('default', ['nodeunit', 'jshint']); };
/* * grunt-check-pages * https://github.com/DavidAnson/grunt-check-pages * * Copyright (c) 2014 David Anson * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration grunt.initConfig({ // Linting jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', 'test/*.js' ], options: { jshintrc: '.jshintrc' } }, // Unit tests nodeunit: { tests: ['test/*_test.js'] } }); // Load required plugins grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Default: Test and lint grunt.registerTask('default', ['nodeunit', 'jshint']); };
Remove unnecessary call to loadTasks.
Remove unnecessary call to loadTasks.
JavaScript
mit
DavidAnson/grunt-check-pages,DavidAnson/grunt-check-pages,DavidAnson/check-pages,Flimm/check-pages,Flimm/check-pages,DavidAnson/check-pages
--- +++ @@ -31,9 +31,6 @@ } }); - // Load this plugin's task - grunt.loadTasks('tasks'); - // Load required plugins grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit');
bcc29ed1011de5f00ea7728f7f2080c061c6fa1c
frontend/src/containers/new-project/new-project.js
frontend/src/containers/new-project/new-project.js
const React = require('react'); const ReactRedux = require('react-redux'); const ReduxForm = require('redux-form'); const selectors = require('@state/selectors'); const selectors = require('@state/selectors'); const PropTypes = require('@root/prop-types'); const CreateProject = require('@components/new-project'); const { connect } = ReactRedux; const { reduxForm } = ReduxForm; const { orgByIdSelector } = selectors; const NewProjectForm = reduxForm({ form: 'create-project', destroyOnUnmount: false, forceUnregisterOnUnmount: true })(CreateProject); const NewProject = (props) => { const { org, push } = props; const onCancel = (values) => push(`/${org.id}/projects`); const onSubmit = (values) => push(`/${org.id}/new-project/billing`); return ( <NewProjectForm onCancel={onCancel} onSubmit={onSubmit} org={org} /> ); }; NewProject.propTypes = { org: PropTypes.org.isRequired, push: React.PropTypes.func }; // TODO we'll need to know whether there any cards // otherwise go to new billing straight away const mapStateToProps = (state, { match = { params: {} } }) => ({ org: orgByIdSelector(match.params.org)(state), router: state.app.router }); const mapDispatchToProps = (dispatch) => ({}); module.exports = connect( mapStateToProps, mapDispatchToProps )(NewProject);
const React = require('react'); const ReactRedux = require('react-redux'); const ReduxForm = require('redux-form'); const selectors = require('@state/selectors'); const PropTypes = require('@root/prop-types'); const CreateProject = require('@components/new-project'); const { connect } = ReactRedux; const { reduxForm } = ReduxForm; const { orgByIdSelector } = selectors; const NewProjectForm = reduxForm({ form: 'create-project', destroyOnUnmount: false, forceUnregisterOnUnmount: true })(CreateProject); const NewProject = (props) => { const { org, push } = props; const onCancel = (values) => push(`/${org.id}/projects`); const onSubmit = (values) => push(`/${org.id}/new-project/billing`); return ( <NewProjectForm onCancel={onCancel} onSubmit={onSubmit} org={org} /> ); }; NewProject.propTypes = { org: PropTypes.org.isRequired, push: React.PropTypes.func }; // TODO we'll need to know whether there any cards // otherwise go to new billing straight away const mapStateToProps = (state, { match = { params: {} } }) => ({ org: orgByIdSelector(match.params.org)(state), router: state.app.router }); const mapDispatchToProps = (dispatch) => ({}); module.exports = connect( mapStateToProps, mapDispatchToProps )(NewProject);
Move form creation to containers for new project
Move form creation to containers for new project
JavaScript
mpl-2.0
yldio/joyent-portal,yldio/copilot,geek/joyent-portal,yldio/copilot,geek/joyent-portal,yldio/joyent-portal,yldio/copilot
--- +++ @@ -1,8 +1,6 @@ const React = require('react'); const ReactRedux = require('react-redux'); const ReduxForm = require('redux-form'); -const selectors = require('@state/selectors'); - const selectors = require('@state/selectors'); const PropTypes = require('@root/prop-types'); const CreateProject = require('@components/new-project');
3d605ebb4a693802b36a65264c588a51cd62dbc4
src/main/webapp/components/BuildSnapshotContainer.js
src/main/webapp/components/BuildSnapshotContainer.js
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; /** * 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) => { // Number of entries to be pulled. // TODO: Determine true value for number of entries. const NUMBER = 2; // The starting point from which the entries are selected. // Relative to the starting index. // TODO: vary multiplier based on page number. const OFFSET = NUMBER * 0; const SOURCE = `/builders/number=${NUMBER}/offset=${OFFSET}`; 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 => res.json()) .then(json => setData(json)) .catch(setData([])); }, []); return ( <div className='build-snapshot-container'> {data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)} </div> ); } );
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; /** * 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) => { // Number of entries to be pulled. // TODO: Determine true value for number of entries. const NUMBER = 2; // The starting point from which the entries are selected. // Relative to the starting index. // TODO: vary multiplier based on page number. const OFFSET = NUMBER * 0; const SOURCE = `/builders/number=${NUMBER}/offset=${OFFSET}`; 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 => res.json()) .then(json => setData(json)) .catch(setData([])); }, []); return ( <div id='build-snapshot-container'> {data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)} </div> ); } );
Change to id from className
Change to id from className
JavaScript
apache-2.0
googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020
--- +++ @@ -36,7 +36,7 @@ }, []); return ( - <div className='build-snapshot-container'> + <div id='build-snapshot-container'> {data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)} </div> );
27486485c9f5821d76090a75f05d5d27991cdf48
client/request.js
client/request.js
/* istanbul ignore file */ const http = require('http') module.exports = function httpRequest(body) { return new Promise((resolve, reject) => { const request = http.request( { hostname: 'server', port: 8653, path: '/graphql', method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8', Accept: 'application/json', 'X-Requested-With': 'Node.js', }, }, response => { let xbody = '' response.setEncoding('utf8') response.on('data', d => { xbody += d }) response.on('end', () => { const { statusCode } = response if (statusCode < 400 && statusCode >= 200) { resolve(JSON.parse(xbody)) } else { reject(JSON.parse(xbody)) } }) } ) request.write(body) request.end() }) }
/* istanbul ignore file */ const http = require('http') function parseJSON(data) { try { return JSON.parse(data) } catch (e) { return data } } module.exports = function httpRequest(body) { return new Promise((resolve, reject) => { const request = http.request( { hostname: 'server', port: 8653, path: '/graphql', method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8', Accept: 'application/json', 'X-Requested-With': 'Node.js', }, }, response => { let xbody = '' response.setEncoding('utf8') response.on('data', d => { xbody += d }) response.on('end', () => { const { statusCode } = response if (statusCode < 400 && statusCode >= 200) { resolve(parseJSON(xbody)) } else { reject(parseJSON(xbody)) } }) } ) request.write(body) request.end() }) }
Update to handle when response isnt json
Update to handle when response isnt json
JavaScript
apache-2.0
heiskr/sagefy,heiskr/sagefy,heiskr/sagefy,heiskr/sagefy
--- +++ @@ -1,5 +1,13 @@ /* istanbul ignore file */ const http = require('http') + +function parseJSON(data) { + try { + return JSON.parse(data) + } catch (e) { + return data + } +} module.exports = function httpRequest(body) { return new Promise((resolve, reject) => { @@ -24,9 +32,9 @@ response.on('end', () => { const { statusCode } = response if (statusCode < 400 && statusCode >= 200) { - resolve(JSON.parse(xbody)) + resolve(parseJSON(xbody)) } else { - reject(JSON.parse(xbody)) + reject(parseJSON(xbody)) } }) }
7b13a9fda936503e476fd9a5aa5ac92146fdb5ed
backbone-once.js
backbone-once.js
(function(Backbone) { _.extend(Backbone.Events, { // Bind an event only once. When executed for the first time, it would // remove itself from the callbacks list. once: function(events, callback, context) { var boundOff = _.bind(this.off, this); var oneOffCallback = function() { boundOff(events, oneOffCallback); callback.apply(context, arguments); }; return this.on(events, oneOffCallback); } }); // Mix `Backbone.Events` again so our `once` method gets picked up. By the // time the classes first mixed `Backbone.Events`, it was not defined. _.each(['Model', 'Collection', 'Router', 'View', 'History'], function(kind) { _.extend(Backbone[kind].prototype, Backbone.Events); }); }).call(this, Backbone);
(function(Backbone) { _.extend(Backbone.Events, { // Bind an event only once. When executed for the first time, it would // remove itself from the callbacks list. once: function(events, callback, context) { var boundOff = _.bind(this.off, this); var oneOffCallback = _.once(function() { boundOff(events, oneOffCallback); callback.apply(context, arguments); }); return this.on(events, oneOffCallback, context); } }); // Mix `Backbone.Events` again so our `once` method gets picked up. By the // time the classes first mixed `Backbone.Events`, it was not defined. _.each(['Model', 'Collection', 'Router', 'View', 'History'], function(kind) { _.extend(Backbone[kind].prototype, Backbone.Events); }); }).call(this, Backbone);
Fix a multiple execution in event handlers
Fix a multiple execution in event handlers As a bonus, also bind to the context, even if not used, to allow the handler to be unbound using the context too.
JavaScript
mit
gsamokovarov/backbone-once
--- +++ @@ -6,12 +6,12 @@ // remove itself from the callbacks list. once: function(events, callback, context) { var boundOff = _.bind(this.off, this); - var oneOffCallback = function() { + var oneOffCallback = _.once(function() { boundOff(events, oneOffCallback); callback.apply(context, arguments); - }; + }); - return this.on(events, oneOffCallback); + return this.on(events, oneOffCallback, context); } });
bda47cb62117f4f29a7e633abaa01e06b21a100e
src/TodoApp/AddTodoForm.js
src/TodoApp/AddTodoForm.js
import React from 'react'; export default class AddTodoForm extends React.Component { static propTypes = { onSubmit: React.PropTypes.func.isRequired } render() { return ( <form onSubmit={this.handleSubmit}> <input type="text" ref="newTodo"></input> <input type="submit" value="Add"></input> </form> ); } handleSubmit = (event) => { event.preventDefault(); this.props.onSubmit(this.refs.newTodo.value); this.refs.newTodo.value = ''; } }
import React from 'react'; export default class AddTodoForm extends React.Component { static propTypes = { onSubmit: React.PropTypes.func.isRequired } render() { return ( <form onSubmit={this.handleSubmit}> <input type="text" ref="newTodo" style={style}></input> <input type="submit" value="Add"></input> </form> ); } handleSubmit = (event) => { event.preventDefault(); this.props.onSubmit(this.refs.newTodo.value); this.refs.newTodo.value = ''; } } const style = { width: '200px', marginRight: '5px' };
Make input wider and spaced out more
Make input wider and spaced out more
JavaScript
cc0-1.0
ksmithbaylor/react-todo-list,ksmithbaylor/react-todo-list
--- +++ @@ -8,7 +8,7 @@ render() { return ( <form onSubmit={this.handleSubmit}> - <input type="text" ref="newTodo"></input> + <input type="text" ref="newTodo" style={style}></input> <input type="submit" value="Add"></input> </form> ); @@ -20,3 +20,8 @@ this.refs.newTodo.value = ''; } } + +const style = { + width: '200px', + marginRight: '5px' +};
16ad51fa278a7c6751b204d04c18a0e5357beea9
tests/unit/services/json-schema-draft4/required-test.js
tests/unit/services/json-schema-draft4/required-test.js
// https://github.com/json-schema/JSON-Schema-Test-Suite/blob/develop/tests/draft4/required.json var scenerios = [ { "description": "required validation", "schema": { "properties": { "foo": {}, "bar": {} }, "required": ["foo"] }, "tests": [ { "description": "present required property is valid", "data": {"foo": 1}, "valid": true }, { "description": "non-present required property is invalid", "data": {"bar": 1}, "valid": false } ] }, { "description": "required default validation", "schema": { "properties": { "foo": {} } }, "tests": [ { "description": "not required by default", "data": {}, "valid": true } ] } ]; import { test } from 'ember-qunit'; import Schema from 'ember-cli-json-schema/schema'; scenerios.map(function(scenerio){ module(scenerio.description); scenerio.tests.map(function(_test){ test(_test.description, function() { var schema = Schema.create(); schema.load("test", scenerio.schema); var obj = schema.createObject("test", _test.data); equal(obj.get('isValid'), _test.valid); }); }); });
// https://github.com/json-schema/JSON-Schema-Test-Suite/blob/develop/tests/draft4/required.json var scenerios = [ { "description": "required validation", "schema": { "properties": { "foo": {}, "bar": {} }, "required": ["foo"] }, "tests": [ { "description": "present required property is valid", "data": {"foo": 1}, "valid": true }, { "description": "non-present required property is invalid", "data": {"bar": 1}, "valid": false } ] }, { "description": "required default validation", "schema": { "properties": { "foo": {} } }, "tests": [ { "description": "not required by default", "data": {}, "valid": true } ] } ]; import { test } from 'ember-qunit'; import Schema from 'ember-cli-json-schema/schema'; var schema = Schema.create(); scenerios.map(function(scenerio){ module(scenerio.description); scenerio.tests.map(function(_test){ test(_test.description, function() { schema.load("test", scenerio.schema); var obj = schema.createObject("test", _test.data); equal(obj.get('isValid'), _test.valid); }); }); });
Add actual image rather than link to travis
Add actual image rather than link to travis
JavaScript
mit
southpolesteve/ember-cli-json-schema,southpolesteve/ember-cli-json-schema
--- +++ @@ -43,11 +43,12 @@ import { test } from 'ember-qunit'; import Schema from 'ember-cli-json-schema/schema'; +var schema = Schema.create(); + scenerios.map(function(scenerio){ module(scenerio.description); scenerio.tests.map(function(_test){ test(_test.description, function() { - var schema = Schema.create(); schema.load("test", scenerio.schema); var obj = schema.createObject("test", _test.data); equal(obj.get('isValid'), _test.valid);
188677d8389f7b2082ecdb606273c34d23127a5c
app/packages/fraction-twitter/lib/tweetHot.next.js
app/packages/fraction-twitter/lib/tweetHot.next.js
'use strict'; if (process.env.NODE_ENV === 'production') { var Twit = Npm.require('twit'); var twitter = new Twit({ consumer_key: process.env.TWIT_KEY, consumer_secret: process.env.TWIT_SECRET, access_token: process.env.TWIT_TOKEN, access_token_secret: process.env.TWIT_TOKEN_SECRET }); var tweetHot = () => { var hot = Posts.find({}, { limit: 50, sort: { heat: -1 }, fields: { oldChildren: false } }).fetch(); var finished = false; _(hot).forEach((item) => { // it hasn't been tweeted yet if (finished === false && (typeof item.tweeted === 'undefined')) { twitter.post('statuses/update', { status: item.title + "\n" + 'http://beta.fraction.io/comments/' + item._id }, (err /*, response */) => { if (err) { throw err; } }); Posts.update({ _id: item._id }, { $set: { tweeted: true } }); console.log('Tweeting "' + item.title + '"'); finished = true; } }); }; //post a new link every 20 minutes Meteor.setInterval(tweetHot, 20 * 60 * 1000); }
'use strict'; if (process.env.NODE_ENV === 'production') { var Twit = Npm.require('twit'); var twitter = new Twit({ consumer_key: process.env.TWIT_KEY, consumer_secret: process.env.TWIT_SECRET, access_token: process.env.TWIT_TOKEN, access_token_secret: process.env.TWIT_TOKEN_SECRET }); var tweetHot = () => { var hot = Posts.find({}, { limit: 50, sort: { heat: -1 }, fields: { oldChildren: false } }).fetch(); var finished = false; _(hot).forEach((item) => { // it hasn't been tweeted yet if (finished === false && (typeof item.tweeted === 'undefined')) { twitter.post('statuses/update', { status: item.title + 'http://beta.fraction.io/comments/' + item._id }, (err /*, response */) => { if (err) { throw err; } }); Posts.update({ _id: item._id }, { $set: { tweeted: true } }); console.log('Tweeting "' + item.title + '"'); finished = true; } }); }; //post a new link every 20 minutes Meteor.setInterval(tweetHot, 20 * 60 * 1000); }
Remove line break in tweets
Remove line break in tweets
JavaScript
mit
rrevanth/news,rrevanth/news
--- +++ @@ -26,8 +26,7 @@ if (finished === false && (typeof item.tweeted === 'undefined')) { twitter.post('statuses/update', { - status: item.title + "\n" + - 'http://beta.fraction.io/comments/' + item._id + status: item.title + 'http://beta.fraction.io/comments/' + item._id }, (err /*, response */) => { if (err) { throw err;
a3b47d5bb732e920cba5f7bcddf3f15eab60c337
src/api-components/Sort.js
src/api-components/Sort.js
import React from 'react'; import { sort } from 'sajari'; import Base from './Base.js'; import Components from '../constants/QueryComponentConstants.js'; const Sort = props => { const { field, order, ...others } = props; return ( <Base {...others} runDefault='update' componentName={Components.SORT} data={sort(field, order)} /> ); }; Sort.propTypes = { field: React.PropTypes.string.isRequired, order: React.PropTypes.string.isRequired, }; export default Sort;
import React from 'react'; import { sort } from 'sajari'; import Base from './Base.js'; import Components from '../constants/QueryComponentConstants.js'; const Sort = props => { const { field, order, ...others } = props; return ( <Base {...others} runDefault='update' componentName={Components.SORT} data={sort(field)} /> ); }; Sort.propTypes = { field: React.PropTypes.string.isRequired, }; export default Sort;
Remove order prop from sort
Remove order prop from sort
JavaScript
mit
sajari/sajari-sdk-react,sajari/sajari-sdk-react
--- +++ @@ -11,14 +11,13 @@ {...others} runDefault='update' componentName={Components.SORT} - data={sort(field, order)} + data={sort(field)} /> ); }; Sort.propTypes = { field: React.PropTypes.string.isRequired, - order: React.PropTypes.string.isRequired, }; export default Sort;
4e48b29570a6b1b85492508f7e34656f130dc476
cli/Gulpfile.js
cli/Gulpfile.js
'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); gulp.task('default', ['lint', 'mocha']); gulp.task('test', ['default']); gulp.task('mocha', function () { return gulp.src('./tests/**/*.js', { read: false }) .pipe(mocha({ reporter: 'spec' })); }); gulp.task('lint', function() { return gulp.src(['./lib/**/*.js', './tests/**/*.js', 'Gulpfile.js']) .pipe(jshint()) .pipe(jshint.reporter('default')); });
'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); gulp.task('default', ['lint', 'mocha']); gulp.task('test', ['default']); gulp.task('mocha', function () { return gulp.src('./tests/**/*.js', { read: false }) .pipe(mocha({ reporter: 'spec' })); }); gulp.task('lint', function() { return gulp.src(['./lib/**/*.js', './tests/**/*.js', 'Gulpfile.js']) .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(jshint.reporter('fail')); });
Fix bug: gulp not failing on lint error
Fix bug: gulp not failing on lint error Without piping the results to the 'fail' reporter inside gulp the build won't fail if an error is introduced.
JavaScript
bsd-3-clause
luizbranco/torus-cli,manifoldco/torus-cli,manifoldco/torus-cli,luizbranco/torus-cli,luizbranco/torus-cli,manifoldco/torus-cli
--- +++ @@ -16,5 +16,6 @@ gulp.task('lint', function() { return gulp.src(['./lib/**/*.js', './tests/**/*.js', 'Gulpfile.js']) .pipe(jshint()) - .pipe(jshint.reporter('default')); + .pipe(jshint.reporter('default')) + .pipe(jshint.reporter('fail')); });
3a086bf6d4fbba72a9393c4d234d5462b5df68e8
header.js
header.js
// ==UserScript== // @name TPP Touchscreen Input Assist // @namespace chfoo/tppinputassist // @version 1.11.0 // @homepage https://github.com/chfoo/tppinputassist // @updateURL https://raw.githubusercontent.com/chfoo/tppinputassist/master/tppinputassist.user.js // @description Touchscreen coordinate tap overlay for inputting into Twitch chat // @author Christopher Foo // @match http://twitch.tv/* // @match http://www.twitch.tv/* // @match https://twitch.tv/* // @match https://www.twitch.tv/* // @grant none // ==/UserScript== /* jshint -W097 */ (function() {
// ==UserScript== // @name TPP Touchscreen Input Assist // @namespace chfoo/tppinputassist // @version 1.11.0 // @homepage https://github.com/chfoo/tppinputassist // @description Touchscreen coordinate tap overlay for inputting into Twitch chat // @author Christopher Foo // @match http://twitch.tv/* // @match http://www.twitch.tv/* // @match https://twitch.tv/* // @match https://www.twitch.tv/* // @grant none // ==/UserScript== /* jshint -W097 */ (function() {
Remove @updateURL to not override alternate hosted version.
Remove @updateURL to not override alternate hosted version. It wasn't even being used correctly. Blame the original Userscripts website tutorial.
JavaScript
mit
chfoo/tppinputassist,chfoo/tppinputassist
--- +++ @@ -3,7 +3,6 @@ // @namespace chfoo/tppinputassist // @version 1.11.0 // @homepage https://github.com/chfoo/tppinputassist -// @updateURL https://raw.githubusercontent.com/chfoo/tppinputassist/master/tppinputassist.user.js // @description Touchscreen coordinate tap overlay for inputting into Twitch chat // @author Christopher Foo // @match http://twitch.tv/*
af375c49371a00e42686c11bc055ed5234a2f596
tests/gtype-signal2.js
tests/gtype-signal2.js
#!/usr/bin/env seed // Returns: 0 // STDIN: // STDOUT:2 Weathermen // STDERR: Seed.import_namespace("GObject"); Seed.import_namespace("Gtk"); Gtk.init(null, null); HelloWindowType = { parent: Gtk.Window, name: "HelloWindow", class_init: function(klass, prototype) { var HelloSignalDefinition = {name: "hello", parameters: [GObject.TYPE_INT, GObject.TYPE_STRING]}; hello_signal_id = klass.install_signal(HelloSignalDefinition); }, } HelloWindow = new GType(HelloWindowType); w = new HelloWindow(); w.signal.hello.connect(function(object, number, string) {Seed.print(number+ " " + string)}); w.signal.hello.emit(2, "Weathermen");
#!/usr/bin/env seed // Returns: 0 // STDIN: // STDOUT:2 Weathermen\n\[object GtkWindow\] // STDERR: Seed.import_namespace("GObject"); Seed.import_namespace("Gtk"); Gtk.init(null, null); HelloWindowType = { parent: Gtk.Window, name: "HelloWindow", class_init: function(klass, prototype) { var HelloSignalDefinition = {name: "hello", parameters: [GObject.TYPE_INT, GObject.TYPE_STRING], return_type: GObject.TYPE_OBJECT}; hello_signal_id = klass.install_signal(HelloSignalDefinition); }, } HelloWindow = new GType(HelloWindowType); w = new HelloWindow(); w.signal.hello.connect(function(object, number, string) {Seed.print(number+ " " + string); return new Gtk.Window()}); Seed.print(w.signal.hello.emit(2, "Weathermen"));
Add test of defining a signal with a return type.
Add test of defining a signal with a return type. svn path=/trunk/; revision=233
JavaScript
lgpl-2.1
danilocesar/seed,danilocesar/seed,danilocesar/seed,danilocesar/seed,danilocesar/seed
--- +++ @@ -1,7 +1,7 @@ #!/usr/bin/env seed // Returns: 0 // STDIN: -// STDOUT:2 Weathermen +// STDOUT:2 Weathermen\n\[object GtkWindow\] // STDERR: Seed.import_namespace("GObject"); @@ -15,7 +15,8 @@ { var HelloSignalDefinition = {name: "hello", parameters: [GObject.TYPE_INT, - GObject.TYPE_STRING]}; + GObject.TYPE_STRING], + return_type: GObject.TYPE_OBJECT}; hello_signal_id = klass.install_signal(HelloSignalDefinition); @@ -26,7 +27,8 @@ w = new HelloWindow(); w.signal.hello.connect(function(object, number, string) - {Seed.print(number+ " " + string)}); + {Seed.print(number+ " " + string); + return new Gtk.Window()}); -w.signal.hello.emit(2, "Weathermen"); +Seed.print(w.signal.hello.emit(2, "Weathermen"));
9810b9950de6f7830c0557abefd3a12e0edaf148
brunch-config.js
brunch-config.js
exports.config = { npm: { enabled: true }, files: { javascripts: { joinTo: 'app.js' }, stylesheets: { joinTo: { 'app.css': /^app\/styles/ } } }, overrides: { production: { plugins: { postcss: { processors: [ require('autoprefixer'), require('cssnano') ] } } } }, plugins: { digest: { prependHost: { production: '/tasty-brunch' }, referenceFiles: /\.(css|html|js)$/ }, postcss: { processors: [ require('autoprefixer') ] }, sass: { options: { includePaths: ['node_modules'] } }, static: { processors: [ require('html-brunch-static')({ handlebars: { enableProcessor: true, helpers: { join (context, block) { return context.join(block.hash.delimiter) }, updated_time () { return new Date().toISOString() } } } }) ] } } }
exports.config = { files: { javascripts: { joinTo: 'app.js' }, stylesheets: { joinTo: { 'app.css': /^app\/styles/ } } }, overrides: { production: { plugins: { postcss: { processors: [ require('autoprefixer'), require('cssnano') ] } } } }, plugins: { digest: { prependHost: { production: '/tasty-brunch' }, referenceFiles: /\.(css|html|js)$/ }, postcss: { processors: [ require('autoprefixer') ] }, sass: { options: { includePaths: ['node_modules'] } }, static: { processors: [ require('html-brunch-static')({ handlebars: { enableProcessor: true, helpers: { join (context, block) { return context.join(block.hash.delimiter) }, updated_time () { return new Date().toISOString() } } } }) ] } } }
Remove npm from config (enabled by default)
Remove npm from config (enabled by default)
JavaScript
mit
makenew/tasty-brunch,makenew/tasty-brunch,rxlabs/tasty-todos,makenew/tasty-brunch,rxlabs/tasty-todos,rxlabs/tasty-todos
--- +++ @@ -1,8 +1,4 @@ exports.config = { - npm: { - enabled: true - }, - files: { javascripts: { joinTo: 'app.js'
c9f9444f3b7ad45cfffc6084de15a5c30796b264
DSA-Campaign-Uplift-Estimation/src/main/webapp/script.js
DSA-Campaign-Uplift-Estimation/src/main/webapp/script.js
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.
//Copyright 2020 Google LLC // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. function getLogsStatus() { fetch('/userapi').then(response => response.json()).then(logStatus => { const link = document.getElementById("login-link"); if(logStatus.Bool) { console.log('User is Logged In'); link.href = '../Home/home.html'; } else { console.log('User is not Logged In'); link.href = logStatus.Url; } }); }
Create new method for logging in
Create new method for logging in
JavaScript
apache-2.0
googleinterns/step51-2020,googleinterns/step51-2020,googleinterns/step51-2020,googleinterns/step51-2020,googleinterns/step51-2020
--- +++ @@ -1,13 +1,30 @@ -// Copyright 2019 Google LLC +//Copyright 2020 Google LLC // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at +//Licensed under the Apache License, Version 2.0 (the "License"); +//you may not use this file except in compliance with the License. +//You may obtain a copy of the License at // -// https://www.apache.org/licenses/LICENSE-2.0 +// https://www.apache.org/licenses/LICENSE-2.0 // -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +//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. + +function getLogsStatus() { + + fetch('/userapi').then(response => response.json()).then(logStatus => { + const link = document.getElementById("login-link"); + + if(logStatus.Bool) { + + console.log('User is Logged In'); + link.href = '../Home/home.html'; + } + else { + console.log('User is not Logged In'); + link.href = logStatus.Url; + } + }); +}
7bdd46cdf2128b65efb8b62e6d5cc5b9c6c3a9d5
src/constants/Endpoints.js
src/constants/Endpoints.js
import { PROD_PROJECT_ID } from '../secrets'; export const OPTIMIZELY_BASE_URL = 'https://www.optimizelyapis.com/experiment/v1/'; export const PROJECTS_URL = `${OPTIMIZELY_BASE_URL}projects/`; export const PROD_EXPERIMENTS_URL = `${PROJECTS_URL}${PROD_PROJECT_ID}/experiments/`; export const getResultsUrl = (experimentId) => `${OPTIMIZELY_BASE_URL}experiments/${experimentId}/results`;
import { PROD_PROJECT_ID } from '../secrets'; export const OPTIMIZELY_BASE_URL = 'https://www.optimizelyapis.com/experiment/v1/'; export const PROJECTS_URL = `${OPTIMIZELY_BASE_URL}projects/`; export const PROD_EXPERIMENTS_URL = `${PROJECTS_URL}${PROD_PROJECT_ID}/experiments/`; export const getResultsUrl = (experimentId) => `${OPTIMIZELY_BASE_URL}experiments/${experimentId}/stats`;
Change to use /stats instead of /results
Change to use /stats instead of /results
JavaScript
mit
zebogen/kapow-optimizely-dashboard,zebogen/kapow-optimizely-dashboard
--- +++ @@ -6,4 +6,4 @@ export const PROD_EXPERIMENTS_URL = `${PROJECTS_URL}${PROD_PROJECT_ID}/experiments/`; -export const getResultsUrl = (experimentId) => `${OPTIMIZELY_BASE_URL}experiments/${experimentId}/results`; +export const getResultsUrl = (experimentId) => `${OPTIMIZELY_BASE_URL}experiments/${experimentId}/stats`;
1cf9b5d0a0946057399b261e598080efe0f686a2
src/skinner/core/resolver.js
src/skinner/core/resolver.js
define (["lib/lodash", "lib/Handlebars", "src/skinner/core/keypath"], function (_, Handlebars, keyPath) { "use strict"; function resolveData(data, subject, additionalDimensionData, context) { var allContext = keyPath(subject, "condition", {}); if (!_.isUndefined(additionalDimensionData)) { allContext = _.extend({}, allContext, additionalDimensionData); } Handlebars.registerHelper("indexed", function (key) { return key[context]; }); function mapper(value) { console.log(value); if (_.isArray(value) || _.isObject(value)) { return resolveData(value, subject, additionalDimensionData, context); } else if (_.isString(value)) { var template = Handlebars.compile(value); return template(allContext); } else { return value; } } if (_.isArray(data)) { return _.map(data, mapper); } else { return _.mapValues(data, mapper); } } return { "resolveData": resolveData }; });
define (["lib/lodash", "lib/Handlebars", "src/skinner/core/keypath"], function (_, Handlebars, keyPath) { "use strict"; function resolveData(data, subject, additionalDimensionData, context) { var allContext = keyPath(subject, "condition", {}); if (!_.isUndefined(additionalDimensionData)) { allContext = _.extend({}, allContext, additionalDimensionData); } Handlebars.registerHelper("indexed", function (key) { return key[context]; }); function mapper(value) { if (_.isArray(value) || _.isObject(value)) { return resolveData(value, subject, additionalDimensionData, context); } else if (_.isString(value)) { var template = Handlebars.compile(value); return template(allContext); } else { return value; } } if (_.isArray(data)) { return _.map(data, mapper); } else { return _.mapValues(data, mapper); } } return { "resolveData": resolveData }; });
Remove a console log statement, so tests run without extraneous logging
Remove a console log statement, so tests run without extraneous logging
JavaScript
mit
dbachrach/skinner,dbachrach/skinner
--- +++ @@ -12,7 +12,6 @@ }); function mapper(value) { - console.log(value); if (_.isArray(value) || _.isObject(value)) { return resolveData(value, subject, additionalDimensionData, context); }
b733ed269de8dee5fd25cb4b273cc9963a21aa1d
examples/pagination/js/callbacks.js
examples/pagination/js/callbacks.js
// TODO
function displayPage(results) { $('#results tbody').empty(); for (let row of results) { let tr = $('<tr />'); for (let field of ['id', 'name', 'category', 'sub_category', 'container_type', 'price_per_unit', 'margin']) { tr.append($('<td />').text(row[field])); } $('#results tbody').append(tr); } } var cache = {}; function ajaxOrCached(query, page, handler) { if ([query, page] in cache) { return handler(cache[[query, page]]); } $.ajax({ 'url' : 'http://localhost:8080?q=' + query + '&page=' + page, 'dataType': 'json', 'success' : result => { cache[[query, page]] = result; handler(result) } }); } function showPage(query, page) { function handler(results) { $('.paging-control').addClass('enabled'); let prev = results.prev; let next = results.next; let list = results.results; displayPage(list); // NOTE: This is not equivalent to the arrows version. This // pre-fetching will not be canceled when the user interacts // with paging controls. ajaxOrCached(query, page, () => {}); const h1 = () => { $('#next').off('click', h2); showPage(query, prev); }; const h2 = () => { $('#prev').off('click', h1); showPage(query, next); }; $('#prev').one('click', h1); $('#next').one('click', h2); } $('.paging-control').addClass('disabled'); ajaxOrCached(query, page, handler); } var clicks = 0; $('#filter').keyup((ev) => { var expected = ++clicks; setTimeout(() => { if (expected != clicks) { return; } $('#prev').unbind('click'); $('#next').unbind('click'); showPage($(ev.target).val(), 1); }, 400); });
Add callback version of pagination.
Add callback version of pagination.
JavaScript
mit
efritz/arrows,JoshuaSCochrane/arrows
--- +++ @@ -1 +1,71 @@ -// TODO +function displayPage(results) { + $('#results tbody').empty(); + + for (let row of results) { + let tr = $('<tr />'); + for (let field of ['id', 'name', 'category', 'sub_category', 'container_type', 'price_per_unit', 'margin']) { + tr.append($('<td />').text(row[field])); + } + + $('#results tbody').append(tr); + } +} + +var cache = {}; + +function ajaxOrCached(query, page, handler) { + if ([query, page] in cache) { + return handler(cache[[query, page]]); + } + + $.ajax({ + 'url' : 'http://localhost:8080?q=' + query + '&page=' + page, + 'dataType': 'json', + 'success' : result => { + cache[[query, page]] = result; + handler(result) + } + }); +} + +function showPage(query, page) { + function handler(results) { + $('.paging-control').addClass('enabled'); + let prev = results.prev; + let next = results.next; + let list = results.results; + + displayPage(list); + + // NOTE: This is not equivalent to the arrows version. This + // pre-fetching will not be canceled when the user interacts + // with paging controls. + + ajaxOrCached(query, page, () => {}); + + const h1 = () => { $('#next').off('click', h2); showPage(query, prev); }; + const h2 = () => { $('#prev').off('click', h1); showPage(query, next); }; + + $('#prev').one('click', h1); + $('#next').one('click', h2); + } + + $('.paging-control').addClass('disabled'); + ajaxOrCached(query, page, handler); +} + +var clicks = 0; + +$('#filter').keyup((ev) => { + var expected = ++clicks; + setTimeout(() => { + if (expected != clicks) { + return; + } + + $('#prev').unbind('click'); + $('#next').unbind('click'); + + showPage($(ev.target).val(), 1); + }, 400); +});
d50634c9bf93893c82400e012c12841644c0d6a2
scripts/getBabelOptions.js
scripts/getBabelOptions.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ 'use strict'; module.exports = function(options) { options = Object.assign( { env: 'production', moduleMap: {}, plugins: [], }, options, ); const fbjsPreset = require('babel-preset-fbjs/configure')({ autoImport: options.autoImport || false, objectAssign: false, inlineRequires: true, stripDEV: options.env === 'production', }); // The module rewrite transform needs to be positioned relative to fbjs's // many other transforms. fbjsPreset.presets[0].plugins.push([ require('./rewrite-modules'), { map: Object.assign({}, require('fbjs/module-map'), options.moduleMap), }, ]); if (options.postPlugins) { fbjsPreset.presets.push({ plugins: options.postPlugins, }); } return { plugins: options.plugins.concat('transform-es2015-spread'), presets: [fbjsPreset], }; };
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @noformat */ 'use strict'; module.exports = function(options) { options = Object.assign( { env: 'production', moduleMap: {}, plugins: [], }, options ); const fbjsPreset = require('babel-preset-fbjs/configure')({ autoImport: options.autoImport || false, objectAssign: false, inlineRequires: true, stripDEV: options.env === 'production', }); // The module rewrite transform needs to be positioned relative to fbjs's // many other transforms. fbjsPreset.presets[0].plugins.push([ require('./rewrite-modules'), { map: Object.assign({}, require('fbjs/module-map'), options.moduleMap), }, ]); if (options.postPlugins) { fbjsPreset.presets.push({ plugins: options.postPlugins, }); } return { plugins: options.plugins.concat('transform-es2015-spread'), presets: [fbjsPreset], }; };
Fix CI for node 6
Fix CI for node 6 Summary: This file is executed without transforms so we can't have trailing commas in function calls until we drop node 6. Closes https://github.com/facebook/relay/pull/2424 Differential Revision: D7754622 Pulled By: kassens fbshipit-source-id: a3a54348cc4890616304c9ed5a739d4a92a9e305
JavaScript
mit
voideanvalue/relay,xuorig/relay,cpojer/relay,kassens/relay,xuorig/relay,xuorig/relay,wincent/relay,iamchenxin/relay,cpojer/relay,xuorig/relay,cpojer/relay,atxwebs/relay,josephsavona/relay,wincent/relay,dbslone/relay,iamchenxin/relay,voideanvalue/relay,xuorig/relay,yungsters/relay,voideanvalue/relay,wincent/relay,xuorig/relay,voideanvalue/relay,freiksenet/relay,zpao/relay,kassens/relay,kassens/relay,facebook/relay,yungsters/relay,freiksenet/relay,wincent/relay,facebook/relay,voideanvalue/relay,zpao/relay,atxwebs/relay,freiksenet/relay,wincent/relay,facebook/relay,zpao/relay,kassens/relay,voideanvalue/relay,wincent/relay,facebook/relay,josephsavona/relay,dbslone/relay,atxwebs/relay,iamchenxin/relay,kassens/relay,kassens/relay,facebook/relay,cpojer/relay,atxwebs/relay,facebook/relay,yungsters/relay,josephsavona/relay,iamchenxin/relay
--- +++ @@ -4,8 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * - * @format + * @noformat */ 'use strict'; @@ -17,7 +16,7 @@ moduleMap: {}, plugins: [], }, - options, + options ); const fbjsPreset = require('babel-preset-fbjs/configure')({
3f9ee727a59c00f955521b1c3f2137c9b901bce9
extension/keysocket-yandex-radio.js
extension/keysocket-yandex-radio.js
var playTarget = '.player-controls__play'; var nextTarget = '.button_round'; function onKeyPress(key) { if (key === NEXT) { var cards = document.querySelectorAll('.slider__item') var nextCard = cards[cards.length - 3]; console.log(nextCard); simulateClick(nextCard.querySelector(nextTarget)); } else if (key === PLAY) { simulateClick(document.querySelector(playTarget)); } }
var playTarget = '.player-controls__play'; var nextTarget = '.button_round'; function onKeyPress(key) { if (key === NEXT) { var nextCard = document.querySelector('.slider__item_next'); console.log(nextCard); simulateClick(nextCard.querySelectorAll(nextTarget)[2]); } else if (key === PLAY) { simulateClick(document.querySelector(playTarget)); } }
Fix issue with forward button at Yandex.Radio
Fix issue with forward button at Yandex.Radio
JavaScript
apache-2.0
feedbee/keysocket,feedbee/keysocket
--- +++ @@ -3,11 +3,10 @@ function onKeyPress(key) { if (key === NEXT) { - var cards = document.querySelectorAll('.slider__item') - var nextCard = cards[cards.length - 3]; - + var nextCard = document.querySelector('.slider__item_next'); + console.log(nextCard); - simulateClick(nextCard.querySelector(nextTarget)); + simulateClick(nextCard.querySelectorAll(nextTarget)[2]); } else if (key === PLAY) { simulateClick(document.querySelector(playTarget)); }
84746b5ce55292e85bdbbb031fff2712c8d40aee
scripts/cd-server.js
scripts/cd-server.js
// Continuous delivery server const { spawn } = require('child_process') const { resolve } = require('path') const { createServer } = require('http') const { urlencoded } = require('body-parser') const hostname = '127.0.0.1' const port = 80 const server = createServer((req, res) => { const { headers, method, url } = req // When a successful build has happened, kill the process, triggering a restart if (req.method === 'POST' && req.url === '/webhook') { // Send response res.statusCode = 200 res.end() let body = [] req .on('error', err => { console.error(err) }) .on('data', chunk => { body.push(chunk) }) .on('end', () => { req.body = Buffer.concat(body).toString() const data = urlencoded({ extended: true })(req) console.log(req.body.payload) if (req.body.payload) { const passed = req.body.payload.state == 'passed' const master = req.body.payload.branch == 'master' process.exit(0) } }) } res.statusCode = 404 res.end() }).listen(port)
// Continuous delivery server const { spawn } = require('child_process') const { resolve } = require('path') const { createServer } = require('http') const { urlencoded } = require('body-parser') const hostname = '127.0.0.1' const port = 80 const server = createServer((req, res) => { const { headers, method, url } = req // When a successful build has happened, kill the process, triggering a restart if (req.method === 'POST' && req.url === '/webhook') { // Send response res.statusCode = 200 res.end() let body = [] req .on('error', err => { console.error(err) }) .on('data', chunk => { body.push(chunk) }) .on('end', () => { req.body = Buffer.concat(body).toString() urlencoded({ extended: true })(req) console.log(req.body) if (req.body.payload) { const passed = req.body.payload.state == 'passed' const master = req.body.payload.branch == 'master' if (passed && master) { process.exit(0) } } }) } res.statusCode = 404 res.end() }).listen(port)
Add branch and state check on CD server.
Add branch and state check on CD server.
JavaScript
mit
jsonnull/jsonnull.com,jsonnull/jsonnull.com,jsonnull/jsonnull.com
--- +++ @@ -25,12 +25,14 @@ }) .on('end', () => { req.body = Buffer.concat(body).toString() - const data = urlencoded({ extended: true })(req) - console.log(req.body.payload) + urlencoded({ extended: true })(req) + console.log(req.body) if (req.body.payload) { const passed = req.body.payload.state == 'passed' const master = req.body.payload.branch == 'master' - process.exit(0) + if (passed && master) { + process.exit(0) + } } }) }
51a3c472ee6e4010971af1e7534ba6a5b2178abd
public/js/script.js
public/js/script.js
(function _bindPlanEvents () { 'use strict'; function getPlanContext (element) { var context = element.parentElement; if ('BODY' === context.tagName) { return null; } else if (context.classList.contains('plan')) { return context; } else { return getPlanContext(context); } } function savePlanPart (element, value) { var context = getPlanContext(element), name = element.name || element.dataset.name, data; if (context && name) { data = { _id: context.id }; data[ name ] = value; req = new XMLHttpRequest(); req.onload = function () { // TODO }; req.onerror = function () { // TODO }; req.open('POST', window.location, true); req.setRequestHeader('Content-Type', 'application/json'); req.send( JSON.stringify(data) ); } } document.addEventListener('focusout', function (event) { if (event.target.classList.contains('planEntries')) { savePlanPart(event.target, event.target.innerText.trim().split("\n")); } }); document.addEventListener('change', function (event) { if (event.target.name === 'draft') { savePlanPart(event.target, event.target.checked); getPlanContext(event.target).classList.toggle(event.target.name, event.target.checked); } }); }());
(function _bindPlanEvents () { 'use strict'; function getPlanContext (element) { var context = element.parentElement; if ('BODY' === context.tagName) { return null; } else if (context.classList.contains('plan')) { return context; } else { return getPlanContext(context); } } function savePlanPart (element, value) { var context = getPlanContext(element), name = element.name || element.dataset.name, data; if (context && name) { data = { _id: context.id }; data[ name ] = value; req = new XMLHttpRequest(); req.onload = function () { // TODO }; req.onerror = function () { // TODO }; req.open('POST', window.location, true); req.setRequestHeader('Content-Type', 'application/json'); req.send( JSON.stringify(data) ); } } document.addEventListener('focusout', function (event) { if (event.target.classList.contains('planEntries')) { savePlanPart(event.target, event.target.textContent.trim().split("\n")); } }); document.addEventListener('change', function (event) { if (event.target.name === 'draft') { savePlanPart(event.target, event.target.checked); getPlanContext(event.target).classList.toggle(event.target.name, event.target.checked); } }); }());
Use textContent instead of innerText
Use textContent instead of innerText
JavaScript
mit
marek-saji/standupper
--- +++ @@ -47,7 +47,7 @@ document.addEventListener('focusout', function (event) { if (event.target.classList.contains('planEntries')) { - savePlanPart(event.target, event.target.innerText.trim().split("\n")); + savePlanPart(event.target, event.target.textContent.trim().split("\n")); } });
5413c871f0d98e27515ee57e5a8a09fadaac11aa
lib/index.js
lib/index.js
/** * @param {mongoose.Schema} schema * @param {?Object=} options */ module.exports = exports = function constantPlugin(schema, options) { var validSchemaTypes = ['String', 'Number', 'Date', 'ObjectID']; function validateSchemaType(path, schemaType) { if (!~validSchemaTypes.indexOf(schemaType.instance)) { throw new Error('Cannot use constant in path ' + path + '.\nConstant can only be used with: ' + validSchemaTypes.join(', ')); } } /* Register validations. */ schema.eachPath(function (path, schemaType) { if (!schemaType.options.constant) return; validateSchemaType(path, schemaType); (function (path) { schemaType.validators.push( [ function () { if (this.isNew || !this.isSelected(path)) return; return !this.isModified(path); }, constantPlugin.ErrorMessages.ERRRESETCONST, 'constant plugin' ] ); })(path); }); }; exports.ErrorMessages = { ERRRESETCONST: 'Constant `{PATH}` cannot be changed.' };
var util = require('util'); /** * @param {mongoose.Schema} schema * @param {?Object=} options */ module.exports = exports = function constantPlugin(schema, options) { options = options || {}; options.ValidSchemaTypes = options.ValidSchemaTypes || ['String', 'Number', 'Date', 'ObjectID']; options.ErrorType = options.ErrorType || constantPlugin.ERROR_TYPE; function validateSchemaType(path, schemaType) { if (!~options.ValidSchemaTypes.indexOf(schemaType.instance)) throw new Error(util.format(constantPlugin.ErrorMessages.ERRINVALIDTYPE, path, schemaType.instance, options.ValidSchemaTypes.join(', '))); } /* Register validations. */ schema.eachPath(function (path, schemaType) { if (!schemaType.options.constant) return; validateSchemaType(path, schemaType); (function (path) { schemaType.validators.push([ function () { if (this.isNew || !this.isSelected(path)) return; return !this.isModified(path); }, constantPlugin.ErrorMessages.ERRCONSTRESET, options.ErrorType ]); })(path); }); }; exports.ErrorMessages = { ERRCONSTRESET: 'Constant `{PATH}` cannot be changed.', ERRINVALIDTYPE: 'Cannot use constant in path `%s` with type `%s`.\nConstant can only be used with: %s' }; exports.ERROR_TYPE = 'constant plugin';
Make valid schema types and validator error type configurable
Make valid schema types and validator error type configurable
JavaScript
isc
cakuki/mongoose-constant
--- +++ @@ -1,15 +1,19 @@ +var util = require('util'); + + /** * @param {mongoose.Schema} schema * @param {?Object=} options */ module.exports = exports = function constantPlugin(schema, options) { - var validSchemaTypes = ['String', 'Number', 'Date', 'ObjectID']; + options = options || {}; + options.ValidSchemaTypes = options.ValidSchemaTypes || ['String', 'Number', 'Date', 'ObjectID']; + options.ErrorType = options.ErrorType || constantPlugin.ERROR_TYPE; function validateSchemaType(path, schemaType) { - if (!~validSchemaTypes.indexOf(schemaType.instance)) { - throw new Error('Cannot use constant in path ' + path + '.\nConstant can only be used with: ' + - validSchemaTypes.join(', ')); - } + if (!~options.ValidSchemaTypes.indexOf(schemaType.instance)) + throw new Error(util.format(constantPlugin.ErrorMessages.ERRINVALIDTYPE, path, schemaType.instance, + options.ValidSchemaTypes.join(', '))); } /* Register validations. */ @@ -19,22 +23,24 @@ validateSchemaType(path, schemaType); (function (path) { - schemaType.validators.push( - [ - function () { - if (this.isNew || !this.isSelected(path)) - return; - return !this.isModified(path); - }, - constantPlugin.ErrorMessages.ERRRESETCONST, - 'constant plugin' - ] - ); + schemaType.validators.push([ + function () { + if (this.isNew || !this.isSelected(path)) + return; + return !this.isModified(path); + }, + constantPlugin.ErrorMessages.ERRCONSTRESET, + options.ErrorType + ]); })(path); }); }; exports.ErrorMessages = { - ERRRESETCONST: 'Constant `{PATH}` cannot be changed.' + ERRCONSTRESET: 'Constant `{PATH}` cannot be changed.', + ERRINVALIDTYPE: 'Cannot use constant in path `%s` with type `%s`.\nConstant can only be used with: %s' }; + + +exports.ERROR_TYPE = 'constant plugin';
867730d0855a81aa7b72118fc969932c37790cfb
packages/accounts/accounts_server.js
packages/accounts/accounts_server.js
/** * Sets the default permissions to new users */ Meteor.users.after.insert(function (userId, doc) { var userId = doc._id; if (orion.adminExists) { // if there is a admin created we will set the default roles. var defaultRoles = Options.get('defaultRoles'); Roles.addUserToRoles(userId, defaultRoles); } else { // If there is no admin, we will add the admin role to this new user. Roles.addUserToRoles(userId, 'admin'); // Pass to the client if the admin exists orion.adminExists = true; Inject.obj('adminExists', { exists: true }); } }); /** * Pass to the client if there is a admin account */ orion.adminExists = Roles._collection.find({ roles: 'admin' }).count() != 0; Inject.obj('adminExists', { exists: orion.adminExists });
/** * Sets the default permissions to new users */ Meteor.users.after.insert(function (userId, doc) { var userId = doc._id; if (orion.adminExists) { // if there is a admin created we will set the default roles. if (Roles._collection.find({ userId: userId }).count() == 0) { var defaultRoles = Options.get('defaultRoles'); Roles.addUserToRoles(userId, defaultRoles); } } else { // If there is no admin, we will add the admin role to this new user. Roles.addUserToRoles(userId, 'admin'); // Pass to the client if the admin exists orion.adminExists = true; Inject.obj('adminExists', { exists: true }); } }); /** * Pass to the client if there is a admin account */ orion.adminExists = Roles._collection.find({ roles: 'admin' }).count() != 0; Inject.obj('adminExists', { exists: orion.adminExists });
Set default roles only if user has no roles
Set default roles only if user has no roles
JavaScript
mit
kevohagan/orion,BudickDa/orion,justathoughtor2/orion,PEM--/orion,Citronnade/orion,mauricionr/orion,PEM--/orion,nabiltntn/orion,Citronnade/orion,orionjs/orion,BudickDa/orion,kevohagan/orion,jorisroling/orion,mauricionr/orion,justathoughtor2/orion,rwatts3/orion,rwatts3/orion,nabiltntn/orion,orionjs/orion,TedEwanchyna/orion,dgleba/orion,TedEwanchyna/orion,dgleba/orion,jorisroling/orion
--- +++ @@ -6,8 +6,11 @@ if (orion.adminExists) { // if there is a admin created we will set the default roles. - var defaultRoles = Options.get('defaultRoles'); - Roles.addUserToRoles(userId, defaultRoles); + + if (Roles._collection.find({ userId: userId }).count() == 0) { + var defaultRoles = Options.get('defaultRoles'); + Roles.addUserToRoles(userId, defaultRoles); + } } else { // If there is no admin, we will add the admin role to this new user. Roles.addUserToRoles(userId, 'admin');
935076aa1cb280bea1fe1ac9c49aa4c52108b820
commands/tell.js
commands/tell.js
var l10n_file = __dirname + '/../l10n/commands/tell.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { var message = args.split(''); var recipient = message.shift(); if (recipient) { player.sayL10n(l10n, 'YOU_TELL', recipient, message); players.eachIf( playerIsOnline, tellPlayer ); return; } player.sayL10n(l10n, 'NOTHING_TOLD'); return; } function tellPlayer (p){ if (recipient.getName() !== player.getName()) p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); } function playerIsOnline(p) { if (p) return (recipient.getName() === p.getName()); }; };
var l10n_file = __dirname + '/../l10n/commands/tell.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { var message = args.split(' '); var recipient = message.shift(); message = message.join(' '); if (recipient) { player.sayL10n(l10n, 'YOU_TELL', recipient, message); players.eachIf( playerIsOnline, tellPlayer ); return; } player.sayL10n(l10n, 'NOTHING_TOLD'); return; function tellPlayer(p) { if (recipient.getName() !== player.getName()) p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); } function playerIsOnline(p) { if (p) return (recipient.getName() === p.getName()); }; } };
Fix split/join and move functions so they can refer to recipient var.
Fix split/join and move functions so they can refer to recipient var.
JavaScript
mit
shawncplus/ranviermud,seanohue/ranviermud,seanohue/ranviermud
--- +++ @@ -4,13 +4,14 @@ exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { - var message = args.split(''); + var message = args.split(' '); var recipient = message.shift(); - + message = message.join(' '); + if (recipient) { player.sayL10n(l10n, 'YOU_TELL', recipient, message); players.eachIf( - playerIsOnline, + playerIsOnline, tellPlayer ); return; @@ -18,15 +19,18 @@ player.sayL10n(l10n, 'NOTHING_TOLD'); return; - } - function tellPlayer (p){ - if (recipient.getName() !== player.getName()) - p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); + + function tellPlayer(p) { + if (recipient.getName() !== player.getName()) + p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); } - function playerIsOnline(p) { - if (p) - return (recipient.getName() === p.getName()); - }; + function playerIsOnline(p) { + if (p) + return (recipient.getName() === p.getName()); + }; + + } + };
070cd9727bdb269a215b0dd087bb30c83fd3d5f5
commands/tell.js
commands/tell.js
var l10n_file = __dirname + '/../l10n/commands/tell.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { var message = args.split(' '); var recipient = message.shift(); message = message.join(' '); if (recipient) { player.sayL10n(l10n, 'YOU_TELL', recipient, message); players.eachIf( playerIsOnline, tellPlayer ); return; } player.sayL10n(l10n, 'NOTHING_TOLD'); return; function tellPlayer(p) { if (recipient.getName() !== player.getName()) p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); } function playerIsOnline(p) { if (p) return (recipient.getName() === p.getName()); }; } };
var l10n_file = __dirname + '/../l10n/commands/tell.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { var message = args.split(' '); var recipient = message.shift(); message = message.join(' '); if (recipient) { player.sayL10n(l10n, 'YOU_TELL', recipient, message); players.eachIf( playerIsOnline, tellPlayer ); return; } player.sayL10n(l10n, 'NOTHING_TOLD'); return; function tellPlayer(p) { if (recipient.toLowercase() !== player.getName().toLowercase()) p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); } function playerIsOnline(p) { if (p) return (recipient.getName() === p.getName()); }; } };
Fix conditional for recipient name/playername
Fix conditional for recipient name/playername
JavaScript
mit
seanohue/ranviermud,shawncplus/ranviermud,seanohue/ranviermud
--- +++ @@ -21,7 +21,7 @@ return; function tellPlayer(p) { - if (recipient.getName() !== player.getName()) + if (recipient.toLowercase() !== player.getName().toLowercase()) p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); }
7722859f57858f8567bb5ab82dfdc023b9470b50
server/privileges.js
server/privileges.js
BlogPosts.allow({ insert: Utils.constant(true), remove: Utils.constant(true), update: Utils.constant(true), });
BlogPosts.allow({ insert: anyoneLoggedIn, remove: onlyTheOwner, update: onlyTheOwner, }); // these documents can be only accessed with custom methods Published.deny({ insert: Utils.constant(true), remove: Utils.constant(true), update: Utils.constant(true), }); function anyoneLoggedIn(userId) { return !!userId; } function onlyTheOwner(userId, doc) { return !!userId && doc.createdBy === userId; }
Secure updates on BlogPost collection
Secure updates on BlogPost collection
JavaScript
mit
anticoders/blog,anticoders/blog,anticoders/blog
--- +++ @@ -1,9 +1,22 @@ BlogPosts.allow({ + insert: anyoneLoggedIn, + remove: onlyTheOwner, + update: onlyTheOwner, +}); +// these documents can be only accessed with custom methods + +Published.deny({ insert: Utils.constant(true), - remove: Utils.constant(true), - update: Utils.constant(true), }); + +function anyoneLoggedIn(userId) { + return !!userId; +} + +function onlyTheOwner(userId, doc) { + return !!userId && doc.createdBy === userId; +}
7b14081f1852c17167ea4295459f7514b234b5b6
server/userGarden.js
server/userGarden.js
'use strict'; const rethinkDB = require('rethinkdb'); const program = require('commander'); const UserDB = require('./UserDB'); const metrics = require('./metrics'); program .version('0.0.1') .option('-p, --port <n>', 'Port for WebSocket', parseInt) .option('-d, --dump <n>', 'Period for dump of user positions, sec', parseInt) .option('-d, --dbname [name]', 'Name of world database') .parse(process.argv); if (require.main === module) { const m = new metrics.Metrics(5000); m.runMeasures(); rethinkDB.connect( {host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; const userDB = new UserDB.UserDB( conn, program.dbname, program.dump, program.port, 100 // location size ); userDB.run(); }); }
'use strict'; const rethinkDB = require('rethinkdb'); const program = require('commander'); const UserDB = require('./UserDB'); const metrics = require('./metrics'); program .version('0.0.1') .option('-p, --port <n>', 'Port for WebSocket', parseInt) .option('-d, --dump <n>', 'Period for dump of user positions, sec', parseInt) .option('-d, --dbname [name]', 'Name of world database') .parse(process.argv); if (program.dump === undefined) { program.dump = 60; } if (require.main === module) { const m = new metrics.Metrics(5000); m.runMeasures(); rethinkDB.connect( {host: 'localhost', port: 28015}, function(err, conn) { if (err) throw err; const userDB = new UserDB.UserDB( conn, program.dbname, program.dump, program.port, 100 // location size ); userDB.run(); }); }
Add default value for period of dump.
Add default value for period of dump.
JavaScript
mit
nobus/Labyrinth,nobus/Labyrinth
--- +++ @@ -14,6 +14,9 @@ .option('-d, --dbname [name]', 'Name of world database') .parse(process.argv); +if (program.dump === undefined) { + program.dump = 60; +} if (require.main === module) { const m = new metrics.Metrics(5000);
42a291286b4627191a18e8848dffee0bf5574c93
settings/js/admin.js
settings/js/admin.js
$(document).ready(function(){ $('#loglevel').change(function(){ $.post(OC.filePath('settings','ajax','setloglevel.php'), { level: $(this).val() },function(){ OC.Log.reload(); } ); }); $('#backgroundjobs input').change(function(){ if($(this).attr('checked')){ var mode = $(this).val(); if (mode == 'ajax' || mode == 'webcron' || mode == 'cron') { OC.AppConfig.setValue('core', 'backgroundjobs_mode', mode); } } }); $('#shareAPIEnabled').change(function() { $('.shareAPI td:not(#enable)').toggle(); }); $('#shareAPI input').change(function() { if ($(this).attr('type') == 'radio') { console.log('radio'); } if ($(this).attr('type') == 'checkbox') { console.log('checked'); } OC.AppConfig.setValue('core', 'shareapi_', $(this).val()); }); });
$(document).ready(function(){ $('#loglevel').change(function(){ $.post(OC.filePath('settings','ajax','setloglevel.php'), { level: $(this).val() },function(){ OC.Log.reload(); } ); }); $('#backgroundjobs input').change(function(){ if($(this).attr('checked')){ var mode = $(this).val(); if (mode == 'ajax' || mode == 'webcron' || mode == 'cron') { OC.AppConfig.setValue('core', 'backgroundjobs_mode', mode); } } }); $('#shareAPIEnabled').change(function() { $('.shareAPI td:not(#enable)').toggle(); }); $('#shareAPI input').change(function() { if ($(this).attr('type') == 'checkbox') { if (this.checked) { var value = 'yes'; } else { var value = 'no'; } } else { var value = $(this).val() } OC.AppConfig.setValue('core', $(this).attr('name'), value); }); });
Fix incorrect Javascript for changing Share API settings
Fix incorrect Javascript for changing Share API settings
JavaScript
agpl-3.0
pmattern/server,pmattern/server,lrytz/core,pixelipo/server,owncloud/core,nextcloud/server,bluelml/core,owncloud/core,Ardinis/server,bluelml/core,phil-davis/core,michaelletzgus/nextcloud-server,pixelipo/server,cernbox/core,Ardinis/server,endsguy/server,pollopolea/core,IljaN/core,cernbox/core,IljaN/core,bluelml/core,whitekiba/server,pixelipo/server,nextcloud/server,Ardinis/server,owncloud/core,michaelletzgus/nextcloud-server,owncloud/core,whitekiba/server,pixelipo/server,lrytz/core,IljaN/core,nextcloud/server,cernbox/core,pollopolea/core,bluelml/core,whitekiba/server,pmattern/server,andreas-p/nextcloud-server,endsguy/server,pollopolea/core,andreas-p/nextcloud-server,lrytz/core,Ardinis/server,IljaN/core,jbicha/server,sharidas/core,pmattern/server,jbicha/server,lrytz/core,endsguy/server,Ardinis/server,xx621998xx/server,pollopolea/core,cernbox/core,endsguy/server,pollopolea/core,xx621998xx/server,xx621998xx/server,xx621998xx/server,nextcloud/server,cernbox/core,sharidas/core,sharidas/core,pixelipo/server,sharidas/core,owncloud/core,lrytz/core,xx621998xx/server,pmattern/server,jbicha/server,jbicha/server,whitekiba/server,michaelletzgus/nextcloud-server,michaelletzgus/nextcloud-server,bluelml/core,andreas-p/nextcloud-server,jbicha/server,IljaN/core,sharidas/core,endsguy/server,andreas-p/nextcloud-server,andreas-p/nextcloud-server,whitekiba/server
--- +++ @@ -19,12 +19,15 @@ }); $('#shareAPI input').change(function() { - if ($(this).attr('type') == 'radio') { - console.log('radio'); - } if ($(this).attr('type') == 'checkbox') { - console.log('checked'); + if (this.checked) { + var value = 'yes'; + } else { + var value = 'no'; + } + } else { + var value = $(this).val() } - OC.AppConfig.setValue('core', 'shareapi_', $(this).val()); + OC.AppConfig.setValue('core', $(this).attr('name'), value); }); });
72d6da5a3550976deba5cc245f5d3b88f770cf4d
lib/utils.js
lib/utils.js
var fs = require('fs'), expandHomeDir = require('expand-home-dir'), async = require('async') ; function readFile(fileLocation, cb) { fs.readFile(fileLocation, {encoding: 'utf8'}, function (err, fileContents) { if (err) { cb(err); return; } cb(null, fileContents); }); } function loadConfigs(configLocations, cb) { async.map(configLocations, function (configLocation, cb) { var absoluteConfigLocation = expandHomeDir(configLocation); fs.exists(absoluteConfigLocation, function (exists) { if (exists) { readFile(absoluteConfigLocation, function (err, rawConfig) { if (err) { console.log("Unable to read config from: ", absoluteConfigLocation); cb(null, {}); return; } try { cb(null, JSON.parse(rawConfig)); } catch (err) { console.log("Unable to parse config from: ", absoluteConfigLocation); } }); } else { cb(null, {}); } }); }, function (err, results) { cb(results); }); } module.exports.readFile = readFile; module.exports.loadConfigs = loadConfigs;
var fs = require('fs'), expandHomeDir = require('expand-home-dir'), async = require('async') ; function readFile(fileLocation, cb) { fs.stat(fileLocation, function (stats) { if (stats.size > Math.pow(1024, 2) || !stats.isFile()) { cb(new Error('File ' + fileLocation + ' too large or not an ordinary file!')); } else { fs.readFile(fileLocation, {encoding: 'utf8'}, function (err, fileContents) { if (err) { cb(err); return; } cb(null, fileContents); }); } }); } function loadConfigs(configLocations, cb) { async.map(configLocations, function (configLocation, cb) { var absoluteConfigLocation = expandHomeDir(configLocation); fs.exists(absoluteConfigLocation, function (exists) { if (exists) { readFile(absoluteConfigLocation, function (err, rawConfig) { if (err) { console.log("Unable to read config from: ", absoluteConfigLocation); cb(null, {}); return; } try { cb(null, JSON.parse(rawConfig)); } catch (err) { console.log("Unable to parse config from: ", absoluteConfigLocation); } }); } else { cb(null, {}); } }); }, function (err, results) { cb(results); }); } module.exports.readFile = readFile; module.exports.loadConfigs = loadConfigs;
Check whether read file is actually a file, and if it's not too big.
Check whether read file is actually a file, and if it's not too big.
JavaScript
mit
dice-cyfronet/hyperflow-client,dice-cyfronet/hyperflow-client
--- +++ @@ -4,12 +4,18 @@ ; function readFile(fileLocation, cb) { - fs.readFile(fileLocation, {encoding: 'utf8'}, function (err, fileContents) { - if (err) { - cb(err); - return; + fs.stat(fileLocation, function (stats) { + if (stats.size > Math.pow(1024, 2) || !stats.isFile()) { + cb(new Error('File ' + fileLocation + ' too large or not an ordinary file!')); + } else { + fs.readFile(fileLocation, {encoding: 'utf8'}, function (err, fileContents) { + if (err) { + cb(err); + return; + } + cb(null, fileContents); + }); } - cb(null, fileContents); }); }
f5b2a9545d57b687b3f3726db255a29a47a5df07
src/global/routers/netinfo.js
src/global/routers/netinfo.js
/* jshint node: true */ /** * Wake Up Platform * (c) Telefonica Digital, 2014 - All rights reserved * License: GNU Affero V3 (see LICENSE file) * Fernando Rodríguez Sela <frsela at tid dot es> * Guillermo López Leal <gll at tid dot es> */ var log = require('../shared_libs/logger'); module.exports.info = { name: 'netInfo', type: 'router', virtualpath: 'netinfo/v1', description: 'Returns a JSON with the MCC-MNC networks and state' }; module.exports.entrypoint = function netInfo(parsedURL, body, req, res) { res.setHeader('Content-Type', 'application/json'); res.statusCode = 200; res.write(JSON.stringify(process.netinfo || {})); };
/* jshint node: true */ /** * Wake Up Platform * (c) Telefonica Digital, 2014 - All rights reserved * License: GNU Affero V3 (see LICENSE file) * Fernando Rodríguez Sela <frsela at tid dot es> * Guillermo López Leal <gll at tid dot es> */ var log = require('../shared_libs/logger'), mn = require('../../common/libs/mobile_networks.js'); module.exports.info = { name: 'netInfo', type: 'router', virtualpath: 'netinfo/v1', description: 'Returns a JSON with the MCC-MNC networks and state' }; module.exports.entrypoint = function netInfo(parsedURL, body, req, res) { res.setHeader('Content-Type', 'application/json'); res.statusCode = 200; res.write(JSON.stringify(mn.getNetworkStatuses() || {})); };
Use Mobile Network module to fetch network statuses data
Use Mobile Network module to fetch network statuses data
JavaScript
agpl-3.0
telefonicaid/wakeup_platform_global,telefonicaid/wakeup_platform_global
--- +++ @@ -7,7 +7,8 @@ * Guillermo López Leal <gll at tid dot es> */ -var log = require('../shared_libs/logger'); +var log = require('../shared_libs/logger'), + mn = require('../../common/libs/mobile_networks.js'); module.exports.info = { name: 'netInfo', @@ -19,5 +20,5 @@ module.exports.entrypoint = function netInfo(parsedURL, body, req, res) { res.setHeader('Content-Type', 'application/json'); res.statusCode = 200; - res.write(JSON.stringify(process.netinfo || {})); + res.write(JSON.stringify(mn.getNetworkStatuses() || {})); };
2eebdd3b129adbaf661c6a6a5e18c5329f4b6311
liphte.ts.js
liphte.ts.js
var fs = require('fs'); var vm = require('vm'); var includeInThisContext = function(path) { var code = fs.readFileSync(path); vm.runInThisContext(code, path); }.bind(this); includeInThisContext("dist/liphte.min.js"); exports.liphte = liphte;
var fs = require('fs'); var vm = require('vm'); var includeInThisContext = function(path) { var code = fs.readFileSync(path); vm.runInThisContext(code, path); }.bind(this); includeInThisContext(__dirname+"/dist/liphte.min.js"); exports.liphte = liphte;
Fix module for NodeJS - apped_dir_name
Fix module for NodeJS - apped_dir_name
JavaScript
mit
maveius/liphte.ts,maveius/liphte.ts
--- +++ @@ -4,5 +4,5 @@ var code = fs.readFileSync(path); vm.runInThisContext(code, path); }.bind(this); -includeInThisContext("dist/liphte.min.js"); +includeInThisContext(__dirname+"/dist/liphte.min.js"); exports.liphte = liphte;
1ffcd46beb7659fa314c6ea799991d6320c828e1
spec/bind_to_spec.js
spec/bind_to_spec.js
var vows = require('vows') , assert = require('assert') , Glue = require(__dirname + "/../lib/glue"); var suite = vows.describe('bindTo') suite.addBatch({ "ensures": { "that the target object of glue is changed": function() { var topic = new Glue({an: "object"}); topic.bindTo({another: "object"}); assert.notDeepEqual(topic.topic, {an: "object"}); assert.deepEqual(topic.target, {another: "object"}); }, "notifies listeners with the old and new target object": function() { var topic = new Glue({an: "object"}) , message = {}; topic.addListener('target', function(msg) { message = msg; }); topic.bindTo({ another: "object" }); assert.deepEqual(message, { oldTarget: { an: "object" } , newTarget: { another: "object" } }); this.target = { an: "object" }; //reset }, "executes a callback if available": function() { var topic = new Glue({an: "object"}) , invoked = false; topic.bindTo({}, function() { invoked = true; }); assert.equal(invoked, true); }, "when invoked, returns itself for chainability": function() { var topic = new Glue({an: "object"}); var returnedValue = topic.addListener(function(){}); assert.equal(topic, returnedValue); } } }); suite.export(module);
var vows = require('vows') , assert = require('assert') , Glue = require(__dirname + "/../lib/glue"); var suite = vows.describe('bindTo') suite.addBatch({ "ensures": { topic: new Glue({}), "that the target object of glue is changed": function(topic) { topic.target = {}; topic.bindTo({an: "object"}); assert.notDeepEqual(topic.topic, {}); assert.deepEqual(topic.target, {an: "object"}); }, "notifies listeners with the old and new target object": function(topic) { var message = {}; topic.target = {}; topic.addListener('target', function(msg) { message = msg; }); topic.bindTo({ an: "object" }); assert.deepEqual(message, { oldTarget: {} , newTarget: { an: "object" } }); this.target = { an: "object" }; //reset }, "executes a callback if available": function(topic) { var invoked = false; topic.target = {}; topic.bindTo({an: "object"}, function() { invoked = true; }); assert.equal(invoked, true); }, "when invoked, returns itself for chainability": function(topic) { var returnedValue = topic.addListener(function(){}); assert.equal(topic, returnedValue); } } }); suite.export(module);
Refactor bind_to spec to better performance
Refactor bind_to spec to better performance
JavaScript
mit
edgecase/glue.js
--- +++ @@ -6,47 +6,49 @@ suite.addBatch({ "ensures": { - "that the target object of glue is changed": function() { - var topic = new Glue({an: "object"}); + topic: new Glue({}), - topic.bindTo({another: "object"}); + "that the target object of glue is changed": function(topic) { + topic.target = {}; - assert.notDeepEqual(topic.topic, {an: "object"}); - assert.deepEqual(topic.target, {another: "object"}); + topic.bindTo({an: "object"}); + + assert.notDeepEqual(topic.topic, {}); + assert.deepEqual(topic.target, {an: "object"}); }, - "notifies listeners with the old and new target object": function() { - var topic = new Glue({an: "object"}) - , message = {}; + "notifies listeners with the old and new target object": function(topic) { + var message = {}; + + topic.target = {}; topic.addListener('target', function(msg) { message = msg; }); - topic.bindTo({ another: "object" }); + topic.bindTo({ an: "object" }); assert.deepEqual(message, { - oldTarget: { an: "object" } - , newTarget: { another: "object" } + oldTarget: {} + , newTarget: { an: "object" } }); this.target = { an: "object" }; //reset }, - "executes a callback if available": function() { - var topic = new Glue({an: "object"}) - , invoked = false; + "executes a callback if available": function(topic) { + var invoked = false; - topic.bindTo({}, function() { + topic.target = {}; + + topic.bindTo({an: "object"}, function() { invoked = true; }); assert.equal(invoked, true); }, - "when invoked, returns itself for chainability": function() { - var topic = new Glue({an: "object"}); - + "when invoked, returns itself for chainability": function(topic) { var returnedValue = topic.addListener(function(){}); assert.equal(topic, returnedValue); }
af4aa45ca05de249b4dc4bee0271c47cc838ddac
src/bot/helpers/incomes.js
src/bot/helpers/incomes.js
import { get } from 'lodash'; import { calculateCurrentEvents } from '../../lib/events'; import { getEbudgie } from './ebudgie'; export const showMontlyIncomesAmount = async (page_scoped_id, reply) => { try { const ebudgie = await getEbudgie(page_scoped_id, reply); if (!ebudgie) { return; } const incomes = get(ebudgie, 'incomes', []); const currency = get(ebudgie, 'currency', '$'); const amount = calculateCurrentEvents(incomes); await reply({ text: `Your current salary is: ${amount}${currency}` }); } catch (e) { console.log('Error during showing salary', e); await reply({ text: 'Something went wrong. Please try again.' }); } };
import { get } from 'lodash'; import { calculateCurrentEvents } from '../../lib/events'; import { getEbudgie } from './ebudgie'; export const showMonthlyIncomesAmount = async (page_scoped_id, reply) => { try { const ebudgie = await getEbudgie(page_scoped_id, reply); if (!ebudgie) { return; } const incomes = get(ebudgie, 'incomes', []); const currency = get(ebudgie, 'currency', '$'); const amount = calculateCurrentEvents(incomes); await reply({ text: `Your current salary is: ${amount}${currency}` }); } catch (e) { console.log('Error during showing salary', e); await reply({ text: 'Something went wrong. Please try again.' }); } };
FIx the typo of showMonthlyIncomesAmount
FIx the typo of showMonthlyIncomesAmount
JavaScript
mit
nikolay-radkov/ebudgie-server,nikolay-radkov/ebudgie-server
--- +++ @@ -3,7 +3,7 @@ import { calculateCurrentEvents } from '../../lib/events'; import { getEbudgie } from './ebudgie'; -export const showMontlyIncomesAmount = async (page_scoped_id, reply) => { +export const showMonthlyIncomesAmount = async (page_scoped_id, reply) => { try { const ebudgie = await getEbudgie(page_scoped_id, reply);
168c9b47763e30982a47c4c1fed683f31788d098
src/ipfs-access-controller.js
src/ipfs-access-controller.js
'use strict' const AccessController = require('./access-controller') const { DAGNode } = require('ipld-dag-pb') class IPFSAccessController extends AccessController { constructor (ipfs) { super() this._ipfs = ipfs } async load (address) { // Transform '/ipfs/QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' // to 'QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' if (address.indexOf('/ipfs') === 0) address = address.split('/')[2] try { const dag = await this._ipfs.object.get(address) const obj = JSON.parse(dag.toJSON().data) this._access = obj } catch (e) { console.log("ACCESS ERROR:", e) } } async save (onlyHash) { let hash try { const access = JSON.stringify(this._access, null, 2) let dag if (onlyHash) { dag = await new Promise(resolve => { DAGNode.create(Buffer.from(access), (err, n) => { resolve(n) }) }) } else { dag = await this._ipfs.object.put(new Buffer(access)) } hash = dag.toJSON().multihash.toString() } catch (e) { console.log("ACCESS ERROR:", e) } return hash } } module.exports = IPFSAccessController
'use strict' const AccessController = require('./access-controller') const { DAGNode } = require('ipld-dag-pb') class IPFSAccessController extends AccessController { constructor (ipfs) { super() this._ipfs = ipfs } async load (address) { // Transform '/ipfs/QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' // to 'QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' if (address.indexOf('/ipfs') === 0) address = address.split('/')[2] try { const dag = await this._ipfs.object.get(address) const obj = JSON.parse(dag.toJSON().data) this._access = obj } catch (e) { console.log("ACCESS ERROR:", e) } } async save (onlyHash) { let hash try { const access = JSON.stringify(this._access, null, 2) let dag if (onlyHash) { dag = await new Promise(resolve => { DAGNode.create(Buffer.from(access), (err, n) => { if (err) { throw err } resolve(n) }) }) } else { dag = await this._ipfs.object.put(new Buffer(access)) } hash = dag.toJSON().multihash.toString() } catch (e) { console.log("ACCESS ERROR:", e) } return hash } } module.exports = IPFSAccessController
Throw error returned from DAGNode.create in access controller
Throw error returned from DAGNode.create in access controller
JavaScript
mit
haadcode/orbit-db,orbitdb/orbit-db,orbitdb/orbit-db,haadcode/orbit-db
--- +++ @@ -32,7 +32,12 @@ let dag if (onlyHash) { dag = await new Promise(resolve => { - DAGNode.create(Buffer.from(access), (err, n) => { resolve(n) }) + DAGNode.create(Buffer.from(access), (err, n) => { + if (err) { + throw err + } + resolve(n) + }) }) } else { dag = await this._ipfs.object.put(new Buffer(access))
f22a82b87463a0abf802af582d52b89520433e46
models/users_model.js
models/users_model.js
import mongoose, { Schema } from 'mongoose'; const userSchema = new Schema({ first_name: { type: String, required: true }, last_name: { type: String, required: true }, email: { type: String, unique: true, required: true }, username: { type: String, unique: true, required: true }, password: { type: String, required: true }, status: { type: String, enum: ['user', 'admin'], required: true }, created_at: { type: Number, default: Date.now, required: true } }); export default mongoose.model('User', userSchema);
import mongoose, { Schema } from 'mongoose'; const userSchema = new Schema({ first_name: { type: String, required: true }, last_name: { type: String, required: true }, email: { type: String, unique: true, required: true }, username: { type: String, unique: true, required: true }, password: { type: String, required: true }, status: { type: String, enum: ['user'], required: true }, created_at: { type: Number, default: Date.now, required: true } }); export default mongoose.model('User', userSchema);
Remove admin privilege from users model for security
Remove admin privilege from users model for security
JavaScript
mit
davidlamt/antfinder-api
--- +++ @@ -6,7 +6,7 @@ email: { type: String, unique: true, required: true }, username: { type: String, unique: true, required: true }, password: { type: String, required: true }, - status: { type: String, enum: ['user', 'admin'], required: true }, + status: { type: String, enum: ['user'], required: true }, created_at: { type: Number, default: Date.now, required: true } });
caa4e2071ae26d012a71eeae77b72cc60bcfe2e1
src/content/shorten-url.js
src/content/shorten-url.js
import fetchJsonP from 'fetch-jsonp'; import queryString from 'query-string'; import url from 'url'; export default function shortenURL(urlToShorten) { let longURL = urlToShorten; if (!longURL.startsWith('https://perf-html.io/')) { const parsedURL = url.parse(longURL); const parsedURLOnCanonicalHost = Object.assign({}, parsedURL, { protocol: 'https:', host: 'perf-html.io', }); longURL = url.format(parsedURLOnCanonicalHost); } const bitlyQueryURL = 'https://api-ssl.bitly.com/v3/shorten?' + queryString.stringify({ 'longUrl': longURL, 'domain': 'perfht.ml', 'access_token': 'b177b00a130faf3ecda6960e8b59fde73e902422', }); return fetchJsonP(bitlyQueryURL).then(response => response.json()).then(json => json.data.url); }
import fetchJsonP from 'fetch-jsonp'; import queryString from 'query-string'; import url from 'url'; export default function shortenURL(urlToShorten) { let longURL = urlToShorten; if (!longURL.startsWith('https://perf-html.io/')) { const parsedURL = url.parse(longURL); const parsedURLOnCanonicalHost = Object.assign({}, parsedURL, { protocol: 'https:', host: 'perf-html.io', }); longURL = url.format(parsedURLOnCanonicalHost); } const bitlyQueryURL = 'https://api-ssl.bitly.com/v3/shorten?' + queryString.stringify({ 'longUrl': longURL, 'domain': 'perfht.ml', 'format': 'json', 'access_token': 'b177b00a130faf3ecda6960e8b59fde73e902422', }); return fetchJsonP(bitlyQueryURL).then(response => response.json()).then(json => json.data.url); }
Add missing 'format' key in the bit.ly API request.
Add missing 'format' key in the bit.ly API request. Bit.ly have recently made a change on their side to ignore the jsonp callback argument if format=json was not specified, and that made our requests fail.
JavaScript
mpl-2.0
devtools-html/perf.html,mstange/cleopatra,squarewave/bhr.html,mstange/cleopatra,squarewave/bhr.html,devtools-html/perf.html
--- +++ @@ -17,6 +17,7 @@ queryString.stringify({ 'longUrl': longURL, 'domain': 'perfht.ml', + 'format': 'json', 'access_token': 'b177b00a130faf3ecda6960e8b59fde73e902422', }); return fetchJsonP(bitlyQueryURL).then(response => response.json()).then(json => json.data.url);
707ab3e66fb6f27a4e6d7e8165b229c3deea8140
client/src/components/SmallSave/styled.js
client/src/components/SmallSave/styled.js
import styled from 'styled-components'; export const Save = styled.div` align-items: center; display: flex; flex-direction: row; justify-content: center; padding: 8px; &:hover { color: #000; } `; export const Bookmark = styled.span` color: ${props => (props.saved ? '#04d092' : '#bbb')}; line-height: 12px; margin-left: 6px; width: 8px; & > .fa { font-size: 12px; } ${Save}:hover & { color: #04d092; } `;
import styled from 'styled-components'; export const Save = styled.div` align-items: center; display: flex; flex-direction: row; justify-content: center; padding: 8px; &:hover { color: #000; } `; export const Bookmark = styled.span` color: ${props => (props.saved ? '#04d092' : '#bbb')}; line-height: 12px; margin-left: 6px; pointer-events: none; width: 8px; & > .fa { font-size: 12px; } ${Save}:hover & { color: #04d092; } `;
Remove pointer events from bookmark symbol
Remove pointer events from bookmark symbol
JavaScript
mit
jenovs/bears-team-14,jenovs/bears-team-14
--- +++ @@ -16,6 +16,7 @@ color: ${props => (props.saved ? '#04d092' : '#bbb')}; line-height: 12px; margin-left: 6px; + pointer-events: none; width: 8px; & > .fa {
c47e5906cd53d9348df05194c511cc5a0c020b8e
routes/index.js
routes/index.js
const router = require('express').Router() // eslint-disable-line new-cap const website = require('../data/website') /* GET API */ router.get('/api', (req, res) => { res.json(website) }) /* GET home page */ router.get('/', (req, res) => { res.render('index', { title: website.author.name, description: website.description, projects: website.included.projects, author: website.author, isHome: true }) }) /* GET any HTML pages */ router.get('/:page', (req, res) => { res.render(req.params.page, { title: `${website.author.name} | ${req.params.page}`, description: website.description, author: website.author.name, isHome: false }) }) module.exports = router
const router = require('express').Router() // eslint-disable-line new-cap const website = require('../data/website') /* GET API */ router.get('/api', (req, res) => { res.json(website) }) /* GET home page */ router.get('/', (req, res) => { res.render('index', { title: website.author.name, description: website.description, author: website.author, isHome: true }) }) /* GET any HTML pages */ router.get('/:page', (req, res) => { res.render(req.params.page, { title: `${website.author.name} | ${req.params.page}`, description: website.description, author: website.author.name, isHome: false }) }) module.exports = router
Remove projects data from API
Remove projects data from API
JavaScript
mit
mlcdf/website,mlcdf/website
--- +++ @@ -12,7 +12,6 @@ res.render('index', { title: website.author.name, description: website.description, - projects: website.included.projects, author: website.author, isHome: true })
dd43ad4214d51d911beae3ecead16705736a5148
routes/users.js
routes/users.js
'use strict'; const userCtr = require('./../controllers/users.js'); const authentication = require('./../middleware/authentication'); const authorisation = require('./../middleware/authorisation'); const userRoutes = (router) => { router .route('/users') .post(userCtr.create); }; module.exports = userRoutes;
'use strict'; const userCtr = require('./../controllers/users.js'); const userAuth = require('./../controllers/authentication.js'); const authentication = require('./../middleware/authentication'); const authorisation = require('./../middleware/authorisation'); const userRoutes = (router) => { router .route('/users') .post(userCtr.create); router.post('/users/login', userAuth.signin); router.post('/users/logout', userAuth.signout); }; module.exports = userRoutes;
Add authentication controller to handle user authentication
Add authentication controller to handle user authentication
JavaScript
mit
andela-oolutola/document-management-system-api
--- +++ @@ -1,6 +1,7 @@ 'use strict'; -const userCtr = require('./../controllers/users.js'); +const userCtr = require('./../controllers/users.js'); +const userAuth = require('./../controllers/authentication.js'); const authentication = require('./../middleware/authentication'); const authorisation = require('./../middleware/authorisation'); @@ -8,6 +9,9 @@ router .route('/users') .post(userCtr.create); + + router.post('/users/login', userAuth.signin); + router.post('/users/logout', userAuth.signout); }; module.exports = userRoutes;
57153e83cc810e5bb5f4c9a6774cc8a9163acddd
addon/helpers/elem.js
addon/helpers/elem.js
import Ember from 'ember'; import { elem, mod } from 'ember-cli-bem/mixins/bem'; const { HTMLBars: { makeBoundHelper }, } = Ember; const BLOCK_KEY = 'blockName'; export default makeBoundHelper(function(params, hash) { const blockName = hash[BLOCK_KEY]; const [ elemName ] = params; if (!blockName) { throw Error(`${BLOCK_KEY} is required for 'elem' helper`); } const elemClassName = elem(blockName, elemName); const modNames = Object.keys(hash).filter((key) => key !== BLOCK_KEY); const modClassNames = modNames.map((modName) => { const modValue = hash[modName]; return mod(elemClassName, { modName, modValue }); }); return [elemClassName, ...modClassNames].filter(Boolean).join(' '); });
import Ember from 'ember'; import { elem, mod } from 'ember-cli-bem/mixins/bem'; const { Helper: { helper } } = Ember; const BLOCK_KEY = 'blockName'; export default helper(function(params, hash) { const blockName = hash[BLOCK_KEY]; const [ elemName ] = params; if (!blockName) { throw Error(`${BLOCK_KEY} is required for 'elem' helper`); } const elemClassName = elem(blockName, elemName); const modNames = Object.keys(hash).filter((key) => key !== BLOCK_KEY); const modClassNames = modNames.map((modName) => { const modValue = hash[modName]; return mod(elemClassName, { modName, modValue }); }); return [elemClassName, ...modClassNames].filter(Boolean).join(' '); });
Remove makeBoundHelper in favor of helper.
Remove makeBoundHelper in favor of helper.
JavaScript
mit
nikityy/ember-cli-bem,nikityy/ember-cli-bem
--- +++ @@ -2,12 +2,12 @@ import { elem, mod } from 'ember-cli-bem/mixins/bem'; const { - HTMLBars: { makeBoundHelper }, + Helper: { helper } } = Ember; const BLOCK_KEY = 'blockName'; -export default makeBoundHelper(function(params, hash) { +export default helper(function(params, hash) { const blockName = hash[BLOCK_KEY]; const [ elemName ] = params;
57103d1f7e4eee6f4405de13c9650663395b0007
src/storage-queue/index.js
src/storage-queue/index.js
var azure = require("azure-storage"); // var nconf = require("nconf"); nconf.env() .file({ file: "config.json", search: true }); var storageName = nconf.get("StorageName"); var storageKey = nconf.get("StorageKey"); var dev = nconf.get("NODE_ENV");
var azure = require("azure-storage"); // var nconf = require("nconf"); nconf.env() .file({ file: "config.json", search: true }); var QueueName = "my-queue"; var storageName = nconf.get("StorageName"); var storageKey = nconf.get("StorageKey"); var dev = nconf.get("NODE_ENV"); // var retryOperations = new azure.ExponentialRetryPolicyFilter(); var queueSvc = azure.createQueueService(storageName, storageKey).withFilter(retryOperations); if(queueSvc) { queueSvc.createQueueIfNotExists(QueueName, function(error, results, response) { if(error) { return; } var created = results; if(created) { console.log("created new queue"); } else { console.log("queue already exists"); } var ticket = { EventId: 4711, Email: "peter@example.com", NumberOfTickets: 2, OrderDate: Date.UTC }; var msg = JSON.stringify(ticket); queueSvc.createMessage(QueueName, msg, function(error, result, response) { if(error) { return; } queueSvc.peekMessages(QueueName, { numOfMessages: 32 }, function(error, result, response){ if(!error){ // Message text is in messages[0].messagetext } }); }); }); }
Add couple of simple queue access methods
Add couple of simple queue access methods
JavaScript
mit
peterblazejewicz/azure-aspnet5-examples,peterblazejewicz/azure-aspnet5-examples
--- +++ @@ -6,6 +6,43 @@ file: "config.json", search: true }); +var QueueName = "my-queue"; var storageName = nconf.get("StorageName"); var storageKey = nconf.get("StorageKey"); var dev = nconf.get("NODE_ENV"); +// +var retryOperations = new azure.ExponentialRetryPolicyFilter(); +var queueSvc = azure.createQueueService(storageName, + storageKey).withFilter(retryOperations); +if(queueSvc) { + queueSvc.createQueueIfNotExists(QueueName, function(error, results, response) { + if(error) { + return; + } + var created = results; + if(created) { + console.log("created new queue"); + } else { + console.log("queue already exists"); + } + var ticket = { + EventId: 4711, + Email: "peter@example.com", + NumberOfTickets: 2, + OrderDate: Date.UTC + }; + var msg = JSON.stringify(ticket); + queueSvc.createMessage(QueueName, msg, function(error, result, response) { + if(error) { + return; + } + queueSvc.peekMessages(QueueName, { + numOfMessages: 32 + }, function(error, result, response){ + if(!error){ + // Message text is in messages[0].messagetext + } + }); + }); + }); +}
7772afb9c69d5c6e4ffc0bbe6507eaf1df257293
app/js/arethusa.core/routes/main.constant.js
app/js/arethusa.core/routes/main.constant.js
"use strict"; angular.module('arethusa.core').constant('MAIN_ROUTE', { controller: 'MainCtrl', template: '<div ng-include="template"></div>', resolve: { loadConfiguration: function($http, confUrl, configurator) { return $http.get(confUrl(true)).then(function(res) { configurator.defineConfiguration(res.data); }); } } });
"use strict"; angular.module('arethusa.core').constant('MAIN_ROUTE', { controller: 'MainCtrl', template: '<div ng-include="template"></div>', resolve: { loadConfiguration: function($http, confUrl, configurator) { var url = confUrl(true); return $http.get(url).then(function(res) { configurator.defineConfiguration(res.data, url); }); } } });
Add the location of a conf file in main route
Add the location of a conf file in main route
JavaScript
mit
Masoumeh/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,Masoumeh/arethusa,latin-language-toolkit/arethusa
--- +++ @@ -5,8 +5,9 @@ template: '<div ng-include="template"></div>', resolve: { loadConfiguration: function($http, confUrl, configurator) { - return $http.get(confUrl(true)).then(function(res) { - configurator.defineConfiguration(res.data); + var url = confUrl(true); + return $http.get(url).then(function(res) { + configurator.defineConfiguration(res.data, url); }); } }
dd1adfab80874c850279a5bd29f1d41c340455c6
jet/static/jet/js/src/layout-updaters/user-tools.js
jet/static/jet/js/src/layout-updaters/user-tools.js
var $ = require('jquery'); var UserToolsUpdater = function($usertools) { this.$usertools = $usertools; }; UserToolsUpdater.prototype = { updateUserTools: function($usertools) { var $list = $('<ul>'); var user = $usertools.find('strong').first().text(); $('<li>').addClass('user-tools-welcome-msg').text(user).appendTo($list); $usertools.find('a').each(function() { var $link = $(this); $('<li>').addClass('user-tools-link').html($link).appendTo($list); }); $usertools.empty().addClass('user-tools').append($list); $list.on('mouseenter', function() { $list.addClass('opened'); }); $list.on('mouseleave', function() { $list.removeClass('opened'); }); }, run: function() { try { this.updateUserTools(this.$usertools); } catch (e) { console.error(e); } this.$usertools.addClass('initialized'); } }; $(document).ready(function() { $('#user-tools').each(function() { new UserToolsUpdater($(this)).run(); }); });
var $ = require('jquery'); require('browsernizr/test/touchevents'); require('browsernizr'); var UserToolsUpdater = function($usertools) { this.$usertools = $usertools; }; UserToolsUpdater.prototype = { updateUserTools: function($usertools) { var $list = $('<ul>'); var user = $usertools.find('strong').first().text(); $('<li>') .addClass('user-tools-welcome-msg') .text(user).appendTo($list) .on('click', function() { if ($(document.documentElement).hasClass('touchevents')) { $list.toggleClass('opened'); } }); $usertools.find('a').each(function() { var $link = $(this); $('<li>').addClass('user-tools-link').html($link).appendTo($list); }); $usertools.empty().addClass('user-tools').append($list); $list.on('mouseenter', function() { $list.addClass('opened'); }).on('mouseleave', function() { $list.removeClass('opened'); }); }, run: function() { try { this.updateUserTools(this.$usertools); } catch (e) { console.error(e); } this.$usertools.addClass('initialized'); } }; $(document).ready(function() { $('#user-tools').each(function() { new UserToolsUpdater($(this)).run(); }); });
Add user tools closing by click
Add user tools closing by click
JavaScript
agpl-3.0
rcotrina94/django-jet,geex-arts/django-jet,pombredanne/django-jet,SalahAdDin/django-jet,geex-arts/django-jet,pombredanne/django-jet,SalahAdDin/django-jet,SalahAdDin/django-jet,rcotrina94/django-jet,rcotrina94/django-jet,geex-arts/django-jet,pombredanne/django-jet
--- +++ @@ -1,4 +1,7 @@ var $ = require('jquery'); + +require('browsernizr/test/touchevents'); +require('browsernizr'); var UserToolsUpdater = function($usertools) { this.$usertools = $usertools; @@ -9,7 +12,14 @@ var $list = $('<ul>'); var user = $usertools.find('strong').first().text(); - $('<li>').addClass('user-tools-welcome-msg').text(user).appendTo($list); + $('<li>') + .addClass('user-tools-welcome-msg') + .text(user).appendTo($list) + .on('click', function() { + if ($(document.documentElement).hasClass('touchevents')) { + $list.toggleClass('opened'); + } + }); $usertools.find('a').each(function() { var $link = $(this); @@ -20,9 +30,7 @@ $list.on('mouseenter', function() { $list.addClass('opened'); - }); - - $list.on('mouseleave', function() { + }).on('mouseleave', function() { $list.removeClass('opened'); }); },
f5f6841d299d4bcfcde428130d48ef7266b36747
dev/staticRss.js
dev/staticRss.js
'use strict'; var moment = require('moment'); var _ = require('lodash'); var config = require('../config'); var paths = require('../elements/PathsMixin'); module.exports = function(page) { return t('feed', {xmlns: 'http://www.w3.org/2005/Atom'}, [ t('title', {}, config.title), t('link', {href: "#{config.baseUrl}atom.xml", rel: 'self'}, ' '), t('link', {href: config.baseUrl}, ' '), t('updated', {}, moment().format()), t('id', {}, config.baseUrl), t('author', {}, [ t('name', {}, config.author.name), t('email', {}, config.author.email), ]), _.map(paths.getAllPosts(), function(post, name) { return t('entry', {}, [ t('title', {}, post.title), t('link', {href: config.baseUrl + name}, ''), t('updated', {}, moment(post.date, 'YYYY-MM-DD').format()), t('content', {type: 'html'}, paths.getPostForPath(name)), ]); }).join('') ]); }; function t(name, attributes, content) { var attrStr = _.map(attributes, function(val, key) { return key + '=' + '"' + val + '"'; }).join(' '); if(_.isArray(content)) { content = content.join(''); } return '<' + name + ' ' + attrStr + '>' + content + '>/' + name + '>'; }
'use strict'; var moment = require('moment'); var _ = require('lodash'); var config = require('../config'); var paths = require('../elements/PathsMixin'); module.exports = function() { return t('feed', {xmlns: 'http://www.w3.org/2005/Atom'}, [ t('title', {}, config.title), t('link', {href: 'config.baseUrl' + 'atom.xml', rel: 'self'}, ' '), t('link', {href: config.baseUrl}, ' '), t('updated', {}, moment().format()), t('id', {}, config.baseUrl), t('author', {}, [ t('name', {}, config.author.name), t('email', {}, config.author.email), ]), _.map(paths.getAllPosts(), function(post, name) { return t('entry', {}, [ t('title', {}, post.title), t('link', {href: config.baseUrl + name}, ''), t('updated', {}, moment(post.date, 'YYYY-MM-DD').format()), t('content', {type: 'html'}, paths.getPostForPath(name)), ]); }).join('') ]); }; function t(name, attributes, content) { var attrStr = _.map(attributes, function(val, key) { return key + '=' + '"' + val + '"'; }).join(' '); if(_.isArray(content)) { content = content.join(''); } return '<' + name + ' ' + attrStr + '>' + content + '>/' + name + '>'; }
Fix typo at RSS bit
Fix typo at RSS bit
JavaScript
mit
antwarjs/antwar,RamonGebben/antwar,RamonGebben/antwar
--- +++ @@ -6,10 +6,10 @@ var paths = require('../elements/PathsMixin'); -module.exports = function(page) { +module.exports = function() { return t('feed', {xmlns: 'http://www.w3.org/2005/Atom'}, [ t('title', {}, config.title), - t('link', {href: "#{config.baseUrl}atom.xml", rel: 'self'}, ' '), + t('link', {href: 'config.baseUrl' + 'atom.xml', rel: 'self'}, ' '), t('link', {href: config.baseUrl}, ' '), t('updated', {}, moment().format()), t('id', {}, config.baseUrl),
a51e96883d8fcc394ac1e2b4744c5634fb16184b
reviewboard/static/rb/js/resources/models/apiTokenModel.js
reviewboard/static/rb/js/resources/models/apiTokenModel.js
RB.APIToken = RB.BaseResource.extend({ defaults: _.defaults({ tokenValue: null, note: null, policy: {}, userName: null }, RB.BaseResource.prototype.defaults), rspNamespace: 'api_token', url: function() { var url = SITE_ROOT + (this.get('localSitePrefix') || '') + 'api/users/' + this.get('userName') + '/api-tokens/'; if (!this.isNew()) { url += this.id + '/'; } return url; }, toJSON: function() { return { note: this.get('note'), policy: JSON.stringify(this.get('policy')) }; }, parseResourceData: function(rsp) { return { tokenValue: rsp.token, note: rsp.note, policy: rsp.policy }; } }, { defaultPolicies: { readWrite: {}, readOnly: { resources: { '*': { allow: ['GET', 'HEAD', 'OPTIONS'], block: ['*'] } } }, custom: { resources: { '*': { allow: ['*'], block: [] } } } } });
RB.APIToken = RB.BaseResource.extend({ defaults: function() { return _.defaults({ tokenValue: null, note: null, policy: {}, userName: null }, RB.BaseResource.prototype.defaults()); }, rspNamespace: 'api_token', url: function() { var url = SITE_ROOT + (this.get('localSitePrefix') || '') + 'api/users/' + this.get('userName') + '/api-tokens/'; if (!this.isNew()) { url += this.id + '/'; } return url; }, toJSON: function() { return { note: this.get('note'), policy: JSON.stringify(this.get('policy')) }; }, parseResourceData: function(rsp) { return { tokenValue: rsp.token, note: rsp.note, policy: rsp.policy }; } }, { defaultPolicies: { readWrite: {}, readOnly: { resources: { '*': { allow: ['GET', 'HEAD', 'OPTIONS'], block: ['*'] } } }, custom: { resources: { '*': { allow: ['*'], block: [] } } } } });
Update the RB.APIToken resource to use a defaults function
Update the RB.APIToken resource to use a defaults function This change updates the `RB.APIToken` resource to use the new `defaults` function that all other resources are using. Testing Done: Ran JS tests. Reviewed at https://reviews.reviewboard.org/r/7394/
JavaScript
mit
KnowNo/reviewboard,chipx86/reviewboard,brennie/reviewboard,beol/reviewboard,davidt/reviewboard,chipx86/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,sgallagher/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,brennie/reviewboard,beol/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,brennie/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,KnowNo/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,reviewboard/reviewboard,reviewboard/reviewboard,davidt/reviewboard,brennie/reviewboard,custode/reviewboard,custode/reviewboard,davidt/reviewboard,chipx86/reviewboard,bkochendorfer/reviewboard,beol/reviewboard,davidt/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,beol/reviewboard
--- +++ @@ -1,10 +1,12 @@ RB.APIToken = RB.BaseResource.extend({ - defaults: _.defaults({ - tokenValue: null, - note: null, - policy: {}, - userName: null - }, RB.BaseResource.prototype.defaults), + defaults: function() { + return _.defaults({ + tokenValue: null, + note: null, + policy: {}, + userName: null + }, RB.BaseResource.prototype.defaults()); + }, rspNamespace: 'api_token',
c5caa31810a39e69ddb281143ecac063d0a9e3d5
app/services/data/get-individual-overview.js
app/services/data/get-individual-overview.js
const knex = require('../../../knex').web module.exports = function (id) { return knex('individual_case_overview') .first('grade_code AS grade', 'team_id AS teamId', 'team_name AS teamName', 'available_points AS availablePoints', 'total_points AS totalPoints', 'total_cases AS cases', 'contracted_hours AS contractedHours', 'reduction_hours AS reduction') .where('workload_owner_id', id) }
const knex = require('../../../knex').web module.exports = function (id) { var table = 'individual_case_overview' var whereClause = '' if (id !== undefined) { whereClause = ' WHERE workload_owner_id = ' + id } var selectColumns = [ 'grade_code AS grade', 'team_id AS teamId', 'team_name AS teamName', 'available_points AS availablePoints', 'total_points AS totalPoints', 'total_cases AS cases', 'contracted_hours AS contractedHours', 'reduction_hours AS reduction' ] return knex.raw( 'SELECT TOP (1) ' + selectColumns.join(', ') + ' FROM ' + table + ' WITH (NOEXPAND)' + whereClause ) .then(function (results) { return results[0] }) }
Add noexpand to individual overview
Add noexpand to individual overview
JavaScript
mit
ministryofjustice/wmt-web,ministryofjustice/wmt-web
--- +++ @@ -1,14 +1,30 @@ const knex = require('../../../knex').web module.exports = function (id) { - return knex('individual_case_overview') - .first('grade_code AS grade', - 'team_id AS teamId', - 'team_name AS teamName', - 'available_points AS availablePoints', - 'total_points AS totalPoints', - 'total_cases AS cases', - 'contracted_hours AS contractedHours', - 'reduction_hours AS reduction') - .where('workload_owner_id', id) + var table = 'individual_case_overview' + var whereClause = '' + + if (id !== undefined) { + whereClause = ' WHERE workload_owner_id = ' + id + } + + var selectColumns = [ + 'grade_code AS grade', + 'team_id AS teamId', + 'team_name AS teamName', + 'available_points AS availablePoints', + 'total_points AS totalPoints', + 'total_cases AS cases', + 'contracted_hours AS contractedHours', + 'reduction_hours AS reduction' + ] + + return knex.raw( + 'SELECT TOP (1) ' + selectColumns.join(', ') + + ' FROM ' + table + ' WITH (NOEXPAND)' + + whereClause + ) + .then(function (results) { + return results[0] + }) }
0da039bab055f1c5c90f6424b67159bcb13b3577
app/assets/javascripts/lib/analytics/travel_insurance_omniture.js
app/assets/javascripts/lib/analytics/travel_insurance_omniture.js
require([ "jquery", "lib/analytics/analytics" ], function($, Analytics) { "use strict"; var analytics = new Analytics(); analytics.trackView(); // Set up Omniture event handlers var windowUnloadedFromSubmitClick = false; // If the user clicks anywhere else on the page, reset the click tracker $(document).on("click", function() { windowUnloadedFromSubmitClick = false; }); // When the user clicks on the submit button, track that it's what // is causing the onbeforeunload event to fire (below) $(document).on("click", "button.cta-button-primary", function(e) { windowUnloadedFromSubmitClick = true; e.stopPropagation(); }); // Before redirection (which the WN widget does, it's not a form submit) // if the user clicked on the submit button, track click with Omniture window.onbeforeunload = function() { if (windowUnloadedFromSubmitClick) { window.s.events = "event42"; window.s.t(); } }; });
require([ "jquery", "lib/analytics/analytics" ], function($, Analytics) { "use strict"; var analytics = new Analytics(); if (window.lp.hasOwnProperty("tracking") && window.lp.tracking.hasOwnProperty("eVar12") && window.lp.tracking.eVar12 !== "dest essential information") { analytics.trackView(); } // Set up Omniture event handlers var windowUnloadedFromSubmitClick = false; // If the user clicks anywhere else on the page, reset the click tracker $(document).on("click", function() { windowUnloadedFromSubmitClick = false; }); // When the user clicks on the submit button, track that it's what // is causing the onbeforeunload event to fire (below) $(document).on("click", "button.cta-button-primary", function(e) { windowUnloadedFromSubmitClick = true; e.stopPropagation(); }); // Before redirection (which the WN widget does, it's not a form submit) // if the user clicked on the submit button, track click with Omniture window.onbeforeunload = function() { if (windowUnloadedFromSubmitClick) { window.s.events = "event42"; window.s.t(); } }; });
Make sure Essential information is not double tracked
Make sure Essential information is not double tracked
JavaScript
mit
Lostmyname/rizzo,lonelyplanet/rizzo,lonelyplanet/rizzo,Lostmyname/rizzo,Lostmyname/rizzo,Lostmyname/rizzo,lonelyplanet/rizzo,lonelyplanet/rizzo,lonelyplanet/rizzo,Lostmyname/rizzo
--- +++ @@ -3,8 +3,9 @@ "use strict"; var analytics = new Analytics(); - - analytics.trackView(); + if (window.lp.hasOwnProperty("tracking") && window.lp.tracking.hasOwnProperty("eVar12") && window.lp.tracking.eVar12 !== "dest essential information") { + analytics.trackView(); + } // Set up Omniture event handlers
ed824d747a12b85c662e9451c69857d20c14ae90
app/assets/javascripts/dialogs/tabular_data/tabular_data_preview.js
app/assets/javascripts/dialogs/tabular_data/tabular_data_preview.js
chorus.dialogs.TabularDataPreview = chorus.dialogs.Base.extend({ constructorName: "TabularDataPreview", templateName: 'tabular_data_preview', title: function() {return t("dataset.data_preview_title", {name: this.model.get("objectName")}); }, events: { "click button.cancel": "cancelTask" }, subviews: { '.results_console': 'resultsConsole' }, setup: function() { _.bindAll(this, 'title'); this.resultsConsole = new chorus.views.ResultsConsole({ footerSize: _.bind(this.footerSize, this), showDownloadDialog: true, tabularData: this.model enableResize: true, enableExpander: true }); this.closePreviewHandle = chorus.PageEvents.subscribe("action:closePreview", this.closeModal, this); this.modalClosedHandle = chorus.PageEvents.subscribe("modal:closed", this.cancelTask, this); }, footerSize: function() { return this.$('.modal_controls').outerHeight(true); }, postRender: function() { this.task = this.model.preview(); this.resultsConsole.execute(this.task); }, cancelTask: function(e) { this.task && this.task.cancel(); chorus.PageEvents.unsubscribe(this.modalClosedHandle); }, close: function() { chorus.PageEvents.unsubscribe(this.closePreviewHandle); } });
chorus.dialogs.TabularDataPreview = chorus.dialogs.Base.extend({ constructorName: "TabularDataPreview", templateName: 'tabular_data_preview', title: function() {return t("dataset.data_preview_title", {name: this.model.get("objectName")}); }, events: { "click button.cancel": "cancelTask" }, subviews: { '.results_console': 'resultsConsole' }, setup: function() { _.bindAll(this, 'title'); this.resultsConsole = new chorus.views.ResultsConsole({ footerSize: _.bind(this.footerSize, this), showDownloadDialog: true, tabularData: this.model, enableResize: true, enableExpander: true }); this.closePreviewHandle = chorus.PageEvents.subscribe("action:closePreview", this.closeModal, this); this.modalClosedHandle = chorus.PageEvents.subscribe("modal:closed", this.cancelTask, this); }, footerSize: function() { return this.$('.modal_controls').outerHeight(true); }, postRender: function() { this.task = this.model.preview(); this.resultsConsole.execute(this.task); }, cancelTask: function(e) { this.task && this.task.cancel(); chorus.PageEvents.unsubscribe(this.modalClosedHandle); }, close: function() { chorus.PageEvents.unsubscribe(this.closePreviewHandle); } });
Fix missing comma in tabular data preview
Fix missing comma in tabular data preview
JavaScript
apache-2.0
hewtest/chorus,mpushpav/chorus,lukepolo/chorus,jamesblunt/chorus,hewtest/chorus,mpushpav/chorus,atul-alpine/chorus,prakash-alpine/chorus,hewtest/chorus,mpushpav/chorus,mpushpav/chorus,lukepolo/chorus,lukepolo/chorus,prakash-alpine/chorus,prakash-alpine/chorus,jamesblunt/chorus,atul-alpine/chorus,hewtest/chorus,jamesblunt/chorus,jamesblunt/chorus,atul-alpine/chorus,hewtest/chorus,atul-alpine/chorus,prakash-alpine/chorus,atul-alpine/chorus,jamesblunt/chorus,lukepolo/chorus,jamesblunt/chorus,mpushpav/chorus,lukepolo/chorus,jamesblunt/chorus,lukepolo/chorus,hewtest/chorus,atul-alpine/chorus,mpushpav/chorus,prakash-alpine/chorus,atul-alpine/chorus,hewtest/chorus,lukepolo/chorus,hewtest/chorus,mpushpav/chorus
--- +++ @@ -15,9 +15,9 @@ setup: function() { _.bindAll(this, 'title'); this.resultsConsole = new chorus.views.ResultsConsole({ - footerSize: _.bind(this.footerSize, this), + footerSize: _.bind(this.footerSize, this), showDownloadDialog: true, - tabularData: this.model + tabularData: this.model, enableResize: true, enableExpander: true });
a49429c4737888bc3e43b50a221d966422841fb2
test/integration/server.js
test/integration/server.js
import nock from 'nock' import req from 'supertest' import test from 'tape' import server from '../../server' nock('http://www.newyorker.com') .get('/') .replyWithFile(200, './test/fixtures/homepage.html') test('server', t => { req(server) .get('/') .expect(200) .expect('Content-Type', /html/) .end((err, res) => { if (err) throw err t.assert(res.text.match(/p.0..p/), 'returns Borowitz Index in HTML') t.end() }) })
import nock from 'nock' import req from 'supertest' import test from 'tape' import server from '../../server' nock('http://www.newyorker.com') .get('/') .replyWithFile(200, './test/fixtures/homepage.html') test('server', t => { req(server) .get('/') .expect(200) .expect('Content-Type', /html/) .end((err, res) => { if (err) throw err t.assert(res.text.match(/h2.0..h2/), 'returns Borowitz Index in HTML') t.end() }) })
Update test to match new markup
Update test to match new markup
JavaScript
mit
mmwtsn/borowitz-index,mmwtsn/borowitz-index
--- +++ @@ -15,7 +15,7 @@ .end((err, res) => { if (err) throw err - t.assert(res.text.match(/p.0..p/), 'returns Borowitz Index in HTML') + t.assert(res.text.match(/h2.0..h2/), 'returns Borowitz Index in HTML') t.end() }) })
a76a96c708c5e6b111bbfff14415b794065d28ee
examples/links/webpack.config.js
examples/links/webpack.config.js
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: ['', '.js'] }, module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }, { test: /\.css?$/, loaders: ['style', 'raw'] }] } };
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: ['', '.js'], alias: { 'react': path.join(__dirname, '..', '..', 'node_modules', 'react') } }, module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }, { test: /\.css?$/, loaders: ['style', 'raw'] }] } };
Use React from root project to avoid duplicate React problem
Use React from root project to avoid duplicate React problem
JavaScript
mit
rackt/redux-router,acdlite/redux-router,mjrussell/redux-router
--- +++ @@ -18,7 +18,10 @@ new webpack.NoErrorsPlugin() ], resolve: { - extensions: ['', '.js'] + extensions: ['', '.js'], + alias: { + 'react': path.join(__dirname, '..', '..', 'node_modules', 'react') + } }, module: { loaders: [{
8fadc42c9711d08efb182eb0d865c51fd39645af
src/chunkify.js
src/chunkify.js
function* chunkify(start, final, chunk, delay) { for (let index = start; index < final; index++) { if ((index > start) && (index % (start + chunk) === 0)) { yield new Promise(resolve => setTimeout(resolve, delay)) } yield index } } export default { interval: ({start, final, chunk, delay}) => { return chunkify(start, final, chunk, delay) } }
let pending_delay_error = (index) => { let pending_delay = `pending delay at index: ${index}; `; pending_delay += `wait ${delay} milliseconds before `; pending_delay += `further invocations of .next()`; throw new Error(pending_delay) }; // Return values from the range `start` to `final` synchronously when between // intervals of size `chunk`. // // Otherwise, return a promise that resolves in `delay` milliseconds. // // An error will be thrown in case the iterator is advanced before a // pending promise has resolved. function* chunkify(start, final, chunk, delay) { let delayed = null; let pending = null; function* do_delay() { yield new Promise(resolve => { setTimeout(() => { delayed = false; pending = false; resolve(); }, delay) }) } for (let index = start; index < final; index++) { if ((index > start) && (index % (start + chunk) === 0)) { delayed = true; pending = true; yield* do_delay() } if (delayed && pending) { pending_delay_error(index); } yield index } } export default { interval: ({start, final, chunk, delay}) => { return chunkify(start, final, chunk, delay) } }
Throw error if iterator advances if delay is pending
Throw error if iterator advances if delay is pending
JavaScript
mit
yangmillstheory/chunkify,yangmillstheory/chunkify
--- +++ @@ -1,7 +1,37 @@ +let pending_delay_error = (index) => { + let pending_delay = `pending delay at index: ${index}; `; + pending_delay += `wait ${delay} milliseconds before `; + pending_delay += `further invocations of .next()`; + throw new Error(pending_delay) +}; + +// Return values from the range `start` to `final` synchronously when between +// intervals of size `chunk`. +// +// Otherwise, return a promise that resolves in `delay` milliseconds. +// +// An error will be thrown in case the iterator is advanced before a +// pending promise has resolved. function* chunkify(start, final, chunk, delay) { + let delayed = null; + let pending = null; + function* do_delay() { + yield new Promise(resolve => { + setTimeout(() => { + delayed = false; + pending = false; + resolve(); + }, delay) + }) + } for (let index = start; index < final; index++) { if ((index > start) && (index % (start + chunk) === 0)) { - yield new Promise(resolve => setTimeout(resolve, delay)) + delayed = true; + pending = true; + yield* do_delay() + } + if (delayed && pending) { + pending_delay_error(index); } yield index }
b5b5aa719f9e28fa73af44179cf2c8648728a646
src/demo/js/ephox/snooker/demo/DemoTranslations.js
src/demo/js/ephox/snooker/demo/DemoTranslations.js
define( 'ephox.snooker.demo.DemoTranslations', [ 'global!Array' ], function (Array) { var keys = { 'table.picker.rows': '{0} high', 'table.picker.cols': '{0} wide' }; return function (key) { if (keys[key] === undefined) throw 'key ' + key + ' not found'; var r = keys[key]; if (arguments.length > 1) { var parameters = Array.prototype.slice.call(arguments, 1); return r.replace(/\{(\d+)\}/g, function (match, contents) { var index = parseInt(contents, 10); if (parameters[index] === undefined) throw 'No value for token: ' + match + ' in translation: ' + r; return parameters[index]; }); } else { return r; } }; } );
define( 'ephox.snooker.demo.DemoTranslations', [ ], function () { return { row: function (row) { return row + ' high'; }, col: function (col) { return col + ' wide'; } }; } );
Update Demo Translations for echo change
Update Demo Translations for echo change
JavaScript
lgpl-2.1
FernCreek/tinymce,tinymce/tinymce,FernCreek/tinymce,FernCreek/tinymce,tinymce/tinymce,TeamupCom/tinymce,tinymce/tinymce,TeamupCom/tinymce
--- +++ @@ -2,29 +2,13 @@ 'ephox.snooker.demo.DemoTranslations', [ - 'global!Array' + ], - function (Array) { - var keys = { - 'table.picker.rows': '{0} high', - 'table.picker.cols': '{0} wide' - }; - - return function (key) { - if (keys[key] === undefined) throw 'key ' + key + ' not found'; - var r = keys[key]; - - if (arguments.length > 1) { - var parameters = Array.prototype.slice.call(arguments, 1); - return r.replace(/\{(\d+)\}/g, function (match, contents) { - var index = parseInt(contents, 10); - if (parameters[index] === undefined) throw 'No value for token: ' + match + ' in translation: ' + r; - return parameters[index]; - }); - } else { - return r; - } + function () { + return { + row: function (row) { return row + ' high'; }, + col: function (col) { return col + ' wide'; } }; } );
900e6845b52ba6389914f85c06d0d09cf07dc342
test/renderer/path-spec.js
test/renderer/path-spec.js
import { expect } from 'chai'; import { remote } from 'electron'; import { defaultPathFallback, cwdKernelFallback } from '../../src/notebook/path'; describe('defaultPathFallback', () => { it('returns a object with the defaultPath', () => { const path = defaultPathFallback('dummy-path'); expect(path).to.deep.equal({ defaultPath: 'dummy-path' }); }); it('returns a object with the correct path', () => { process.chdir('/') const path = defaultPathFallback(); expect(path).to.deep.equal({ defaultPath: '/home/home/on/the/range' }); }); });
import { expect } from 'chai'; import { remote } from 'electron'; import { defaultPathFallback, cwdKernelFallback } from '../../src/notebook/path'; describe('defaultPathFallback', () => { it('returns a object with the defaultPath', () => { const path = defaultPathFallback('dummy-path'); expect(path).to.deep.equal({ defaultPath: 'dummy-path' }); }); it('returns a object with the correct path', () => { if (process.platform !== 'win32') { process.chdir('/') const path = defaultPathFallback(); expect(path).to.deep.equal({ defaultPath: '/home/home/on/the/range' }); } }); });
Disable path fallback test on windows
chore(tests): Disable path fallback test on windows
JavaScript
bsd-3-clause
jdfreder/nteract,nteract/composition,rgbkrk/nteract,rgbkrk/nteract,captainsafia/nteract,0u812/nteract,nteract/composition,0u812/nteract,jdetle/nteract,0u812/nteract,jdetle/nteract,nteract/nteract,jdetle/nteract,rgbkrk/nteract,jdfreder/nteract,nteract/nteract,rgbkrk/nteract,nteract/nteract,temogen/nteract,nteract/nteract,temogen/nteract,nteract/nteract,captainsafia/nteract,captainsafia/nteract,nteract/composition,jdetle/nteract,jdfreder/nteract,rgbkrk/nteract,0u812/nteract,captainsafia/nteract,jdfreder/nteract,temogen/nteract
--- +++ @@ -11,9 +11,10 @@ expect(path).to.deep.equal({ defaultPath: 'dummy-path' }); }); it('returns a object with the correct path', () => { - process.chdir('/') - const path = defaultPathFallback(); - expect(path).to.deep.equal({ defaultPath: '/home/home/on/the/range' }); - + if (process.platform !== 'win32') { + process.chdir('/') + const path = defaultPathFallback(); + expect(path).to.deep.equal({ defaultPath: '/home/home/on/the/range' }); + } }); });
a97533599023613ad8c99a8ab2e2b55e3224f291
app/reducers/index.js
app/reducers/index.js
import { TAP_ASSERT_DONE, TAP_PLAN } from '../actions' const initialState = { assertions: {}, currentCount: 0, nextEstimatedCount: 0, plan: undefined } export default (state = initialState, action) => { switch (action.type) { case TAP_ASSERT_DONE: return { ...state, assertions: { ...state.assertions, [`assert_${action.payload.id}`]: action.payload }, currentCount: state.currentCount + 1, plan: undefined } case TAP_PLAN: return { ...state, currentCount: 0, plan: action.payload, nextEstimatedCount: state.currentCount } default: return state } }
import { TAP_ASSERT_DONE, TAP_COMMENT, TAP_PLAN } from '../actions' const initialState = { assertions: {}, currentCount: 0, lastComment: null, nextEstimatedCount: 0, plan: undefined } const assertName = (name, lastComment) => ( lastComment ? `[ ${lastComment.replace(/^#\s+/, '')} ] ${name}` : name ) export default (state = initialState, action) => { switch (action.type) { case TAP_ASSERT_DONE: return { ...state, assertions: { ...state.assertions, [`assert_${action.payload.id}`]: { ...action.payload, name: assertName(action.payload.name, state.lastComment) } }, currentCount: state.currentCount + 1, lastComment: null, plan: undefined } case TAP_COMMENT: return { ...state, lastComment: action.payload } case TAP_PLAN: return { ...state, currentCount: 0, plan: action.payload, nextEstimatedCount: state.currentCount } default: return state } }
Use comments to build the assertion name
Use comments to build the assertion name
JavaScript
mit
cskeppstedt/electron-tap-view,cskeppstedt/electron-tap-view
--- +++ @@ -1,14 +1,22 @@ import { TAP_ASSERT_DONE, + TAP_COMMENT, TAP_PLAN } from '../actions' const initialState = { assertions: {}, currentCount: 0, + lastComment: null, nextEstimatedCount: 0, plan: undefined } + +const assertName = (name, lastComment) => ( + lastComment + ? `[ ${lastComment.replace(/^#\s+/, '')} ] ${name}` + : name +) export default (state = initialState, action) => { switch (action.type) { @@ -17,10 +25,20 @@ ...state, assertions: { ...state.assertions, - [`assert_${action.payload.id}`]: action.payload + [`assert_${action.payload.id}`]: { + ...action.payload, + name: assertName(action.payload.name, state.lastComment) + } }, currentCount: state.currentCount + 1, + lastComment: null, plan: undefined + } + + case TAP_COMMENT: + return { + ...state, + lastComment: action.payload } case TAP_PLAN:
8807d8e4b4e1583cff1b389b3d1d6354395fdff7
test/test_with_nodeunit.js
test/test_with_nodeunit.js
var utils = require("bolt-internal-utils"); module.exports = { testStringStartsWith: function(test) { test.equal(utils.String.startsWith("characters", "c"), true, "Expecting \"characters\" to start with \"c\""); test.done(); } }
var utils = require("../utils"); module.exports = { testStringStartsWith: function(test) { test.equal(utils.String.startsWith("characters", "c"), true, "Expecting \"characters\" to start with \"c\""); test.done(); } }
Put right relative path to 'utils.js'
Put right relative path to 'utils.js'
JavaScript
mit
Chieze-Franklin/bolt-internal-utils
--- +++ @@ -1,4 +1,4 @@ -var utils = require("bolt-internal-utils"); +var utils = require("../utils"); module.exports = { testStringStartsWith: function(test) {
79d95c34c3b3b132d95ed47140328298458dad53
table/static/js/saveAsFile.js
table/static/js/saveAsFile.js
$("#saveAsFile").click(function() { html2canvas($("#course-table")).then(function(canvas) { var bgcanvas = document.createElement("canvas"); bgcanvas.width = canvas.width; bgcanvas.height = canvas.height; var ctx = bgcanvas.getContext("2d"); var gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height); gradient.addColorStop(0, "rgba(255, 255, 255, 0.9)"); gradient.addColorStop(1, "rgba(221, 232, 255, 0.9)"); ctx.fillStyle = gradient; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height); var data = bgcanvas.toDataURL("image/png"); data = data.replace("image/png", "image/octet-stream"); var downloadLink = document.createElement("a"); downloadLink.href = data; downloadLink.download = "course-table.png"; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); }); });
$("#saveAsFile").click(function() { var tmp_attr = $("#course-table").attr("class"); $("#course-table").removeAttr("class"); $("#course-table").css("width", "200%"); $("#course-table").css("height", "auto"); $("#course-table td, th").css("padding", "5px"); $("#course-table").css("font-size", "180%"); html2canvas($("#course-table")).then(function(canvas) { var bgcanvas = document.createElement("canvas"); bgcanvas.width = canvas.width; bgcanvas.height = canvas.height; var ctx = bgcanvas.getContext("2d"); var gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height); gradient.addColorStop(0, "rgba(255, 255, 255, 0.9)"); gradient.addColorStop(1, "rgba(221, 232, 255, 0.9)"); ctx.fillStyle = gradient; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height); var data = bgcanvas.toDataURL("image/png"); data = data.replace("image/png", "image/octet-stream"); var downloadLink = document.createElement("a"); downloadLink.href = data; downloadLink.download = "course-table.png"; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); }); $("#course-table").removeAttr("height"); $("#course-table").css("width", "100%"); $("#course-table td, th").removeAttr("padding"); $("#course-table").attr("class", tmp_attr); $("#course-table").css("font-size", "100%"); });
Add scale to 200% table output
Add scale to 200% table output
JavaScript
mit
henryyang42/NTHU_Course,henryyang42/NTHU_Course,leVirve/NTHU_Course,sonicyang/NCKU_Course,leVirve/NTHU_Course,sonicyang/NCKU_Course,henryyang42/NTHU_Course,henryyang42/NTHU_Course,sonicyang/NCKU_Course,sonicyang/NCKU_Course,leVirve/NTHU_Course,leVirve/NTHU_Course
--- +++ @@ -1,4 +1,10 @@ $("#saveAsFile").click(function() { + var tmp_attr = $("#course-table").attr("class"); + $("#course-table").removeAttr("class"); + $("#course-table").css("width", "200%"); + $("#course-table").css("height", "auto"); + $("#course-table td, th").css("padding", "5px"); + $("#course-table").css("font-size", "180%"); html2canvas($("#course-table")).then(function(canvas) { var bgcanvas = document.createElement("canvas"); bgcanvas.width = canvas.width; @@ -21,4 +27,9 @@ downloadLink.click(); document.body.removeChild(downloadLink); }); + $("#course-table").removeAttr("height"); + $("#course-table").css("width", "100%"); + $("#course-table td, th").removeAttr("padding"); + $("#course-table").attr("class", tmp_attr); + $("#course-table").css("font-size", "100%"); });
3d40e7e6a469a59bed25f6f19e3b9595e164ab55
tests/helpers/start-app.js
tests/helpers/start-app.js
import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; export default function startApp(attrs) { let application; // use defaults, but you can override let attributes = Ember.assign({}, config.APP, attrs); Ember.run(() => { application = Application.create(attributes); application.setupForTesting(); application.injectTestHelpers(); }); return application; }
import Ember from 'ember'; import Application from '../../app'; import config from '../../config/environment'; export default function startApp() { let application; Ember.run(() => { application = Application.create(config.APP); application.setupForTesting(); application.injectTestHelpers(); }); return application; }
Make tests run in all versions of Ember from 2.4 LTS onwards
Make tests run in all versions of Ember from 2.4 LTS onwards
JavaScript
mit
minutebase/ember-portal,minutebase/ember-portal
--- +++ @@ -2,14 +2,11 @@ import Application from '../../app'; import config from '../../config/environment'; -export default function startApp(attrs) { +export default function startApp() { let application; - // use defaults, but you can override - let attributes = Ember.assign({}, config.APP, attrs); - Ember.run(() => { - application = Application.create(attributes); + application = Application.create(config.APP); application.setupForTesting(); application.injectTestHelpers(); });
b10951fb48b5afb916213f44482e657bfee4b17e
tests/integration/links.js
tests/integration/links.js
import {assert} from 'chai' import {uniq} from 'lodash' import URI from 'urijs' import request from 'request' import events from 'utils/eventsDirectoryToSlideArray' describe('Event Links', function() { describe('are valid', function() { const timeout = 15000 this.timeout(timeout*4) this.slow(1200) const eventsString = JSON.stringify(events, null, ' ') const urls = [] URI.withinString( eventsString, url => urls.push(url.split('\\">')[0]) ) uniq(urls).forEach(url => { it(url, done => { function tryRequest(uri, tries=0) { request.get({uri, timeout, maxRedirects: 20}, (error, response, body) => { if (error && tries < 4) { // Retry request if failed (usually due to a timeout) return tryRequest(uri, ++tries) } assert.isNull(error) assert.equal(response.statusCode, 200) done() }) } tryRequest(url) }) }) }) })
import {assert} from 'chai' import {uniq} from 'lodash' import URI from 'urijs' import request from 'request' import events from 'utils/eventsDirectoryToSlideArray' describe('Event Links', function() { describe('are valid', function() { const maxRedirects = 20 const timeout = 10000 this.timeout(timeout*4) this.slow(1200) const eventsString = JSON.stringify(events, null, ' ') const urls = [] URI.withinString( eventsString, url => urls.push(url.split('\\">')[0]) ) uniq(urls).forEach(url => { it(url, done => { function tryRequest(uri, tries=0) { request.get({uri, timeout, maxRedirects}, (error, response, body) => { if (error && tries < 4) { // Retry request if failed (usually due to a timeout) return tryRequest(uri, ++tries) } assert.isNull(error) assert.equal(response.statusCode, 200) done() }).setMaxListeners(maxRedirects) } tryRequest(url) }) }) }) })
Fix possible EventEmitter memory leak console statement
Fix possible EventEmitter memory leak console statement
JavaScript
mit
L4GG/timeline,L4GG/timeline,L4GG/timeline
--- +++ @@ -6,7 +6,8 @@ describe('Event Links', function() { describe('are valid', function() { - const timeout = 15000 + const maxRedirects = 20 + const timeout = 10000 this.timeout(timeout*4) this.slow(1200) @@ -19,7 +20,7 @@ uniq(urls).forEach(url => { it(url, done => { function tryRequest(uri, tries=0) { - request.get({uri, timeout, maxRedirects: 20}, (error, response, body) => { + request.get({uri, timeout, maxRedirects}, (error, response, body) => { if (error && tries < 4) { // Retry request if failed (usually due to a timeout) return tryRequest(uri, ++tries) @@ -27,7 +28,7 @@ assert.isNull(error) assert.equal(response.statusCode, 200) done() - }) + }).setMaxListeners(maxRedirects) } tryRequest(url) })
20797136cd834312a2418b0698021413f63a7366
raw/assets/js/layout/admin/auth/login/admin_auth_login_common_layout.js
raw/assets/js/layout/admin/auth/login/admin_auth_login_common_layout.js
/** * This <server-gardu-reporter> project created by : * Name : syafiq * Date / Time : 28 June 2017, 11:03 PM. * Email : syafiq.rezpector@gmail.com * Github : syafiqq */ (function ($) { $(function () { $('input').iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', increaseArea: '20%' // optional }); }); /* * Run right away * */ })(jQuery);
/** * This <server-gardu-reporter> project created by : * Name : syafiq * Date / Time : 28 June 2017, 11:03 PM. * Email : syafiq.rezpector@gmail.com * Github : syafiqq */ (function ($) { $(function () { $('form#login').on('submit', function (event) { event.preventDefault(); var input = $(this).serializeObject(); input['remember_me'] = $(this).find('input[type=checkbox][name=remember_me]').prop('checked'); if ((input['remember_me'] === undefined) || (input['remember_me'] === null)) { input['remember_me'] = false; } console.log(input); }); $('input').iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', increaseArea: '20%' // optional }); }); /* * Run right away * */ })(jQuery);
Add initial form submit function
Add initial form submit function
JavaScript
mit
Syafiqq/server-gardu-reporter,Syafiqq/server-gardu-reporter,Syafiqq/server-gardu-reporter,Syafiqq/server-gardu-reporter
--- +++ @@ -10,6 +10,21 @@ { $(function () { + $('form#login').on('submit', function (event) + { + event.preventDefault(); + + var input = $(this).serializeObject(); + + input['remember_me'] = $(this).find('input[type=checkbox][name=remember_me]').prop('checked'); + if ((input['remember_me'] === undefined) || (input['remember_me'] === null)) + { + input['remember_me'] = false; + } + + console.log(input); + }); + $('input').iCheck({ checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue',
376f2ccff34e733f01caca72b12f0e4e613429b9
packages/lesswrong/lib/modules/utils/schemaUtils.js
packages/lesswrong/lib/modules/utils/schemaUtils.js
import Users from 'meteor/vulcan:users'; export const generateIdResolverSingle = ({collectionName, fieldName}) => { return async (doc, args, context) => { if (!doc[fieldName]) return null const { currentUser } = context const collection = context[collectionName] const { checkAccess } = collection const resolvedDoc = await collection.loader.load(doc[fieldName]) if (checkAccess && !checkAccess(currentUser, resolvedDoc)) return null const restrictedDoc = Users.restrictViewableFields(currentUser, collection, resolvedDoc) return restrictedDoc } } export const generateIdResolverMulti = ({collectionName, fieldName}) => { return async (doc, args, context) => { if (!doc[fieldName]) return [] const { currentUser } = context const collection = context[collectionName] const { checkAccess } = collection const resolvedDocs = await collection.loader.loadMany(doc[fieldName]) const existingDocs = _.filter(resolvedDocs, d=>!!d); const filteredDocs = checkAccess ? _.filter(existingDocs, d => checkAccess(currentUser, d)) : resolvedDocs const restrictedDocs = Users.restrictViewableFields(currentUser, collection, filteredDocs) return restrictedDocs } } export const addFieldsDict = (collection, fieldsDict) => { for (let key in fieldsDict) { collection.addField({ fieldName: key, fieldSchema: fieldsDict[key] }); } }
import Users from 'meteor/vulcan:users'; export const generateIdResolverSingle = ({collectionName, fieldName}) => { return async (doc, args, context) => { if (!doc[fieldName]) return null const { currentUser } = context const collection = context[collectionName] const { checkAccess } = collection const resolvedDoc = await collection.loader.load(doc[fieldName]) if (checkAccess && !checkAccess(currentUser, resolvedDoc)) return null const restrictedDoc = Users.restrictViewableFields(currentUser, collection, resolvedDoc) return restrictedDoc } } export const generateIdResolverMulti = ({collectionName, fieldName}) => { return async (doc, args, context) => { if (!doc[fieldName]) return [] const { currentUser } = context const collection = context[collectionName] const { checkAccess } = collection const resolvedDocs = await collection.loader.loadMany(doc[fieldName]) const existingDocs = _.filter(resolvedDocs, d=>!!d); const filteredDocs = checkAccess ? _.filter(existingDocs, d => checkAccess(currentUser, d)) : resolvedDocs const restrictedDocs = Users.restrictViewableFields(currentUser, collection, filteredDocs) return restrictedDocs } } export const addFieldsDict = (collection, fieldsDict) => { let translatedFields = []; for (let key in fieldsDict) { translatedFields.push({ fieldName: key, fieldSchema: fieldsDict[key] }); } collection.addField(translatedFields); }
Add all at once so multi-part fields work
addFieldsDict: Add all at once so multi-part fields work
JavaScript
mit
Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Telescope,Discordius/Telescope,Discordius/Lesswrong2
--- +++ @@ -34,10 +34,12 @@ } export const addFieldsDict = (collection, fieldsDict) => { + let translatedFields = []; for (let key in fieldsDict) { - collection.addField({ + translatedFields.push({ fieldName: key, fieldSchema: fieldsDict[key] }); } + collection.addField(translatedFields); }
4b0beda4f602f48870cb77d6c825e95367105d02
test/e2e/pages/classesPage.js
test/e2e/pages/classesPage.js
export default { elements: { classTableRows: { selector: '//div[@class="classes-list"]/div[2]/div', locateStrategy: 'xpath' } } };
import utils from '../utils'; export default { elements: { classesListMenu: { selector: '//div[@class="classes-list"]/div[1]/div[@class="col-menu"]//button', locateStrategy: 'xpath' }, createModalNameInput: { selector: 'input[name=class]' }, createModalFieldNameInput: { selector: 'input[name=fieldName]' }, createModalDropdownType: { selector: '//div[@class="fieldType-dropdown"]/div/div', locateStrategy: 'xpath' }, createModalDescriptionInput: { selector: 'input[name="description"]' }, classTableRows: { selector: '//div[@class="classes-list"]/div[2]/div', locateStrategy: 'xpath' }, classTableRow: { selector: `//div[text()="${utils.addSuffix('class')}"]`, locateStrategy: 'xpath' }, userProfileClassName: { selector: '[data-e2e="user_profile-list-item-name"]' }, userClassListItem: { selector: '[data-e2e="user_profile-check-icon"]' }, classTableRowDescription: { selector: `div[data-e2e="${utils.addSuffix('class')}-list-item-description"]` }, classTableName: { selector: `div[data-e2e="${utils.addSuffix('class')}-list-item-name"]` }, checkboxSelected: { selector: '//span[@class="synicon-checkbox-marked-outline"]', locateStrategy: 'xpath' }, classesListItemDropDown: { selector: `//div[text()="${utils.addSuffix('class')}"]/../../../ following-sibling::div//span[@class="synicon-dots-vertical"]`, locateStrategy: 'xpath' } } };
Add some selectors in order to not crash other tests
[DASH-2376] Add some selectors in order to not crash other tests
JavaScript
mit
Syncano/syncano-dashboard,Syncano/syncano-dashboard,Syncano/syncano-dashboard
--- +++ @@ -1,7 +1,52 @@ +import utils from '../utils'; + export default { elements: { + classesListMenu: { + selector: '//div[@class="classes-list"]/div[1]/div[@class="col-menu"]//button', + locateStrategy: 'xpath' + }, + createModalNameInput: { + selector: 'input[name=class]' + }, + createModalFieldNameInput: { + selector: 'input[name=fieldName]' + }, + createModalDropdownType: { + selector: '//div[@class="fieldType-dropdown"]/div/div', + locateStrategy: 'xpath' + }, + createModalDescriptionInput: { + selector: 'input[name="description"]' + }, classTableRows: { selector: '//div[@class="classes-list"]/div[2]/div', + locateStrategy: 'xpath' + }, + classTableRow: { + selector: `//div[text()="${utils.addSuffix('class')}"]`, + locateStrategy: 'xpath' + }, + userProfileClassName: { + selector: '[data-e2e="user_profile-list-item-name"]' + }, + userClassListItem: { + selector: '[data-e2e="user_profile-check-icon"]' + }, + classTableRowDescription: { + selector: `div[data-e2e="${utils.addSuffix('class')}-list-item-description"]` + }, + classTableName: { + selector: `div[data-e2e="${utils.addSuffix('class')}-list-item-name"]` + }, + + checkboxSelected: { + selector: '//span[@class="synicon-checkbox-marked-outline"]', + locateStrategy: 'xpath' + }, + classesListItemDropDown: { + selector: `//div[text()="${utils.addSuffix('class')}"]/../../../ + following-sibling::div//span[@class="synicon-dots-vertical"]`, locateStrategy: 'xpath' } }
6a7350757520d1577a1751041355fa0b1eb9662d
migrations/0002-create-dns-record.js
migrations/0002-create-dns-record.js
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('dns_records', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, type: { type: Sequelize.STRING(4), allowNull: false }, name: { type: Sequelize.STRING(64), allowNull: false }, ipv4address: { type: Sequelize.STRING(15) }, ipv6address: { type: Sequelize.STRING(39) }, cname: { type: Sequelize.STRING(255) }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE }, UserId: { type: Sequelize.INTEGER, onDelete: 'CASCADE', allowNull: false, references: { model: 'Users', key: 'id' } } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('dns_records'); } };
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('dns_records', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, type: { type: Sequelize.ENUM('A', 'CNAME', 'MX', 'SOA', 'TXT', 'NS'), allowNull: false }, name: { type: Sequelize.STRING(64), allowNull: false }, ipv4address: { type: Sequelize.STRING(15) }, ipv6address: { type: Sequelize.STRING(39) }, cname: { type: Sequelize.STRING(255) }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE }, UserId: { type: Sequelize.INTEGER, onDelete: 'CASCADE', allowNull: false, references: { model: 'Users', key: 'id' } } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('dns_records'); } };
Fix some curious issue on SQL Record insertion
Fix some curious issue on SQL Record insertion
JavaScript
mit
nowhere-cloud/node-api-gate
--- +++ @@ -9,7 +9,7 @@ type: Sequelize.INTEGER }, type: { - type: Sequelize.STRING(4), + type: Sequelize.ENUM('A', 'CNAME', 'MX', 'SOA', 'TXT', 'NS'), allowNull: false }, name: {
be2ea1d95b5e4764ec9255c1ec3c09db1ab92c14
src/lib/GoogleApi.js
src/lib/GoogleApi.js
export const GoogleApi = function(opts) { opts = opts || {}; if (!opts.hasOwnProperty('apiKey')) { throw new Error('You must pass an apiKey to use GoogleApi'); } const apiKey = opts.apiKey; const libraries = opts.libraries || ['places']; const client = opts.client; const URL = opts.url || 'https://maps.googleapis.com/maps/api/js'; const googleVersion = opts.version || '3.31'; let script = null; let google = (typeof window !== 'undefined' && window.google) || null; let loading = false; let channel = null; let language = opts.language; let region = opts.region || null; let onLoadEvents = []; const url = () => { let url = URL; let params = { key: apiKey, callback: 'CALLBACK_NAME', libraries: libraries.join(','), client: client, v: googleVersion, channel: channel, language: language, region: region }; let paramStr = Object.keys(params) .filter(k => !!params[k]) .map(k => `${k}=${params[k]}`) .join('&'); return `${url}?${paramStr}`; }; return url(); }; export default GoogleApi;
export const GoogleApi = function(opts) { opts = opts || {}; if (!opts.hasOwnProperty('apiKey')) { throw new Error('You must pass an apiKey to use GoogleApi'); } const apiKey = opts.apiKey; const libraries = opts.libraries || ['places']; const client = opts.client; const URL = opts.url || 'https://maps.googleapis.com/maps/api/js'; const googleVersion = opts.version || '3.31'; let script = null; let google = (typeof window !== 'undefined' && window.google) || null; let loading = false; let channel = null; let language = opts.language; let region = opts.region || null; let onLoadEvents = []; const url = () => { let url = URL; let params = { key: apiKey, callback: 'CALLBACK_NAME', libraries: libraries.join(','), client: client, v: googleVersion, channel: channel, language: language, region: region, onError: 'ERROR_FUNCTION' }; let paramStr = Object.keys(params) .filter(k => !!params[k]) .map(k => `${k}=${params[k]}`) .join('&'); return `${url}?${paramStr}`; }; return url(); }; export default GoogleApi;
Add an error call back param
Add an error call back param This allows you to set an onError callback function in case the map doesn't load correctly.
JavaScript
mit
fullstackreact/google-maps-react,fullstackreact/google-maps-react
--- +++ @@ -31,7 +31,8 @@ v: googleVersion, channel: channel, language: language, - region: region + region: region, + onError: 'ERROR_FUNCTION' }; let paramStr = Object.keys(params)
1ee8f0447a3cee59c695276256ff1d67f6d465ad
plugins/livedesk-embed/gui-resources/scripts/js/core/utils/str.js
plugins/livedesk-embed/gui-resources/scripts/js/core/utils/str.js
define(['utils/utf8'],function(utf8){ str = function(str){ this.init(str); } str.prototype = { init: function(str) { this.str = str; }, format: function() { var arg = arguments, idx = 0; if (arg.length == 1 && typeof arg[0] == 'object') arg = arg[0]; return this.str.replace(/%?%(?:\(([^\)]+)\))?([disr])/g, function(all, name, type) { if (all[0] == all[1]) return all.substring(1); var value = arg[name || idx++]; if(typeof value === 'undefined') { return all; } return (type == 'i' || type == 'd') ? +value : utf8.decode(value); }); }, toString: function() { return utf8.decode(this.str); } }; return str; });
define(['utils/utf8'],function(utf8){ str = function(str){ this.init(str); } str.prototype = { init: function(str) { this.str = str; }, format: function() { var arg = arguments, idx = 0; if (arg.length == 1 && typeof arg[0] == 'object') arg = arg[0]; return utf8.decode(this.str.replace(/%?%(?:\(([^\)]+)\))?([disr])/g, function(all, name, type) { if (all[0] == all[1]) return all.substring(1); var value = arg[name || idx++]; if(typeof value === 'undefined') { return all; } return (type == 'i' || type == 'd') ? +value : value; })); }, toString: function() { return utf8.decode(this.str); } }; return str; });
Create embed theme for STT
LB-421: Create embed theme for STT fixed dust utf decode.
JavaScript
agpl-3.0
superdesk/Live-Blog,vladnicoara/SDLive-Blog,vladnicoara/SDLive-Blog,superdesk/Live-Blog,vladnicoara/SDLive-Blog,superdesk/Live-Blog,superdesk/Live-Blog
--- +++ @@ -10,14 +10,14 @@ var arg = arguments, idx = 0; if (arg.length == 1 && typeof arg[0] == 'object') arg = arg[0]; - return this.str.replace(/%?%(?:\(([^\)]+)\))?([disr])/g, function(all, name, type) { + return utf8.decode(this.str.replace(/%?%(?:\(([^\)]+)\))?([disr])/g, function(all, name, type) { if (all[0] == all[1]) return all.substring(1); var value = arg[name || idx++]; if(typeof value === 'undefined') { return all; } - return (type == 'i' || type == 'd') ? +value : utf8.decode(value); - }); + return (type == 'i' || type == 'd') ? +value : value; + })); }, toString: function() { return utf8.decode(this.str);
23367bd69f3b293ec5a338914937c2ae81f11bf5
web/tailwind.config.js
web/tailwind.config.js
module.exports = { purge: [], darkMode: false, // or 'media' or 'class' theme: { extend: {}, }, variants: { extend: {}, }, plugins: [], }
module.exports = { purge: [], darkMode: false, // or 'media' or 'class' theme: { extend: {}, }, variants: { extend: {}, }, plugins: [], prefix: 'tw-', }
Add prefix setting to Tailwind
chore(web): Add prefix setting to Tailwind
JavaScript
mit
ruedap/nekostagram,ruedap/nekostagram,ruedap/nekostagram,ruedap/nekostagram
--- +++ @@ -8,4 +8,5 @@ extend: {}, }, plugins: [], + prefix: 'tw-', }
79a3444d39b69a341f4ac9ecc41147bee51b89df
src/common/fermenter/fermenterEnv.js
src/common/fermenter/fermenterEnv.js
import { Record } from 'immutable'; export default Record({ createdAt: null, temperature: null, humidity: null, isValid: false, errors: 0, });
import { Record } from 'immutable'; export default Record({ createdAt: null, temperature: null, humidity: null, isValid: false, errors: 0, iterations: 0 });
Add support for fermenter-iteration attribute.
Add support for fermenter-iteration attribute.
JavaScript
mit
cjk/smart-home-app
--- +++ @@ -6,4 +6,5 @@ humidity: null, isValid: false, errors: 0, + iterations: 0 });
d967a3c6647697a8e3af70bc9e508843cc534f02
src/apps/DataObjects/DataObjectsTable/DataObjectsTableDateCell.js
src/apps/DataObjects/DataObjectsTable/DataObjectsTableDateCell.js
import React from 'react'; import Moment from 'moment'; const DataObjectsTableDateCell = ({ content }) => { const dateValue = content.value; const date = Moment(dateValue).format('DD/MM/YYYY'); const time = Moment(dateValue).format('LTS'); const title = `${date} ${time}`; return ( <div title={title}> {date} </div> ); }; export default DataObjectsTableDateCell;
import React from 'react'; import Moment from 'moment'; const DataObjectsTableDateCell = ({ content }) => { const date = Moment(content).format('DD/MM/YYYY'); const time = Moment(content).format('LTS'); const title = `${date} ${time}`; return ( <div title={title}> {date} </div> ); }; export default DataObjectsTableDateCell;
Fix ‘created_at’ and ‘updated_at’ values in data objects table
Fix ‘created_at’ and ‘updated_at’ values in data objects table
JavaScript
mit
Syncano/syncano-dashboard,Syncano/syncano-dashboard,Syncano/syncano-dashboard
--- +++ @@ -2,9 +2,8 @@ import Moment from 'moment'; const DataObjectsTableDateCell = ({ content }) => { - const dateValue = content.value; - const date = Moment(dateValue).format('DD/MM/YYYY'); - const time = Moment(dateValue).format('LTS'); + const date = Moment(content).format('DD/MM/YYYY'); + const time = Moment(content).format('LTS'); const title = `${date} ${time}`; return (
cd5afa980aa07571f2a094d1243500c3f9d80308
eventFactory.js
eventFactory.js
var assert = require('assert'); var uuid = require('uuid'); module.exports = { NewEvent: function(eventType, data, metadata) { assert(eventType); assert(data); var event = { eventId: uuid.v4(), eventType: eventType, data: data } if (metadata !== undefined) event.metadata = metadata; return event; } };
var assert = require('assert'); var uuid = require('uuid'); module.exports = { NewEvent: function(eventType, data, metadata, eventId) { assert(eventType); assert(data); var event = { eventId: eventId || uuid.v4(), eventType: eventType, data: data } if (metadata !== undefined) event.metadata = metadata; return event; } };
Add support for custom eventId
Add support for custom eventId
JavaScript
mit
RemoteMetering/geteventstore-promise,RemoteMetering/geteventstore-promise
--- +++ @@ -2,12 +2,12 @@ var uuid = require('uuid'); module.exports = { - NewEvent: function(eventType, data, metadata) { + NewEvent: function(eventType, data, metadata, eventId) { assert(eventType); assert(data); var event = { - eventId: uuid.v4(), + eventId: eventId || uuid.v4(), eventType: eventType, data: data }
3a1ad0c467e02854c8b8cceda133c698a63fcaca
fateOfAllFools.dev.user.js
fateOfAllFools.dev.user.js
// ==UserScript== // @author Robert Slifka (GitHub @rslifka) // @connect docs.google.com // @connect rslifka.github.io // @copyright 2017-2018, Robert Slifka (https://github.com/rslifka/fate_of_all_fools) // @description (DEVELOPMENT) Enhancements to the Destiny Item Manager // @grant GM_addStyle // @grant GM_getResourceText // @grant GM_getValue // @grant GM_log // @grant GM_setValue // @grant GM_xmlhttpRequest // @homepage https://github.com/rslifka/fate_of_all_fools // @license MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt // @match https://*.destinyitemmanager.com/* // @name (DEVELOPMENT) Fate of All Fools // @require file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/build/fateOfAllFools.js // @resource fateOfAllFoolsCSS file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/build/fateOfAllFools.css // @run-at document-idle // @supportURL https://github.com/rslifka/fate_of_all_fools/issues // ==/UserScript==
// ==UserScript== // @author Robert Slifka (GitHub @rslifka) // @connect docs.google.com // @connect rslifka.github.io // @copyright 2017-2018, Robert Slifka (https://github.com/rslifka/fate_of_all_fools) // @description (DEVELOPMENT) Enhancements to the Destiny Item Manager // @grant GM_addStyle // @grant GM_getResourceText // @grant GM_getValue // @grant GM_log // @grant GM_setValue // @grant GM_xmlhttpRequest // @homepage https://github.com/rslifka/fate_of_all_fools // @license MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt // @match https://*.destinyitemmanager.com/* // @name (DEVELOPMENT) Fate of All Fools // @require file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.js // @resource fateOfAllFoolsCSS file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.css // @run-at document-idle // @supportURL https://github.com/rslifka/fate_of_all_fools/issues // ==/UserScript==
Update path for local development
Update path for local development
JavaScript
mit
rslifka/fate_of_all_fools,rslifka/fate_of_all_fools
--- +++ @@ -14,8 +14,8 @@ // @license MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt // @match https://*.destinyitemmanager.com/* // @name (DEVELOPMENT) Fate of All Fools -// @require file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/build/fateOfAllFools.js -// @resource fateOfAllFoolsCSS file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/build/fateOfAllFools.css +// @require file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.js +// @resource fateOfAllFoolsCSS file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.css // @run-at document-idle // @supportURL https://github.com/rslifka/fate_of_all_fools/issues // ==/UserScript==
1cc390262adb5c03968aee1753bcd1e8aad3b604
webpack.config.base.js
webpack.config.base.js
/** * Base webpack config used across other specific configs */ const path = require('path'); const validate = require('webpack-validator'); const config = validate({ entry: [ 'babel-polyfill', './views/components/App.jsx' ], module: { loaders: [{ test: /\.jsx?$/, loaders: ['babel-loader'], exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }] }, output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', // https://github.com/webpack/webpack/issues/1114 libraryTarget: 'commonjs2' }, // https://webpack.github.io/docs/configuration.html#resolve resolve: { extensions: ['', '.js', '.jsx', '.json'], packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'] }, plugins: [], externals: [ // put your node 3rd party libraries which can't be built with webpack here // (mysql, mongodb, and so on..) ] }); module.exports = config;
/** * Base webpack config used across other specific configs */ const path = require('path'); const validate = require('webpack-validator'); const config = validate({ entry: [ 'babel-polyfill', './views/App.jsx' ], module: { loaders: [{ test: /\.jsx?$/, loaders: ['babel-loader'], exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }] }, output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', // https://github.com/webpack/webpack/issues/1114 libraryTarget: 'commonjs2' }, // https://webpack.github.io/docs/configuration.html#resolve resolve: { extensions: ['', '.js', '.jsx', '.json'], packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'] }, plugins: [], externals: [ // put your node 3rd party libraries which can't be built with webpack here // (mysql, mongodb, and so on..) ] }); module.exports = config;
Fix problem launching app with webpack
Fix problem launching app with webpack
JavaScript
mit
amoshydra/nus-notify,amoshydra/nus-notify
--- +++ @@ -8,7 +8,7 @@ const config = validate({ entry: [ 'babel-polyfill', - './views/components/App.jsx' + './views/App.jsx' ], module: {
4c3fa5fa31e24f4633f65060ba3a4e5ee278d6ac
test/multidevice/selectAny.js
test/multidevice/selectAny.js
"use strict"; var assert = require('chai').assert; var xdTesting = require('../../lib/index') var templates = require('../../lib/templates'); var q = require('q'); describe('MultiDevice - selectAny', function () { var test = this; test.baseUrl = "http://localhost:8090/"; it('should select a single device @large', function () { var options = { A: templates.devices.chrome(), B: templates.devices.chrome() }; return xdTesting.multiremote(options) .selectAny(device => device .getCount().then(count => assert.equal(count, 1)) ) .end() }); it('should execute promises callback @large', function () { var options = { A: templates.devices.chrome(), B: templates.devices.chrome() }; var queue = ''; return xdTesting.multiremote(options) .then(() => queue += '0') .selectAny(device => { queue += '1'; return device.then(() => { queue += '2'; }); }) .then(() => queue += '3') .then(() => assert.equal(queue, '0123')) .end(); }); });
"use strict"; var assert = require('chai').assert; var xdTesting = require('../../lib/index') var templates = require('../../lib/templates'); var q = require('q'); describe('MultiDevice - selectAny', function () { var test = this; test.baseUrl = "http://localhost:8090/"; it('should select a single device @medium', function () { var options = { A: templates.devices.chrome(), B: templates.devices.chrome() }; return xdTesting.multiremote(options) .getCount().then(count => assert.equal(count, 2)) .selectAny(device => device .getCount().then(count => assert.equal(count, 1)) ) .end() }); it('should execute promises callback @medium', function () { var options = { A: templates.devices.chrome(), B: templates.devices.chrome() }; var queue = ''; return xdTesting.multiremote(options) .then(() => queue += '0') .selectAny(device => { queue += '1'; return device.then(() => { queue += '2'; }); }) .then(() => queue += '3') .then(() => assert.equal(queue, '0123')) .end(); }); });
Update test, fix test size
Update test, fix test size
JavaScript
mit
spiegelm/xd-testing,spiegelm/xd-testing,spiegelm/xd-testing
--- +++ @@ -10,20 +10,21 @@ test.baseUrl = "http://localhost:8090/"; - it('should select a single device @large', function () { + it('should select a single device @medium', function () { var options = { A: templates.devices.chrome(), B: templates.devices.chrome() }; return xdTesting.multiremote(options) + .getCount().then(count => assert.equal(count, 2)) .selectAny(device => device .getCount().then(count => assert.equal(count, 1)) ) .end() }); - it('should execute promises callback @large', function () { + it('should execute promises callback @medium', function () { var options = { A: templates.devices.chrome(), B: templates.devices.chrome()
769520bf1ac90987d942cec4e08bd78b34480c5c
app/assets/javascripts/views/experiences/add_image_to_experience_form.js
app/assets/javascripts/views/experiences/add_image_to_experience_form.js
function addImageToExperienceForm(experienceID) { var assetURL = "/users/" + getCurrentUser() + "/assets/new" $.ajax({ method: "get", url: assetURL, }) .done(function(response){ var postURL = "/users/" + getCurrentUser() + "/assets" clearMainFrame() hideMainMenu() var $experienceID = $("<input>").attr({ type: "hidden", value: experienceID, name: "assets[experience_id]" }) $dropzone = $(response) $dropzone.find('#multi-upload').append($experienceID) appendToMainFrame($dropzone) var dropzone = new Dropzone("#multi-upload", { url: postURL }); // s3Run() }) }
function addImageToExperienceForm(experienceID) { var assetURL = "/users/" + getCurrentUser() + "/assets/new" $.ajax({ method: "get", url: assetURL, }) .done(function(response){ var postURL = "/users/" + getCurrentUser() + "/assets" clearMainFrame() hideMainMenu() var $experienceID = $("<input>").attr({ type: "hidden", value: experienceID, name: "assets[experience_id]" }) $dropzone = $(response) $dropzone.find('#multi-upload').append($experienceID) $submit = $("<input type='submit'>").addClass("form-submit").appendTo($dropzone) appendToMainFrame($dropzone) var dropzone = new Dropzone("#multi-upload", { url: postURL }); // s3Run() }) }
Add submit button to upload images dialog
Add submit button to upload images dialog
JavaScript
mit
dma315/ambrosia,dma315/ambrosia,dma315/ambrosia
--- +++ @@ -15,6 +15,7 @@ }) $dropzone = $(response) $dropzone.find('#multi-upload').append($experienceID) + $submit = $("<input type='submit'>").addClass("form-submit").appendTo($dropzone) appendToMainFrame($dropzone) var dropzone = new Dropzone("#multi-upload", { url: postURL }); // s3Run()
df46bb81776cba0723fa09a686bd13a2bb9ccd7d
public/js/app/controllers/ApplicationController.js
public/js/app/controllers/ApplicationController.js
define(["app/app", "ember"], function(App, Ember) { "use strict"; App.ApplicationController = Ember.Controller.extend({ hasMessage: function() { var message = this.get('session.message') return message && message.length > 0 }.property('session.message'), displayError: function(error) { this.get('session').set('message', error.responseJSON.err) } }) })
define(["app/app", "ember"], function(App, Ember) { "use strict"; App.ApplicationController = Ember.Controller.extend({ hasMessage: function() { var message = this.get('session.message') return message && message.length > 0 }.property('session.message'), displayError: function(error) { window.setTimeout(function () { $(".box-message").slideUp(300, function () { $(this).remove() }) }, 5000) this.get('session').set('message', error.responseJSON.err) } }) })
Remove info message after 5sec.
Remove info message after 5sec.
JavaScript
mit
pepyatka/pepyatka-html,dsumin/freefeed-html,pepyatka/pepyatka-html,FreeFeed/freefeed-html,SiTLar/pepyatka-html,FreeFeed/freefeed-html,dsumin/freefeed-html,epicmonkey/pepyatka-html,SiTLar/pepyatka-html,epicmonkey/pepyatka-html
--- +++ @@ -9,6 +9,11 @@ }.property('session.message'), displayError: function(error) { + window.setTimeout(function () { + $(".box-message").slideUp(300, function () { + $(this).remove() + }) + }, 5000) this.get('session').set('message', error.responseJSON.err) } })
4022f0ad98948a27db464f2f11e84c811c3a1165
lib/emitters/custom-event-emitter.js
lib/emitters/custom-event-emitter.js
var util = require("util") , EventEmitter = require("events").EventEmitter module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); } util.inherits(CustomEventEmitter, EventEmitter) CustomEventEmitter.prototype.run = function() { var self = this return this } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct) return this } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct) return this } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }) return this } return CustomEventEmitter })()
var util = require("util") , EventEmitter = require("events").EventEmitter module.exports = (function() { var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; } util.inherits(CustomEventEmitter, EventEmitter) CustomEventEmitter.prototype.run = function() { var self = this; process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); return this; } CustomEventEmitter.prototype.success = CustomEventEmitter.prototype.ok = function(fct) { this.on('success', fct) return this } CustomEventEmitter.prototype.failure = CustomEventEmitter.prototype.fail = CustomEventEmitter.prototype.error = function(fct) { this.on('error', fct) return this } CustomEventEmitter.prototype.done = CustomEventEmitter.prototype.complete = function(fct) { this.on('error', function(err) { fct(err, null) }) .on('success', function(result) { fct(null, result) }) return this } return CustomEventEmitter })()
Move process.nextTick() to run() method
Move process.nextTick() to run() method Hope this fixes the tests. Thanks @janmeier
JavaScript
mit
IrfanBaqui/sequelize
--- +++ @@ -5,17 +5,19 @@ var CustomEventEmitter = function(fct) { this.fct = fct; var self = this; + } + util.inherits(CustomEventEmitter, EventEmitter) + + CustomEventEmitter.prototype.run = function() { + var self = this; + process.nextTick(function() { if (self.fct) { self.fct.call(self, self) } }.bind(this)); - } - util.inherits(CustomEventEmitter, EventEmitter) - - CustomEventEmitter.prototype.run = function() { - var self = this - return this + + return this; } CustomEventEmitter.prototype.success =