commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
96639d2d9d9e5eaab6813e34c67946f541ab0031
Update maintenance-utils.js
js/maintenance-utils.js
js/maintenance-utils.js
( function (window) { var self = this; // private variables var _landingPage = "https://software-development-of-better-tomorrow.org/"; var disallowdResolutionsArray = ["1024", "600"]; var _interval; // ~ private variables // private functions function getIntervalOrDefault_Internal() { var hash_value_of_interval = 1000; var hash = location.hash.substring(1).trim(); if(hash.length > 0) { hash_value_of_interval = parseInt(hash); } return hash_value_of_interval * 1000; } function tryAccessLandingPage_Internal() { window.location.href = _landingPage; } function checkWebsiteAvailability_Internal() { _interval = getIntervalOrDefault_Internal(); setInterval(function() { tryAccessLandingPage_Internal(); }, _interval); } // ~ private functions // Public API self.checkWebsiteAvailability = function () { return checkWebsiteAvailability_Internal(); }; // ~ Public API window.maintenance = window.maintenance || self; } )(window)
JavaScript
0.000001
@@ -651,24 +651,26 @@ ) %7B%0A +// window.locat @@ -693,16 +693,20 @@ ingPage; + :D %0A %7D%0A%0A
3f7a5b77da65064398987fc9031f7936f1cd5c45
Enable tailwind-2-0-like purge mode
ruby_event_store-browser/elm/tailwind.config.js
ruby_event_store-browser/elm/tailwind.config.js
module.exports = { purge: ['./src/style/style.css'], theme: { extend: {} }, variants: {}, plugins: [] }
JavaScript
0
@@ -12,16 +12,65 @@ rts = %7B%0A + future: %7B%0A purgeLayersByDefault: true,%0A %7D,%0A purge:
ea3b385ddba9f0b7cbef1b984f0425a7e3b3a912
fix dictinct
app/views/stats.js
app/views/stats.js
define(['lodash','authentication'], function(_) { return ['$scope', '$http', '$timeout', '$location', '$q', function ($scope, $http, $timeout, $location, $q) { $scope.requests = []; $scope.refresh = refresh; $scope.sum = sum; $scope.distinct = distinct; $scope.getFromLast = getFromLast; $scope.isPending = function(r) { return is(r, 'pending' ); }; $scope.isPendingHeld = function(r) { return is(r, 'pending-held' ); }; $scope.isProcessing = function(r) { return is(r, 'processing' ); }; $scope.isProcessingStop = function(r) { return is(r, 'processing-stopped' ); }; $scope.isCompleted = function(r) { return is(r, 'completed' ); }; $scope.isCanceled = function(r) { return is(r, 'canceled' ); }; $scope.isAborted = function(r) { return is(r, 'aborted' ); }; $scope.isCleared = function(r) { return is(r, 'cleared' ); }; var qAutoRefresh = null; $scope.$on('$routeChangeStart', function() { if(!qAutoRefresh) return; console.log('Canceling autoRefresh'); $timeout.cancel(qAutoRefresh); qAutoRefresh = null; }); $scope.$watch(function() { return $location.path(); }, function(path) { if(path != "/") { $scope.badge = ""; $scope.$root.contact = null; } }); autoRefresh(); function autoRefresh() { qAutoRefresh = null; refresh(); qAutoRefresh = $timeout(autoRefresh, 30*1000); } function refresh() { $scope.loading = { downloads : true, prints : true } var r1, r2; r1 = $http.get("/api/v2014/printsmart-requests", { params : { badge : $location.search().badge } }).then(function(res){ $scope.requests = res.data; }).catch(function(err) { if(err.status==403){ $location.url('/403'); return; } console.error(err.data||err); }).finally(function(){ delete $scope.loading.prints; }) r2 = $http.get("/api/v2014/printsmart-downloads", { params : { badge : $location.search().badge } }).then(function(res){ var downloads = res.data; var totalDownloads = 0; _.each(downloads, function(d){ totalDownloads += d.items.length * (d.downloads||0); }); $scope.totalDownloads = totalDownloads; }).catch(function(err) { if(err.status==403){ $location.url('/403'); return; } console.error(err.data||err); }).finally(function(){ delete $scope.loading.downloads; }) $q.all([r1, r2]).finally(function(){ delete $scope.loading; }) } $scope.averageJobTime = function(slot, last) { var requests = $scope.requests; requests = _.filter(requests, function(r) { return r && r.status && r.status[slot]; }); requests = requests.splice (requests.length-11, last); return sum(_.map(requests, function(r) { return r.status[slot] - r.status['time-at-creation']; })) / requests.length; }; function is(request, status) { if(status=="cleared") { return request && request.completed; } return request && request.status && request.status['job-state'] === status; } function getFromLast(minutes) { var time = new Date(); time.setMinutes(time.getMinutes()-minutes); var sTime = formatDate(time); return _.filter($scope.requests, function(r) { return r && r.createdOn && r.createdOn > sTime; }); } function distinct(value, member1, member2, member3, member4, member5) { if(value===undefined) return []; if(value===null) return []; var values = []; if(_.isArray(value)) { _.each(value, function(entry) { if(member1) values = _.union(values, distinct(entry[member1], member2, member3, member4, member5)); else if(value!==undefined && value!==null) values = _.union(values, value); }); } else if(member1) values = _.union(values, distinct(value[member1], member2, member3, member4, member5)); else values = _.union(values, value); return _.uniq(values); } function sum(value, member1, member2, member3, member4, member5) { if(value===undefined) return 0; if(value===null) return 0; var total = 0; if(_.isArray(value)) { _.each(value, function(entry) { if(member1) total += sum(entry[member1], member2, member3, member4, member5); else if(_.isNumber(entry)) total += entry; }); } else if(member1) { total += sum(value[member1], member2, member3, member4, member5); } else if(_.isNumber(value)) { total += value; } return total; } //============================================================ // // //============================================================ function formatDate(date) { var pad = function(s) { s = ''+s; return s.length<2 ? '0'+s : s; }; return pad(date.getUTCFullYear())+'-'+ pad(date.getUTCMonth()+1) +'-'+ pad(date.getUTCDate()) +'T'+ pad(date.getUTCHours()) +':'+ pad(date.getUTCMinutes()) +':'+ pad(date.getUTCSeconds()) +'.000Z'; } }]; });
JavaScript
0.000004
@@ -4254,21 +4254,23 @@ values, +%5B value +%5D );%0A%0A%09%09%09r
f1fe4e4c0e2e2328ff123ee3ebee1c2fca633cd2
fix fonts path
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var less = require('gulp-less'); var cleanCSS = require('gulp-clean-css'); var rename = require("gulp-rename"); var replace = require('gulp-replace'); var htmlmin = require('gulp-htmlmin'); var minifyInline = require('gulp-minify-inline'); var vulcanize = require('gulp-vulcanize'); var path = require('path'); var swPrecache = require('sw-precache'); // Minify HTML gulp.task('minify-html', function() { return gulp.src('app/index.html') .pipe(htmlmin({ collapseWhitespace: true, removeComments: true, minifyCSS: true, minifyJS: true })) .pipe(replace('src/critical.html', 'critical.html')) .pipe(replace('src/deferred.html', 'deferred.html')) .pipe(gulp.dest('dist')); }); // Compile LESS files from /less into /css gulp.task('less', function() { return gulp.src('app/less/clean-blog.less') .pipe(less()) .pipe(gulp.dest('css')); }); // Minify compiled CSS gulp.task('minify-css', ['less'], function() { return gulp.src('app/css/clean-blog.css') .pipe(cleanCSS({ compatibility: 'ie8' })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('css')); }); // Vulcanize Web Components gulp.task('vulcanize', ['minify-css'], function () { gulp.src('app/src/critical.html') .pipe(vulcanize({ stripComments: true, inlineScripts: true, inlineCss: true })) .pipe(htmlmin({ collapseWhitespace: true, removeComments: true, minifyCSS: true, minifyJS: true })) .pipe(minifyInline()) .pipe(gulp.dest('dist')); gulp.src('app/src/deferred.html') .pipe(vulcanize({ stripComments: true, inlineScripts: true, inlineCss: true })) .pipe(htmlmin({ collapseWhitespace: true, removeComments: true, minifyCSS: true, minifyJS: true })) .pipe(minifyInline()) .pipe(replace('../bower_components/font-awesome/fonts/', 'fonts/')) .pipe(gulp.dest('dist')); }); gulp.task('generate-service-worker', function(callback) { var rootDir = 'dist'; swPrecache.write(path.join(rootDir, 'service-worker.js'), { staticFileGlobs: [rootDir + '/**/*.{js,html,jpg,otf,eot,ttf,woff,woff2,md}'], stripPrefix: rootDir }, callback); }); // Copy files gulp.task('copy', function() { gulp.src(['app/posts/**']) .pipe(gulp.dest('dist/posts')) gulp.src(['app/img/**']) .pipe(gulp.dest('dist/img')) gulp.src(['bower_components/font-awesome/fonts/**']) .pipe(gulp.dest('dist/fonts')) gulp.src(['bower_components/webcomponentsjs/webcomponents-lite.min.js']) .pipe(gulp.dest('dist/js')); }) // Run everything gulp.task('default', ['less', 'minify-css', 'minify-html', 'vulcanize', 'generate-service-worker', 'copy']);
JavaScript
0.000022
@@ -1952,16 +1952,19 @@ ace('../ +../ bower_co
e3fed360978c5948f179bbea068d5784e3b14e7c
add gulp tasks
gulpfile.js
gulpfile.js
JavaScript
0.000006
@@ -0,0 +1,250 @@ +'use strict';%0Avar gulp = require('gulp');%0Avar shell = require('gulp-shell');%0A%0Agulp.task('default', %5B'build'%5D);%0Agulp.task('build', shell.task('npm run build'));%0Agulp.task('test' , shell.task('npm test'));%0Agulp.task('run' , shell.task('npm start'));%0A
01131ba4d787f42e8b6164a7740065706c8a9105
update 04.30
js/pages/AboutUsPage.js
js/pages/AboutUsPage.js
import React, {Component} from "react"; import { View, StyleSheet, Text, Navigator, TouchableOpacity, Image, ScrollView, Dimensions, WebView } from "react-native"; import CommonNav from "../common/CommonNav"; import TextPingFang from "../common/TextPingFang"; import AboutUsWebPage from "./AboutUsWebPage"; const WIDTH = Dimensions.get("window").width const INNERWIDTH = WIDTH - 16 const HEIGHT = Dimensions.get("window").height export default class AboutUsPage extends Component { render() { return <View style={styles.container}> <Image style={styles.bg} source={require("../../res/images/about_bg.png")}> <CommonNav title={"关于我们"} navigator={this.props.navigator} navStyle={styles.opacity0} navBarStyle={styles.opacity0}/> </Image> <Image style={styles.logo} source={require("../../res/images/about_logo.png")}/> <View style={styles.text}> <Text style={styles.slogan}>ONE</Text> <TextPingFang style={styles.name}>一图</TextPingFang> <Text style={styles.slogan}>LIBRARY</Text> <View style={styles.border}></View> </View> <View style={styles.names}> <Text style={styles.name}>Back-End:Airing</Text> <Text style={styles.name}>UI Design:Albert Leung</Text> <Text style={styles.name}>IOS APP:YiFan Wang</Text> <View> <TouchableOpacity style={styles.contact} onPress={()=>{ this.props.navigator.push({ component:AboutUsWebPage, }) }} > <Text style={styles.contact_font}>联系我们</Text> </TouchableOpacity> </View> </View> <Text style={styles.version}>Verison1.0</Text> </View> } } const styles = StyleSheet.create({ container: { width:WIDTH, height:HEIGHT, alignItems:"center" }, bg:{ width:WIDTH, }, opacity0:{ backgroundColor:"rgba(0,0,0,0)" }, logo: { marginTop:-126, }, text:{ alignItems:"center", marginTop:18*HEIGHT/667 }, name:{ color:"#666666", fontSize:24 }, slogan:{ fontSize:64, color:"rgb(250,250,250)", }, border: { width:2, height:74/667*HEIGHT, backgroundColor:"#999999", marginTop:-74/667*HEIGHT }, names: { marginTop:32*HEIGHT/667, alignItems:"center" }, name: { color:"#999999", fontSize:14, marginBottom:4/667 }, version:{ position:"absolute", bottom:5, color:"#999999", fontSize:14, }, contact: { width:INNERWIDTH, height:44*HEIGHT/667, marginTop:20*HEIGHT/667, alignItems:"center" }, contact_font:{ textDecorationLine:"underline", } })
JavaScript
0
@@ -1605,17 +1605,17 @@ erison1. -0 +1 %3C/Text%3E%0A
12ab19182deb854da33439fd7968f129c4efbb63
enable captcha
apps/home/index.js
apps/home/index.js
var express = require('express'); var app = module.exports = express(); var util = require("util"); var settings = require('../../settings') var Recaptcha = require('recaptcha').Recaptcha; app.set('views', __dirname); app.get('/', captureReferrer, showFaucet); app.post('/', validateCaptcha, validateAddress, validateFrequency, dispense, showFaucet); function captureReferrer(req, res, next) { if(req.query.r) req.session.referrer = req.query.r; next(); } function showFaucet(req, res, next) { var recaptcha = new Recaptcha(settings.recaptcha.key, settings.recaptcha.secret); res.render("index", { recaptcha_form: recaptcha.toHTML() }); } function validateCaptcha(req, res, next) { var recaptcha = new Recaptcha(settings.recaptcha.key, settings.recaptcha.secret); var data = { remoteip: req.connection.remoteAddress, challenge: req.body.recaptcha_challenge_field, response: req.body.recaptcha_response_field }; recaptcha.verify(function(success, err) { //res.captchaPassed = success; //if(!success) res.locals.error = "Captcha Invalid. Please Try Again!" res.captchaPassed = true; next(); }); } function validateAddress(req, res, next) { req.coinRPC.validateaddress(req.body.address, function(err, info) { res.addressValid = !info.isvalid; if(!info.isvalid) res.locals.error = "Invalid Dogecoin Address" next(); }) } function validateFrequency(req, res, next) { req.dbConn.query('SELECT TIMEDIFF(DATE_ADD(ts, INTERVAL ? MINUTE), NOW()) AS remainingTime FROM transactions WHERE (address=? OR ip=?) AND ts > DATE_SUB(NOW(), INTERVAL ? MINUTE);', [settings.payout.frequency, req.body.address, req.connection.remoteAddress, settings.payout.frequency], function(err, rows, fields) { if (err) throw err; res.addressValid = rows.length === 0; if(rows.length > 0) res.locals.error = "Too Soon! Come back in " + rows[0].remainingTime; next(); }); } function dispense(req, res, next) { if(res.locals.error) return next(); var bracketOdds = 0; res.locals.dispenseAmt = settings.payout.bracket[0].amt; res.locals.luckyNumber = Math.random() * 100; for(x = 0; x < settings.payout.bracket.length; x++) { bracketOdds += settings.payout.bracket[x].odds if(res.locals.luckyNumber < bracketOdds) { res.locals.dispenseAmt = settings.payout.bracket[x].amt; break; } } req.dbConn.query('INSERT INTO transactions (address, ip, amount, referrer) VALUES (?,?,?,?)', [req.body.address, req.connection.remoteAddress, res.locals.dispenseAmt, req.session.referrer, false], function(err, result) { if (err) throw err; if(result.affectedRows === 1) { res.locals.success = true; checkUserBalance(req, function(err, balance) { res.locals.userBalance = balance; next(); }) } else { res.locals.error = "Error dispenseing, please try again." next() } }); } function checkUserBalance(req, callback) { req.dbConn.query('SELECT SUM(amount) AS userBalance FROM transactions WHERE dispensed is NULL AND address=?', [req.body.address], function(err, rows, fields) { callback(err, rows[0].userBalance); }); }
JavaScript
0.000001
@@ -1011,18 +1011,16 @@ %7B%0A %09 -// res.capt @@ -1049,10 +1049,8 @@ %09 -// if(! @@ -1119,39 +1119,8 @@ n!%22%0A - %09res.captchaPassed = true;%0A
720e3b3048cff646c8e5bb55b6517935cc4a34fd
test zuul task completed
gulpfile.js
gulpfile.js
(function(){ var gulp = require("gulp"); var mocha = require("gulp-mocha"); var browserify = require("./support/browserify.js"); var file = require("gulp-file"); // Task names var TASK_BUILD = "build"; // rebuild var TASK_WATCHER = "watch"; // auto rebuild on changes var TASK_TEST = "test"; // multiplexes to test-node / test-zuul var TASK_TEST_NODE = "test-node"; var TASK_TEST_ZUUL = "test-zuul"; var TASK_TEST_COV = "test-cov"; //////////////////////////////////////// // BUILDING //////////////////////////////////////// var BUILD_TARGET_FILENAME = "engine.io.js"; var BUILD_TARGET_DIR = "./"; var WATCH_GLOBS = [ "lib/*.js", "lib/transports/*.js", "package.json" ]; gulp.task("default", [TASK_BUILD]); // "gulp watch" from terminal to automatically rebuild when // files denoted in WATCH_GLOBS have changed. gulp.task(TASK_WATCHER, function(){ gulp.watch(WATCH_GLOBS, [TASK_BUILD]); }); // generate engine.io.js using browserify gulp.task(TASK_BUILD, function(){ browserify(function(err, output){ if (err) throw err; // TODO: use browserify/webpack as stream file(BUILD_TARGET_FILENAME, output, { src: true }) .pipe(gulp.dest(BUILD_TARGET_DIR)); }); }); //////////////////////////////////////// // TESTING //////////////////////////////////////// var REPORTER = "dot"; var TEST_FILE = "./test/index.js"; var TEST_SUPPORT_SERVER_FILE = "./test/support/server.js"; gulp.task(TASK_TEST, function(){ if (process.env.hasOwnProperty("BROWSER_NAME")) { testZuul(); } else { testNode(); } }); gulp.task(TASK_TEST_NODE, testNode); gulp.task(TASK_TEST_ZUUL, testZuul); gulp.task(TASK_TEST_COV, function(){ }); function testNode() { var MOCHA_OPTS = { reporter: REPORTER, require: [TEST_SUPPORT_SERVER_FILE] }; gulp.src(TEST_FILE, { read: false }) .pipe(mocha(MOCHA_OPTS)) // following lines to fix gulp-mocha not terminating (see gulp-mocha webpage) .once("error", function(){ process.exit(1); }) .once("end", function(){ process.exit(); }); } function testZuul() { } })();
JavaScript
0.998857
@@ -171,16 +171,64 @@ -file%22); +%0A var spawn = require(%22child-process%22).spawn; %0A%0A // @@ -1949,24 +1949,38 @@ function()%7B%0A + //TODO %0A %7D);%0A%0A @@ -2443,16 +2443,791 @@ ul() %7B%0A%0A + if (!(process.env.hasOwnProperty(%22BROWSER_NAME%22)%0A && process.env.hasOwnProperty(%22BROWSER_VERSION%22))) %7B%0A throw %22travis env vars for zuul/saucelabs not accessible from %22 +%0A %22process.env (BROWSER_NAME or BROWSER_VERSION)%22;%0A %7D%0A%0A var ZUUL_CMD = %22./node_modules/zuul/bin/zuul%22;%0A var args = %5B%0A %22--browser-name%22,%0A process.env.BROWSER_NAME,%0A %22--browser-version%22,%0A process.env.BROWSER_VERSION%0A %5D;%0A // add browser platform argument if valid%0A if (process.env.hasOwnProperty(%22BROWSER_PLATFORM%22)) %7B%0A args.push(%22--browser-platform%22);%0A args.push(process.env.BROWSER_PLATFORM);%0A %7D%0A%0A spawn(ZUUL_CMD, args, %7B stdio: %22inherit%22 %7D);%0A %7D%0A%0A%7D
179deeb60ac9b6c5c7d42d3cf53196c29753aa45
Add unsubscribe method to communication module.
js/src/communication.js
js/src/communication.js
/* eslint-disable */ const logging = require('./logging'); const state = require('./state'); let session; let accPack; let callProperties; let screenProperties; let containers = {}; let autoSubscribe; let active = false; const defaultCallProperties = { insertMode: 'append', width: '100%', height: '100%', showControls: false, style: { buttonDisplayMode: 'off', }, }; /** * Converts a string to proper case (e.g. 'camera' => 'Camera') * @param {String} text * @returns {String} */ const properCase = text => `${text[0].toUpperCase()}${text.slice(1)}`; /** * Trigger an event through the API layer * @param {String} event - The name of the event * @param {*} [data] */ const triggerEvent = (event, data) => accPack.triggerEvent(event, data); /** Create a camera publisher object */ const createPublisher = () => new Promise((resolve, reject) => { // TODO: Handle adding 'name' option to props const props = Object.assign({}, callProperties); // TODO: Figure out how to handle common vs package-specific options const container = containers.publisher.camera || 'publisherContainer'; const publisher = OT.initPublisher(container, props, error => { error ? reject(error) : resolve(publisher); }); }); /** * Publish the local camera stream and update state * @returns {Promise} <resolve: -, reject: Error> */ const publish = () => new Promise((resolve, reject) => { createPublisher() .then((publisher) => { state.addPublisher('camera', publisher); session.publish(publisher); resolve() }) .catch((error) => { const errorMessage = error.code === 1010 ? 'Check your network connection' : error.message; triggerEvent('error', errorMessage); reject(error); }); }); /** * Ensure all required options are received * @param {Object} options */ const validateOptions = (options) => { const requiredOptions = ['session', 'publishers', 'subscribers', 'streams', 'accPack']; requiredOptions.forEach((option) => { if (!options[option]) { logging.error(`${option} is a required option.`); } }); session = options.session; accPack = options.accPack; containers = options.containers; callProperties = options.callProperties || defaultCallProperties; autoSubscribe = options.hasOwnProperty('autoSubscribe') ? options.autoSubscribe : true; screenProperties = options.screenProperties || Object.assign({}, defaultCallProperties, { videoSource: 'window' }); }; /** * Subscribe to new stream unless autoSubscribe is set to false * @param {Object} stream */ const onStreamCreated = ({ stream }) => active && autoSubscribe && subscribe(stream); /** * Update state and trigger corresponding event(s) when stream is destroyed * @param {Object} stream */ const onStreamDestroyed = ({ stream }) => { state.removeStream(stream) const type = stream.videoType; type === 'screen' && triggerEvent('endViewingSharedScreen'); // Legacy event triggerEvent(`unsubscribeFrom${properCase(type)}`, state.currentPubSub()); }; /** * Listen for API-level events */ const createEventListeners = () => { accPack.on('streamCreated', onStreamCreated); accPack.on('streamDestroyed', onStreamDestroyed); }; /** * Start publishing the local camera feed and subscribing to streams in the session * @returns {Promise} <resolve: Object, reject: Error> */ const startCall = () => new Promise((resolve, reject) => { publish() .then(() => { const streams = state.getStreams(); const initialSubscriptions = Object.keys(state.getStreams()).map(streamId => subscribe(streams[streamId])); Promise.all(initialSubscriptions).then(() => { const pubSubData = state.currentPubSub(); triggerEvent('startCall', pubSubData); active = true; resolve(pubSubData); }, (reason) => logging.message(`Failed to subscribe to all existing streams: ${reason}`)); }); }); /** * Subscribe to a stream and update the state * @param {Object} stream - An OpenTok stream object * @returns {Promise} <resolve: > */ const subscribe = stream => new Promise((resolve, reject) => { if (state.getStreams()[stream.id]) { resolve(); } const type = stream.videoType; const container = containers.subscriber[type] || 'subscriberContainer'; const options = type === 'camera' ? callProperties : screenProperties; const subscriber = session.subscribe(stream, container, options, (error) => { if (error) { reject(error); } else { state.addSubscriber(subscriber); triggerEvent(`subscribeTo${properCase(type)}`, Object.assign({}, { subscriber }, state.currentPubSub())); type === 'screen' && triggerEvent('startViewingSharedScreen', subscriber); // Legacy event resolve(); } }); }) /** * Stop publishing and unsubscribe from all streams */ const endCall = () => { const publishers = state.currentPubSub().publishers; const unpublish = publisher => session.unpublish(publisher); Object.keys(publishers.camera).forEach(id => unpublish(publishers.camera[id])); Object.keys(publishers.screen).forEach(id => unpublish(publishers.screen[id])); state.removeAllPublishers(); active = false; }; /** * Enable/disable local audio or video * @param {String} source - 'audio' or 'video' * @param {Boolean} enable */ const enableLocalAV = (id, source, enable) => { const method = `publish${properCase(source)}`; const { publishers } = state.currentPubSub() publishers.camera[id][method](enable); }; /** * Enable/disable remote audio or video * @param {String} subscriberId * @param {String} source - 'audio' or 'video' * @param {Boolean} enable */ const enableRemoteAV = (subscriberId, source, enable) => { const method = `subscribeTo${properCase(source)}`; const { subscribers } = state.currentPubSub(); subscribers.camera[subscriberId][method](enable); }; /** * Initialize the communication component * @param {Object} options * @param {Object} options.session * @param {Object} options.publishers * @param {Object} options.subscribers * @param {Object} options.streams */ const init = (options) => new Promise((resolve) => { validateOptions(options); createEventListeners(); resolve(); }); module.exports = { init, startCall, endCall, subscribe, enableLocalAV, enableRemoteAV, };
JavaScript
0
@@ -4883,16 +4883,343 @@ ;%0A %7D)%0A%0A +/**%0A * Unsubscribe from a stream and update the state%0A * @param %7BObject%7D subscriber - An OpenTok subscriber object%0A * @returns %7BPromise%7D %3Cresolve: empty%3E%0A */%0A const unsubscribe = subscriber =%3E%0A new Promise((resolve) =%3E %7B%0A getSession().unsubscribe(subscriber);%0A state.removeSubscriber(subscriber);%0A resolve();%0A %7D);%0A%0A %0A/**%0A * @@ -6735,16 +6735,31 @@ scribe,%0A + unsubscribe,%0A enable
0a496edf7f1584a4720e7bc3e3b2bf6207f22749
Update gulpfile
gulpfile.js
gulpfile.js
/* eslint-disable */ var gulp = require('gulp'); var eslint = require('gulp-eslint'); var util = require('gulp-util'); var plumber = require('gulp-plumber'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var git = require('gulp-git'); var gulpif = require('gulp-if'); var prompt = require('gulp-prompt'); var bump = require('gulp-bump'); var browserify = require('browserify'); var babel = require('gulp-babel'); var buffer = require('vinyl-buffer'); var del = require('del'); var source = require('vinyl-source-stream'); var runSequence = require('run-sequence'); var semverRegex = require('semver-regex'); var spawn = require('child_process').spawn; var webpack = require('webpack'); var gulpWebpack = require('webpack-stream'); var path = require('path'); function errorHandler(err) { util.log(err.toString()); this.emit('end'); } gulp.task('lint', function() { return gulp.src('src/**/*.js') .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('clean', function(done) { return del(['build', 'dist'], done); }); gulp.task('build', ['clean', 'lint'], function() { return gulp.src('src/**/*.js') .pipe(babel()) .pipe(gulp.dest('./build')) }); gulp.task('bundle', ['build'], function() { return gulp.src('./build/index.js') .pipe(gulpWebpack({ context: __dirname + '/build', entry: './index.js', output: { path: __dirname + '/dist', filename: 'kinvey-angular.js' }, resolve: { alias: { device$: path.resolve(__dirname, 'build/device.js'), popup: path.resolve(__dirname, 'build/popup.js') } } }, webpack)) .pipe(gulp.dest('./dist')) .pipe(rename('kinvey-angular.min.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('./dist')) .on('error', errorHandler); }); gulp.task('uploadS3', ['build'], function () { var packageJSON = require('./package.json'); var version = packageJSON.version; gulp.src([ 'dist/kinvey.js', 'dist/kinvey.min.js' ]) .pipe(plumber()) .pipe(gulpif('kinvey.js', rename({ basename: `kinvey-angular-${version}` }))) .pipe(gulpif('kinvey.min.js', rename({ basename: `kinvey-angular-${version}.min` }))) .pipe(gulp.dest('./sample')); }); gulp.task('commit', function() { return gulp.src('./') .pipe(prompt.prompt({ type: 'input', name: 'message', message: 'What would you like to say for the commit message?', validate: function(message) { if (message && message.trim() !== '') { return true; } return false; } }, function(res) { gulp.src('./*') .pipe(git.add()) .pipe(git.commit(res.message)); })); }); gulp.task('bump', function() { var packageJSON = require('./package.json'); var version = packageJSON.version; return gulp.src('./') .pipe(prompt.prompt({ type: 'input', name: 'version', message: `The current version is ${version}. What is the new version?`, validate: function(version) { return semverRegex().test(version); } }, function(res) { gulp.src(['bower.json', 'package.json']) .pipe(bump({ version: res.version })) .pipe(gulp.dest('./')); })); }); gulp.task('tag', ['bump'], function(done) { var packageJSON = require('./package.json'); var version = packageJSON.version; git.tag(version, null, function (err) { if (err) { errorHandler(err); } done(err); }); }); gulp.task('push', function(done) { git.push('origin', 'master', { args: '--follow-tags -f' }, function(error) { if (error) { errorHandler(error); } done(error); }); }); gulp.task('publish', function(done) { spawn('publish', ['publish'], { stdio: 'inherit' }).on('close', done); }); gulp.task('release', function() { runSequence('uploadS3', 'commit', 'tag', ['push', 'publish']); }); gulp.task('default', function() { runSequence('bundle'); });
JavaScript
0.000001
@@ -1614,16 +1614,17 @@ popup +$ : path.r
ae498ac005d8f379bdbcc88ad68dcab02a793fe4
Add error handler to SASS so it won't crash on error
gulpfile.js
gulpfile.js
//initialize all of our variables var app, base, concat, connect, directory, gulp, gutil, hostname, http, lr, open, path, refresh, sass, server, uglify, imagemin, cache, minifyCSS, clean; //load all of our dependencies //add more here if you want to include more libraries gulp = require('gulp'); gutil = require('gulp-util'); concat = require('gulp-concat'); uglify = require('gulp-uglify'); sass = require('gulp-sass'); refresh = require('gulp-livereload'); open = require('gulp-open'); connect = require('connect'); http = require('http'); path = require('path'); lr = require('tiny-lr'); imagemin = require('gulp-imagemin'); cache = require('gulp-cache'); minifyCSS = require('gulp-minify-css'); clean = require('gulp-clean'); //start our server server = lr(); //this starts the webserver so we can run localhost:3000 and sync with the LiveReload plugin gulp.task('webserver', function() { //the port to run our local webserver on var port = 3000; hostname = null; //the directory to our working environment base = path.resolve('app'); directory = path.resolve('app'); //start up the server app = connect().use(connect["static"](base)).use(connect.directory(directory)); http.createServer(app).listen(port, hostname); }); //connecting to the live reload plugin, basically notifies the browser to refresh when we want it to gulp.task('livereload', function() { //this is the default port, you shouldn't need to edit it server.listen(35729, function(err) { if (err != null) { return console.log(err); } }); }); //compressing images & handle SVG files gulp.task('images', function() { gulp.src(['app/images/*.jpg', 'app/images/*.png']) .pipe(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })); }); //compressing images & handle SVG files gulp.task('images-deploy', function() { gulp.src(['app/images/*']) .pipe(gulp.dest('dist/images')); }); //compiling our Javascripts gulp.task('scripts', function() { //this is where our dev JS scripts are return gulp.src('app/scripts/src/**/*.js') //this is the filename of the compressed version of our JS .pipe(concat('app.js')) //catch errors .on('error', gutil.log) //compress :D .pipe(uglify()) //where we will store our finalized, compressed script .pipe(gulp.dest('app/scripts')) //notify LiveReload to refresh .pipe(refresh(server)); }); //compiling our Javascripts for deployment gulp.task('scripts-deploy', function() { //this is where our dev JS scripts are return gulp.src('app/scripts/src/**/*.js') //this is the filename of the compressed version of our JS .pipe(concat('app.js')) //compress :D .pipe(uglify()) //where we will store our finalized, compressed script .pipe(gulp.dest('dist/scripts')); }); //compiling our SCSS files gulp.task('styles', function() { //the initializer / master SCSS file, which will just be a file that imports everything return gulp.src('app/styles/scss/init.scss') //include SCSS and list every "include" folder .pipe(sass({ includePaths: [ 'app/styles/scss/' ] })) //catch errors .on('error', gutil.log) //the final filename of our combined css file .pipe(concat('styles.css')) //where to save our final, compressed css file .pipe(gulp.dest('app/styles')) //notify LiveReload to refresh .pipe(refresh(server)); }); //compiling our SCSS files for deployment gulp.task('styles-deploy', function() { //the initializer / master SCSS file, which will just be a file that imports everything return gulp.src('app/styles/scss/init.scss') //include SCSS includes folder .pipe(sass({ includePaths: [ 'app/styles/scss', ] })) //the final filename of our combined css file .pipe(concat('styles.css')) .pipe(minifyCSS()) //where to save our final, compressed css file .pipe(gulp.dest('dist/styles')); }); //basically just keeping an eye on all HTML files gulp.task('html', function() { //watch any and all HTML files and refresh when something changes return gulp.src('app/*.html') .pipe(refresh(server)) //catch errors .on('error', gutil.log); }); //migrating over all HTML files for deployment gulp.task('html-deploy', function() { //grab everything, which should include htaccess, robots, etc gulp.src('app/*') .pipe(gulp.dest('dist')); gulp.src('app/fonts/*') .pipe(gulp.dest('dist/fonts')); //grab all of the styles gulp.src('app/styles/*.css') .pipe(gulp.dest('dist/styles')); }); //cleans our dist directory in case things got deleted gulp.task('clean', function() { return gulp.src(['dist/*'], {read: false}) .pipe(clean()); }); //this is our master task when you run `gulp` in CLI / Terminal //this is the main watcher to use when in active development // this will: // startup the web server, // start up livereload // compress all scripts and SCSS files gulp.task('default', ['webserver', 'livereload', 'scripts', 'styles', 'images'], function() { //a list of watchers, so it will watch all of the following files waiting for changes gulp.watch('app/scripts/src/**', ['scripts']); gulp.watch('app/styles/scss/**', ['styles']); gulp.watch('app/images/**', ['images']); gulp.watch('app/*.html', ['html']); }); //this is our deployment task, it will set everything for deployment-ready files gulp.task('deploy', ['clean'], function () { gulp.start('scripts-deploy', 'styles-deploy', 'html-deploy', 'images-deploy'); });
JavaScript
0.000001
@@ -3408,32 +3408,77 @@ .pipe(sass(%7B%0A + errLogToConsole: true,%0A
c24647c57ee3e5e9102feab200940945fb53f938
remove gapi from books.server.ctrl
app/controllers/books.server.controller.js
app/controllers/books.server.controller.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors'), Book = mongoose.model('Book'), _ = require('lodash'), googleapi = require('node-google-api')('AIzaSyAffzxPYpgZ14gieEE04_u4U-5Y26UQ8_0'); exports.gbooks = function(req, res) { googleapi.build(function(api) { for(var k in api){ console.log(k); } }); // var favoriteslist = req.favoriteslist; // favoriteslist.googleapi.build(function(err, api){ // }) // googleapi.build(function(api) { // api.books.mylibrary.bookshelves.list({ // userId: '114705319517394488779', // source: 'gbs_lp_bookshelf_list' // }, function(result){ // if(result.error) { // console.log(result.error); // } else { // for(var i in result.items) { // console.log(result.items[i].summary); // } // } // }); // }); }; /** * Create a Book */ exports.create = function(req, res) { var book = new Book(req.body); book.user = req.user; book.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(book); } }); }; /** * Show the current Book */ exports.read = function(req, res) { res.jsonp(req.book); }; /** * Update a Book */ exports.update = function(req, res) { var book = req.book ; book = _.extend(book , req.body); book.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(book); } }); }; /** * Delete an Book */ exports.delete = function(req, res) { var book = req.book ; book.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(book); } }); }; /** * List of Books */ exports.list = function(req, res) { Book.find().sort('-created').populate('user', 'displayName').exec(function(err, books) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(books); } }); }; /** * Book middleware */ exports.bookByID = function(req, res, next, id) { Book.findById(id).populate('user', 'displayName').exec(function(err, book) { if (err) return next(err); if (! book) return next(new Error('Failed to load Book ' + id)); req.book = book ; next(); }); }; /** * Book authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.book.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
JavaScript
0.000001
@@ -167,19 +167,28 @@ lodash') -,%0A%09 +;%0A%09// ,%0A%09// googleap @@ -264,16 +264,19 @@ _0');%0A%0A%0A +// exports. @@ -305,16 +305,19 @@ res) %7B%0A +// %09googlea @@ -341,16 +341,19 @@ (api) %7B%0A +// %09 for(v @@ -366,16 +366,19 @@ n api)%7B%0A +// %09 con @@ -394,13 +394,19 @@ k);%0A +// %09 %7D%0A +// %09%7D); @@ -897,16 +897,19 @@ %09// %7D);%0A +// %7D;%09%0A%0A/**
0240aca75276f501e2e8093e27d58286ca668c70
Update tagging script
gulpfile.js
gulpfile.js
/* Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; var gulp = require('gulp'); var mocha = require('gulp-mocha'); var jshint = require('gulp-jshint'); var eslint = require('gulp-eslint'); var istanbul = require('gulp-istanbul'); var bump = require('gulp-bump'); var filter = require('gulp-filter'); var git = require('gulp-git'); var tagVersion = require('gulp-tag-version'); var SRC = [ 'lib/*.js' ]; var TEST = [ 'test/*.js' ]; var LINT = [ 'gulpfile.js' ].concat(SRC); var ESLINT_OPTION = { 'rules': { 'quotes': 0, 'eqeqeq': 0, 'no-use-before-define': 0, 'no-underscore-dangle': 0, 'no-shadow': 0, 'no-constant-condition': 0, 'no-multi-spaces': 0, 'dot-notation': [2, {'allowKeywords': false}] }, 'env': { 'node': true } }; gulp.task('test', function (cb) { gulp.src(SRC) .pipe(istanbul()) // Covering files .on('finish', function () { gulp.src(TEST) .pipe(mocha({ reporter: 'spec', timeout: 100000 // 100s })) .pipe(istanbul.writeReports()) // Creating the reports after tests runned .on('end', cb); }); }); gulp.task('lint', function () { return gulp.src(LINT) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter(require('jshint-stylish'))) .pipe(jshint.reporter('fail')) .pipe(eslint(ESLINT_OPTION)) .pipe(eslint.formatEach('compact', process.stderr)) .pipe(eslint.failOnError()); }); /** * Bumping version number and tagging the repository with it. * Please read http://semver.org/ * * You can use the commands * * gulp patch # makes v0.1.0 -> v0.1.1 * gulp feature # makes v0.1.1 -> v0.2.0 * gulp release # makes v0.2.1 -> v1.0.0 * * To bump the version numbers accordingly after you did a patch, * introduced a feature or made a backwards-incompatible release. */ function inc(importance) { // get all the files to bump version in return gulp.src(['./package.json']) // bump the version number in those files .pipe(bump({type: importance})) // save it back to filesystem .pipe(gulp.dest('./')) // commit the changed version number .pipe(git.commit('Bumps package version')) // read only one file to get the version number .pipe(filter('package.json')) // **tag it in the repository** .pipe(tagVersion()); } gulp.task('patch', [ 'travis' ], function () { return inc('patch'); }); gulp.task('minor', [ 'travis' ], function () { return inc('minor'); }); gulp.task('major', [ 'travis' ], function () { return inc('major'); }); gulp.task('travis', [ 'lint', 'test' ]); gulp.task('default', [ 'travis' ]);
JavaScript
0.000001
@@ -3817,16 +3817,30 @@ Version( +%7B prefix: '' %7D ));%0A%7D%0A%0Ag
ec6819facf870ba5cc5e529c7d0ad2d8a953e97f
Include lodash in an npm v3-compatible way
gulpfile.js
gulpfile.js
'use strict'; const gulp = require('gulp'); const addSrc = require('gulp-add-src'); const concat = require('gulp-concat'); const insert = require('gulp-insert'); const remoteSrc = require('gulp-remote-src'); const replace = require('gulp-replace'); const uglify = require('gulp-uglify'); const BENCHMARKJS_VERSION = '2.1.0'; const requestOptions = { 'gzip': true, 'strictSSL': true }; gulp.task('js', function() { // Fetch Platform.js, Benchmark.js, and its jsPerf UI dependencies. remoteSrc([ 'bestiejs/platform.js/1.3.1/platform.js', `bestiejs/benchmark.js/${ BENCHMARKJS_VERSION }/benchmark.js`, `bestiejs/benchmark.js/${ BENCHMARKJS_VERSION }/example/jsperf/ui.js`, `bestiejs/benchmark.js/${ BENCHMARKJS_VERSION }/plugin/ui.browserscope.js`, ], { 'base': 'https://raw.githubusercontent.com/', 'requestOptions': requestOptions } ) // Use whatever version of lodash Benchmark.js is using. .pipe(addSrc.prepend( 'node_modules/benchmark/node_modules/lodash/lodash.js' )) .pipe(concat('all.js')) // Set the Google Analytics ID. .pipe(replace('gaId = \'\'', 'gaId = \'UA-6065217-40\'')) // jsPerf is browser-only. Ensure we’re detected as a browser environment, // even if this is an AMD test, for example. .pipe(replace(/freeDefine = (?:[^;]+)/, 'freeDefine = false')) .pipe(replace(/freeExports = (?:[^;]+)/, 'freeExports = false')) .pipe(replace(/freeModule = (?:[^;]+)/, 'freeModule = false')) .pipe(replace(/freeRequire = (?:[^;]+)/, 'freeRequire = false')) .pipe(replace(/(if\s*\()(typeof define|freeDefine)\b/, '$1false')) // Set the CSS selector for the Browserscope results. .pipe(replace('\'selector\': \'\'', '\'selector\': \'#bs-results\'')) // Avoid exposing `_` and `platform` as global variables. .pipe(insert.wrap( '(function(){var _,platform;', '}.call(this))' )) // Minify the result. //.pipe(uglify()) .pipe(gulp.dest('./dist/')); }); gulp.task('assets', function() { // Update Platform.js, Benchmark.js, and its jsPerf UI dependencies. remoteSrc([ 'index.html', 'main.css' ], { 'base': `https://raw.githubusercontent.com/bestiejs/benchmark.js/${ BENCHMARKJS_VERSION }/example/jsperf/`, 'requestOptions': requestOptions } ) .pipe(replace('<script src="../../node_modules/lodash/index.js"></script>', '')) .pipe(replace('<script src="../../node_modules/platform/platform.js"></script>', '')) .pipe(replace('<script src="../../benchmark.js"></script>', '')) .pipe(replace('<script src="ui.js"></script>', '')) .pipe(replace( '<script src="../../plugin/ui.browserscope.js"></script>', '<script src="all.js"></script>' )) .pipe(gulp.dest('./dist')); }); gulp.task('default', ['js', 'assets']);
JavaScript
0
@@ -939,67 +939,33 @@ end( -%0A%09%09'node_modules/benchmark/node_modules/lodash/lodash.js'%0A%09 +require.resolve('lodash') ))%0A%0A
c3177113ff7348654ef9d0f0917ddcc9fc1bb52c
fix build output with new vulcanize
gulpfile.js
gulpfile.js
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http:polymer.github.io/LICENSE.txt * The complete set of authors may be found at http:polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http:polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http:polymer.github.io/PATENTS.txt */ // jshint node: true 'use strict'; var gulp = require('gulp'); var audit = require('gulp-audit'); var replace = require('gulp-replace'); var rename = require('gulp-rename'); var vulcanize = require('gulp-vulcanize'); var runseq = require('run-sequence'); var lazypipe = require('lazypipe'); var polyclean = require('polyclean'); var del = require('del'); var path = require('path'); var micro = "polymer-micro.html"; var mini = "polymer-mini.html"; var max = "polymer.html"; var workdir = 'dist'; var distMicro = path.join(workdir, micro); var distMini = path.join(workdir, mini); var distMax = path.join(workdir, max); var pkg = require('./package.json'); var cleanupPipe = lazypipe() // Reduce script tags .pipe(replace, /<\/script>\s*<script>/g, '\n\n') // Add real version number .pipe(replace, /(Polymer.version = )'master'/, '$1"' + pkg.version + '"') // remove leading whitespace and comments .pipe(polyclean.leftAlignJs) // remove html wrapper .pipe(replace, '<html><head><meta charset="UTF-8">', '') .pipe(replace, '</head><body></body></html>', '') ; function vulcanizeWithExcludes(target, excludes) { if (excludes) { excludes = excludes.map(function(ex) { return path.resolve(ex); }); } return function() { return gulp.src(target) .pipe(vulcanize({ stripComments: true, excludes: excludes })) .pipe(cleanupPipe()) .pipe(gulp.dest(workdir)); }; } gulp.task('micro', vulcanizeWithExcludes(micro)); gulp.task('mini', vulcanizeWithExcludes(mini, [micro])); gulp.task('max', vulcanizeWithExcludes(max, [mini, micro])); gulp.task('clean', function(cb) { del(workdir, cb); }); // copy bower.json into dist folder gulp.task('copy-bower-json', function() { return gulp.src('bower.json').pipe(gulp.dest(workdir)); }); // Default Task gulp.task('default', function(cb) { runseq('clean', ['micro', 'mini', 'max'], cb); }); // switch src and build for testing gulp.task('save-src', function() { return gulp.src([mini, micro, max]) .pipe(rename(function(p) { p.extname += '.bak'; })) .pipe(gulp.dest('.')); }); gulp.task('restore-src', function() { return gulp.src([mini + '.bak', micro + '.bak', max + '.bak']) .pipe(rename(function(p) { p.extname = ''; })) .pipe(gulp.dest('.')); }); gulp.task('cleanup-switch', function(cb) { del([mini + '.bak', micro + '.bak', max + '.bak'], cb); }); gulp.task('switch-build', function() { return gulp.src([distMini, distMicro, distMax]) .pipe(gulp.dest('.')); }); gulp.task('switch', function(cb) { runseq('default', 'save-src', 'switch-build', cb); }); gulp.task('restore', function(cb) { runseq('restore-src', 'cleanup-switch', cb); }); gulp.task('audit', function() { return gulp.src([distMini, distMicro, distMax]) .pipe(audit('build.log', { repos: ['.'] })) .pipe(gulp.dest(workdir)); }); gulp.task('release', function(cb) { runseq('default', ['copy-bower-json', 'audit'], cb); });
JavaScript
0.000001
@@ -1521,16 +1521,41 @@ l%3E%3Chead%3E +', '')%0A .pipe(replace, ' %3Cmeta ch @@ -1607,16 +1607,78 @@ %3E%3Cbody%3E%3C +div hidden=%22%22 by-vulcanize=%22%22%3E', '')%0A .pipe(replace, '%3C/div%3E%3C /body%3E%3C/
299965701bdc62383da97e9c128627f6262a3a5c
fix regression
connectors/saavn.js
connectors/saavn.js
'use strict'; /* global Connector, Util */ /** * An example of connector that loads information about song asynchronously. * Note that current time and duration are still synchronous. */ /** * The latest track info URL. * @type {String} */ let lastTrackInfoUrl = null; /** * Object that holds information about song. * @type {Object} */ let songInfo = Util.emptyArtistTrack; /** * Connector object setup. */ Connector.playerSelector = '#now-playing'; Connector.currentTimeSelector = '#track-elapsed'; Connector.durationSelector = '#track-time'; Connector.getArtistTrack = function() { requestSongInfo(); return songInfo; }; Connector.isPlaying = function() { if (Util.isSongInfoEmpty(songInfo)) { return false; } return $('#controls #play').hasClass('hide'); }; /** * Helper functions. */ /** * Update current song info asynchronously. */ function requestSongInfo() { let scriptBody = $('#player-track-name a').attr('onclick'); let trackInfoUrl = getUrlFromScript(scriptBody); let isNewSong = (trackInfoUrl && trackInfoUrl !== lastTrackInfoUrl); if (isNewSong) { resetSongInfo(); fetchSongInfo(trackInfoUrl).then((data) => { songInfo = data; }).catch((err) => { console.error(`Error: ${err}`); }); lastTrackInfoUrl = trackInfoUrl; } } /** * Reset current song info. */ function resetSongInfo() { songInfo = Util.emptyArtistTrack; } /** * Load artist page asynchronously and fetch artist name. * @param {String} trackInfoUrl Track info URL * @return {Promise} Promise that will be resolved with the song info */ function fetchSongInfo(trackInfoUrl) { return new Promise((resolve, reject) => { $.ajax({ url: trackInfoUrl }).done((html) => { let $doc = $(html); let artist = $doc.find('.page-meta-group > .meta-list') .first().text() || null; let track = $('#player-track-name').text() || null; resolve({ artist, track }); }).fail((jqXhr, textStatus, errorThrown) => { reject(errorThrown); }); }); } /** * Get URL from Saavn JavaScript script body. * @param {String} scriptBody Script body * @return {String} URL */ function getUrlFromScript(scriptBody) { // Script format: Util.logAndGoToUrl('whatever', 'URL'); let pattern = /.+?\('.+?',\s'(.+?)'\)/; let match = pattern.exec(scriptBody); if (match) { return match[1]; } return null; }
JavaScript
0.000018
@@ -687,24 +687,27 @@ (Util.is -SongInfo +ArtistTrack Empty(so
9fbbe1ab014e51a3db91106ec06584f472242aac
Include source maps as part of build output
gulpfile.js
gulpfile.js
var gulp = require('gulp'), webpack = require('gulp-webpack'), htmlcompress = require('gulp-minify-html'), livereloadembed = require('gulp-embedlr'), livereload = require('gulp-livereload'), gutil = require('gulp-util'), filelog = require('gulp-filelog'), // NOTE: Used for debug runSequence = require('run-sequence'), extend = require('extend'), openbrowser = require('open'), settings = { index: './src/index.html', entry: './src/index.js', output: './dist', server: './dist', port: 8080 }, webpackAction = function(modifyConfig) { var config = require('./webpack.config.js'); if (modifyConfig) { config = extend(true, {}, config); config = modifyConfig(config); } return gulp.src(settings.entry) .pipe(webpack(config)) .pipe(gulp.dest(settings.output)); }, defaultSetup = function(config) { // Build settings to include source maps and pathinfo //config.devtool = '#inline-source-map'; config.output.pathinfo = true; return config; }, watchSetup = function(config) { config = defaultSetup(config); // Dev settings to turn on watch config.watch = true; return config; }, prodSetup = function(config) { var webpack = require('webpack'); // Dev settings to turn on watch config.plugins = config.plugins.concat( new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.OccurenceOrderPlugin() ); return config; }; gulp.task('build', [ 'build-html' ], function() { return webpackAction(defaultSetup); }); gulp.task('build-watch', [ 'build-html' ], function() { console.log('WARNING!!!!! This task does not currently work correctly'); return webpackAction(watchSetup) .pipe(livereload({ auto: false })); }); gulp.task('build-prod', [ 'build-html' ], function() { return webpackAction(prodSetup); }); gulp.task('build-html', function() { return gulp.src(settings.index) .pipe(livereloadembed()) .pipe(htmlcompress()) .pipe(gulp.dest(settings.output)); }); gulp.task('open', function(cb) { var port = settings.port; gutil.log('Opening browser using port: ' + gutil.colors.red(port)); openbrowser('http://localhost:' + port, function() { cb(); }); }); gulp.task('server', function(cb) { var stat = require('node-static'), server = new stat.Server(settings.server, { cache: false }), port = settings.port; gutil.log('Starting Server'); livereload.listen(); require('http').createServer(function(request, response) { request.addListener('end', function() { server.serve(request, response); }).resume(); }).listen(port, function() { gutil.log('Started Server on port: ' + gutil.colors.red(port)); cb(); }); }); gulp.task('dev', function(cb) { runSequence('server', 'open', 'build-watch', function() { cb(); }); }); gulp.task('prod', [ 'build', 'build-prod' ]); gulp.task('default', [ 'dev' ]);
JavaScript
0
@@ -1038,18 +1038,16 @@ -// config.d
b5ded8b8f0b6d6de541ac2d9d6e8027dee1d89de
Remove unused list of types
arborweb/js/app.js
arborweb/js/app.js
/*jslint browser: true, nomen: true */ (function (flow, _, Backbone, d3, girder) { "use strict"; // The main app view flow.App = Backbone.View.extend({ el: 'body', types: ['table', 'tree', 'string', 'image', 'r'], visualizationDescriptors: [ { name: "table", inputs: [{name: "data", type: "table", format: "rows"}] }, { name: "timeline", inputs: [ {name: "data", type: "table", format: "rows"}, {name: "date", type: "json", "default": {format: "inline", data: {"field": "Date"}}}, {name: "y", type: "json", "default": {format: "inline", data: [{"field": "y"}]}} ] }, { name: "dendrogram", inputs: [ {name: "data", type: "tree", format: "nested"}, {name: "distance", type: "json", "default": {format: "inline", data: {"field": "edge_data.weight"}}}, {name: "lineStyle", type: "string", domain: ["axisAligned", "curved"]}, {name: "orientation", type: "string", domain: ["horizontal", "vertical"]} ] }, { name: "tablelink", inputs: [ {name: "data", type: "table", format: "rows"}, {name: "source", type: "string", domain: {input: "data", format: "column.names"}}, {name: "target", type: "string", domain: {input: "data", format: "column.names"}} ] }, { name: "image", inputs: [ {name: "data", type: "image", format: "png.base64"} ] }, { name: "string", inputs: [ {name: "data", type: "string", format: "text", inputMode: "dataset"} ] }, { name: "treeHeatmap", inputs: [ { name: "tree", type: "tree", format: "vtktree.serialized", dataIsURI: true }, { name: "table", type: "table", format: "vtktable.serialized", dataIsURI: true } ] } ], events: { 'click #login': function () { girder.events.trigger('g:loginUi'); }, 'click #logout': function () { girder.restRequest({ path: 'user/authentication', type: 'DELETE' }).done(_.bind(function () { girder.currentUser = null; girder.events.trigger('g:login'); }, this)); }, 'click #register': function () { girder.events.trigger('g:registerUi'); } }, initialize: function () { girder.restRequest({ path: 'user/authentication', error: null }).done(_.bind(function (resp) { resp.user.token = resp.authToken.token; girder.currentUser = new girder.models.UserModel(resp.user); this.render(); }, this)).error(_.bind(function () { this.render(); }, this)); this.$("#control-panel").controlPanel(); this.collection = new girder.collections.CollectionCollection(); this.collection.append = false; this.collection.pageLimit = 100; this.collection.fetch(); this.view = new flow.CollectionsView({el: this.$('#collections'), itemView: flow.CollectionView, collection: this.collection}); this.view.on('flow:change-active', this.collectionVisibilityChange, this); this.view.render(); this.datasets = new flow.DatasetCollection(); this.datasets.append = true; this.datasets.pageLimit = 100; this.datasetsView = new flow.DatasetManagementView({el: this.$('#dataset-management'), datasets: this.datasets}); this.datasetsView.render(); this.analyses = new girder.collections.ItemCollection(); this.analyses.append = true; this.analyses.pageLimit = 100; this.analysesView = new flow.AnalysisManagementView({el: this.$('#analysis-management'), analyses: this.analyses, datasets: this.datasets}); this.analysesView.render(); this.visualizations = new Backbone.Collection(this.visualizationDescriptors); this.visualizationsView = new flow.VisualizationManagementView({el: this.$('#visualization-management'), visualizations: this.visualizations, datasets: this.datasets}); this.visualizationsView.render(); girder.events.on('g:loginUi', this.loginDialog, this); girder.events.on('g:registerUi', this.registerDialog, this); girder.events.on('g:login', this.login, this); }, render: function () { if (girder.currentUser) { this.$("#logged-in").removeClass("hidden"); this.$("#logged-out").addClass("hidden"); this.$("#name").text("Logged in as " + girder.currentUser.get('firstName') + " " + girder.currentUser.get('lastName')); } else { this.$("#logged-in").addClass("hidden"); this.$("#logged-out").removeClass("hidden"); } }, /** * Show a dialog allowing a user to login or register. */ loginDialog: function () { if (!this.loginView) { this.loginView = new girder.views.LoginView({ el: this.$('#g-dialog-container') }); } this.loginView.render(); }, registerDialog: function () { if (!this.registerView) { this.registerView = new girder.views.RegisterView({ el: this.$('#g-dialog-container') }); } this.registerView.render(); }, collectionVisibilityChange: function (collection) { if (collection.get('active')) { d3.json(girder.apiRoot + '/folder?parentType=collection&parentId=' + collection.id, _.bind(function (error, folders) { folders.forEach(function (f) { if (f.name === "Analyses") { collection.set({analysisFolder: f._id}); } else if (f.name === "Data") { collection.set({dataFolder: f._id}); } }); if (collection.get('analysisFolder')) { this.analyses.offset = 0; this.analyses.off('add', null, this).on('add', function (analysis) { analysis.set({collection: collection}); }, this).fetch({ folderId: collection.get('analysisFolder') }); } if (collection.get('dataFolder')) { this.datasets.offset = 0; this.datasets.off('add', null, 'set-collection').on('add', function (dataset) { dataset.set({collection: collection}); }, 'set-collection').fetch({ folderId: collection.get('dataFolder') }); } }, this)); } else { this.analyses.remove(this.analyses.where({collection: collection})); this.datasets.remove(this.datasets.where({collection: collection})); } }, login: function () { this.render(); this.collection.fetch({}, true); } }); }(window.flow, window._, window.Backbone, window.d3, window.girder));
JavaScript
0.000002
@@ -184,67 +184,8 @@ ',%0A%0A - types: %5B'table', 'tree', 'string', 'image', 'r'%5D,%0A%0A
d493ca8e3c3bc908bc09557dd599f031df768de3
Rename gulp develop task to dev
gulpfile.js
gulpfile.js
var gulp = require('gulp'), livereload = require('gulp-livereload'), nodemon = require('gulp-nodemon'), fs = require('fs'); gulp.task('develop', function () { livereload.listen(); nodemon({ script: 'server.js', stdout: false, ext: 'js jade css', execMap: { js: 'node --debug-brk=5560' } }).on('readable', function() { this.stdout.pipe(fs.createWriteStream('output.txt')); this.stderr.pipe(fs.createWriteStream('err.txt')); livereload.reload(); } )}); gulp.task('default', function () { nodemon({ script: 'server.js', ext: 'js jade css' }); });
JavaScript
0.000437
@@ -150,12 +150,8 @@ 'dev -elop ', f @@ -501,10 +501,12 @@ %0A %7D -%0A ) +;%0A%0A %7D);%0A
5a9e7edaf0cbbbfce3f7e778ba50b6c3fe00d466
fix path to js in gulpfile
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'), jshint = require('gulp-jshint'), stylish = require('jshint-stylish'); gulp.task('default', ['jshint']); gulp.task('jshint', lint); function lint () { return gulp .src('./lib/**/*.js') .pipe(jshint()) .pipe(jshint.reporter(stylish, {verbose: true})) .pipe(jshint.reporter('fail')); }
JavaScript
0
@@ -222,11 +222,11 @@ ('./ -lib +src /**/
2832a5b8279424e86a9c4d4185e9481b3a59e6d4
fix build tasks.
gulpfile.js
gulpfile.js
const gulp = require('gulp'); const _ = require('lodash'); const webpack = require('webpack'); const webpackStream = require('webpack-stream'); const WebpackDevServer = require('webpack-dev-server'); const run = require('gulp-run'); const server = require('./server'); const webpackConfig = require('./webpack.config'); const serverConfig = require('./config.json'); const modules = [ '', 'D', 'Alphabet', 'Arr', 'BlobObject', 'Dat', 'Elem', 'Fetch', 'Func', 'Num', 'Promise', 'Router', 'Str', 'Super', 'Switcher' ]; gulp.task('default', (callback) => { new WebpackDevServer(webpack(webpackConfig), { stats: { colors: true } }).listen(serverConfig.webpackDevServer.port, 'localhost', callback); }); gulp.task('build', ['build:default', 'build:min']); gulp.task('jsdoc', ['test-server', 'jsdoc:compile'], () => ( gulp.watch(['./lib/**/*.js'], ['jsdoc:compile']) )); gulp.task('jsdoc:public', ['test-server', 'jsdoc:public:compile'], () => ( gulp.watch(['./lib/**/*.js'], ['jsdoc:public:compile']) )); modules.forEach((module) => { const taskName = `test${ module ? `:${ module }` : '' }`; const deps = module === 'Fetch' || !module ? ['test-server'] : []; gulp.task(taskName, deps, (callback) => { const fileName = module || 'all'; const config = _.cloneDeep(webpackConfig); config.entry = [ `mocha!./test/${ fileName }.js`, './browser.js' ]; new WebpackDevServer(webpack(config), { stats: { colors: true } }).listen(serverConfig.webpackTestServer.port, 'localhost', callback); }); }); gulp.task('test-server', () => server(serverConfig.testServer.port) ); gulp.task('build:default', () => { const config = _.cloneDeep(webpackConfig); delete config.devtool; return gulp.src('./browser.js') .pipe(webpackStream(config)) .pipe(gulp.dest('./')); }); gulp.task('build:min', () => { const config = _.cloneDeep(webpackConfig); delete config.devtool; config.plugins.push(new webpack.optimize.UglifyJsPlugin()); return gulp.src('./browser.js') .pipe(webpackStream(config)) .pipe(gulp.dest('./')); }); gulp.task('jsdoc:compile', () => ( run('./node_modules/jsdoc/jsdoc.js -c conf.json').exec() )); gulp.task('jsdoc:public:compile', () => ( run('./node_modules/jsdoc/jsdoc.js -c conf.public.json').exec() ));
JavaScript
0
@@ -1789,16 +1789,55 @@ vtool;%0A%0A + config.output.filename = 'domc.js';%0A%0A return @@ -2023,32 +2023,74 @@ onfig.devtool;%0A%0A + config.output.filename = 'domc.min.js';%0A config.plugins
ce4a27c57d39d17f411ec3cd6ebd487a28a29145
add some semicolons and remove a log statement about orbited
jsio/env/browser/csp.js
jsio/env/browser/csp.js
require('jsio', ['Class', 'bind']); require('jsio.logging'); require('jsio.interfaces'); require('jsio.csp.client', 'CometSession'); var logger = jsio.logging.getLogger('env.browser.csp') exports.Connector = Class(jsio.interfaces.Connector, function() { this.connect = function() { logger.debug('create Orbited.TCPSocket'); var conn = new CometSession(); conn.onopen = bind(this, function() { logger.debug('conn has opened'); this.onConnect(new Transport(conn)); }); conn.onclose = bind(this, function(code) { logger.debug('conn closed without opening, code:', code); }) logger.debug('open the conection'); conn.connect(this._opts.url, {encoding: 'plain'}); } }); var Transport = Class(jsio.interfaces.Transport, function() { this.init = function(conn) { this._conn = conn; } this.makeConnection = function(protocol) { this._conn.onread = bind(protocol, 'dataReceived'); this._conn.onclose = bind(protocol, 'connectionLost'); // TODO: map error codes } this.write = function(data, encoding) { this._conn.write(data); } this.loseConnection = function(protocol) { this._conn.close(); } });
JavaScript
0.000011
@@ -181,17 +181,18 @@ er.csp') +; %0A - %0Aexports @@ -286,58 +286,8 @@ ) %7B%0A - logger.debug('create Orbited.TCPSocket');%0A @@ -604,16 +604,17 @@ %7D) +; %0A @@ -1050,28 +1050,25 @@ codes%0A %7D%0A - +%09 %0A this.wr
08cbd722bdb63a88dbd4c09eef4e4a14e28227e9
Remove unused gulp task
gulpfile.js
gulpfile.js
const config = require('./gulp/config'); config.environment.check(); process.env.NODE_ENV = config.environment.type; const gulp = require('gulp'); const requireDir = require('require-dir'); requireDir('./gulp/tasks'); /* API */ gulp.task('default', ['serve']); gulp.task('build', ['prepare']); gulp.task('css', ['less']);
JavaScript
0.000018
@@ -294,32 +294,4 @@ %5D);%0A -gulp.task('css', %5B'less'%5D);%0A
4683c9366d1f9897b1d6fe11ef8cdfd371aa9b09
Clean before packing for dist
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var path = require('path'); var del = require('del'); var browserify = require('browserify'); var argv = require('yargs').argv; var config = require('./gulp.config.js'); var packageInfo = require('./package.json'); var $ = require('gulp-load-plugins')(); gulp.task('watch', ['build'], function () { gulp.watch('src/**/*.js', ['build:js']); gulp.watch('src/**/*.less', ['build:styles']); gulp.watch('src/**/*.html', ['build:other']); }); gulp.task('clean', function(cb) { del(['build-dev', 'build-dist'], cb()); }); gulp.task('build', ['build:styles', 'build:js', 'build:other', 'build:setVersion']); gulp.task('build:js', ['build:js:popup', 'build:js:background']); gulp.task('build:styles', function(cb) { return gulp.src(config.styles) .pipe($.less({ paths: [ path.join(__dirname, 'bower_components') ] })) .pipe($.if(isDist(), $.minifyCss())) .pipe($.rename('extension.css')) .pipe(gulp.dest(buildPath('css'))); }); gulp.task('build:js:popup', function() { var filter = $.filter(['src/**/*.js', '!src/js/popup/ga.js'], {restore: true}); return gulp.src(filterFiles(config.scripts.popup), {base: '.'}) .pipe(filter) .pipe($.jshint()) .pipe($.jshint.reporter('default')) .pipe(filter.restore) .pipe($.concat('popup.js')) .pipe($.ngAnnotate()) .pipe($.if(isDist(), $.uglify())) .pipe(gulp.dest(buildPath('js'))); }); gulp.task('build:js:background', function() { return gulp.src(config.scripts.background) .pipe($.jshint()) .pipe($.jshint.reporter('default')) .pipe($.concat('background.js')) .pipe($.browserify({ insertGlobals: true, debug: isDev() })) .pipe($.if(argv.dist, $.uglify())) .pipe(gulp.dest(buildPath('js'))); }); gulp.task('build:other', function(cb) { return gulp.src(config.other, {base: 'src'}) .pipe(gulp.dest(buildPath())); }); gulp.task('build:setVersion', ['build:other'], function(cb) { return gulp.src(buildPath('manifest.json')) .pipe($.replace('@@VERSION@@', packageInfo.version)) .pipe(gulp.dest(buildPath())); }); gulp.task('pack', ['clean'], function(cb) { return gulp.src('build-dist/**') .pipe($.zip('dist-' + packageInfo.version + '.zip')) .pipe(gulp.dest('build-dist')); }); /** * Auxiliary functions */ function buildPath(path) { return (isDev() ? 'build-dev' : 'build-dist') + (path ? '/' + path : ''); } function isDist() { return argv.dist; } function isDev() { return !isDist(); } function filterFiles(input) { var output = []; input.forEach(function(item) { var path; if (typeof item === 'string') { output.push(item); return; } if (item.env === 'dist' && !isDev()) { output.push(item.path); return; } if (item.env === 'dev' && isDev()) { output.push(item.path); return; } }); return output; }
JavaScript
0
@@ -2127,19 +2127,8 @@ ck', - %5B'clean'%5D, fun
57b9954d9cb59da1c4f1efeff4eea5c9d07e6177
support params with value of undefined
react/features/base/config/parseURLParams.js
react/features/base/config/parseURLParams.js
/* @flow */ import { reportError } from '../util'; /** * Parses the query/search or fragment/hash parameters out of a specific URL and * returns them as a JS object. * * @param {string} url - The URL to parse. * @param {boolean} dontParse - If falsy, some transformations (for parsing the * value as JSON) will be executed. * @param {string} source - If {@code 'search'}, the parameters will parsed out * of {@code url.search}; otherwise, out of {@code url.hash}. * @returns {Object} */ export default function parseURLParams( url: URL, dontParse: boolean = false, source: string = 'hash'): Object { const paramStr = source === 'search' ? url.search : url.hash; const params = {}; const paramParts = (paramStr && paramStr.substr(1).split('&')) || []; // Detect and ignore hash params for hash routers. if (source === 'hash' && paramParts.length === 1) { const firstParam = paramParts[0]; if (firstParam.startsWith('/') && firstParam.split('&').length === 1) { return params; } } paramParts.forEach(part => { const param = part.split('='); const key = param[0]; if (!key) { return; } let value; try { value = param[1]; if (!dontParse) { value = JSON.parse(decodeURIComponent(value).replace(/\\&/, '&')); } } catch (e) { reportError( e, `Failed to parse URL parameter value: ${String(value)}`); return; } params[key] = value; }); return params; }
JavaScript
0.000002
@@ -1289,16 +1289,17 @@ ram%5B1%5D;%0A +%0A @@ -1340,47 +1340,24 @@ -value%0A = JSON.parse( +const decoded = deco @@ -1397,16 +1397,99 @@ &/, '&') +;%0A%0A value = decoded === 'undefined' ? undefined : JSON.parse(decoded );%0A
a1326652869fc77b6c4de1cf14fc249c05ed1bcf
Add sass compression
gulpfile.js
gulpfile.js
require('es6-promise').polyfill(); var gulp = require('gulp'); var browserify = require('browserify'); var concatCss = require('gulp-concat-css'); var minifyCss = require('gulp-minify-css'); var sass = require('gulp-sass'); var uglify = require('gulp-uglify'); var buffer = require('vinyl-buffer'); var source = require('vinyl-source-stream'); var sourcemaps = require('gulp-sourcemaps'); var merge = require('merge-stream'); var postcss = require('gulp-postcss'); var pxtorem = require('postcss-pxtorem'); var autoprefixer = require('autoprefixer'); var cssProcessors = [ autoprefixer(), pxtorem({ rootValue: 14, replace: false, propWhiteList: [] }) ]; gulp.task('js', function() { browserify('./jet/static/jet/js/src/main.js') .bundle() .on('error', function(error) { console.error(error); }) .pipe(source('bundle.min.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('./jet/static/jet/js/build/')); }); gulp.task('vendor-css', function() { merge( gulp.src([ './node_modules/select2/dist/css/select2.css', './node_modules/jquery-ui/themes/base/all.css', './node_modules/timepicker/jquery.ui.timepicker.css' ]), gulp.src([ './node_modules/perfect-scrollbar/src/css/main.scss' ]) .pipe(sass()) .on('error', function(error) { console.error(error); }) ) .pipe(postcss(cssProcessors)) .on('error', function(error) { console.error(error); }) .pipe(minifyCss()) .on('error', function(error) { console.error(error); }) .pipe(concatCss('vendor.css')) .on('error', function(error) { console.error(error); }) .pipe(gulp.dest('./jet/static/jet/css')); }); gulp.task('vendor-i18n', function() { gulp.src(['./node_modules/jquery-ui/ui/i18n/*.js']) .pipe(gulp.dest('./jet/static/jet/js/i18n/jquery-ui/')); gulp.src(['./node_modules/timepicker/i18n/*.js']) .pipe(gulp.dest('./jet/static/jet/js/i18n/jquery-ui-timepicker/')); gulp.src(['./node_modules/select2/dist/js/i18n/*.js']) .pipe(gulp.dest('./jet/static/jet/js/i18n/select2/')); }); gulp.task('scss', function() { gulp.src('./jet/static/jet/css/**/*.scss') .pipe(sourcemaps.init()) .pipe(sass()) .on('error', function(error) { console.error(error); }) .pipe(postcss(cssProcessors)) .on('error', function(error) { console.error(error); }) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./jet/static/jet/css')); }); gulp.task('watch', function() { gulp.watch('./jet/static/jet/js/src/**/*.js', ['js']); gulp.watch('./jet/static/jet/css/**/*.scss', ['scss']); }); gulp.task('default', ['js', 'scss', 'vendor-css', 'vendor-i18n', 'watch']);
JavaScript
0.000002
@@ -1388,32 +1388,89 @@ .pipe(sass( +%7B%0A outputStyle: 'compressed'%0A %7D ))%0A . @@ -2517,16 +2517,65 @@ pe(sass( +%7B%0A outputStyle: 'compressed'%0A %7D ))%0A
b314780898a594d1fdcf7c0080668bd00a757b5a
test with coveralls
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var browserify = require('browserify'); var buffer = require('vinyl-buffer'); var cover = require('gulp-coverage'); var coveralls = require('gulp-coveralls'); var jasmine = require('gulp-jasmine'); var eslint = require('gulp-eslint'); var uglify = require('gulp-uglify'); var reactify = require('reactify'); var rename = require('gulp-rename'); var source = require('vinyl-source-stream'); var sourcemaps = require('gulp-sourcemaps'); var webserver = require('gulp-webserver'); gulp.task('default', ['lint', 'bundle', 'test']); gulp.task('bundle', function() { var b = browserify({ entries: './index.js', standalone: 'koara', debug: true, transform: [reactify] }); return b.bundle() .pipe(source('index.js')) .pipe(rename('koara.js')) .pipe(buffer()) .pipe(gulp.dest('dist')) .pipe(rename('koara.min.js')) .pipe(sourcemaps.init({loadMaps: true})) .pipe(uglify()) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('dist')); }); gulp.task('lint', function() { return gulp.src(['lib/**/*.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('serve', ['bundle'], function() { gulp.src('.').pipe(webserver()); }); gulp.task('test', function () { return gulp.src('test/*.js').pipe(jasmine()); }); gulp.task('test-travisci', function () { return gulp.src('test/*.js') .pipe(cover.instrument({ pattern: ['lib/koara/**/*.js'] })) .pipe(jasmine()) .pipe(cover.gather()) .pipe(cover.format({ reporter: 'lcov' })) //.pipe(coveralls()); });
JavaScript
0.000001
@@ -1561,10 +1561,8 @@ -// .pip
d19f860a41f09dca5f28f1f6c918882b58120590
change to gulpfile
gulpfile.js
gulpfile.js
// *** dependencies *** // const path = require('path'); const gulp = require('gulp'); const jshint = require('gulp-jshint'); const jscs = require('gulp-jscs'); const runSequence = require('run-sequence'); const nodemon = require('gulp-nodemon'); const plumber = require('gulp-plumber'); const server = require('tiny-lr')(); // *** config *** // const paths = { scripts: [ path.join('src', '**', '*.js'), path.join('src', '*.js') ], styles: [ path.join('src', 'client', 'css', '*.css') ], views: [ path.join('src', 'server', '**', '*.html'), path.join('src', 'server', '*.html') ], server: path.join('src', 'server', 'server.js') }; const lrPort = 35729; const nodemonConfig = { script: paths.server, ext: 'html js css', ignore: ['node_modules'], env: { NODE_ENV: 'development' } }; // *** default task *** // gulp.task('default', () => { runSequence( ['jshint'], ['jscs'], ['lr'], ['nodemon'], ['watch'] ); }); // *** sub tasks ** // gulp.task('jshint', () => { return gulp.src(paths.scripts) .pipe(plumber()) .pipe(jshint({ esnext: true })) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }); gulp.task('jscs', () => { return gulp.src(paths.scripts) .pipe(plumber()) .pipe(jscs()) .pipe(jscs.reporter()) .pipe(jscs.reporter('fail')); }); gulp.task('styles', () => { return gulp.src(paths.styles) .pipe(plumber()); }); gulp.task('views', () => { return gulp.src(paths.views) .pipe(plumber()); }); gulp.task('lr', () => { server.listen(lrPort, (err) => { if (err) { return console.error(err); } }); }); gulp.task('nodemon', () => { return nodemon(nodemonConfig); }); gulp.task('watch', () => { gulp.watch(paths.html, ['html']); gulp.watch(paths.scripts, ['jshint', 'jscs']); gulp.watch(paths.styles, ['styles']); });
JavaScript
0.000001
@@ -906,38 +906,8 @@ ce(%0A - %5B'jshint'%5D,%0A %5B'jscs'%5D,%0A
3ac4c0732229d750c5e9ecd875c6235d5c07f3b8
Fix release task bug.
gulpfile.js
gulpfile.js
/** * Created by xubt on 4/30/16. */ var gulp = require('gulp'); var jshint = require('gulp-jshint'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var ngmin = require('gulp-ngmin'); var ngAnnotate = require('gulp-ng-annotate'); var less = require('gulp-less'); var gulpSequence = require('gulp-sequence'); var clean = require('gulp-clean'); var lib = require('bower-files')({ overrides: { 'x-editable': { main: './dist/bootstrap3-editable/js/bootstrap-editable.js', dependencies: { "jquery": ">=1.6" } } } }); var cleanCSS = require('gulp-clean-css'); // 语法检查 gulp.task('jshint', function () { return gulp.src(['kanban/**/*.js', '!kanban/static/**/*.js', '!kanban/**/util/*.js']) .pipe(jshint()) .pipe(jshint.reporter('default')); }); // 合并压缩第三方类库 gulp.task('minify-bower-components', function () { gulp.src(lib.ext('js').files) .pipe(concat('lib.min.js')) .pipe(gulp.dest('kanban/static/js/')) .pipe(ngmin()) .pipe(ngAnnotate()) .pipe(uglify({mangle: false})) .pipe(gulp.dest('kanban/static/js/')); }); // 合并CSS gulp.task('minify-css', function () { return gulp.src(['kanban/**/*.css', '!kanban/static/css/*.css']) .pipe(concat('thiki-kanban.min.css')) .pipe(cleanCSS({compatibility: 'ie8'})) .pipe(gulp.dest('kanban/static/css')); }); // 合并LESS gulp.task('minify-less', function () { return gulp.src(['kanban/**/*.less', '!kanban/static/**/*.less']) .pipe(concat('thiki-kanban.min.less')) .pipe(cleanCSS({compatibility: 'ie8'})) .pipe(gulp.dest('kanban/static/less')); }); //Less转css gulp.task('build-less-to-css', function () { return gulp.src('kanban/static/less/thiki-kanban.min.less') .pipe(concat('thiki-kanban.min.less-css.css')) .pipe(less()) .pipe(gulp.dest('kanban/static/less')); }); gulp.task('clean-static', function () { return gulp.src(['kanban/static/js'], {read: false}) .pipe(clean()); }); // 合并文件之后压缩代码 gulp.task('minify-js', ['clean-static'], function () { return gulp.src(['kanban/*.js', 'kanban/**/*.js', '!kanban/static/**/*.js']) .pipe(concat('thiki-kanban.min.js')) .pipe(gulp.dest('kanban/static/js')) .pipe(ngmin()) .pipe(ngAnnotate()) .pipe(uglify({mangle: false})) .pipe(gulp.dest('kanban/static/js')); }); gulp.task('clean-release', function () { return gulp.src(['release/*'], {read: false}) .pipe(clean()); }); gulp.task('release', ['clean-release'], function () { gulp.src("kanban/static/js/*") .pipe(gulp.dest('release/static/js')); gulp.src("kanban/static/css/thiki-kanban.min.css") .pipe(gulp.dest('release/static/css')); gulp.src("kanban/static/img/**") .pipe(gulp.dest('release/static/img')); gulp.src("kanban/static/fonts/**") .pipe(gulp.dest('release/static/fonts')); gulp.src("kanban/component/**/*.html") .pipe(gulp.dest('release/component')); gulp.src("kanban/foundation/modal/partials/**") .pipe(gulp.dest('release/foundation/modal/partials')); gulp.src("kanban/index.html") .pipe(gulp.dest('release')); }); // 监视文件的变化 gulp.task('watch', function () { gulp.watch(['kanban/*.js', 'kanban/**/*.js', 'kanban/styles/*.css', 'kanban/**/*.less', 'kanban/**/*.css', 'gulpfile.js', '!kanban/static/**/*.js', '!kanban/static/**/*.css'], ['jshint', 'minify-bower-components', 'minify-js', 'minify-less', 'build-less-to-css', 'minify-css']); }); // 注册缺省任务 gulp.task('default', gulpSequence('jshint', 'minify-bower-components', 'minify-js', 'minify-less', 'build-less-to-css', 'minify-css', 'release'));
JavaScript
0
@@ -3310,24 +3310,25 @@ est('release +/ '));%0A%7D);%0A%0A//
246078627189738c3a227df582a52f2569e4c271
Add --production build tasks, and remove z-index optimization
gulpfile.js
gulpfile.js
var gulp = require('gulp'), browserSync = require('browser-sync'), childprocess = require('child_process'), concat = require('gulp-concat'), cssnano = require('gulp-cssnano'), //Contains autoprefixer filter = require('gulp-filter'), gutil = require('gulp-util'), jshint = require('gulp-jshint'), sass = require('gulp-sass'), sourcemaps = require('gulp-sourcemaps'), uglify = require('gulp-uglify'); var src = { scss: 'assets/_src/scss/{,*/}*.{scss,sass}', js: ['assets/_src/js/vendor/*.js', 'assets/_src/js/main.js'] }; var config = { production: !!gutil.env.production }; /** * $ gulp sass (--production) * Compile and minify sass files + generate generate sourceemaps + place compiled css in both '/assets/' and '_site/assets/' for reloading * Passing --production flag disables sourcemaps */ gulp.task('sass', function () { return gulp.src(src.scss) .pipe(config.production ? gutil.noop() : sourcemaps.init()) // Skip sourcemaps if --production .pipe(sass()) .on('error', function (err) { browserSync.notify("Uh oh, there's an error!"); gutil.log( err.name + ' in '+ gutil.colors.cyan(err.plugin) + ':' +'\n'+ gutil.colors.grey('----------------------------------') +"\n"+ ' File: ' + gutil.colors.magenta(err.relativePath) +"\n"+ ' Line: ' + gutil.colors.magenta(err.line) +'\n'+ ' Message: ' + gutil.colors.yellow(err.messageOriginal) +"\n"+ gutil.colors.grey('----------------------------------') ); this.emit('end'); }) .pipe(cssnano({ autoprefixer: {browsers: ['last 2 versions', 'ie 9'], add: true} })) .pipe(config.production ? gutil.noop() : sourcemaps.write()) // Skip sourcemaps if --production .pipe(gulp.dest('_site/assets/css')) .pipe(gulp.dest('assets/css')) .pipe(browserSync.reload({ stream: true })); }); /** * $ gulp scripts (--production) * Lint, concat and uglify scripts and place file into both '/assets/' and '_site/assets/' for reloading * Passing --production flag disables sourcemaps */ gulp.task('scripts', function () { var excludeVendorFilter = filter(['**','!*assets/_src/js/vendor/*.js'], {restore: true}); //Filter for excluding vendor js files from linting return gulp.src(src.js) .pipe(excludeVendorFilter) .pipe(jshint()) .pipe(jshint.reporter('default')) .pipe(excludeVendorFilter.restore) .pipe(config.production ? gutil.noop() : sourcemaps.init()) // Skip sourcemaps if --production .pipe(concat('scripts.js')) .pipe(uglify()) .on('error', function (err) { browserSync.notify("Uh oh, there's an error!"); gutil.log( err.name + ' in '+ gutil.colors.cyan(err.plugin) + ':' +'\n'+ gutil.colors.grey('----------------------------------') +"\n"+ ' File: ' + gutil.colors.magenta(err.fileName) +"\n"+ ' Line: ' + gutil.colors.magenta(err.lineNumber) +'\n'+ ' Message: ' + gutil.colors.yellow(err.message) +"\n"+ gutil.colors.grey('----------------------------------') ); this.emit('end'); }) .pipe(config.production ? gutil.noop() : sourcemaps.write()) // Skip sourcemaps if --production .pipe(gulp.dest('_site/assets/js')) .pipe(gulp.dest('assets/js')) .pipe(browserSync.reload({ stream: true })); }); /** * $ gulp browser-sync * Start a BrowserSync server */ gulp.task('browser-sync', function() { browserSync({ server: { baseDir: '_site' } }); }); /** * $ gulp jekyll * Build Jekyll Site with an incremental build */ gulp.task('jekyll', function (done) { browserSync.notify('Building Jekyll site...'); return childprocess.spawn('jekyll', ['build', '--incremental'], {stdio: 'inherit'}) .on('close', done); }); /** * $ gulp serve * Serve site, watch for changes and run tasks as needed */ gulp.task('serve', ['sass', 'scripts', 'jekyll', 'browser-sync'], function () { gulp.watch(src.scss, ['sass']); gulp.watch(src.js, ['scripts']); gulp.watch(['index.html', '_includes/*.html', '_layouts/*.html', '*.md', '_posts/*'], ['jekyll']); gulp.watch(['_site/**/*.html']).on('change', browserSync.reload); });
JavaScript
0
@@ -1875,16 +1875,47 @@ d: true%7D +,%0A zindex: false %0A @@ -4269,32 +4269,412 @@ e', done);%0A%7D);%0A%0A +/**%0A * $ gulp jekyll-prod%0A * Build Jekyll Site for production%0A */%0Agulp.task('jekyll-prod', function (done) %7B%0A browserSync.notify('Building Jekyll site for production...');%0A var productionEnv = process.env;%0A productionEnv.JEKYLL_ENV = 'production';%0A%0A return childprocess.spawn('jekyll', %5B'build'%5D, %7B stdio: 'inherit' , env:productionEnv %7D)%0A .on('close', done);%0A%7D);%0A%0A /**%0A * $ gulp se @@ -4908,21 +4908,17 @@ watch(%5B' -index +* .html', @@ -4974,16 +4974,31 @@ posts/*' +, '_projects/*' %5D, %5B'jek @@ -5074,12 +5074,278 @@ reload);%0A%7D); +%0A%0A/**%0A * $ gulp build --production%0A * Builds the site, sass and scripts for production. Remember to set --production flag.%0A */%0A gulp.task('build', %5B'jekyll-prod', 'sass', 'scripts'%5D, function (done) %7B%0A browserSync.notify('Building site for production...');%0A %7D);%0A
4f939867a61691dd85df700009d76ade6a8f7e23
Fix typo
gulpfile.js
gulpfile.js
/** * @license * Copyright (c) 2016 Abdón Rodríguez Davila (@abdonrd). All rights reserved. * This code may only be used under the MIT style license found at https://abdonrd.github.io/LICENSE.txt */ /* eslint-disable no-console */ 'use strict'; const del = require('del'); const gulp = require('gulp'); const gulpif = require('gulp-if'); const htmlmin = require('gulp-htmlmin'); const imagemin = require('gulp-imagemin'); const jsonmin = require('gulp-jsonmin'); const mergeStream = require('merge-stream'); const polymerBuild = require('polymer-build'); const uglify = require('gulp-uglify'); const swPrecacheConfig = require('./sw-precache-config.js'); const polymerJson = require('./polymer.json'); const polymerProject = new polymerBuild.PolymerProject(polymerJson); const buildDirectory = 'build'; /** * Waits for the given ReadableStream */ function waitFor(stream) { return new Promise((resolve, reject) => { stream.on('end', resolve); stream.on('error', reject); }); } function build() { return new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars // Okay, so first thing we do is clear the build directory console.log(`Deleting ${buildDirectory} directory...`); del([buildDirectory]) .then(() => { // Okay, now let's get your source files let sourcesStream = polymerProject.sources() .pipe(polymerProject.splitHtml()) .pipe(gulpif(/\.js$/, uglify())) // .pipe(gulpif(/\.css$/, cssSlam())) .pipe(gulpif(/\.html$/, htmlmin({ collapseWhitespace: true }))) .pipe(gulpif(/\.(png|gif|jpg|svg)$/, imagemin())) .pipe(gulpif(/\.json$/, jsonmin())) .pipe(polymerProject.rejoinHtml()); // Okay, now let's do the same to your dependencies let dependenciesStream = polymerProject.dependencies() .pipe(polymerProject.splitHtml()) // .pipe(gulpif(/\.js$/, uglify())) // .pipe(gulpif(/\.css$/, cssSlam())) // .pipe(gulpif(/\.html$/, htmlMinifier())) .pipe(polymerProject.rejoinHtml()); // Okay, now let's merge them into a single build stream let buildStream = mergeStream(sourcesStream, dependenciesStream) .once('data', () => { console.log('Analyzing build dependencies...'); }); // If you want bundling, pass the stream to polymerProject.bundler. // This will bundle dependencies into your fragments so you can lazy // load them. buildStream = buildStream.pipe(polymerProject.bundler); // Okay, time to pipe to the build directory buildStream = buildStream.pipe(gulp.dest(buildDirectory)); // waitFor the buildStream to complete return waitFor(buildStream); }) .then(() => { console.log('Generating the Service Worker...'); return polymerBuild.addServiceWorker({ project: polymerProject, buildRoot: buildDirectory, bundled: true, swPrecacheConfig: swPrecacheConfig }); }) .then(() => { console.log('Build complete!'); resolve(); }); }); } gulp.task('build', build);
JavaScript
0.999999
@@ -2729,21 +2729,22 @@ // -waitF +Wait f or the b
60966c35c6725f581a9bdc21d2c92a83e7ea6254
make sure Fall Back is visible in two-week view background fills
js/plot/util/fill.js
js/plot/util/fill.js
/* * == BSD2 LICENSE == * Copyright (c) 2014, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. * == BSD2 LICENSE == */ var d3 = require('d3'); var _ = require('lodash'); var log = require('bows')('Fill'); module.exports = function(pool, opts) { var fills = [], defaults = { classes: { 0: 'darkest', 3: 'dark', 6: 'lighter', 9: 'light', 12: 'lightest', 15: 'lighter', 18: 'dark', 21: 'darker' }, duration: 3, gutter: 0, fillClass: '', x: function(t) { return Date.parse(t.normalTime); } }; _.defaults(opts || {}, defaults); function fill(selection) { opts.xScale = pool.xScale().copy(); // fillClass is used to control opacity of weekend day pools in two-week view if(opts.fillClass) { selection.attr('class', opts.fillClass); } if (opts.guidelines) { fill.drawGuidelines(selection); } selection.each(function(currentData) { var fills = selection.selectAll('rect.d3-fill') .data(currentData, function(d) { return d.id; }); fills.enter() .append('rect') .attr({ cursor: opts.cursor ? opts.cursor : 'auto', x: function(d, i) { if (opts.dataGutter) { if (i === 0) { return fill.xPosition(d) - opts.dataGutter; } else { return fill.xPosition(d); } } else { return fill.xPosition(d); } }, y: function() { if (opts.gutter.top) { return opts.gutter.top; } else { return opts.gutter; } }, width: function(d, i) { if (opts.dataGutter) { if ((i === 0) || (i === currentData.length - 1)) { return fill.width(d) + opts.dataGutter; } else { return fill.width(d); } } else { return fill.width(d); } }, height: function() { if (opts.gutter.top) { return pool.height() - opts.gutter.top - opts.gutter.bottom; } else { return pool.height() - 2 * opts.gutter; } }, id: function(d) { return d.id; }, 'class': function(d) { return 'd3-fill d3-rect-fill d3-fill-' + d.fillColor; } }) .on('click', function() { if (opts.emitter) { opts.emitter.emit('clickInPool', d3.event.offsetX); } }); fills.exit().remove(); }); } fill.xPosition = function(d) { return opts.xScale(opts.x(d)); }; fill.width = function(d) { var s = Date.parse(d.normalTime), e = Date.parse(d.normalEnd); return opts.xScale(e) - opts.xScale(s); }; fill.drawGuidelines = function(selection) { var linesGroup = pool.group().selectAll('#' + pool.id() + '_guidelines').data([opts.guidelines]); linesGroup.enter().append('g').attr('id', pool.id() + '_guidelines'); linesGroup.selectAll('line') .data(opts.guidelines) .enter() .append('line') .attr({ 'class': function(d) { return 'd3-line-guide ' + d['class']; }, x1: opts.xScale.range()[0], x2: opts.xScale.range()[1], y1: function(d) { return opts.yScale(d.height); }, y2: function(d) { return opts.yScale(d.height); } }); }; return fill; };
JavaScript
0
@@ -1555,24 +1555,53 @@ rentData) %7B%0A + currentData.reverse();%0A var fi @@ -1923,17 +1923,38 @@ (i === -0 +currentData.length - 1 ) %7B%0A
c23fdedd591830548a82cf3528524b6d5825a605
Move server things to the bottom
gulpfile.js
gulpfile.js
var gulp = require('gulp') var gutil = require('gulp-util') var signalhub = require('signalhub/server.js') var source = require('vinyl-source-stream') var browserify = require('browserify') var watchify = require('watchify') var babelify = require('babelify') var notifier = require('node-notifier') var chalk = require('chalk') var concat = require('gulp-concat') var sass = require('gulp-sass') var livereload = require('gulp-livereload') var http = require('http') var st = require('st') // Start signalhub server on port 7000 function startSignalhub () { var port = 7000 var host = '' var server = signalhub() server.on('subscribe', function (channel) { gutil.log('subscribe: %s', channel) }) server.on('publish', function (channel, message) { gutil.log('broadcast: %s (%d)', channel, message.length) }) server.listen(port, host, function () { gutil.log('signalhub listening on port %d', server.address().port) }) } // Log errors in the watchers to the console var failing = false function handleErrors (error) { // Save the error status for the compile functions failing = true // Generate a clean error message var regex = new RegExp(__dirname.replace(/\\/g, '[\\\\\/]*'), 'gi') error = error.toString().replace(regex, '') // Write in console and notify the user gutil.log(chalk.bold.red('[Build failed] ' + error)) notifier.notify({ title: 'Gulp build failed', message: error, sound: true }) } // Log successful tasks function handleSuccess (start, message) { var ms = Date.now() - start message = message + ' in ' + ms + 'ms' gutil.log(chalk.green(message)) if (failing) { failing = false notifier.notify({ title: 'Gulp build passed!', message: message, sound: true }) } } // Compile the javascript and watch for file changes function browserifyTask (deploy) { // Give browserify the initial file, it automatically grabs the dependencies // We also wanna convert JSX to javascript, transpile es6, and turn on source mapping var bundler = browserify({ entries: ['./app/index.jsx'], transform: [[babelify, {'presets': ['es2015', 'stage-0', 'react']}]], debug: true, cache: {}, packageCache: {}, fullPaths: true }) var watcher = deploy === true ? bundler : watchify(bundler, { poll: true }) function compileJS () { var start = Date.now() var pipe = watcher.bundle() .on('error', handleErrors) .pipe(source('bundle.js')) .pipe(gulp.dest('./public/build/')) if (!deploy) { pipe.pipe(livereload()) } handleSuccess(start, 'Compiled JS') } // Listen for updates if (!deploy) { watcher.on('update', compileJS) } // Run once on task execution return compileJS() } // Compile SCSS into CSS on file changes function scssTask (deploy) { function compileSCSS () { var start = Date.now() var pipe = gulp.src('./styles/**/*.scss') .pipe(sass().on('error', handleErrors)) .pipe(concat('bundle.css')) .pipe(gulp.dest('./public/build/')) if (!deploy) { pipe.pipe(livereload()) } handleSuccess(start, 'Compiled CSS') } // Listen for updates if (!deploy) { gulp.watch('./styles/**/*.scss', compileSCSS) } // Run once on task execution compileSCSS() } // Enable livereload in the browser (http://livereload.com/extensions/) // and just start all the watchers and the server gulp.task('default', function () { startSignalhub() livereload({start: true}) browserifyTask() scssTask() http.createServer(st({path: __dirname + '/public', index: 'index.html', cache: false})).listen(8000) }) // Create the assets once, without watchers gulp.task('deploy', function () { browserifyTask(true) scssTask(true) })
JavaScript
0
@@ -489,471 +489,8 @@ ')%0A%0A -// Start signalhub server on port 7000%0Afunction startSignalhub () %7B%0A var port = 7000%0A var host = ''%0A var server = signalhub()%0A%0A server.on('subscribe', function (channel) %7B%0A gutil.log('subscribe: %25s', channel)%0A %7D)%0A%0A server.on('publish', function (channel, message) %7B%0A gutil.log('broadcast: %25s (%25d)', channel, message.length)%0A %7D)%0A%0A server.listen(port, host, function () %7B%0A gutil.log('signalhub listening on port %25d', server.address().port)%0A %7D)%0A%7D%0A%0A // L @@ -2848,16 +2848,696 @@ SS()%0A%7D%0A%0A +// Start signalhub server on port 7000%0Afunction startSignalhub () %7B%0A var port = 7000%0A var host = ''%0A var server = signalhub()%0A%0A server.on('subscribe', function (channel) %7B%0A gutil.log('subscribe: %25s', channel)%0A %7D)%0A%0A server.on('publish', function (channel, message) %7B%0A gutil.log('broadcast: %25s (%25d)', channel, message.length)%0A %7D)%0A%0A server.listen(port, host, function () %7B%0A gutil.log('signalhub listening on port %25d', server.address().port)%0A %7D)%0A%7D%0A%0A// Start normal server on port 8000%0Afunction startServer() %7B%0A http.createServer(st(%7Bpath: __dirname + '/public', index: 'index.html', cache: false%7D)).listen(8000)%0A gutil.log('server listening on port %25d', 8000)%0A%7D%0A%0A%0A // Enabl @@ -3600,16 +3600,16 @@ sions/)%0A - // and j @@ -3689,27 +3689,8 @@ ) %7B%0A - startSignalhub()%0A li @@ -3751,107 +3751,39 @@ )%0A -http.createServer(st(%7Bpath: __dirname + '/public', index: 'index.html', cache: false%7D)).listen(8000 +startSignalhub()%0A startServer( )%0A%7D)
5eb6c76d6048ea0aef4bf3fc776359471d68a244
Add gulp task for project traitDetails js
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); var sassLint = require('gulp-sass-lint'); var concat = require('gulp-concat'); var sourcemaps = require('gulp-sourcemaps'); var babel = require('gulp-babel'); require('babel-core/register'); // testing var mocha = require('gulp-mocha'); /** * * @param outFolder string * @param outFileBase string * @return {*} */ function runBabelOnFolder(outFolder, outFileBase) { if(outFolder !== '' && outFolder.slice(-1) !== '/'){ outFolder += '/'; } return gulp.src('app/Resources/client/jsx/'+outFolder+outFileBase+'/*.js?(x)') .pipe(babel({ presets: ['es2015', 'react'] })) .pipe(concat(outFileBase+'.js')) .pipe(gulp.dest('web/assets/js/'+outFolder)); } gulp.task('babel-helpers', function() { return runBabelOnFolder('', 'helpers'); }); gulp.task('babel-base', function() { return runBabelOnFolder('', 'base'); }); gulp.task('babel-project-details', function() { return runBabelOnFolder('project', 'details'); }); gulp.task('babel-trait-browse', function() { return runBabelOnFolder('trait', 'browse'); }); gulp.task('test', function() { return gulp.src('tests/js/**/*.js', {read: false}) .pipe(mocha({reporter: 'spec', useColors: true})) }); gulp.task('sass', function () { return gulp.src('app/Resources/client/scss/*.scss') .pipe(sourcemaps.init()) .pipe(sass().on('error', sass.logError)) .pipe(sourcemaps.write('.', {includeContent: false})) .pipe(gulp.dest('web/assets/css')); }); gulp.task('sassLint', function() { gulp.src('web/assets/scss/*.s+(a|c)ss') .pipe(sassLint()) .pipe(sassLint.format()) .pipe(sassLint.failOnError()); }); gulp.task('babel', ['babel-helpers','babel-base','babel-project-details','babel-trait-browse'], function () { }); gulp.task('css', ['sassLint','sass'], function () { }); gulp.task('default', ['css','babel','test'], function() { // place code for your default task here });
JavaScript
0.000001
@@ -1054,32 +1054,147 @@ details');%0A%7D);%0A%0A +gulp.task('babel-project-trait-details', function() %7B%0A return runBabelOnFolder('project', 'traitDetails');%0A%7D);%0A%0A gulp.task('babel @@ -1931,24 +1931,54 @@ ils','babel- +project-trait-details','babel- trait-browse
ec62f682c25c3df3ed62e7fdb0ff7824603f6239
Replace deprecated gulp.run() method
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var iife = require('gulp-iife'); var uglify = require('gulp-uglify'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); gulp.task('default', ['scripts']); gulp.task('scripts', function () { gulp.src('src/**/*.js') .pipe(concat('vk-api-angular.js')) .pipe(iife()) .pipe(gulp.dest('dist/')) .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('dist/')); }); gulp.task('watch', ['default'], function () { gulp.watch('src/**/*.js', function () { gulp.run('scripts'); }); });
JavaScript
0.000432
@@ -532,35 +532,9 @@ s', -function () %7B%0A gulp.run( +%5B 'scr @@ -542,14 +542,9 @@ pts' -);%0A %7D +%5D );%0A%7D
3df9aac94cb51bf1a533bb622f4e4cf9f71983ad
update gulpfile
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var gutil = require('gulp-util'); var bower = require('bower'); var concat = require('gulp-concat'); var sass = require('gulp-sass'); var minifyCss = require('gulp-minify-css'); var rename = require('gulp-rename'); var sh = require('shelljs'); var paths = { sass: ['./scss/**/*.scss'] }; gulp.task('default', ['sass']); gulp.task('sass', function(done) { gulp.src('./scss/ionic.app.scss') .pipe(sass()) .on('error', sass.logError) .pipe(gulp.dest('./www/css/')) .pipe(minifyCss({ keepSpecialComments: 0 })) .pipe(rename({ extname: '.min.css' })) .pipe(gulp.dest('./www/css/')) .on('end', done); }); gulp.task('watch', function() { gulp.watch(paths.sass, ['sass']); }); gulp.task('install', ['git-check'], function() { return bower.commands.install() .on('log', function(data) { gutil.log('bower', gutil.colors.cyan(data.id), data.message); }); }); gulp.task('git-check', function(done) { if (!sh.which('git')) { console.log( ' ' + gutil.colors.red('Git is not installed.'), '\n Git, the version control system, is required to download Ionic.', '\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.', '\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.' ); process.exit(1); } done(); });
JavaScript
0.000001
@@ -264,16 +264,101 @@ elljs'); +%0Avar browserify = require('browserify');%0Avar source = require('vinyl-source-stream'); %0A%0Avar pa @@ -393,16 +393,42 @@ *.scss'%5D +,%0A bundle: %5B'./lib/*.js'%5D %0A%7D;%0A%0Agul @@ -842,32 +842,124 @@ %5B'sass'%5D);%0A%7D);%0A%0A +gulp.task('watch:bundle', function() %7B%0A gulp.watch(paths.bundle, %5B'browserify-api'%5D);%0A%7D);%0A%0A gulp.task('insta @@ -1130,32 +1130,354 @@ );%0A %7D);%0A%7D);%0A%0A +gulp.task('browserify-api', function() %7B%0A return browserify('./lib/api.js')%0A .require('./lib/api.js', %7B%0A expose: '/lib/api'%0A %7D)%0A .bundle()%0A //Pass desired output filename to vinyl-source-stream%0A .pipe(source('bundle.js'))%0A // Start piping stream to tasks!%0A .pipe(gulp.dest('./www/js/'));%0A%7D);%0A%0A%0A%0A gulp.task('git-c
b252ba630d2732b3badec5f5282dbb5f0e6d1498
add todo in gulpfile
gulpfile.js
gulpfile.js
/* global require */ var gulp = require('gulp'); var shell = require('gulp-shell'); var minifyHtml = require('gulp-htmlmin'); var autoprefixer = require('gulp-autoprefixer'); var minifyCss = require('gulp-clean-css'); var rename = require('gulp-rename'); var concatCss = require('gulp-concat-css'); var minifyImg = require('gulp-imagemin'); var download = require('gulp-download'); var htmlSource = '_site/**/*.html'; var cssSource = 'public/css/*.css'; var imgSource = 'public/imgs/*'; var destination = '../blog-src/'; var htmlWrite = destination; var cssWrite = destination + 'public/css/'; var imgWrite = destination + 'public/imgs/'; var jsWrite = destination + 'public/js/'; var clean = '~/repos/blog-src/*'; // todo: // optimize font loading // seo stuff // only do img, html, css if changed // ??? gulp.task('dev-build', function(done) { return gulp.src('index.html', { read: false }) .pipe(shell([ 'bundle exec jekyll build --config _config.yml,_config_dev.yml' ])); done(); }); gulp.task('prod-build', function(done) { return gulp.src('index.html', { read: false }) .pipe(shell([ 'bundle exec jekyll build --config _config.yml' ])); done(); }); gulp.task('html', function(done) { return gulp.src(htmlSource) .pipe(minifyHtml({ collapseWhitespace: true, sortAttributes: true, sortClassName: true, removeComments: true })) .pipe(gulp.dest(htmlWrite)); done(); }); gulp.task('css', function(done) { return gulp.src(cssSource) .pipe(autoprefixer()) .pipe(concatCss(cssWrite)) .pipe(rename('style.min.css')) .pipe(minifyCss()) .pipe(gulp.dest(cssWrite)); done(); }); gulp.task('images', function () { return gulp.src(imgSource) .pipe(minifyImg()) .pipe(gulp.dest(imgWrite)); done(); }); gulp.task('analytics', function(done) { return download('https://www.google-analytics.com/analytics.js') .pipe(gulp.dest(jsWrite)); done(); }); gulp.task('clean', function(done) { return gulp.src(destination, { read: false }) .pipe(shell([ ( 'rm -r ' + clean ) ])); done(); }); gulp.task('default', gulp.series('dev-build','html','css','images','analytics', function(done) { done(); })); gulp.task('prod', gulp.series('prod-build','html','css','images','analytics', function(done) { done(); }));
JavaScript
0.000001
@@ -890,16 +890,150 @@ // ???%0A%0A +// FIXME issue with hangman css - 'New Game' button too close to input box. Clicking on 'New Game' puts it where it's supposed to be%0A%0A %0Agulp.ta
9d1def5008c49889438d70f4ac28204e12caf51b
Use strict
gulpfile.js
gulpfile.js
let gulp = require('gulp'); let sass = require('gulp-sass'); let autoprefixer = require('gulp-autoprefixer'); let cssnano = require('gulp-cssnano'); let rename = require('gulp-rename'); const src = './src/sass/zebra.scss'; const destination = './dist/css/'; const autoprefixrBrowsers = ['last 2 versions', 'ie >= 8']; gulp.task('sass', function () { return gulp.src('./src/sass/zebra.scss') .pipe(sass().on('error', sass.logError)) .pipe(autoprefixer({ browsers: autoprefixrBrowsers, cascade: false })) .pipe(gulp.dest(destination)) .pipe(cssnano()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest(destination)); }); gulp.task('default', function () { gulp.watch('./src/sass/*.scss', ['sass']); });
JavaScript
0.000083
@@ -1,12 +1,27 @@ +%22use strict%22;%0A%0A let gulp = r
c294f4cdb29049b455bd7530b32be4fd2051ed59
Add less output to Theo for theme use
gulpfile.js
gulpfile.js
// See Salesforce UX's design-tokens project for more information var path = require('path'); var rimraf = require('rimraf'); var async = require('async'); var _ = require('lodash'); var gulp = require('gulp'); var jsonlint = require('gulp-json-lint'); var rename = require('gulp-rename'); var theo = require('theo'); //////////////////////////////////////////////////////////////////// // Helpers //////////////////////////////////////////////////////////////////// function clean(f, done) { var p = path.resolve(__dirname, f); rimraf(f, done); } //////////////////////////////////////////////////////////////////// // Tasks - Clean //////////////////////////////////////////////////////////////////// gulp.task('clean', function(done) { async.each(['dist/tokens'], clean, done); }); //////////////////////////////////////////////////////////////////// // Tasks - Tokens //////////////////////////////////////////////////////////////////// var convertOptions = _({ 'web': [ 'styl', 'less', 'sass', 'default.sass', 'scss', 'default.scss', 'map.scss', 'map.variables.scss', 'html', 'json', 'common.js', 'amd.js' ], 'ios': ['ios.json'], 'android': ['android.xml'] }).map(function(formats, transform) { return formats.map(function(format) { return { format: format, transform: transform }; }); }).flatten().value(); function convert(options, done) { gulp.src([ './tokens/*.json', '!./tokens/_*.json' ]) .pipe(theo.plugins.transform(options.transform)) .on('error', done) .pipe(theo.plugins.format(options.format)) .on('error', done) .pipe(gulp.dest(path.resolve(__dirname, 'dist/tokens'))) .on('error', done) .on('finish', done); } gulp.task('tokens', ['clean', 'lint'], function(done) { async.each(convertOptions, convert, done); }); //////////////////////////////////////////////////////////////////// // Tasks - Lint //////////////////////////////////////////////////////////////////// gulp.task('lint', function() { return gulp.src('./tokens/*.json') .pipe(jsonlint({ comments: true })) .pipe(jsonlint.report('verbose')); }); //////////////////////////////////////////////////////////////////// // Tasks //////////////////////////////////////////////////////////////////// gulp.task('dev', function() { gulp.watch('./tokens/**', ['tokens']); }); gulp.task('default', ['tokens']);
JavaScript
0.000002
@@ -953,13 +953,37 @@ //%0A%0A -var c +// for external use%0Avar distC onve @@ -1389,16 +1389,51 @@ ransform +,%0A outputFolder: 'dist/tokens' %0A %7D;%0A @@ -1461,16 +1461,204 @@ lue();%0A%0A +// for use in MCtheme (output one type)%0Avar themeConvertOptions = %5B%0A %7B%0A format: 'less',%0A transform: 'web',%0A outputFolder: 'less/tokens'%0A %7D%5D;%0A%0Aconsole.log(themeConvertOptions);%0A%0A function @@ -1924,29 +1924,36 @@ irname, -'dist/tokens' +options.outputFolder )))%0A .o @@ -2006,17 +2006,21 @@ p.task(' -t +distT okens', @@ -2068,17 +2068,137 @@ nc.each( -c +distConvertOptions, convert, done);%0A%7D);%0A%0Agulp.task('themeTokens', %5B'clean', 'lint'%5D, function(done) %7B%0A async.each(themeC onvertOp @@ -2736,25 +2736,29 @@ kens/**', %5B' -t +distT okens'%5D);%0A%7D) @@ -2784,16 +2784,35 @@ lt', %5B't +hemeTokens', 'distT okens'%5D)
0c1f85c439e554badb4b3dfc6b0b6033a02b6d1e
correct namespace
allow_fullscreen_on_every_embed_youtube.user.js
allow_fullscreen_on_every_embed_youtube.user.js
// ==UserScript== // @name youtube: allow fullscreen on every embed // @namespace totalamd github // @match *://*/* // @version 1.0.0.1 // @downloadURL https://github.com/totalamd/GM-scripts/raw/master/allow_fullscreen_on_every_embed_youtube.user.js // @updateURL https://github.com/totalamd/GM-scripts/raw/master/allow_fullscreen_on_every_embed_youtube.user.js // @noframes // ==/UserScript== "use strict"; const l = function(){}, i = function(){}; (function () { // const l = console.log.bind(console, `${GM_info.script.name} debug:`), i = console.info.bind(console, `${GM_info.script.name} debug:`); Array.from(document.querySelectorAll('iframe')).forEach((iframe) => { if (iframe.src.match(/^https?:\/\/(?:www\.)?youtube\.com\/embed\//)) { iframe.allowFullscreen = true; } }); const target = document.body; const config = { childList: true, subtree: true }; const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { Array.from(mutation.addedNodes).forEach((node) => { if (node.tagName === "IFRAME" && node.src.match(/^https?:\/\/(?:www\.)?youtube\.com\/embed\//)) { node.allowFullscreen = true; } }); }); }); observer.observe(target, config); })();
JavaScript
0.028653
@@ -84,24 +84,35 @@ space +github.com/ totalamd github%0A @@ -103,23 +103,16 @@ totalamd - github %0A// @mat @@ -150,17 +150,17 @@ 1.0.0. -1 +2 %0A// @dow
e11dbc1df4ee8d0c482d6ecf316b2de39cccb229
tag update: hide this one instead of dumb class remove
js/toggle-spoiler.js
js/toggle-spoiler.js
/* * toggle-spoiler.js * * Allows user to un-hide spoilers and custom styles like .roleplay * * Usage: * $config['additional_javascript'][] = 'js/jquery.min.js'; * $config['additional_javascript'][] = 'js/settings.js'; * $config['additional_javascript'][] = 'js/toggle-spoiler.js'; * */ onready(function(){ if (settings.textSpoiler) { var do_unspoil = function() { $('span.spoiler').css({'color':'black', 'background-color': '#BBBBBB'}) } do_unspoil(document); // allow to work with auto-reload.js, etc. $(document).bind('new_post', function(e, post) { do_unspoil(post); }); } if (settings.hideRoleplay) { var do_unroleplay = function() { $('.body span.roleplay').removeClass('roleplay'); } do_unroleplay(document); // allow to work with auto-reload.js, etc. $(document).bind('new_post', function(e, post) { do_unroleplay(post); }); } });
JavaScript
0
@@ -723,24 +723,9 @@ move -Class('roleplay' +( );%0A%09
3b53660957391934e87d9790cb43cf58e1cfd10a
fix logic when there are multiple versions returned and the first result match user's version-no change is made on the version but mpg info is still achieved
js/vehicleRequest.js
js/vehicleRequest.js
var metaMpgData = {}; var vehicleRequest = {}; var $vehicleDefer = $.Deferred(); vehicleRequest.index = function() { var $carYear = $('.carYear'); var $carMake = $('.carMake'); var $carModel = $('.carModel'); var $carVersion = $('.carVersion'); var $avgMpg = $('.avgMpg'); var $minMpg = $('.minMpg'); var $maxMpg = $('.maxMpg'); var $errorVehicle = $('.errorVehicle'); var date = new Date(); var currentYear = date.getFullYear(); for (ii = 1984; ii <= currentYear; ii++) { $carYear.append('<option>' + ii + '</option>') }; $carYear.on('change', function() { console.log('carYear event fires'); var userSelectedYear = "" $(".carYear option:selected").each(function() { userSelectedYear += $(this).text(); }); var ajaxRequest = $.ajax({ type: "GET", url: 'http://www.fueleconomy.gov/ws/rest/vehicle/menu/make?year=' + userSelectedYear, dataType: "xml", }); ajaxRequest.done(function(xml) { $carMake.html(''); $carMake.append('<option>Make</option>'); $(xml).find("value").each(function() { $carMake.append('<option>' + $(this).text() + '</option>'); }) // $vehicleDefer.resolve(); }); }); //MODELSd $carMake.change(function() { console.log('carMake event fires'); var userSelectedMake = ""; $(".carMake option:selected").each(function() { userSelectedMake += $(this).text(); }); ajaxRequest = $.ajax({ type: "GET", url: 'http://www.fueleconomy.gov/ws/rest/vehicle/menu/model?year=2012&make=' + userSelectedMake, dataType: "xml", }); ajaxRequest.done(function(xml) { $carModel.html(''); $carModel.append('<option>Model</option>'); $(xml).find("value").each(function() { $carModel.append('<option>' + $(this).text() + '</option>'); }) // $vehicleDefer.resolve(); // console.log("vehicleDefer resolved"); }); }); $carModel.on('change', function() { userCarVersion(); }); function userCarVersion() { userYear = $(".carYear option:selected").text(); userMake = $(".carMake option:selected").text(); userModel = $(".carModel option:selected").text(); ajaxRequest = $.ajax({ type: "GET", url: 'http://www.fueleconomy.gov/ws/rest/vehicle/menu/options?year=' + userYear + '&make=' + userMake + '&model=' + userModel, dataType: "xml", }); ajaxRequest.done(function(xml) { $carVersion.html(''); $(xml).find("text").each(function() { $carVersion.append('<option>' + $(this).text() + '</option>'); }); if($carVersion.children().length===1){ var vehicleID = $(xml).find("text:contains('" + $carVersion.val() + "')").next("value").text(); console.log(vehicleID); userCarId(vehicleID); }else if ($carVersion.children().length===0){ $errorVehicle.append('Sorry, we could not find the information about the vehicle.'); } $carVersion.on('change', function() { var vehicleID = $(xml).find("text:contains('" + $carVersion.val() + "')").next("value").text(); userCarId(vehicleID); }); function userCarId(vehicleID) { console.log(vehicleID); ajaxRequest = $.ajax({ type: "GET", url: 'http://www.fueleconomy.gov/ws/rest/ympg/shared/ympgVehicle/' + vehicleID, dataType: "xml", statusCode: { 404: function() { //resets and error message in drop down section $errorVehicle.append('Sorry, we could not find the information about the vehicle.'); $carYear.val(0); $carMake.val(0); $carModel.val(0); $carVersion.val(0); } } }); console.log(xml); ajaxRequest.done(function(xml) { $(xml).find("avgMpg").each(function() { metaMpgData.avgmpg = Math.round(parseInt($(this).text())); console.log(metaMpgData.avgmpg); $avgMpg.append($(this).text()); }); $(xml).find("maxMpg").each(function() { metaMpgData.maxmpg = $(this).text(); $maxMpg.append($(this).text()); }); $(xml).find("minMpg").each(function() { metaMpgData.minmpg = $(this).text(); $minMpg.append($(this).text()); console.log(metaMpgData); }); $vehicleDefer.resolve(); console.log("vehicle defer resolved"); }) } //userCarId }); //ajax done #1 } //userCarVersion }; //vehicleRequest closed vehicleRequest.index();
JavaScript
0
@@ -2971,33 +2971,32 @@ %7D);%0A -%0A if($ @@ -2993,16 +2993,17 @@ if + ($carVer @@ -3031,12 +3031,132 @@ h=== -1 +0 )%7B%0A + $errorVehicle.append('Sorry, we could not find the information about the vehicle.');%0A %7Delse%7B%0A @@ -3345,167 +3345,8 @@ D);%0A - %7Delse if ($carVersion.children().length===0)%7B%0A $errorVehicle.append('Sorry, we could not find the information about the vehicle.');%0A @@ -3355,17 +3355,16 @@ %7D%0A -%0A @@ -3564,32 +3564,32 @@ %7D);%0A%0A - func @@ -3612,24 +3612,64 @@ ehicleID) %7B%0A + $errorVehicle.html('');%0A
07fdc39d8b67b1baa1cc5dc6658fd9470aebfa06
fix save attachments
js/views/sendmail.js
js/views/sendmail.js
/* global Backbone, Handlebars, Mail, models */ var views = views || {}; views.SendMail = Backbone.View.extend({ // The collection will be kept here attachments: null, sentCallback: null, aliases: null, currentAccountId: null, events: { "click #new-message-send" : "sendMail", "click .mail_account" : "changeAlias" }, initialize: function(options) { this.attachments = new models.Attachments(); this.aliases = options.aliases; this.el = options.el; this.currentAccountId = this.aliases[0].accountId; }, changeAlias: function(event) { this.currentAccountId = parseInt($(event.target).val()); }, sendMail: function() { // // TODO: // - input validation // - feedback on success // - undo lie - very important // // loading feedback: show spinner and disable elements var newMessageBody = $('#new-message-body'); var newMessageSend = $('#new-message-send'); newMessageBody.addClass('icon-loading'); var to = $('#to'); var cc = $('#cc'); var bcc = $('#bcc'); var subject = $('#subject'); $('.mail_account').prop('disabled', true); to.prop('disabled', true); cc.prop('disabled', true); bcc.prop('disabled', true); subject.prop('disabled', true); $('.new-message-attachments-action').css('display', 'none'); $('#mail_new_attachment').prop('disabled', true); newMessageBody.prop('disabled', true); newMessageSend.prop('disabled', true); newMessageSend.val(t('mail', 'Sending …')); var self = this; // send the mail $.ajax({ url:OC.generateUrl('/apps/mail/accounts/{accountId}/send', {accountId: this.currentAccountId}), beforeSend:function () { OC.msg.startAction('#new-message-msg', {}); }, type: 'POST', data:{ 'to': to.val(), 'cc': cc.val(), 'bcc': bcc.val(), 'subject': subject.val(), 'body':newMessageBody.val(), 'attachments': self.attachments.toJSON() }, success:function () { OC.msg.finishedAction('#new-message-msg', { status: 'success', data: { message: t('mail', 'Mail sent to {Receiver}', {Receiver: to.val()}) } }); // close composer if (self.sentCallback !== null) { self.sentCallback(); } else { $('#new-message').slideUp(); } $('#mail_new_message').prop('disabled', false); $('#to').val(''); $('#subject').val(''); $('#new-message-body').val(''); self.attachments.reset(); }, error: function (jqXHR) { OC.msg.finishedAction('#new-message-msg', { status: 'error', data: { message: jqXHR.responseJSON.message } }); }, complete: function() { // remove loading feedback newMessageBody.removeClass('icon-loading'); $('.mail_account').prop('disabled', false); $('#to').prop('disabled', false); $('#cc').prop('disabled', false); $('#bcc').prop('disabled', false); $('#subject').prop('disabled', false); $('.new-message-attachments-action').css('display', 'inline-block'); $('#mail_new_attachment').prop('disabled', false); newMessageBody.prop('disabled', false); newMessageSend.prop('disabled', false); newMessageSend.val(t('mail', 'Send')); } }); return false; }, render: function() { var source = $("#new-message-template").html(); var template = Handlebars.compile(source); var html = template({aliases: this.aliases}); this.$el.html(html); var view = new views.Attachments({ el: $('#new-message-attachments'), collection: this.attachments }); // And render it view.render(); $('textarea').autosize(); return this; } });
JavaScript
0.000001
@@ -29,20 +29,26 @@ rs, -Mail, models +, escapeHTML */%0A @@ -619,16 +619,20 @@ t).val() +, 10 );%0A%09%7D,%0A%0A @@ -2071,24 +2071,35 @@ ceiver: +escapeHTML( to.val() %7D)%0A%09%09%09%09%09 @@ -2090,16 +2090,17 @@ to.val() +) %7D)%0A%09%09%09%09%09
16634592d409d6ee877ac1b9c69c7cfe0256182e
use separate webpack path to avoid path collisions
js/webpack.config.js
js/webpack.config.js
const path = require('path'); var rules = [ { test: /\.css$/, use: [{loader: "style-loader"}, {loader: "css-loader" }]}, { test: /\.less$/, use: [{loader: "style-loader"}, {loader: "css-loader" }, {loader: "less-loader" }]}, { test: /\.(jpg|png|gif)$/, use: "file" }, // required to load font-awesome { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: "url?limit=10000&mimetype=application/font-woff" }, { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: "url?limit=10000&mimetype=application/font-woff" }, { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: "url?limit=10000&mimetype=application/octet-stream" }, { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: "file" }, { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: "url?limit=10000&mimetype=image/svg+xml" } ]; module.exports = [ {// Notebook extension entry: './lib/extension.js', output: { filename: 'extension.js', path: path.resolve(__dirname, '../bqplot/static'), libraryTarget: 'amd' }, externals: ['@jupyter-widgets/base'], mode: 'production' }, {// bqplot bundle for the classic notebook entry: './lib/index-classic.js', output: { filename: 'index.js', path: path.resolve(__dirname, '../bqplot/static'), libraryTarget: 'amd' }, devtool: 'source-map', module: { rules: rules }, externals: ['@jupyter-widgets/base'], mode: 'production' }, {// bqplot bundle for unpkg. entry: './lib/index-embed.js', output: { filename: 'index.js', path: path.resolve(__dirname, './dist/'), libraryTarget: 'amd' }, devtool: 'source-map', module: { rules: rules }, externals: ['@jupyter-widgets/base'], mode: 'production' } ];
JavaScript
0.000002
@@ -991,33 +991,139 @@ aryTarget: 'amd' +,%0A devtoolModuleFilenameTemplate: 'webpack://jupyter-widgets/bqplot/%5Bresource-path%5D?%5Bloaders%5D', %0A - %7D,%0A @@ -1424,32 +1424,138 @@ aryTarget: 'amd' +,%0A devtoolModuleFilenameTemplate: 'webpack://jupyter-widgets/bqplot/%5Bresource-path%5D?%5Bloaders%5D', %0A %7D,%0A @@ -1889,24 +1889,24 @@ './dist/'),%0A - @@ -1925,16 +1925,122 @@ t: 'amd' +,%0A devtoolModuleFilenameTemplate: 'webpack://jupyter-widgets/bqplot/%5Bresource-path%5D?%5Bloaders%5D', %0A
bf493cf8438f04180b94ac1d6891998b77612ea2
Fix a bug where the icons to share a page on social medias wouldn't work
app/javascript/components/public/footer.js
app/javascript/components/public/footer.js
import React from 'react'; import PropTypes from 'prop-types'; import queryString from 'query-string'; import { Icon } from 'components'; import { settingsUtils } from 'utils'; class Footer extends React.PureComponent { getShareUrl(service) { const { site } = this.props; const availableServices = { facebook: 'http://www.facebook.com/sharer.php?u=', twitter: 'https://twitter.com/share?url=', gplus: 'https://plus.google.com/share?url=', linkedin: 'https://www.linkedin.com/shareArticle?url=' } if (service === 'linkedin') { const linkedInParams = { url: window.location.href, title: `${site.page.name}-${site.current.name}`, summary: site.page.description } return availableServices['linkedin'] + `?${queryString.stringify(linkedInParams)}`; } const servicesParams = { url: window.location.href } return availableServices[service] + `?${queryString.stringify(servicesParams)}`; } renderContactInfo() { const { settings } = this.props.site; return (<li className="site-link-item"> <a href={`mailto: ${settingsUtils.getValue('contact_email_address', settings)}`} className="site-link">Contact us</a> </li>); } preFooter() { const { settings } = this.props.site; return ( <div className="c-pre-footer"> <div className="wrapper" dangerouslySetInnerHTML={{ __html: settingsUtils.getValue('pre_footer', settings) }} /> </div> ); } render () { const { settings } = this.props.site; return (<div> {settingsUtils.isset(settingsUtils.find('pre_footer', settings)) && this.preFooter()} <footer className="c-footer"> <div className="wrapper"> <ul className="site-links-list"> <li className="site-link-item"> <a href="/terms-and-privacy" className="site-link">Terms of Service</a> </li> <li className="site-link-item"> <a href="/privacy-policy" className="site-link">Privacy Policy</a> </li> {settingsUtils.isset(settingsUtils.find('contact_email_address', settings)) && this.renderContactInfo()} </ul> <div className="share"> <span className="share-text">Share the Atlas</span> <ul className="share-links-list"> <li className="share-link-item"> <a className="share-link -facebook" href={this.getShareUrl('facebook')} target="_blank"> <Icon name="icon-Facebook" className="icon icon-Facebook" /> </a> </li> <li className="share-link-item"> <a className="share-link -twitter" href={this.getShareUrl('twitter')} target="_blank"> <Icon name="icon-Twitter" className="icon icon-Twitter" /> </a> </li> <li className="share-link-item"> <a className="share-link -googleplus" href={this.getShareUrl('gplus')} target="_blank"> <Icon name="icon-Google" className="icon icon-Google" /> </a> </li> <li className="share-link-item"> <a className="share-link -linkedin" href={this.getShareUrl('linkedin')} target="_blank"> <Icon name="icon-Linkedin" className="icon icon-Linkedin" /> </a> </li> </ul> </div> </div> </footer> </div>) } } Footer.propTypes = { }; export default Footer;
JavaScript
0.000001
@@ -362,11 +362,8 @@ .php -?u= ',%0A @@ -394,37 +394,32 @@ witter.com/share -?url= ',%0A gplus: @@ -448,21 +448,16 @@ om/share -?url= ',%0A @@ -509,13 +509,8 @@ icle -?url= '%0A @@ -510,24 +510,56 @@ cle'%0A %7D%0A%0A + const servicesParams = %7B%7D;%0A%0A if (serv @@ -590,45 +590,28 @@ -const linkedInParams = %7B%0A url: +servicesParams.url = win @@ -631,24 +631,38 @@ href -, +; %0A - +servicesParams. title -: + = %60$%7B @@ -702,26 +702,40 @@ me%7D%60 -, +; %0A - +servicesParams. summary -: + = sit @@ -756,123 +756,116 @@ tion +; %0A - %7D -%0A return availableServices%5B'linkedin'%5D + %60?$%7BqueryString.stringify(linkedInParams)%7D%60;%0A %7D%0A%0A const + else if (service === 'facebook') %7B%0A servicesParams.u = window.location.href;%0A %7D else %7B%0A ser @@ -879,23 +879,14 @@ rams - = %7B%0A url: +.url = win @@ -902,16 +902,17 @@ ion.href +; %0A %7D%0A%0A @@ -2536,34 +2536,60 @@ target=%22_blank%22 + rel=%22noopener noreferrer%22 %3E%0A - @@ -2833,32 +2833,58 @@ target=%22_blank%22 + rel=%22noopener noreferrer%22 %3E%0A @@ -3129,32 +3129,58 @@ target=%22_blank%22 + rel=%22noopener noreferrer%22 %3E%0A @@ -3321,32 +3321,32 @@ are-link-item%22%3E%0A - @@ -3432,16 +3432,42 @@ %22_blank%22 + rel=%22noopener noreferrer%22 %3E%0A
fd6dcd34cf8ca80056206a773d477264974dfadd
Make sure debaterTwo exists in debater filter Fixes DEBATEVIDIO-4
app/assets/components/Videos/helpers/filters.js
app/assets/components/Videos/helpers/filters.js
import { List, Map } from 'immutable'; import { Filter } from 'components/store/records'; export const createFilters = ({ levels, types, tournaments, schools, teams, debaters, tags }) => { return List([ new Filter({ id: 'level', label: 'Level', type: 'select', options: levels.set('Any', 'any').sort().reverse(), value: 'any', filter(videos) { if(this.value === 'any') { return videos; } else { const intValue = parseInt(this.value); return videos.filter((video) => video.debateLevel === intValue); } }, }), new Filter({ id: 'type', label: 'Format', type: 'select', options: types.set('Any', 'any').sort().reverse(), value: 'any', filter(videos) { if(this.value === 'any') { return videos; } else { const intValue = parseInt(this.value); return videos.filter((video) => video.debateType === intValue); } }, }), new Filter({ id: 'year', label: 'Year', type: 'select', options: Map(tournaments.map(t => t.year).groupBy(y => y).keySeq().sort().map((y) => [y, y])).set('Any', 'any').reverse(), value: 'any', filter(videos) { if(this.value === 'any') { return videos; } else { const intValue = parseInt(this.value); return videos.filter((video) => video.tournament.year === intValue); } }, }), new Filter({ id: 'tournament', label: 'Tournament', type: 'select', options: tournaments.map(t => t.getYearAndName()).set('any', 'Any').sort().flip(), value: 'any', filter(videos) { if(this.value === 'any') { return videos; } else { const intValue = parseInt(this.value); return videos.filter((video) => video.tournament.id === intValue); } }, }), new Filter({ id: 'school', label: 'School', type: 'select', options: schools.map(s => s.getName()).set('any', 'Any').sort().flip(), value: 'any', filter(videos) { if(this.value === 'any') { return videos; } else { const intValue = parseInt(this.value); return videos.filter((video) => video.affTeam.school.id === intValue || video.negTeam.school.id === intValue); } }, }), new Filter({ id: 'team', label: 'Team', type: 'select', options: teams.map(t => t.getTeamCode()).set('any', 'Any').sort().flip(), value: 'any', filter(videos) { if(this.value === 'any') { return videos; } else { const intValue = parseInt(this.value); return videos.filter((video) => video.affTeam.id === intValue || video.negTeam.id === intValue); } }, }), new Filter({ id: 'debater', label: 'Debater', type: 'select', options: debaters.map(d => d.getName()).set('any', 'Any').sort().flip(), value: 'any', filter(videos) { if(this.value === 'any') { return videos; } else { const intValue = parseInt(this.value); return videos.filter((video) => { return ( video.affTeam.debaterOne.id === intValue || video.affTeam.debaterTwo.id === intValue || video.negTeam.debaterOne.id === intValue || video.negTeam.debaterTwo.id === intValue ); }); } }, }), new Filter({ id: 'tag', label: 'Tag', type: 'select', options: tags.map(t => t.title).set('any', 'Any').sort().flip(), value: 'any', filter(videos) { if(this.value === 'any') { return videos; } else { return videos.filter((video) => video.matchingTagId(this.value)); } }, }), ]); };
JavaScript
0
@@ -3347,32 +3347,60 @@ %7C%7C%0A + video.affTeam.debaterTwo && video.affTeam.d @@ -3491,32 +3491,60 @@ %7C%7C%0A + video.negTeam.debaterTwo && video.negTeam.d
af7a6d41abcd423c5dd69c54a7fc5dfefd2bb71f
Fix tests.
app/assets/javascripts/FormMessageController.js
app/assets/javascripts/FormMessageController.js
/** * Created by elisahilprecht on 09/04/15. */ window.FormMessageController = {}; (function(FormMessageController){ var getElementsByClassName = function(node, classname) { var a = []; var re = new RegExp('(^| )'+classname+'( |$)'); var els = node.getElementsByTagName("*"); for(var i=0,j=els.length; i<j; i++) if(re.test(els[i].className))a.push(els[i]); return a; }; FormMessageController.clickOnErrorMessage = function(ele) { if(ele.id.indexOf('agreement')===-1){ ele.setAttribute('class','help-inline display-none'); document.getElementById(ele.id.replace('ErrorText','')).focus(); } }; FormMessageController.clickOnInputField = function(e){ var element = e.srcElement ? e.srcElement : e.toElement; element = element ? element : e.target; var errorText = document.getElementById(element.id.replace('_agreement', '')+'ErrorText'); if(errorText){ errorText.setAttribute('class','help-inline display-none'); } }; var helpInlines = getElementsByClassName(document.getElementById('signup_form'), 'help-inline'); for(var i=0; i<helpInlines.length; i++){ var ele = helpInlines[i]; if(ele.getAttribute('class')==='help-inline'){ var inputId = ele.id.replace('ErrorText', ''); var inputValue = document.getElementById(inputId).value; if(inputValue!==undefined && inputValue!==''){ ele.setAttribute('class', 'help-inline help-inline__bottom' ) } } } var inputFields = document.getElementsByTagName('input'); for(var j=0; j<inputFields.length; j++){ inputFields[j].onclick = FormMessageController.clickOnInputField; inputFields[j].onfocus = FormMessageController.clickOnInputField; } })(window.FormMessageController);
JavaScript
0
@@ -701,16 +701,29 @@ ion(e)%7B%0A + if(e)%7B%0A var @@ -775,16 +775,18 @@ lement;%0A + elem @@ -821,24 +821,26 @@ target;%0A + var errorTex @@ -918,24 +918,26 @@ Text');%0A + if(errorText @@ -939,16 +939,18 @@ rText)%7B%0A + er @@ -1003,24 +1003,32 @@ lay-none');%0A + %7D%0A %7D%0A %7D;%0A%0A
2b6b746590604ebb2941a56ae068a27ffd8ad106
remove duplication from statscontrolelr
app/assets/javascripts/stats/statsController.js
app/assets/javascripts/stats/statsController.js
angular.module('ocWebGui.stats', ['ui.router', 'nvd3']) .config(function ($stateProvider) { $stateProvider .state('stats', { url: '/stats', views: { nav: { templateUrl: 'navbar/navbar_others.html' }, content: { templateUrl: 'stats/_stats.html', controller: 'StatsController', controllerAs: 'stats' } } }); }) .controller('StatsController', function ($interval, $scope, $http, Settings, ChartJuttu) { var vm = this; vm.title = 'Tilastot'; vm.api = {}; vm.options = { chart: { type: 'scatterChart', width: 700, height: 300, margin: { top: 30, right: 90, bottom: 60, left: 90 }, color: d3.scale.category10().range(), showDistX: true, showDistY: true, xAxis: { axisLabel: 'Kellonaika', tickFormat: function (d) { return d3.time.format('%H.%M')(new Date(d)); } }, yAxis: { axisLabel: 'Jonotusaika', axisLabelDistance: 10, tickFormat: function (seconds) { var formatTime = d3.time.format('%H:%M'); return formatTime(new Date(1864, 7, 7, 0, seconds)); } }, x: function (d) { return d.hour; }, y: function (d) { return d.calls; } } }; vm.data = [{ 'key': 'Jonotusaika', 'values': [] }]; vm.api2 = {}; vm.options2 = { chart: { type: 'multiChart', width: 700, height: 550, margin: { top: 30, right: 90, bottom: 60, left: 90 }, x: function (d) { return d.hour; }, y: function (d) { return d.calls; }, duration: 500, xAxis: { axisLabel: 'Kellonaika' }, yAxis1: { axisLabel: 'Jonottajat', yDomain: [0, 10] }, yAxis2: { axisLabel: 'Aikaa', tickFormat: function (seconds) { var formatTime = d3.time.format('%H:%M'); return formatTime(new Date(1864, 7, 7, 0, seconds)); }, yDomain: [0, 10] } } }; vm.data2 = [{ 'key': 'Henkilöitä', 'values': [], 'type': 'line', 'yAxis': 1, 'color': '#ff00ff' }, { 'key': 'Luopuneet', 'values': [], 'type': 'area', 'yAxis': 1, 'color': '#0000ff' }, { 'key': 'Jonotuksen keskiarvo', 'values': [], 'type': 'bar', 'yAxis': 2, 'color': '#00ff00' }, { 'key': 'Palvelutaso', 'values': [], 'type': 'line', 'yAxis': 2, 'color': '#ff0000' }]; function getMaxValPlusOne(i) { var maxVal = d3.max(vm.data2[i].values, function (x) { return x.calls; }); if (maxVal == null) { return 1; } return maxVal + 1; } function fetchContactStats() { Settings.getOthers().then(function (others) { vm.otherSettings = others; }); $http.get('contacts/stats.json').then(function (response) { var data = response.data; var beginningOfDay = new Date(); beginningOfDay.setDate(beginningOfDay.getDate()); beginningOfDay.setHours(8, 0, 0); var endOfDay = new Date(); endOfDay.setDate(endOfDay.getDate()); endOfDay.setHours(18, 0, 0); var queueDurationsByTimes = data.queue_durations_by_times .map(function (j) { return { hour: new Date(j[0]).getTime(), calls: j[1] }; }); vm.data[0].values = queueDurationsByTimes; vm.options.chart.xAxis.tickValues = d3.time.hour.range(beginningOfDay, endOfDay, 1) .map(function (f) { return f.getTime(); }); vm.api.refresh(); var callsByHours = ChartJuttu.mapAndFilter(data.calls_by_hour, vm.otherSettings); var missedCallsByHours = ChartJuttu.mapAndFilter(data.missed_calls_by_hour, vm.otherSettings); var averageQueueDurationByHour = ChartJuttu.mapAndFilter(data.average_queue_duration_by_hour, vm.otherSettings); vm.data2[0].values = callsByHours; vm.data2[1].values = missedCallsByHours; vm.data2[2].values = averageQueueDurationByHour; // use 0 because all calls is always same or bigger than missed calls var callMax = getMaxValPlusOne(0); // Multiply by 1.05 so highest value is high enough that highest point in chart isn't hidden var queueMax = getMaxValPlusOne(2) * 1.05; var sla = 300; if (sla <= queueMax) { var slaLine = data.calls_by_hour .map(function (calls, hour) { return { hour: hour, calls: sla }; }) .filter(function (item) { return item.hour >= 8 && item.hour <= 18; }); vm.data2[3].values = slaLine; } vm.options2.chart.yAxis1.yDomain = callMax; vm.options2.chart.yAxis2.yDomain = queueMax; var yAxis1OldTicks = vm.options2.chart.yAxis1.tickValues; var yAxis2OldTicks = vm.options2.chart.yAxis2.tickValues; var yAxis1NewTicks = [callMax / 4, callMax / 2, callMax / (1 + 1.0 / 3)]; var yAxis2NewTicks = [queueMax / 4, queueMax / 2, queueMax / (1 + 1.0 / 3)]; if (!angular.equals(yAxis1OldTicks, yAxis1NewTicks) || !angular.equals(yAxis2OldTicks, yAxis2NewTicks)) { vm.options2.chart.yAxis1.tickValues = yAxis1NewTicks; vm.options2.chart.yAxis2.tickValues = yAxis2NewTicks; vm.api2.refresh(); } }); } var fetchContactStatsInterval = $interval(fetchContactStats, 5 * 60 * 1000); $scope.$on('$destroy', function () { $interval.cancel(fetchContactStatsInterval); }); fetchContactStats(); });
JavaScript
0.999648
@@ -2807,210 +2807,8 @@ %5D;%0A%0A - function getMaxValPlusOne(i) %7B%0A var maxVal = d3.max(vm.data2%5Bi%5D.values, function (x) %7B return x.calls; %7D);%0A if (maxVal == null) %7B%0A return 1;%0A %7D%0A return maxVal + 1;%0A %7D%0A%0A @@ -4239,24 +4239,35 @@ r callMax = +ChartJuttu. getMaxValPlu @@ -4275,12 +4275,21 @@ One( -0 +vm.data2%5B0%5D ); - %0A @@ -4409,16 +4409,27 @@ ueMax = +ChartJuttu. getMaxVa @@ -4437,17 +4437,27 @@ PlusOne( -2 +vm.data2%5B2%5D ) * 1.05
f3fadfeac69ef023b34ac89757c0d822a5abb13a
Refactor components to be mulitline.
assets/js/components/user-input/UserInputApp.js
assets/js/components/user-input/UserInputApp.js
/** * User Input App. * * Site Kit by Google, 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. */ export default function UserInputApp() { return featureFlags.widgets.userInput.enabled ? ( <div>TODO: Implement logic and UI.</div> ) : ( <div>You need a higher level of permission.</div> ); }
JavaScript
0
@@ -632,16 +632,89 @@ e.%0A */%0A%0A +/**%0A * WordPress dependencies%0A */%0Aimport %7B __ %7D from '@wordpress/i18n';%0A%0A export d @@ -751,14 +751,14 @@ %7B%0A%09 -return +if ( ! fea @@ -797,110 +797,138 @@ led -? ( %3Cdiv%3ETODO: Implement logic and UI.%3C/div%3E ) : ( %3Cdiv%3EYou need a higher level of permission +) %7B%0A%09%09return %3Cdiv%3E%7B __( 'Something went wrong.', 'google-site-kit' ) %7D%3C/div%3E;%0A%09%7D%0A%0A%09return %3Cdiv%3ETODO: Implement logic and UI .%3C/div%3E - ) ;%0A%7D%0A
ec53f82ff615745a4020957da193a08aa34d1422
use the new bigger width of new section form
app/javascripts/taskar/sections/new_form.js
app/javascripts/taskar/sections/new_form.js
Taskar.Sections.NewForm = function(container){ container.on('click', '.add_section', show); container.on('click', 'input[type=button]', hide); container.on('key:esc', 'form', hide); container.on('submit', 'form', Taskar.Sections.validateForm); var form = $('new_section'), restore = container.style.width, width = (parseInt(container.style.width) + 238) + 'px', appear = new S2.FX.Style(form, { before: function(e){ form.setStyle({ width: '0px', opacity: 0.0 }); }, after: function(e){ form.down('input[type=text]').focus(); } }); function show(e, element){ e && e.stop(); form.down('form').reset(); form.down('input[name*=insert_before]').setValue(element.getAttribute('data-before')); if (element.previous() == form && form.visible()){ return; } form.hide(); element.hide() element.show.bind(element).defer(); element.insert({before: form}); container.style.width = width; form.show(); appear.play(null, {style: 'opacity:1; width:' + form.getWidth() + 'px'}); } function hide(){ form.hide(); container.style.width = restore; } if (container.select('.section').length == 0){ show(null, container.down('.add_section')); } };
JavaScript
0.000001
@@ -424,9 +424,9 @@ + 2 -3 +4 8) +
740de8689d0461b61d058ea42ad10387498f5466
remove listener on modal close
sauce/features/budget/enter-to-move/index.js
sauce/features/budget/enter-to-move/index.js
import { Feature } from 'toolkit/core/feature'; import * as toolkitHelper from 'toolkit/helpers/toolkit'; const MOVE_POPUP = 'ynab-u modal-popup modal-budget modal-budget-move-money ember-view modal-overlay active'; const CATEGORY_DROPDOWN = 'dropdown-container categories-dropdown-container'; const BUTTON_PRIMARY = 'button button-primary '; export class EnterToMove extends Feature { modalIsOpen = false; constructor() { super(); this.onKeyDownHandler = this.onKeyDown.bind(this); } shouldInvoke() { return toolkitHelper.getCurrentRouteName().indexOf('budget') !== -1; } invoke() {} onKeyDown(e) { const keycode = e.keycode || e.which; if (keycode === 13) { const OK = $( '.modal-budget-move-money .modal-actions button:first-child' ); OK.click(); document.removeEventListener('keydown', this.onKeyDownHandler, false); } } observe(changedNodes) { if (!this.shouldInvoke()) return; if (changedNodes.has(MOVE_POPUP)) { this.modalIsOpen = true; } if ( this.modalIsOpen && changedNodes.has(CATEGORY_DROPDOWN) && changedNodes.has(BUTTON_PRIMARY) ) { document.addEventListener('keydown', this.onKeyDownHandler, false); } } }
JavaScript
0
@@ -343,165 +343,159 @@ ';%0A -%0Aexport class EnterToMove extends Feature %7B%0A modalIsOpen = false;%0A%0A constructor() %7B%0A super();%0A this.onKeyDownHandler = this.onKeyDown.bind(this);%0A %7D +const BUTTON_CANCEL = 'button button-cancel';%0Aconst MODAL_CONTENT = 'modal-content';%0A%0Aexport class EnterToMove extends Feature %7B%0A modalIsOpen = false; %0A%0A @@ -619,11 +619,15 @@ Down -(e) + = e =%3E %7B%0A @@ -813,85 +813,8 @@ ();%0A - document.removeEventListener('keydown', this.onKeyDownHandler, false);%0A @@ -814,24 +814,25 @@ );%0A %7D%0A %7D +; %0A%0A observe( @@ -1087,24 +1087,55 @@ RY)%0A ) %7B%0A + // Ready to click button%0A docume @@ -1183,15 +1183,307 @@ Down -Handler +, false);%0A %7D%0A%0A if (%0A this.modalIsOpen &&%0A changedNodes.has(BUTTON_PRIMARY) &&%0A changedNodes.has(BUTTON_CANCEL) &&%0A changedNodes.has(MODAL_CONTENT)%0A ) %7B%0A // Modal has closed%0A this.modalIsOpen = false;%0A document.removeEventListener('keydown', this.onKeyDown , fa
5c8e3994bff9411a17d9fe48cad6fc0743a55375
update patch markers on library install
packages/xod-client/src/hinting/patchMarkers.js
packages/xod-client/src/hinting/patchMarkers.js
import * as R from 'ramda'; import * as XP from 'xod-project'; import { foldMaybe, isAmong } from 'xod-func-tools'; import * as PAT from '../project/actionTypes'; import * as EAT from '../editor/actionTypes'; // :: Action -> Boolean const isLoadingProjectAction = R.propSatisfies( isAmong([PAT.PROJECT_IMPORT, PAT.PROJECT_OPEN]), 'type' ); // :: String -> Boolean const oneOfInfoMarkers = isAmong([ XP.DEPRECATED_MARKER_PATH, XP.UTILITY_MARKER_PATH, ]); // :: Action -> Boolean const doesMarkerNodeAdded = R.allPass([ R.propEq('type', PAT.NODE_ADD), R.pathSatisfies(oneOfInfoMarkers, ['payload', 'typeId']), ]); const doesMarkerNodePasted = R.allPass([ R.propEq('type', EAT.PASTE_ENTITIES), R.pathSatisfies(R.any(R.pipe(XP.getNodeType, oneOfInfoMarkers)), [ 'payload', 'entities', 'nodes', ]), ]); // :: Action -> Boolean const doesAnyNodeDeleted = R.allPass([ R.propEq('type', PAT.BULK_DELETE_ENTITIES), R.pathSatisfies(nodeList => nodeList.length > 0, ['payload', 'nodeIds']), ]); // :: Action -> Boolean export const shallUpdatePatchMarkers = R.anyPass([ // Update on loading a project isLoadingProjectAction, // Update on adding a marker Node doesMarkerNodeAdded, // Update on pasting a marker Node doesMarkerNodePasted, // Update on deleting any Node // Without checking for deleting only marker nodes, // because it worst by performance doesAnyNodeDeleted, ]); // :: Patch -> PatchMarkers const getPatchMarkersForPatch = patch => ({ utility: XP.isUtilityPatch(patch), deprecated: XP.isDeprecatedPatch(patch), }); // :: StrMap PatchPath PatchMarkers -> Project -> StrMap PatchPath PatchMarkers const getPatchMarkersForEntireProject = R.curry((oldPatchMarkers, newProject) => R.compose( R.map(getPatchMarkersForPatch), R.indexBy(XP.getPatchPath), XP.listPatches )(newProject) ); // :: StrMap PatchPath PatchMarkers -> PatchPath -> Project -> StrMap PatchPath PatchMarkers const updatePatchMarkersForChangedPatch = R.curry( (oldPatchMarkers, patchPath, newProject) => R.compose( foldMaybe( R.omit([patchPath], oldPatchMarkers), R.compose( R.assoc(patchPath, R.__, oldPatchMarkers), getPatchMarkersForPatch ) ), XP.getPatchByPath )(patchPath, newProject) ); // :: StrMap PatchPath PatchMarkers -> Project -> Action -> StrMap PatchPath PatchMarkers export const getNewPatchMarkers = R.curry( (oldPatchMarkers, newProject, action) => R.ifElse( isLoadingProjectAction, () => getPatchMarkersForEntireProject(oldPatchMarkers, newProject), R.compose( updatePatchMarkersForChangedPatch(oldPatchMarkers, R.__, newProject), R.path(['payload', 'patchPath']) ) )(action) );
JavaScript
0
@@ -286,16 +286,21 @@ sAmong(%5B +%0A PAT.PROJ @@ -310,16 +310,20 @@ _IMPORT, +%0A PAT.PRO @@ -331,16 +331,56 @@ ECT_OPEN +,%0A EAT.INSTALL_LIBRARIES_COMPLETE,%0A %5D),%0A 't
86c646f10f1c0560cddf7f70dcb76539b4c3efdd
Unblock cutscene creation by fixing schema (#379)
app/schemas/models/cutscene.schema.ozar.js
app/schemas/models/cutscene.schema.ozar.js
const schema = require('./../schemas') const CutsceneSchema = schema.object({ description: 'Data for a cinematic', title: 'Cutscene' }, { // Deprecated. Instead upload and use Cloudflare. vimeoId: schema.shortString({ title: 'VimeoID', description: '"DEPRECATED - Upload to Cloudflare instead." - The id of the vimeo video we want to play.' }), cloudflareID: schema.shortString({ title: 'Cloudflare ID', description: 'Cloudflare video stream ID' }), chinaVideoSrc: schema.shortString({ title: 'Video URL for China', description: 'Raw video URL for china. Recommend this video is stored in the aliyun S3 equivalent OSS.' }), captions: schema.object({}, { src: { type: 'string', title: 'Caption file', format: 'vtt-file', description: "If this vtt file doesn't upload you may need to use a different browser like Firefox." }, label: schema.shortString({ title: 'Language Label' }) }), i18n: { type: 'object', format: 'i18n', props: ['name', 'captions', 'displayName'], description: 'This cutscene translation required srt files.' }, displayName: schema.shortString({ title: 'Display Name' }) }) schema.extendBasicProperties(CutsceneSchema, 'cutscene') schema.extendTranslationCoverageProperties(CutsceneSchema) schema.extendNamedProperties(CutsceneSchema) module.exports = CutsceneSchema
JavaScript
0
@@ -1262,16 +1262,65 @@ Schema)%0A +schema.extendPatchableProperties(CutsceneSchema)%0A schema.e
cfd2c2d5312ea8aacd58994d18942837331810d5
Add additional prescription dispatch functions to withPrescriptions HOC
app/pages/prescription/withPrescriptions.js
app/pages/prescription/withPrescriptions.js
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import assign from 'lodash/assign'; import forEach from 'lodash/forEach'; import { components as vizComponents } from '@tidepool/viz'; import * as actions from '../../redux/actions'; const { Loader } = vizComponents; const withPrescriptions = Component => props => { const { prescriptions, fetchers, fetchingPrescriptions } = props; React.useEffect(() => { if (!fetchers) { return } forEach(fetchers, fetcher => { fetcher(); }); }, []) return fetchingPrescriptions.inProgress ? <Loader /> : <Component prescriptions={prescriptions} {...props} />; }; /** * Expose "Smart" Component that is connect-ed to Redux */ export function getFetchers(dispatchProps, stateProps, api) { const fetchers = []; if (!stateProps.fetchingPrescriptions.inProgress && !stateProps.fetchingPrescriptions.completed) { fetchers.push(dispatchProps.fetchPrescriptions.bind(null, api)); } return fetchers; } export function mapStateToProps(state) { return { prescriptions: state.blip.prescriptions, fetchingPrescriptions: state.blip.working.fetchingPrescriptions, }; } let mapDispatchToProps = dispatch => bindActionCreators({ fetchPrescriptions: actions.async.fetchPrescriptions, }, dispatch); let mergeProps = (stateProps, dispatchProps, ownProps) => { var api = ownProps.routes[0].api; return assign( {}, stateProps, { fetchers: getFetchers(dispatchProps, stateProps, api), trackMetric: ownProps.routes[0].trackMetric } ); }; export default Component => connect(mapStateToProps, mapDispatchToProps, mergeProps)(withPrescriptions(Component));
JavaScript
0
@@ -177,16 +177,80 @@ rEach';%0A +import get from 'lodash/get';%0Aimport keyBy from 'lodash/keyBy';%0A import %7B @@ -450,23 +450,12 @@ st %7B - prescriptions, +%0A fet @@ -456,24 +456,28 @@ fetchers, +%0A fetchingPre @@ -486,16 +486,58 @@ riptions +,%0A prescriptions,%0A prescriptionId,%0A %7D = pro @@ -678,16 +678,89 @@ %7D, %5B%5D)%0A%0A + const prescription = get(keyBy(prescriptions, 'id'), prescriptionId);%0A%0A return @@ -786,41 +786,23 @@ ons. -inProgress%0A ? %3CLoader /%3E +completed %0A -: +? %3CCo @@ -843,18 +843,63 @@ ns%7D -%7B...props%7D +prescription=%7Bprescription%7D %7B...props%7D /%3E%0A : %3CLoader /%3E; @@ -1310,47 +1310,219 @@ -prescriptions: state.blip.prescriptions +creatingPrescription: state.blip.working.creatingPrescription,%0A creatingPrescriptionRevision: state.blip.working.creatingPrescriptionRevision,%0A deletingPrescription: state.blip.working.deletingPrescription ,%0A @@ -1588,16 +1588,61 @@ ptions,%0A + prescriptions: state.blip.prescriptions,%0A %7D;%0A%7D%0A%0A @@ -1699,16 +1699,200 @@ ators(%7B%0A + createPrescription: actions.async.createPrescription,%0A createPrescriptionRevision: actions.async.createPrescriptionRevision,%0A deletePrescription: actions.async.deletePrescription,%0A fetchP @@ -2097,16 +2097,260 @@ ,%0A %7B%0A + createPrescription: dispatchProps.createPrescription.bind(null, api),%0A createPrescriptionRevision: dispatchProps.createPrescriptionRevision.bind(null, api),%0A deletePrescription: dispatchProps.deletePrescription.bind(null, api),%0A fe @@ -2398,24 +2398,66 @@ rops, api),%0A + prescriptionId: ownProps.params.id,%0A trackM @@ -2493,16 +2493,17 @@ ckMetric +, %0A %7D%0A
43b5b361614f2105c9bf953764dacb02e15c4286
Remove unecessary modules
server/controllers/user.server.controller.js
server/controllers/user.server.controller.js
var User = require('../models/user.server.model'), jwt = require('jsonwebtoken'), bluebird = require('bluebird'), Q = require('q'), fs = bluebird.promisifyAll(require('fs')), multiparty = require('multiparty'), path = require('path'), uuid = require('node-uuid'), cloudinary = require('cloudinary'), gravatar = require('gravatar'), nodemailer = require('nodemailer'), _ = require('lodash'), secrets = require('../../config/secrets'), token = require('../../config/token'); module.exports = { /** * Welcome Notice * @param req * @param res * @return Void */ welcome: function(req, res){ return res.status(200).json({ message: 'Welcome to Yourtube Api'}); }, /** * Register User with Full Name, Email and password * @param req * @param res * @return Void */ registerUser: function(req, res) { User.findOne({ email: req.body.email }, '+password', function(err, existingUser) { if (existingUser) { return res.status(409).json({ message: 'Email is already taken' }); } // Obtain the avatar from gravatar service var secureImageUrl = gravatar.url(req.body.email, {s: '200', r: 'x', d: 'retro'}, true); var user = new User({ fullName: req.body.fullName, email: req.body.email, password: req.body.password, user_avatar: secureImageUrl }); user.save(function(err, result) { if (err) { res.status(500).json({ message: err.message }); } res.send({ token: token.createJWT(result) }); }); }); }, /** * Fetch Logged In User Details * @param req * @param res * @param next * @return Void */ getLoggedInUserDetail: function(req, res) { User.findById(req.user, function(err, user) { res.send(user); }); }, /** * Update Logged In User Details * @param req [description] * @param res [description] * @return {[type]} [description] */ updateLoggedInUserDetail: function(req, res) { User.findById(req.user, function(err, user) { if (!user) { return res.status(400).send({ message: 'User not found' }); } user.fullName = req.body.fullName || user.fullName; user.email = req.body.email || user.email; user.save(function(err) { res.status(200).send({ message: 'Profile Update Succesfully'}); }); }); }, /** * Update User Details * @param req * @param res * @param next * @return Void */ updateEachUserDetails: function(req, res, next){ var userId = req.params.user_id; var userDetails = req.body; User.update({_id: userId}, userDetails, function (err) { if(err) { return res.status(404).json({success: false, message: 'User Details Not Found', err: err}); } res.status(200).json({success: true, message: 'Update Successful'}); next(); }); }, /** * Delete A User * @param req * @param res * @param next * @return Void */ deleteEachUserDetails: function(req, res, next){ var userId = req.params.user_id; User.remove({_id: userId}, function (err, user) { if(err) { return res.status(404).json({success: false, message: 'User Details Not Found'}); } res.json({success: true, message: 'Delete Successful'}); next(); }); }, /** * Authenticate a User via Email and Password * @param req * @param res * @return json */ authenticate: function(req, res) { User.findOne({ email: req.body.email }, function(err, user) { if (!user) { return res.status(401).json({ message: 'Invalid Email' }); } user.comparePassword(req.body.password, function(err, isMatch) { if (!isMatch) { return res.status(401).json({ message: 'Invalid Password' }); } res.send({ token: token.createJWT(user) }); }); }); } };
JavaScript
0.000002
@@ -59,444 +59,80 @@ -jwt = require('jsonwebtoken'),%0A bluebird = require('bluebird'),%0A Q = require('q'),%0A fs = bluebird.promisifyAll(require('fs')),%0A multiparty = require('multiparty'),%0A path = require('path'),%0A uuid = require('node-uuid'),%0A cloudinary = require('cloudinary'),%0A gravatar = require('gravatar'),%0A nodemailer = require('nodemailer'),%0A _ = require('lodash +cloudinary = require('cloudinary'),%0A gravatar = require('gravatar '),%0A @@ -1639,30 +1639,16 @@ am req - %5Bdescription%5D %0A * @p @@ -1661,62 +1661,34 @@ res - %5Bdescription%5D%0A * @return %7B%5Btype%5D%7D %5Bdescription%5D +%0A * @return json %7C void %0A
ee26e7ade584e9d307355d181a5e560abd7bfa6e
use strict for Guidebox Spice.
share/spice/guidebox/getid/guidebox_getid.js
share/spice/guidebox/getid/guidebox_getid.js
function ddg_spice_guidebox_getid (api_result) { "use strict"; if (!api_result.results) return; var SKIP_ARRAY = ["online","tv","episode","episodes","free","guidebox","watch","full"], results = api_result.results.result, relevant; // Check which show is relevant to our query. $.each(results, function(key, result) { if (DDG.isRelevant(result.title, SKIP_ARRAY, 3) && !relevant) { relevant = result; } }); // Exit if we didn't find anything relevant. if (!relevant) { return; } // Prevent jQuery from appending "_={timestamp}" in our url. $.ajaxSetup({ cache: true }); var script = $('[src*="/js/spice/guidebox/getid/"]')[0], source = decodeURIComponent($(script).attr("src")), matched = source.match(/\/js\/spice\/guidebox\/getid\/([a-zA-Z0-9\s]+)/), query = matched[1]; var metadata = { res_title : relevant.title, network : relevant.network, more : relevant.url, query : query, }; ddg_spice_guidebox_getid.metadata = metadata; $.getScript("/js/spice/guidebox/lastshows/series/" + relevant.id); } function ddg_spice_guidebox_lastshows (api_result) { var metadata = ddg_spice_guidebox_getid.metadata; Spice.render({ data : api_result, header1 : metadata.res_title + " (TV - " + metadata.network + ")", source_name : "Guidebox", source_url : metadata.more, template_frame : "carousel", spice_name : "guidebox", template_options : { items : api_result.results.result, template_item : "guidebox_getid", template_detail : "guidebox_getid_details", li_width : 120, li_height : 105 } }); }; Handlebars.registerHelper("checkSeason", function(season_number, episode_number, options) { if(season_number !== "0") { return options.fn({ season_number: season_number, episode_number: episode_number }); } }); Handlebars.registerHelper("getQuery", function() { return ddg_spice_guidebox_getid.metadata.query; }); Handlebars.registerHelper("getTitle", function() { return ddg_spice_guidebox_getid.metadata.res_title; }); Handlebars.registerHelper("getDate", function(first_aired) { "use strict"; var aired = DDG.getDateFromString(first_aired), days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'], months = [ 'January','February','March','April','May','June','July','August','September','October','November','December']; return days[aired.getDay()] + ", " + months[aired.getMonth()] + " " + aired.getDate() + ", " + aired.getFullYear() }); Handlebars.registerHelper("pluralize", function(string, options) { if (options.hash && options.hash.singular && options.hash.plural){ var arr = string.split("|"); return arr.length > 1 ? options.hash.plural : options.hash.singular } return ""; }); Handlebars.registerHelper("split", function(string) { return string.replace(/^\||\|$/g, "").replace(/\|/g, ", "); }); Handlebars.registerHelper("creators", function(options) { if (this.writers.length || this.directors.length){ return options.fn(this) } return ""; }); Handlebars.registerHelper("get_network", function(options) { return ddg_spice_guidebox_getid.metadata.network; });
JavaScript
0
@@ -93,16 +93,24 @@ lts) + %7B%0A return; %0A%0A @@ -105,16 +105,22 @@ return; +%0A %7D %0A%0A va @@ -1260,16 +1260,34 @@ esult) %7B +%0A %22use strict%22; %0A%0A va @@ -2088,24 +2088,43 @@ options) %7B%0A + %22use strict%22;%0A%0A if(seaso @@ -2295,32 +2295,51 @@ %22, function() %7B%0A + %22use strict%22;%0A%0A return ddg_s @@ -2426,24 +2426,43 @@ unction() %7B%0A + %22use strict%22;%0A%0A return d @@ -3051,24 +3051,42 @@ options) %7B %0A + %22use strict%22;%0A %0A if @@ -3339,24 +3339,47 @@ (string) %7B %0A + %22use strict%22;%0A %0A return s @@ -3489,24 +3489,42 @@ (options) %7B%0A + %22use strict%22;%0A %0A if @@ -3621,32 +3621,32 @@ return %22%22;%0A%7D);%0A%0A - Handlebars.regis @@ -3692,16 +3692,35 @@ ns) %7B %0A + %22use strict%22;%0A%0A retu
982478364f93f3025ff3e0583d386a72aaadc103
Update cunmute.js
bot/commands/cunmute.js
bot/commands/cunmute.js
/** * This method should return the response directly to the channel * @param {*string array} params * @param {*message} message */ async function command(params, message) { let permissions = message.channel.permissionsFor(message.member); if (permissions.has("MANAGE_MESSAGES")) { if (message.mentions.users && message.mentions.users.first()) { await Promise.all(message.mentions.users .map(u => { let p = message.channel.permissionOverwrites.get(u.id); if(p) p.delete(); })) message.reply("Unmuted " + m.size + " users"); } else message.reply("No one to unmute"); } else message.reply("You aren't Worthy\nhttps://media.tenor.com/images/c472d1ee8c75a50f700bd028cc1b10b9/tenor.gif") } /** * description of the command */ const description = "unmutes a user"; /** * Define Exports */ module.exports = { execute: command, description: description };
JavaScript
0
@@ -641,16 +641,37 @@ ed %22 + m +essage.mentions.users .size +
69b34c1af47d3683e75be9832d8cb78f604673a0
change window onerror handling for more data and stackTrace
browser/Bootstrapper.js
browser/Bootstrapper.js
/** * __BrowserBundle.js template file * @reference builders/BootstrapperBuilder */ var Catberry = require('./node_modules/catbee/dist/browser/Catberry.js'); var BootstrapperBase = require('./node_modules/catbee/dist/lib/base/BootstrapperBase.js'); var ModuleApiProvider = require('./node_modules/catbee/dist/browser/providers/ModuleApiProvider'); var CookieWrapper = require('./node_modules/catbee/dist/browser/CookieWrapper'); var Logger = require('./node_modules/catbee/dist/browser/Logger.js'); var util = require('util'); /*eslint-disable */ var watchers = [ /**__watchers**/ ]; var components = [ /**__components**/ ]; var signals = [ /**__signals**/ ]; var routes = '__routes' || []; /*eslint-enable */ const DEBUG_DOCUMENT_UPDATED = 'Document updated (%d watcher(s) changed)'; const DEBUG_COMPONENT_BOUND = 'Component "%s" is bound'; const DEBUG_COMPONENT_UNBOUND = 'Component "%s" is unbound'; /** * Creates new instance of the browser Catberry's bootstrapper. * @constructor * @extends BootstrapperBase */ class Bootstrapper extends BootstrapperBase { constructor () { super(Catberry); this.create = this.create.bind(this); } /** * Configures Catberry's service locator. * @param {Object} configObject Application config object. * @param {ServiceLocator} locator Service locator to configure. */ configure (configObject, locator) { super.configure(configObject, locator); locator.register('moduleApiProvider', ModuleApiProvider, configObject, true); locator.register('cookieWrapper', CookieWrapper, configObject, true); locator.register('logger', Logger, configObject, true); locator.registerInstance('window', window); var logger = locator.resolve('logger'); var eventBus = locator.resolve('eventBus'); this._wrapEventsWithLogger(configObject, eventBus, logger); window.onerror = function errorHandler (msg, uri, line) { logger.fatal(uri + ':' + line + ' ' + msg); return true; }; routes.forEach(route => locator.registerInstance('routeDefinition', route)); watchers.forEach(watcher => locator.registerInstance('watcher', watcher)); signals.forEach(signal => locator.registerInstance('signal', signal)); components.forEach(component => locator.registerInstance('component', component)); } _wrapEventsWithLogger (config, eventBus, logger) { super._wrapEventsWithLogger(config, eventBus, logger); var isRelease = Boolean(config.isRelease); if (isRelease) { return; } eventBus .on('documentUpdated', args => { logger.debug(util.format(DEBUG_DOCUMENT_UPDATED, args.length)); }) .on('componentBound', args => { logger.debug(util.format( DEBUG_COMPONENT_BOUND, args.element.tagName + (args.id ? '#' + args.id : '') )); }) .on('componentUnbound', args => { logger.debug(util.format( DEBUG_COMPONENT_UNBOUND, args.element.tagName + (args.id ? '#' + args.id : '') )); }); } } module.exports = new Bootstrapper();
JavaScript
0
@@ -1857,133 +1857,49 @@ dow. -onerror = function errorHandler (msg, uri, line) %7B%0A logger.fatal(uri + ':' + line + ' ' + msg);%0A return true;%0A %7D +addEventListener('error', logger.onerror) ;%0A%0A
7dc168dbc5fe564794f20075ab2cca7358138092
remove yosay from react-frontend
generators/react-frontend/index.js
generators/react-frontend/index.js
'use strict'; const cp = require('child_process'); const path = require('path'); const camelCase = require('camelcase'); const chalk = require('chalk'); const Generator = require('yeoman-generator'); const yosay = require('yosay'); let username = ' '; try { username = cp.execSync('git config user.name').toString(); } catch (e) { /* istanbul ignore next */ console.error('Missing git configuration'); } module.exports = class extends Generator { prompting() { // Have Yeoman greet the user. this.log( yosay( `Behold the almighty ${chalk.red('generator-cheminfo')} generator!`, ), ); const prompts = [ { type: 'input', name: 'name', message: 'Your project name', default: path.basename(this.destinationRoot()), // Default to current folder name }, { type: 'input', name: 'org', message: 'GitHub organization', default: 'cheminfo', }, { type: 'input', name: 'userName', message: 'Your name', default: username.substring(0, username.length - 1), }, { type: 'input', name: 'description', message: 'Your package description', }, ]; return this.prompt(prompts).then( function (props) { // To access props later use this.props.name; this.props = props; }.bind(this), ); } writing() { const date = new Date(); const day = date.getDate(); const month = date.getMonth(); const year = date.getFullYear(); const camelName = camelCase(this.props.name); const prefix = this.props.org === 'mljs' ? 'ml-' : ''; const includes = { npmName: prefix + this.props.name, name: this.props.name, org: this.props.org, userName: this.props.userName, description: this.props.description, date: year + '-' + month + '-' + day, year: year, camelName: camelName, }; this.fs.copy( this.templatePath('gitignore'), this.destinationPath('.gitignore'), ); this.fs.copy( this.templatePath('prettierrc'), this.destinationPath('.prettierrc'), ); // tailwind related this.fs.copy( this.templatePath('postcss.config.js'), this.destinationPath('postcss.config.js'), ); this.fs.copy( this.templatePath('tailwind.js'), this.destinationPath('tailwind.js'), ); this.fs.copy( this.templatePath('tailwind.config.js'), this.destinationPath('tailwind.config.js'), ); // public this.fs.copy( this.templatePath('public/index.html'), this.destinationPath('public/index.html'), ); this.fs.copy( this.templatePath('public/favicon.ico'), this.destinationPath('public/favicon.ico'), ); this.fs.copy( this.templatePath('public/logo192.png'), this.destinationPath('public/logo192.png'), ); this.fs.copy( this.templatePath('public/logo512.png'), this.destinationPath('public/logo512.png'), ); this.fs.copy( this.templatePath('public/manifest.json'), this.destinationPath('public/manifest.json'), ); this.fs.copy( this.templatePath('public/robots.txt'), this.destinationPath('public/robots.txt'), ); // src this.fs.copy( this.templatePath('src/index.js'), this.destinationPath('src/index.js'), ); this.fs.copy( this.templatePath('src/App.js'), this.destinationPath('src/App.js'), ); this.fs.copy( this.templatePath('src/App.test.js'), this.destinationPath('src/__tests__/App.test.js'), ); this.fs.copy( this.templatePath('src/assets/tailwind.css'), this.destinationPath('src/assets/tailwind.css'), ); this.fs.copyTpl( this.templatePath('LICENSE'), this.destinationPath('LICENSE'), includes, ); this.fs.copyTpl( this.templatePath('README.md'), this.destinationPath('README.md'), includes, ); this.fs.copyTpl( this.templatePath('package'), this.destinationPath('package.json'), includes, ); } install() { let deps = [ // dependencies '@testing-library/jest-dom', '@testing-library/react', '@testing-library/user-event', 'react', 'react-dom', 'react-scripts', // dev dependencies 'autoprefixer', 'eslint', 'eslint-config-cheminfo-react', 'eslint-plugin-import', 'eslint-plugin-jest', 'eslint-plugin-prettier', 'eslint-plugin-react', 'eslint-plugin-react-hooks', 'postcss-cli', 'prettier', 'prop-types', 'tailwindcss', ]; this.npmInstall(deps, { 'save-dev': true }); } };
JavaScript
0.000014
@@ -120,40 +120,8 @@ ');%0A -const chalk = require('chalk');%0A cons @@ -166,40 +166,8 @@ r'); -%0Aconst yosay = require('yosay'); %0A%0Ale @@ -387,16 +387,16 @@ rator %7B%0A + prompt @@ -407,164 +407,8 @@ ) %7B%0A - // Have Yeoman greet the user.%0A this.log(%0A yosay(%0A %60Behold the almighty $%7Bchalk.red('generator-cheminfo')%7D generator!%60,%0A ),%0A );%0A%0A
5a9a844235876d5e4d0624ee13a123f98abafd1a
update webpack config to work with `webapp-webpack-plugin`
gh-pages-src/config/webpack.dev.js
gh-pages-src/config/webpack.dev.js
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const ExtractCssChunks = require('extract-css-chunks-webpack-plugin') module.exports = { entry: [ './src/index.js' ], mode: "development", devtool: 'source-map', output: { filename: "app.bundle.js", // `resolve` will construct an absolute path path: path.resolve(__dirname, "../dist"), }, devServer: { overlay: true, // print errors in browser host: '0.0.0.0', useLocalIp: true }, module: { rules: [ { test: /\.css$/, use: [ ExtractCssChunks.loader, 'css-loader' ] }, { test: /\.(jpe?g|gif|png|bmp|svg)$/, use: [ { // NOTE file-loader can also be used to work with the below font types as well // woff,woff2,eot,ttf,otf loader: "file-loader", options: { name: "images/[name].[ext]" } } ] } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }), new ExtractCssChunks({ filename: '[name].css', chunkFilename: '[id].css', hot: true, orderWarning: true, reloadAll: true, cssModules: true }) ] }
JavaScript
0
@@ -1101,16 +1101,377 @@ %7D),%0A + new WebappWebpackPlugin(%7B%0A logo: './src/images/logo.svg',%0A cache: true,%0A prefix: 'assets/',%0A inject: true,%0A favicons: %7B%0A appName: 'KegCop',%0A appDescription: null,%0A developerName: '@ipatch',%0A developerURL: null,%0A icons: %7B%0A coast: false,%0A yandex: false,%0A %7D%0A %7D,%0A %7D),%0A new
48287ae8563bf4dd96a77c6f66211cdcdd8790af
Set error compoent to display as analytics.
assets/js/modules/adsense/components/dashboard/DashboardTopEarningPagesWidget.js
assets/js/modules/adsense/components/dashboard/DashboardTopEarningPagesWidget.js
/** * DashboardTopEarningPagesWidget component. * * Site Kit by Google, 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. */ /** * WordPress dependencies */ import { __, _x } from '@wordpress/i18n'; import { compose } from '@wordpress/compose'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { STORE_NAME as ANALYTICS_STORE } from '../../../analytics/datastore/constants'; import { STORE_NAME as CORE_USER } from '../../../../googlesitekit/datastore/user/constants'; import whenActive from '../../../../util/when-active'; import PreviewTable from '../../../../components/preview-table'; import { getDataTableFromData, TableOverflowContainer } from '../../../../components/data-table'; import Layout from '../../../../components/layout/layout'; import AdSenseLinkCTA from '../../../analytics/components/common/AdSenseLinkCTA'; import getDataErrorComponent from '../../../../components/notifications/data-error'; import getNoDataComponent from '../../../../components/notifications/nodata'; const { useSelect } = Data; function DashboardTopEarningPagesWidget() { const { isAdSenseLinked, data, error, loading, } = useSelect( ( select ) => { const store = select( ANALYTICS_STORE ); const args = { dateRange: select( CORE_USER ).getDateRange(), dimensions: [ 'ga:pageTitle', 'ga:pagePath' ], metrics: [ { expression: 'ga:adsenseRevenue', alias: 'Earnings' }, { expression: 'ga:adsenseECPM', alias: 'Page RPM' }, { expression: 'ga:adsensePageImpressions', alias: 'Impressions' }, ], orderby: { fieldName: 'ga:adsenseRevenue', sortOrder: 'DESCENDING', }, limit: 10, }; return { isAdSenseLinked: store.getAdsenseLinked(), data: store.getReport( args ), error: store.getErrorForSelector( 'getReport', [ args ] ), loading: store.isResolving( 'getReport', [ args ] ), }; } ); if ( loading ) { return ( <PreviewTable rows={ 5 } padding /> ); } if ( error ) { return getDataErrorComponent( 'adsense', error.message, false, false, false, error ); } if ( ! isAdSenseLinked ) { return <AdSenseLinkCTA />; } if ( ! data || ! data.length || ! data[ 0 ]?.data?.rows ) { return getNoDataComponent( _x( 'Analytics', 'Service name', 'google-site-kit' ) ); } const headers = [ { title: __( 'Top Earning Pages', 'google-site-kit' ), tooltip: __( 'Top Earning Pages', 'google-site-kit' ), primary: true, }, { title: __( 'Revenue', 'google-site-kit' ), tooltip: __( 'Revenue', 'google-site-kit' ), }, ]; const links = []; const dataMapped = data[ 0 ].data.rows.map( ( row, i ) => { links[ i ] = row.dimensions[ 1 ]; return [ row.dimensions[ 0 ], Number( row.metrics[ 0 ].values[ 0 ] ).toFixed( 2 ), ]; } ); const options = { hideHeader: false, chartsEnabled: false, cap: 5, links, }; const dataTable = getDataTableFromData( dataMapped, headers, options ); return ( <Layout className="googlesitekit-top-earnings-pages" footer footerCtaLabel={ _x( 'Analytics', 'Service name', 'google-site-kit' ) } footerCtaLink="http://analytics.google.com" fill > <TableOverflowContainer> { dataTable } </TableOverflowContainer> </Layout> ); } export default compose( whenActive( { moduleName: 'adsense' } ), whenActive( { moduleName: 'analytics' } ), )( DashboardTopEarningPagesWidget );
JavaScript
0
@@ -2540,22 +2540,24 @@ nent( 'a -dsense +nalytics ', error
f193599bfbb3e15235ce9e33d17eb0c82ad18807
Add toLowerCase for backwards compability
client/app/dashboard/requests/detail/pre_evaluation/pre_evaluation.controller.js
client/app/dashboard/requests/detail/pre_evaluation/pre_evaluation.controller.js
'use strict'; angular.module('impactApp') .filter('age', function() { function calculAge(dateNaiss) { var ageDiff = Date.now() - Date.parse(dateNaiss); var ageDate = new Date(ageDiff); return Math.abs(ageDate.getUTCFullYear() - 1970); } return function(dateNaiss) { return calculAge(dateNaiss); }; }) .controller('RequestPreEvaluationCtrl', function($scope, $http, $window, $cookies, currentUser, currentMdph, request, DocumentsService, NotificationService, prestations, prestationsQuitus) { $scope.token = $cookies.get('token'); $scope.toutesPrestations = prestations; $scope.prestationsQuitus = prestationsQuitus; $scope.currentMdph = currentMdph; $scope.currentUser = currentUser; var prestationsById = _.indexBy(prestations, 'id'); $scope.documentsObligatoires = DocumentsService.filterMandatory(request.documents); $scope.documentsComplementaires = DocumentsService.filterNonMandatory(request.documents); $scope.resendMail = function() { $http.get('api/requests/' + request.shortId + '/resend-mail').then(function() { $window.alert('Mail renvoyé avec succès'); }); }; $scope.getTitle = function(prestationId) { return prestationsById[prestationId].title; }; $scope.isSelected = function(prestation) { return request.prestations.indexOf(prestation.label) < 0; }; $scope.removePrestation = function(index) { request.prestations.splice(index, 1); request.$update(); }; $scope.addPrestation = function(prestation) { request.prestations.push(prestation.label); request.$update(); }; });
JavaScript
0.000471
@@ -1221,24 +1221,89 @@ tationId) %7B%0A + if (!prestationId) %7B%0A return prestationId;%0A %7D%0A%0A return @@ -1331,16 +1331,30 @@ tationId +.toLowerCase() %5D.title;
4f8aa2243b4b13958ac7e3847323d507674abbe7
add functions stub on module for updating the active connection. return error if settings file json cannot be parsed
connection.js
connection.js
const fs = require('fs'); const settings = fs.readFileSync('sqade-settings.json'); /** * ADD YOUR CONNECTIONS TO sqade-settings.json * SEE https://github.com/TDress/sql-aide * * Parse connections from sqade-settings.json * Below is some documentation on how to set * configuration settings for your database connections * in that file. * TO DO: clean up the example below and add * another one for a different database management system * * Connection object properties are validated for correct form * and type on every run from the command line in order to * catch typos and other simple mistakes. * Additionally, you can set the `verifyOnValidate` key to * true to run a trivial test query against the database * to ensure that the connection is working. * Note that this verification is only performed for the * currently active database, and will be run on every command. * * connection keys: * type {string} The type of SQL database management system. * Case insensitive. * Valid types: `mysql`, `mssql`. * host {string} The host of the database server. * port {integer} The port number of the database server. * database {string} The name of the database to connect to. * login {string} The login string to authenticate with. * password: {string} The password to use for authentication. * verifyOnValidate {Boolean} True to run a basic connection * health check on each command. This is NOT a health * check of the database in any way -- only a * verification that the connection to the database * engine is good. * * E.G. * myDb: { * type: mssql * host: localhost, * port: 400, * database: db1, * login: username, * password: weakPassword, * verifyOnValidate: true * } */ const connections = settings.connections; module.exports = { configMap: new Map(Object.entries(configuration)), }
JavaScript
0.000001
@@ -29,55 +29,30 @@ nst -settings = fs.readFileSync('sqade-settings.json +colog = require('colog ');%0A @@ -1800,72 +1800,651 @@ */%0A -const connections = settings.connections;%0A%0Amodule.exports = %7B %0A%09 +%0A// TO DO: create an error utility for these exceptions%0Atry %7B%0A%09const settings = fs.readFileSync('sqade-settings.json');%0A%7D catch (e) %7B%0A%09if (e.code === 'ENOENT') %7B %0A%09%09// TO DO: Add a reminder in the message about copying %0A%09%09// default settings file.%0A%09%09colog.error('Unable to read sqade-settings.json file');%0A%09%09process.exit();%0A%09%7D else %7B %0A%09%09throw e;%0A%09%7D%0A%7D%0Aconst connections = settings.connections;%0A// Run configuration settings through some validations.%0A// To Do: get errors with line numbers from parsing json %0Aif (!connections) %7B %0A%09colog.error(%60Unable to parse sqade-settings.json file. %0A%09%09Make sure it is valid json%60);%0A%09process.exit();%0A%7D%0Aconst conf @@ -2448,17 +2448,18 @@ onfigMap -: + = new Map @@ -2481,21 +2481,285 @@ (con -figuration)),%0A +nections));%0A// To Do: iterate over config and check that we have%0A// everything we need for each connection. %0A%0Amodule.exports = %7B %0A%09configMap,%0A%09active: connections.activeDB,%0A%09updateActive: function(name) =%3E %7B %0A%09%09this.active = name;%0A%09%09// TO DO: update the actual settings file%0A%09%7D %0A%7D%0A
39c573816607b6df809aa070c54fcec56181cc79
Return the send promise
analytics.js
analytics.js
import { Platform, Dimensions } from 'react-native'; import { Constants } from 'expo'; import { ScreenHit, PageHit, Event, Serializable } from './hits'; const { width, height } = Dimensions.get('window'); let defaultOptions = { debug: false }; export default class Analytics { customDimensions = [] constructor(propertyId, additionalParameters = {}, options = defaultOptions){ this.propertyId = propertyId; this.options = options; this.clientId = Constants.deviceId; this.options = options; this.promiseGetWebViewUserAgentAsync = Constants.getWebViewUserAgentAsync() .then(userAgent => { this.userAgent = userAgent; this.parameters = { an: Constants.manifest.name, aid: Constants.manifest.slug, av: Constants.manifest.version, sr: `${width}x${height}`, ...additionalParameters }; if(this.options.debug){ console.log(`[expo-analytics] UserAgent=${userAgent}`); console.log(`[expo-analytics] Additional parameters=`, this.parameters); } }); } hit(hit){ // send only after the user agent is saved return this.promiseGetWebViewUserAgentAsync .then(() => { this.send(hit); }); } event(event){ // send only after the user agent is saved return this.promiseGetWebViewUserAgentAsync .then(() => { this.send(event); }); } addCustomDimension(index, value){ this.customDimensions[index] = value; } removeCustomDimension(index){ delete this.customDimensions[index]; } send(hit) { /* format: https://www.google-analytics.com/collect? + * &tid= GA property ID (required) * &v= GA protocol version (always 1) (required) * &t= hit type (pageview / screenview) * &dp= page name (if hit type is pageview) * &cd= screen name (if hit type is screenview) * &cid= anonymous client ID (optional if uid is given) * &uid= user id (optional if cid is given) * &ua= user agent override * &an= app name (required for any of the other app parameters to work) * &aid= app id * &av= app version * &sr= screen resolution * &cd{n}= custom dimensions * &z= cache buster (prevent browsers from caching GET requests -- should always be last) */ const customDimensions = this.customDimensions.map((value, index) => `cd${index}=${value}`).join('&'); const params = new Serializable(this.parameters).toQueryString(); const url = `https://www.google-analytics.com/collect?tid=${this.propertyId}&v=1&cid=${this.clientId}&${hit.toQueryString()}&${params}&${customDimensions}&z=${Math.round(Math.random() * 1e8)}`; let options = { method: 'get', headers: { 'User-Agent': this.userAgent } } if(this.options.debug){ console.log(`[expo-analytics] Sending GET request to ${url}`); } return fetch(url, options); } }
JavaScript
0.999792
@@ -1386,55 +1386,22 @@ =%3E -%7B%0A this.send(hit);%0A %7D +this.send(hit) );%0A @@ -1550,34 +1550,16 @@ en(() =%3E - %7B%0A this.se @@ -1571,23 +1571,8 @@ ent) -;%0A %7D );%0A
feaaa7830fe994f4a2ce4bddaaddd099660934e4
Make JS more compatibly with ancient jQuery versions (as used in e.g. Django 1.4).
geoposition/static/geoposition/geoposition.js
geoposition/static/geoposition/geoposition.js
if (jQuery != undefined) { var django = { 'jQuery': jQuery, } } (function($) { $(document).ready(function() { try { var _ = google; } catch (ReferenceError) { console.log('geoposition: "google" not defined. You might not be connected to the internet.'); return; } var mapDefaults = { 'mapTypeId': google.maps.MapTypeId.ROADMAP, 'scrollwheel': false, 'streetViewControl': false, 'panControl': false }; var markerDefaults = { 'draggable': true, 'animation': google.maps.Animation.DROP }; $('.geoposition-widget').each(function() { var $container = $(this), $mapContainer = $('<div class="geoposition-map" />'), $addressRow = $('<div class="geoposition-address" />'), $searchRow = $('<div class="geoposition-search" />'), $searchInput = $('<input>', {'type': 'search', 'placeholder': 'Start typing an address …'}), $latitudeField = $container.find('input.geoposition:eq(0)'), $longitudeField = $container.find('input.geoposition:eq(1)'), latitude = parseFloat($latitudeField.val()) || null, longitude = parseFloat($longitudeField.val()) || null, map, mapLatLng, mapOptions, mapCustomOptions, markerOptions, markerCustomOptions, marker; $mapContainer.css('height', $container.data('map-widget-height') + 'px'); mapCustomOptions = $container.data('map-options') || {}; markerCustomOptions = $container.data('marker-options') || {}; function doSearch() { var gc = new google.maps.Geocoder(); $searchInput.parent().find('ul.geoposition-results').remove(); gc.geocode({ 'address': $searchInput.val() }, function(results, status) { if (status == 'OK') { var updatePosition = function(result) { if (result.geometry.bounds) { map.fitBounds(result.geometry.bounds); } else { map.panTo(result.geometry.location); map.setZoom(18); } marker.setPosition(result.geometry.location); google.maps.event.trigger(marker, 'dragend'); }; if (results.length == 1) { updatePosition(results[0]); } else { var $ul = $('<ul />', {'class': 'geoposition-results'}); $.each(results, function(i, result) { var $li = $('<li />'); $li.text(result.formatted_address); $li.on('click', function() { updatePosition(result); $li.closest('ul').remove(); }); $li.appendTo($ul); }); $searchInput.after($ul); } } }); } function doGeocode() { var gc = new google.maps.Geocoder(); gc.geocode({ 'latLng': marker.position }, function(results, status) { $addressRow.text(''); if (results && results[0]) { $addressRow.text(results[0].formatted_address); } }); } var autoSuggestTimer = null; $searchInput.on('keydown', function(e) { if (autoSuggestTimer) { clearTimeout(autoSuggestTimer); autoSuggestTimer = null; } // if enter, search immediately if (e.keyCode == 13) { e.preventDefault(); doSearch(); } else { // otherwise, search after a while after typing ends autoSuggestTimer = setTimeout(function(){ doSearch(); }, 1000); } }).on('abort', function() { $(this).parent().find('ul.geoposition-results').remove(); }); $searchInput.appendTo($searchRow); $container.append($searchRow, $mapContainer, $addressRow); mapLatLng = new google.maps.LatLng(latitude, longitude); mapOptions = $.extend({}, mapDefaults, mapCustomOptions); if (!(latitude === null && longitude === null && mapOptions['center'])) { mapOptions['center'] = mapLatLng; } if (!mapOptions['zoom']) { mapOptions['zoom'] = latitude && longitude ? 15 : 1; } map = new google.maps.Map($mapContainer.get(0), mapOptions); markerOptions = $.extend({}, markerDefaults, markerCustomOptions, { 'map': map }); if (!(latitude === null && longitude === null && markerOptions['position'])) { markerOptions['position'] = mapLatLng; } marker = new google.maps.Marker(markerOptions); google.maps.event.addListener(marker, 'dragend', function() { $latitudeField.val(this.position.lat()); $longitudeField.val(this.position.lng()); doGeocode(); }); if ($latitudeField.val() && $longitudeField.val()) { google.maps.event.trigger(marker, 'dragend'); } $latitudeField.add($longitudeField).on('keyup', function(e) { var latitude = parseFloat($latitudeField.val()) || 0; var longitude = parseFloat($longitudeField.val()) || 0; var center = new google.maps.LatLng(latitude, longitude); map.setCenter(center); map.setZoom(15); marker.setPosition(center); doGeocode(); }); }); }); })(django.jQuery);
JavaScript
0
@@ -1626,30 +1626,35 @@ $container. +attr(' data -(' +- map-widget-h @@ -1693,32 +1693,43 @@ CustomOptions = +JSON.parse( $container.data( @@ -1723,22 +1723,27 @@ ntainer. +attr(' data -(' +- map-opti @@ -1747,22 +1747,17 @@ ptions') - %7C%7C %7B%7D +) ;%0A @@ -1784,16 +1784,27 @@ tions = +JSON.parse( $contain @@ -1810,14 +1810,19 @@ ner. +attr(' data -(' +- mark @@ -1837,14 +1837,9 @@ ns') - %7C%7C %7B%7D +) ;%0A%0A @@ -3174,18 +3174,20 @@ $li. -on +bind ('click' @@ -4076,18 +4076,20 @@ chInput. -on +bind ('keydow @@ -4696,18 +4696,20 @@ %7D). -on +bind ('abort' @@ -6189,18 +6189,20 @@ eField). -on +bind ('keyup'
541f254474ec5edb6722dcf0f7360edf0854e2c1
sam 1
api/index.js
api/index.js
'use strict'; var moment = require('moment'); exports.handler = (event, context, callback) => { var originURL = process.env.ORIGIN_URL || '*'; emitLambdaAge(); // This variable can be updated and checked in to your repository // to update the number of SAM squirrels on the screen. var samCount = 2; // Or you can update your Lambda function's environment variable. var samMultiplier = process.env.SAM_MULTIPLIER || 1; var totalSAMs = samCount * samMultiplier; console.log('The number of SAMs to show: ' + samCount); console.log('Multiplier to apply to SAMs: ' + samMultiplier); console.log('Total number of SAMs to show: ' + totalSAMs); callback(null, { "statusCode": 200, "body": totalSAMs, "headers": { "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token", "Access-Control-Allow-Methods": "GET,OPTIONS", "Access-Control-Allow-Origin": originURL } }); } function emitLambdaAge() { var now = moment(); var lambdaAnnouncement = moment('2014-11-04'); var daysOld = now.diff(lambdaAnnouncement, 'days'); console.log('Lambda is ' + daysOld + ' days old!'); }
JavaScript
0.999291
@@ -314,17 +314,17 @@ Count = -2 +1 ;%0A%0A /
1d41e6f2339ba7cde734b571072ee47441b8eabe
fix server side rendering
src/animateKeyframes.js
src/animateKeyframes.js
// @flow import React from 'react'; import createTag from './style/createTag'; import createRandomName from './utils/createRandomName'; import { AnimateContext } from './animateGroup'; import type { AnimationStateType } from './animate'; export type Keyframes = Array<Object>; type Props = { keyframes: Keyframes, easeType?: string, durationSeconds?: number, render?: (?Object) => any, play: boolean, playState?: string, delaySeconds?: number, direction?: string, fillMode?: string, iterationCount?: string | number, animationStates: AnimationStateType, children?: any, register?: any => void, sequenceId?: string, sequenceIndex?: number, }; type State = { play: boolean, }; export class AnimateKeyframesChild extends React.PureComponent<Props, State> { static defaultProps = { durationSeconds: 0.3, delaySeconds: 0, easeType: 'linear', render: undefined, playState: 'running', direction: 'normal', fillMode: 'none', iterationCount: 1, children: undefined, sequenceId: undefined, sequenceIndex: undefined, register: undefined, }; constructor(props: Props) { super(props); const { register, keyframes } = this.props; this.animationName = createRandomName(); const { styleTag, index } = createTag({ animationName: this.animationName, keyframes }); register && register(this.props); this.styleTag = styleTag; this.index = index; } state = { play: false, }; static getDerivedStateFromProps(nextProps: Props, prevState: State) { const { animationStates, play, sequenceId, sequenceIndex } = nextProps; const id = sequenceId || sequenceIndex; let currentPlay = play; if (id !== undefined && animationStates && animationStates[id]) { const state = animationStates[id]; currentPlay = state.play; } return { ...(currentPlay !== prevState.play ? { play: currentPlay } : null), }; } componentWillUnmount() { this.styleTag.sheet.deleteRule(this.index); } animationName: string; index: number; styleTag: any; render() { const { children, play, render, durationSeconds = 0.3, delaySeconds = 0, easeType = 'linear', playState = 'running', direction = 'normal', fillMode = 'none', iterationCount = 1, } = this.props; const style = play || this.state.play ? { animation: `${durationSeconds}s ${easeType} ${delaySeconds}s ${iterationCount} ${direction} ${fillMode} ${playState} ${ this.animationName }`, } : null; return render ? render(style) : <div {...(style ? { style } : null)}>{children}</div>; } } // $FlowIgnoreLine: flow complain about React.forwardRef disable for now export default React.forwardRef((props: Props, ref) => ( <AnimateContext.Consumer> {({ animationStates = {}, register = undefined }) => ( <AnimateKeyframesChild {...{ ...props, animationStates, register }} forwardedRef={ref} /> )} </AnimateContext.Consumer> ));
JavaScript
0.000001
@@ -1205,24 +1205,106 @@ this.props;%0A + register && register(this.props);%0A%0A if (typeof window !== 'undefined') %7B%0A this.ani @@ -1336,16 +1336,18 @@ Name();%0A + cons @@ -1438,45 +1438,8 @@ %0A%0A - register && register(this.props);%0A%0A @@ -1464,24 +1464,26 @@ yleTag;%0A + this.index = @@ -1490,16 +1490,22 @@ index;%0A + %7D%0A %7D%0A%0A s @@ -2440,16 +2440,22 @@ style = +%0A play %7C%7C @@ -2481,12 +2481,16 @@ + ? %7B%0A + @@ -2623,24 +2623,26 @@ + this.animati @@ -2658,16 +2658,18 @@ + %7D%60,%0A @@ -2672,18 +2672,22 @@ -%7D%0A + %7D%0A :
6a14a8296a7b69e764463d4019a73d0e46c09319
update cluster distance
arches/app/media/js/map/resource-layer-model.js
arches/app/media/js/map/resource-layer-model.js
define([ 'jquery', 'openlayers', 'underscore', 'arches', 'map/layer-model' ], function($, ol, _, arches, LayerModel) { var hexToRgb = function (hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; }; return function(config, featureCallback) { config = _.extend({ entitytypeid: 'all', vectorColor: '#808080' }, config); var layer = function () { var rgb = hexToRgb(config.vectorColor); var iconUnicode = '\uf060'; var zIndex = 0; var style = function(feature, resolution) { var mouseOver = feature.get('mouseover'); var iconSize = mouseOver ? 38 : 32; var styles = [new ol.style.Style({ text: new ol.style.Text({ text: iconUnicode, font: 'normal ' + iconSize + 'px octicons', offsetX: 5, offsetY: ((iconSize/2)*-1)-5, fill: new ol.style.Fill({ color: 'rgba(126,126,126,0.3)', }) }), zIndex: mouseOver ? zIndex*1000000000: zIndex }), new ol.style.Style({ text: new ol.style.Text({ text: iconUnicode, font: 'normal ' + iconSize + 'px octicons', offsetY: (iconSize/2)*-1, stroke: new ol.style.Stroke({ // color: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',1)', color: 'white', width: 3 }), fill: new ol.style.Fill({ color: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',0.9)', }) }), zIndex: mouseOver ? zIndex*2000000000 : zIndex+1 })]; zIndex += 2; feature.set('arches_marker', true); return styles; }; var source = new ol.source.GeoJSON({ projection: 'EPSG:3857', url: arches.urls.map_markers + config.entitytypeid }); $('.map-loading').show(); var loadListener = source.on('change', function(e) { if (source.getState() == 'ready') { featureCallback(source.getFeatures()); ol.Observable.unByKey(loadListener); $('.map-loading').hide(); } }); var vectorLayer = new ol.layer.Vector({ maxResolution: arches.mapDefaults.cluster_min, source: source, style: style }); var clusterSource = new ol.source.Cluster({ distance: 40, source: source }); var styleCache = {}; var clusterStyle = function(feature, resolution) { var size = feature.get('features').length; var mouseOver = feature.get('mouseover'); var radius = mouseOver ? 12 : 10; if (size === 1) { return style(feature, resolution); } if (size > 200) { radius = mouseOver ? 20 : 18; } else if (size > 150) { radius = mouseOver ? 18 : 16; } else if (size > 100) { radius = mouseOver ? 16 : 14; } else if (size > 50) { radius = mouseOver ? 14 : 12; } feature.set('arches_cluster', true); return [new ol.style.Style({ image: new ol.style.Circle({ radius: radius, stroke: new ol.style.Stroke({ color: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',0.4)', width: radius }), fill: new ol.style.Fill({ color: 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',0.8)', }) }), text: new ol.style.Text({ text: size.toString(), fill: new ol.style.Fill({ color: '#fff' }) }) })]; }; var clusterLayer = new ol.layer.Vector({ minResolution: arches.mapDefaults.cluster_min, source: clusterSource, style: clusterStyle }); return new ol.layer.Group({ layers: [ vectorLayer, clusterLayer ] }); }; return new LayerModel(_.extend({ layer: layer, onMap: true }, config) ); }; });
JavaScript
0
@@ -3140,17 +3140,17 @@ stance: -4 +5 0,%0A
c1a362f1ce3f7d827b80c1fe68510e32ae750a47
Update for 전자신문 (Fix #283)
src/impl/전자신문.js
src/impl/전자신문.js
import $ from 'jquery'; import { clearStyles } from '../util'; export default function () { let jews = {}; jews.title = $('.hgroup h1').text() || undefined; jews.subtitle = $('.hgroup h3').text(); jews.content = (function () { var content = $('.article_body')[0].cloneNode(true); $('#openLine, .art_reporter, .article_ad, .sns_area2, *[src^="http://adv"]', content).remove(); $('.daum_ddn_area, [id^=beacon]', content).remove(); $('.a_ict_word', content).each(function (i, el) { $(el).replaceWith($('.ict_word', el).text()); }); return clearStyles(content).innerHTML; })(); jews.timestamp = { created: new Date(($('.a_date').text().match(/\d+\.\d+\.\d+/)||[""])[0].replace(/\./g, '/')), modefied: undefined }; jews.reporters = [{ name: $('.art_reporter strong').text(), mail: $('.art_reporter .mail').text() }]; jews.cleanup = function () { $('#scrollDiv').remove(); }; return jews; }
JavaScript
0
@@ -130,17 +130,21 @@ $('. -hgroup h1 +article_title ').t @@ -187,30 +187,17 @@ e = -$('.hgroup h3').text() +undefined ;%0A @@ -304,57 +304,76 @@ $(' -#openLine, .art_reporter, .article_ad, .sns_area2 +.ad, .footer_btnwrap, img%5Bsrc%5E=%22http://img.etnews.com/2017/banner/%22%5D , *%5B @@ -711,15 +711,12 @@ ate( -( $('. -a_ date @@ -729,40 +729,29 @@ t(). -match(/%5Cd+%5C.%5Cd+%5C.%5Cd+/)%7C%7C%5B%22%22%5D)%5B0%5D +replace('%EB%B0%9C%ED%96%89%EC%9D%BC : ', '') .rep @@ -830,109 +830,8 @@ = %5B -%7B%0A name: $('.art_reporter strong').text(),%0A mail: $('.art_reporter .mail').text()%0A %7D %5D;%0A
392f2bfb6973d09a5037f8ff2172e3ece00cc46a
Update test.express.js
test/test.express.js
test/test.express.js
/** * Copyright 2015 IBM Corp. 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; var app = require('../app'); var request = require('supertest'); describe('POST /api/message', function() { it('Generate Error when no content passed', function(done) { request(app).post('/api/message').expect(500, done); }); // it('Generate 200 when passing in context', function(done) { // request(app).post('/api/message').send('{"context":{}, "input":{"text": "Hi"}}').expect(200, done); // }); });
JavaScript
0.000008
@@ -1044,8 +1044,9 @@ %7D);%0A%7D); +%0A
c8df59b6b1192e892b6bf0683906ae917c9d8438
Resolve JSHint error on deploy.js blueprint
blueprints/deploy-config/files/config/deploy.js
blueprints/deploy-config/files/config/deploy.js
module.exports = { //development: { //store: { //type: 'redis', // the default store is 'redis' //host: 'localhost', //port: 6379 //}, //assets: { //type: 's3', // default asset-adapter is 's3' //gzip: false, // if undefined or set to true, files are gziped //gzipExtensions: ['js', 'css', 'svg'], // if undefined, js, css & svg files are gziped //accessKeyId: '<your-access-key-goes-here>', //secretAccessKey: process.env['AWS_ACCESS_KEY'], //bucket: '<your-bucket-name>' //} //}, //staging: { //buildEnv: 'staging', // Override the environment passed to the ember asset build. Defaults to 'production' //store: { //host: 'staging-redis.example.com', //port: 6379 //}, //assets: { //accessKeyId: '<your-access-key-goes-here>', //secretAccessKey: process.env['AWS_ACCESS_KEY'], //bucket: '<your-bucket-name>' //} //}, //production: { //store: { //host: 'production-redis.example.com', //port: 6379, //password: '<your-redis-secret>' //}, //assets: { //accessKeyId: '<your-access-key-goes-here>', //secretAccessKey: process.env['AWS_ACCESS_KEY'], //bucket: '<your-bucket-name>' //} //} }
JavaScript
0
@@ -1,8 +1,33 @@ +/* jshint node: true */%0A%0A module.e
47f62308b4b2e1cb182d5f2600e8ac8d2adf3fc9
Implement nodemailer contact route
02-Express/express-website/routes/contact.js
02-Express/express-website/routes/contact.js
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('contact', { title: 'Contact' }); }); router.post(); module.exports = router;
JavaScript
0
@@ -57,16 +57,56 @@ outer(); +%0Avar nodemailer = require('nodemailer'); %0A%0A/* GET @@ -219,20 +219,910 @@ );%0A%0A -router.post( +// For posting contacting email%0Arouter.post('/send', function(req, res, next) %7B%0A%09var transporter = nodemailer.createTransport(%7B%0A%09%09service: %09'Gmail',%0A%09%09auth: %7B%0A%09%09%09user: 'account@gmail.com',%0A%09%09%09pass: 'account-password' %0A%09%09%7D%0A%09%7D);%0A%0A%09var mailOptions = %7B%0A%09%09from: %09 'john@outlook.com',%0A%09%09to: %09 'account@gmail.com',%0A%09%09subject: 'Website Submission',%0A%09%09text: %09 'You have a new submission with the details of name: ' +req.body.name+ %0A%09%09%09%09 'email: ' +req.body.email+ ' Message: ' +req.body.message,%0A%09%09html: %09 '%3Cp%3EYou have a new submission with the following details%3C/p%3E %3Cul%3E%3Cli%3EName: ' +req.body.name+ %0A%09%09%09%09 '%3C/li%3E%3Cli%3Eemail: ' +req.body.email+ '%3C/li%3E%3Cli%3E Message: ' +req.body.message+ '%3C/li%3E%3C/ul%3E'%0A%09%7D;%0A%0A%09transporter.sendMail(mailOptions, function(error, info)%7B%0A%09%09if (error) %7B %0A%09%09%09console.log(error);%0A%09%09%09res.redirect('/');%0A%09%09%7D else %7B%0A%09%09%09console.log('Message Sent '+info.response);%0A%09%09%09res.redirect('/');%0A%09%09%7D%0A%09%7D);%0A%0A%7D );%0A%0A
0329b8f000c47bb4d3f43191b790b5b2e8515e6b
Connect elements
example/js/index.js
example/js/index.js
window.addEventListener("load", function () { var cyto = new Cytoscape(".graph", { toolbox: ".toolbox" }, { nodes: { "node_a": { name: "A" , id: "node_a" , icon: "&#10084;" } , "node_b": { name: "B" , id: "node_b" , icon: "&#9762;" , subelms: { "sub_elm_1": { id: "sub_elm_1" , parent: "node_b" , label: "Subelement 1" , icon: "&#10052;" } } } } , lines: { "node_a__node_b": { source: "node_a" , target: "node_b" , id: "node_a__node_b" } } }); cyto.on("addElement", function (data) { cyto.connect(data.source, cyto.addElement({ name: Math.random().toString() })); }); });
JavaScript
0
@@ -1010,13 +1010,99 @@ %0A %7D); +%0A%0A cyto.on(%22connectElements%22, function (s, t) %7B%0A cyto.connect(s, t);%0A %7D); %0A%7D);%0A
fe6468f6afccc538c1ddaeee93bb3bb7eea4739f
fix current tag retrieval
tagcheck.js
tagcheck.js
#!/usr/bin/env node 'use strict'; var assert = require('assert'); var path = require('path'); var fs = require('fs'); var fmt = require('util').format; var exec = require('child_process').exec; var green = '\u001b[32m'; var red = '\u001b[31m'; var reset = '\u001b[39m'; if (require.main == module) { var pkg = JSON.parse(fs.readFileSync( path.join(process.cwd(), 'package.json'))); return tagCheck(pkg, console.log); } module.exports = tagCheck; function tagCheck (pkg, log, done) { assert(pkg, 'package.json data required'); log = log || console.log; log('Retrieving tags...\n'); var sshDeps = [ 'dependencies', 'devDependencies', 'peerDependencies' ].reduce(function (deps, key) { var sshDeps = Object.keys(pkg[key] || { }) .map(function (name) { return pkg[key][name]; }) .filter(RegExp.prototype.test.bind(/^git\+ssh:\/\//)); return deps.concat(sshDeps); }, []); var tagsChecked = sshDeps.length; var allUpToDate = true; sshDeps.forEach(function (sshDep) { var cmd = fmt('git ls-remote %s', (sshDep.match(/\/\/([^#]+)/) || [])[1]); exec(cmd, function onexec (error, stdout, stderr) { if (error) { log(error.stack); if (done) { done(error); } else { process.exit(allUpToDate ? 0 : -1); } } var tags = stdout.match(/refs\/tags\/(v?[\d\.][^\}\{]+)$/gm) || []; var yourVersion = (sshDep.match(/#(v?[\d\.]+)$/) || ['', '[none]'])[1]; var latestVersion = tags.map(function (tag) { return tag.split('/').pop(); }).sort().pop().trim(); var upToDate = (yourVersion === latestVersion); if (!upToDate) { allUpToDate = false; } log('package: %s', sshDep); log('your version: %s\tlatest version: %s %s\n', yourVersion, latestVersion, upToDate ? fmt('%sOK%s', green, reset) : fmt('%sUPGRADE SUGGESTED%s', red, reset)); tagsChecked--; if (tagsChecked === 0) { if (done) { done(null, allUpToDate); } else { process.exit(allUpToDate ? 0 : -1); } } }); }); }
JavaScript
0.000013
@@ -1460,16 +1460,17 @@ v?%5B%5Cd%5C.%5D +. +)$/) %7C%7C
ebcd34fa8c959568cc3c987189056426111ef054
Fix karma configure
karma.saucelabs.conf.js
karma.saucelabs.conf.js
// Karma configuration // Generated on Sat Jun 17 2017 00:55:49 GMT+0800 (CST) module.exports = function(config) { const customLanchers = { 'SL_Chrome': { base: 'SauceLabs', browserName: 'chrome', version: '45' }, 'SL_Firefox': { base: 'SauceLabs', browserName: 'firefox', version: '45' }, 'SL_Safari_8': { base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.10', version: '8' }, 'SL_Safari_9': { base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.11', version: '9' }, 'SL_Safari_10': { base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.12', version: '10' }, 'SL_IE_8': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows XP', version: '8' }, 'SL_IE_9': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 7', version: '9' }, 'SL_IE_10': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 7', version: '10' }, 'SL_IE_11': { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 7', version: '11' }, 'SL_EDGE': { base: 'SauceLabs', browserName: 'microsoftedge', platform: 'Windows 10', version: '14' }, 'SL_iOS_8_1': { base: 'SauceLabs', browserName: 'iphone', platform: 'iPhone 6', version: '8.1' }, 'SL_iOS_9_0': { base: 'SauceLabs', browserName: 'iphone', platform: 'iPhone 6', version: '9.0' }, 'SL_iOS_10_2': { base: 'SauceLabs', browserName: 'iphone', platform: 'iPhone 7', version: '10.2' }, 'SL_Android_4_4': { base: 'SauceLabs', browserName: 'android', version: '4.4' }, 'SL_Android_5': { base: 'SauceLabs', browserName: 'android', version: '5' }, 'SL_Android_6': { base: 'SauceLabs', browserName: 'android', version: '6' }, 'SL_Android_7': { base: 'SauceLabs', browserName: 'android', version: '7' }, }; config.set({ basePath: '', frameworks: ['mocha'], files: [ 'node_modules/chai/chai.js', 'dist/tiny-cookie.js', 'test/setup.js', 'test/index.spec.js' ], reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_DEBUG, autoWatch: false, browsers: Object.keys(customLaunchers),, sauceLabs: { testName: 'tiny-cookie' }, customLanchers: customLaunchers, singleRun: true, concurrency: Infinity }) }
JavaScript
0.000001
@@ -2589,17 +2589,16 @@ nchers), -, %0A sau
4eb3e6d2532683f6356699789917bc3704f59fe8
Update main.js
src/app/scripts/main.js
src/app/scripts/main.js
/*jslint browser: true*/ /*global L */ /*global GEOHEX */ var geohexCode = null; var startZoomLevel = 13; var localStoragePrefix = "EW_"; // earthWatchers var user = localStorage.getItem(localStoragePrefix + "user") || "anonymous"; var satelliteImages = null; var map = null; var defaultGeohexLevel = null; var defaultSatelliteType = "Sentinel"; var selectedObservationType = null; var project = null; var projectObservationTypes = null; var observationTypesObject = null; var dragMarkerPosition = null; var projectName = null; function cbVisibilityClicked(isVisible){ if(!isVisible){ map.removeLayer(findLayerByType("earthWatchersNow")); map.removeLayer(findLayerByType("earthWatchersPrevious")); map.removeLayer(findLayerByType("earthWatchersOld")); } else{ drawSatelliteImages(map, defaultSatelliteType); } } function gotoNextHexagon() { var url = location.href.replace(location.hash, "#/" + projectName); location.href = url; window.location.reload(); } function goToHexagon(event) { event.originalEvent.preventDefault(); var newGeohexCode = event.originalEvent.srcElement.id; goToGeohexCode(newGeohexCode); } function goToGeohexCode(code){ var url = location.href.replace(location.hash, "#/" + projectName + "/" + code); location.href = url; var previousSelectedHexagon = geohexCode; geohexCode = code; removeMakersByType("navigation"); removeMakersByType("observation"); removeStyles(previousSelectedHexagon); addCurrentHexagonStyle(code); loadJSON("/api/observations/" + projectName + "/" + geohexCode + "/" + user, function (observations) { showObservations(observations); }); getHexagonNavigation(geohexCode, map, user, projectName); var polygon = findLayerByName("hexagon" + code); centerOnPolygon(polygon); drawSatelliteImages(map, document.getElementById("satTypeLabel").innerText); } function showObservations(observations) { var status = getStatusHexagon(observations); if (status === "hasObservations") { drawObservations(observations, observationTypesObject); //setHexagonColor("hasObservations"); } } function clearhexagon() { var observations = getObservationsCount(); if (observations === 0) { //post/save there are no observations for this hexagon var geohexpoly = getGeohexPolygon(geohexCode,null); var cp = geohexpoly.getBounds().getCenter(); postclearHexagon(user, geohexCode, cp.lng, cp.lat, project.properties.Name, function (resp1) { postObservation("clear", user, geohexCode, cp.lng, cp.lat, project.properties.Name, function (resp) { setHexagonColor("clear"); var total = document.getElementById("hexagonstotal").innerHTML; loadUserStatistics(project.properties.Name,user,total); }); }); } else { var messageDiv = document.getElementById("messageDiv"); messageDiv.style.display = 'block'; messageDiv.innerHTML = "Remove observations first!"; messageDiv.className = "message messagesShown"; window.setTimeout(function(){messageDiv.style.display = 'none';},1500); } } function setObservationType(observationType) { selectedObservationType = observationType; styleObservationTypeButtons(projectObservationTypes, observationType.type); } function onMapClick(e) { var isInside = isPointInHexagon(geohexCode, e.latlng); if (isInside) { var observations = getObservationsCount(); postObservation(selectedObservationType.type, user, geohexCode, e.latlng.lng, e.latlng.lat, project.properties.Name, function (resp) { var newMarker = getObservationMarker(map, e.latlng.lng, e.latlng.lat, geohexCode, selectedObservationType.name, resp.id, selectedObservationType,user,project.properties.Name); newMarker.options.type = "observation"; newMarker.addTo(map); // update statistics var total = document.getElementById("hexagonstotal").innerHTML; loadUserStatistics(project.properties.Name,user,total); }); if (observations === 0) { setHexagonColor("hasObservations"); } } } function setHexagonColor(status) { var layer = findLayerByName("hexagon" + geohexCode); if (status === "hasObservations") { layer.setStyle({color: "#FF0000"}); } else if (status === "clear") { layer.setStyle({color: "#00FF00"}); } } function initializeRouting() { Path.map("#/:project").to(function () { // sample: #/borneo geohexCode = null; projectName = this.params["project"]; }); Path.map("#/:project/:hex").to(function () { // sample: #/borneo/PO2670248 projectName = this.params["project"]; geohexCode = this.params["hex"]; }); Path.listen(); } (function (window, document, L) { "use strict"; L.Icon.Default.imagePath = "images/"; initializeRouting(); initUserPanel(); loadJSON("data/observationTypes.json", function (observationTypes) { loadJSON("data/projects.geojson", function (projects) { if (projectName === null) { // first project is the default project... projectName = projects.features[0].properties.Name; } project = getProjectByName(projects, projectName); projectObservationTypes = project.properties.ObservationCategories.split(","); observationTypesObject = observationTypes; addObservationTypeButtons(projectObservationTypes, observationTypes); defaultGeohexLevel = project.properties.GeohexLevel; if (geohexCode === null) { geohexCode = getRandomHexagon(project, defaultGeohexLevel); location.hash = "#/" + projectName + "/" + geohexCode; } var hexagons = getTotalHexagons(); console.log("Total Hexagons: " + hexagons.length); loadJSON("/api/observations/" + projectName + "/" + geohexCode + "/" + user, function (observations) { loadUserStatistics(projectName, user, hexagons.length); map = L.map("map", { maxZoom: 13, zoomControl: false, attributionControl: false }); L.control.zoom({ position:'topleft' }).addTo(map); map.on("click", onMapClick); drawSatelliteImages(map, defaultSatelliteType); drawHexagons(map, hexagons); getHexagonNavigation(geohexCode, map,user,projectName); var polygon = getGeohexPolygon(geohexCode, null); addCurrentHexagonStyle(geohexCode); var centerHex = centerOnPolygon(polygon); showObservations(observations); L.control.scale({imperial: false, position: "topleft"}).addTo(map); var ggl2 = new L.Google("HYBRID"); map.addLayer(ggl2); L.geoJson(projects, {fill: false}).addTo(map); }); }); }); }(window, document, L));
JavaScript
0.000001
@@ -6366,10 +6366,81 @@ m: 1 -3, +8, //used to be 13, but add maxNativeZoom to allow bloating deeper levels %0A
87d2373453dadb8f0f04aa298375000b886fa55f
fix filter terms not maintaining their special color when removing one of two tags
arches/app/media/js/views/search/term-filter.js
arches/app/media/js/views/search/term-filter.js
define(['jquery', 'backbone', 'arches', 'select2', 'knockout'], function ($, Backbone, arches, Select2, ko) { return Backbone.View.extend({ initialize: function(options) { $.extend(this, options); var self = this; this.query = { filter: { terms: ko.observableArray() }, isEmpty: function(){ if (this.filter.terms.length === 0){ return true; } return false; }, changed: ko.pureComputed(function(){ var ret = ko.toJSON(this.query.filter.terms()); return ret; }, this)//.extend({ rateLimit: 200 }) }; this.render(); }, render: function(){ var self = this; this.searchbox = this.$el.select2({ multiple: true, //maximumselectionsize: 1, minimumInputLength: 2, ajax: { url: this.getUrl(), dataType: 'json', data: function (term, page) { return { q: term, // search term page_limit: 30 }; }, results: function (data, page) { var value = $('div.resource_search_widget').find('.select2-input').val(); var results = [{ inverted: false, type: 'string', context: 'string', id: value, text: value, value: value }]; $.each(data.hits.hits, function(){ results.push({ inverted: false, type: this._source.options.conceptid ? 'concept' : 'term', context: this._source.context, id: this._source.term, text: this._source.term, value: this._source.options.conceptid ? this._source.options.conceptid : this._source.term }); }, this); return {results: results}; } }, formatResult:function(result, container, query, escapeMarkup){ var markup=[]; window.Select2.util.markMatch(result.text, query.term, markup, escapeMarkup); var formatedresult = '<span class="concept_result">' + markup.join("") + '</span><i class="concept_result_schemaname">(' + result.context + ')</i>'; //var formatedresult = '<div class="search_term_result" data-id="' + result.id + '"><i class="fa fa-minus" style="margin-right: 7px;display:none;"></i>' + markup.join("") + '</div>'; return formatedresult; }, formatSelection: function(result){ var markup = '<div data-filter="external-filter">' + result.text + '</div>'; return markup; }, escapeMarkup: function(m) { return m; } }).on("select2-selecting", function(e, el) { self.trigger("select2-selecting", e, el); }).on("change", function(e, el){ self.trigger("change", e, el); if(e.added){ if(e.added.type !== 'filter-flag'){ self.query.filter.terms.push(e.added); } } if(e.removed){ if(e.removed.type === 'filter-flag'){ self.trigger('filter-removed', e.removed); }else{ self.query.filter.terms.remove(function(item){ return item.id === e.removed.id && item.context === e.removed.context; }); } } }); s = this; }, getUrl: function(){ return arches.urls.search_terms; }, addTag: function(term){ var terms = this.searchbox.select2('data'); terms.unshift({ inverted: '', type: 'filter-flag', context: '', id: term, text: term, value: term }); this.searchbox.select2('data', terms); $('.resource_search_widget').find('.select2-search-choice').each(function(i, el) { if ($(el).data('select2-data').type === 'filter-flag') { $(el).addClass('filter-flag'); } }); }, removeTag: function(term){ var terms = this.searchbox.select2('data'); for (var i=terms.length-1; i>=0; i--) { if(terms[i].id == term && terms[i].text == term && terms[i].value == term){ terms.splice(i, 1); break; } } this.searchbox.select2('data', terms); }, restoreState: function(filter){ var self = this; if(typeof filter !== 'undefined' && filter.length > 0){ var results = []; $.each(filter, function(){ self.query.filter.terms.push(this); results.push({ inverted: this.inverted, type: this.type, context: this.context, id: this.id, text: this.text, value: this.value }); }); this.searchbox.select2('data', results).trigger('change'); } }, clear: function(){ this.query.filter.terms.removeAll(); this.searchbox.select2('data', []); } }); });
JavaScript
0
@@ -4922,299 +4922,25 @@ his. -searchbox.select2('data', terms);%0D%0A%0D%0A $('.resource_search_widget').find('.select2-search-choice').each(function(i, el) %7B%0D%0A if ($(el).data('select2-data').type === 'filter-flag') %7B%0D%0A $(el).addClass('filter-flag');%0D%0A %7D%0D%0A %7D +updateTerms(terms );%0D%0A @@ -5299,56 +5299,409 @@ %7D%0D%0A - this.searchbox.select2('data', terms +%0D%0A this.updateTerms(terms);%0D%0A %7D,%0D%0A%0D%0A updateTerms: function(terms)%7B%0D%0A this.searchbox.select2('data', terms);%0D%0A%0D%0A $('.resource_search_widget').find('.select2-search-choice').each(function(i, el) %7B%0D%0A if ($(el).data('select2-data').type === 'filter-flag') %7B%0D%0A $(el).addClass('filter-flag');%0D%0A %7D%0D%0A %7D );%0D%0A
d69654ea1f2b9b3232f997d01746e714b620415d
Fix radiobox in advanced settings (set value = false)
apps/common/main/lib/component/RadioBox.js
apps/common/main/lib/component/RadioBox.js
/* * * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ /** * RadioBox.js * * Created by Julia Radzhabova on 2/26/14 * Copyright (c) 2018 Ascensio System SIA. All rights reserved. * */ /** * Radiobox can be in two states: true or false. * To get the radiobox state use getValue() function. It can return true/false. * * @property {String} name * The name of the group of radioboxes. * * name: 'group-name', * * @property {Boolean} checked * Initial state of radiobox. * * checked: false, * * **/ if (Common === undefined) var Common = {}; define([ 'common/main/lib/component/BaseView', 'underscore' ], function (base, _) { 'use strict'; Common.UI.RadioBox = Common.UI.BaseView.extend({ options : { labelText: '' }, disabled : false, rendered : false, template : _.template('<div class="radiobox" data-hint="<%= dataHint %>" data-hint-direction="<%= dataHintDirection %>" data-hint-offset="<%= dataHintOffset %>">' + '<input type="radio" name="<%= name %>" id="<%= id %>" class="button__radiobox">' + '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">' + '<circle class="rb-circle" cx="8" cy="8" r="6.5" />' + '<circle class="rb-check-mark" cx="8" cy="8" r="4" />' + '</svg>' + '<span></span></div>'), initialize : function(options) { Common.UI.BaseView.prototype.initialize.call(this, options); this.dataHint = options.dataHint; this.dataHintDirection = options.dataHintDirection; this.dataHintOffset = options.dataHintOffset; var me = this; this.name = this.options.name || Common.UI.getId(); this.render(); if (this.options.disabled) this.setDisabled(this.options.disabled); if (this.options.checked!==undefined) this.setValue(this.options.checked, true); this.setCaption(this.options.labelText); // handle events }, render: function () { var el = this.$el || $(this.el); el.html(this.template({ labelText: this.options.labelText, name: this.name, id: Common.UI.getId('rdb-'), dataHint: this.dataHint, dataHintDirection: this.dataHintDirection, dataHintOffset: this.dataHintOffset })); this.$radio = el.find('input[type=radio]'); this.$label = el.find('div.radiobox'); this.$span = this.$label.find('span'); this.$label.on({ 'keydown': this.onKeyDown.bind(this), 'click': function(e){ if ( !this.disabled ) this.setValue(true); }.bind(this),}); this.rendered = true; return this; }, setDisabled: function(disabled) { if (!this.rendered) return; disabled = !!disabled; if (disabled !== this.disabled) { this.$label.toggleClass('disabled', disabled); this.$radio.toggleClass('disabled', disabled); (disabled) ? this.$radio.attr({disabled: disabled}) : this.$radio.removeAttr('disabled'); if (this.tabindex!==undefined) { disabled && (this.tabindex = this.$label.attr('tabindex')); this.$label.attr('tabindex', disabled ? "-1" : this.tabindex); } } this.disabled = disabled; }, isDisabled: function() { return this.disabled; }, onItemCheck: function (e) { if (!this.disabled) this.setValue(true); }, setRawValue: function(value) { var value = (value === true || value === 'true' || value === '1' || value === 1 ); $('input[type=radio][name=' + this.name + ']').removeClass('checked'); this.$radio.toggleClass('checked', value); this.$radio.prop('checked', value); }, setValue: function(value, suspendchange) { if (this.rendered) { var lastValue = this.$radio.hasClass('checked'); this.setRawValue(value); if (suspendchange !== true && lastValue !== value) this.trigger('change', this, this.$radio.is(':checked')); } else { this.options.checked = value; } }, getValue: function() { return this.$radio.is(':checked'); }, setCaption: function(text) { this.$span.text(text); this.$span.css('visibility', text ? 'visible' : 'hidden'); }, onKeyDown: function(e) { if (e.isDefaultPrevented()) return; if (e.keyCode === Common.UI.Keys.SPACE) this.onItemCheck(e); }, focus: function() { this.$label && this.$label.focus(); }, setTabIndex: function(tabindex) { if (!this.rendered) return; this.tabindex = tabindex.toString(); !this.disabled && this.$label.attr('tabindex', this.tabindex); } }); });
JavaScript
0
@@ -5703,16 +5703,25 @@ + value && $('inpu
4fa27c09fa8bac8f99f42571858587a93d51dcea
fix user dialog toggle
src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js
src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js
(function () { "use strict"; function AppHeaderDirective(eventsService, appState, userService) { function link(scope, el, attr, ctrl) { var evts = []; // the null is important because we do an explicit bool check on this in the view // the avatar is by default the umbraco logo scope.authenticated = null; scope.user = null; scope.avatar = [ { value: "assets/img/application/logo.png" }, { value: "assets/img/application/logo@2x.png" }, { value: "assets/img/application/logo@3x.png" } ]; // when a user logs out or timesout evts.push(eventsService.on("app.notAuthenticated", function() { scope.authenticated = false; scope.user = null; })); // when the application is ready and the user is authorized setup the data evts.push(eventsService.on("app.ready", function(evt, data) { scope.authenticated = true; scope.user = data.user; if (scope.user.avatars) { scope.avatar = []; if (angular.isArray(scope.user.avatars)) { for (var i = 0; i < scope.user.avatars.length; i++) { scope.avatar.push({ value: scope.user.avatars[i] }); } } } })); evts.push(eventsService.on("app.userRefresh", function(evt) { userService.refreshCurrentUser().then(function(data) { scope.user = data; if (scope.user.avatars) { scope.avatar = []; if (angular.isArray(scope.user.avatars)) { for (var i = 0; i < scope.user.avatars.length; i++) { scope.avatar.push({ value: scope.user.avatars[i] }); } } } }); })); // toggle the help dialog by raising the global app state to toggle the help drawer scope.helpClick = function () { var showDrawer = appState.getDrawerState("showDrawer"); var drawer = { view: "help", show: !showDrawer }; appState.setDrawerState("view", drawer.view); appState.setDrawerState("showDrawer", drawer.show); }; scope.avatarClick = function () { scope.userDialog = { view: "user", show: true, close: function (oldModel) { scope.userDialog.show = false; scope.userDialog = null; } }; }; } var directive = { transclude: true, restrict: "E", replace: true, templateUrl: "views/components/application/umb-app-header.html", link: link, scope: {} }; return directive; } angular.module("umbraco.directives").directive("umbAppHeader", AppHeaderDirective); })();
JavaScript
0.000002
@@ -2601,32 +2601,76 @@ = function () %7B%0A + if(!scope.userDialog) %7B%0A @@ -2686,24 +2686,28 @@ rDialog = %7B%0A + @@ -2748,16 +2748,20 @@ + show: tr @@ -2784,16 +2784,20 @@ + + close: f @@ -2813,24 +2813,28 @@ oldModel) %7B%0A + @@ -2892,32 +2892,36 @@ + scope.userDialog @@ -2941,34 +2941,42 @@ + + %7D%0A + @@ -2974,24 +2974,163 @@ %7D;%0A + %7D else %7B%0A scope.userDialog.show = false;%0A scope.userDialog = null;%0A %7D%0A
b2b6527acdaa309b76c051d99431bd99e82137d2
Reorder imports.
assets/js/components/ErrorNotice.stories.js
assets/js/components/ErrorNotice.stories.js
/** * ErrorNotice stories. * * Site Kit by Google, Copyright 2022 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. */ /** * Internal dependencies */ import { provideModules } from '../../../tests/js/utils'; import WithRegistrySetup from '../../../tests/js/WithRegistrySetup'; import { MODULES_ANALYTICS } from '../modules/analytics/datastore/constants'; import ErrorNotice from './ErrorNotice'; const notFoundError = { code: 404, message: 'Not found', data: { status: 404, }, }; const Template = ( { setupRegistry = () => {}, ...args } ) => ( <WithRegistrySetup func={ setupRegistry }> <ErrorNotice { ...args } /> </WithRegistrySetup> ); export const Default = Template.bind( {} ); Default.args = { error: new Error( 'This is error text' ), }; export const WithRetryLink = Template.bind( {} ); WithRetryLink.args = { error: notFoundError, storeName: MODULES_ANALYTICS, setupRegistry: ( registry ) => { provideModules( registry, [ { active: true, connected: true, slug: 'analytics', }, ] ); registry .dispatch( MODULES_ANALYTICS ) .receiveError( notFoundError, 'getReport', [] ); }, }; export default { title: 'Components/ErrorNotice', component: ErrorNotice, };
JavaScript
0
@@ -739,145 +739,145 @@ ort -WithRegistrySetup from '../../../tests/js/WithRegistrySetup';%0Aimport %7B MODULES_ANALYTICS %7D from '../modules/analytics/datastore/constants +%7B MODULES_ANALYTICS %7D from '../modules/analytics/datastore/constants';%0Aimport WithRegistrySetup from '../../../tests/js/WithRegistrySetup ';%0Ai
58ed2d29c81de6d9be6f1c5a74d43f58a89f7896
Update Listeners.js
Examples/simple-fcm-client/app/Listeners.js
Examples/simple-fcm-client/app/Listeners.js
import { Platform, AsyncStorage } from 'react-native'; import FCM, {FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType} from "react-native-fcm"; AsyncStorage.getItem('lastNotification').then(data=>{ if(data){ // if notification arrives when app is killed, it should still be logged here console.log('last notification', JSON.parse(data)); AsyncStorage.removeItem('lastNotification'); } }) export function registerKilledListener(){ // these callback will be triggered even when app is killed FCM.on(FCMEvent.Notification, notif => { AsyncStorage.setItem('lastNotification', JSON.stringify(notif)); }); } // these callback will be triggered only when app is foreground or background export function registerAppListener(){ FCM.on(FCMEvent.Notification, notif => { console.log("Notification", notif); if(notif.local_notification){ return; } if(notif.opened_from_tray){ return; } if(Platform.OS ==='ios'){ //optional //iOS requires developers to call completionHandler to end notification process. If you do not call it your background remote notifications could be throttled, to read more about it see the above documentation link. //This library handles it for you automatically with default behavior (for remote notification, finish with NoData; for WillPresent, finish depend on "show_in_foreground"). However if you want to return different result, follow the following code to override //notif._notificationType is available for iOS platfrom switch(notif._notificationType){ case NotificationType.Remote: notif.finish(RemoteNotificationResult.NewData) //other types available: RemoteNotificationResult.NewData, RemoteNotificationResult.ResultFailed break; case NotificationType.NotificationResponse: notif.finish(); break; case NotificationType.WillPresent: notif.finish(WillPresentNotificationResult.All) //other types available: WillPresentNotificationResult.None break; } } }); FCM.on(FCMEvent.RefreshToken, token => { console.log("TOKEN (refreshUnsubscribe)", token); this.props.onChangeToken(token); }); FCM.enableDirectChannel(); FCM.on(FCMEvent.DirectChannelConnectionChanged, (data) => { console.log('direct channel connected' + data); }); setTimeout(function() { FCM.isDirectChannelEstablished().then(d => console.log(d)); }, 1000); }
JavaScript
0
@@ -2144,16 +2144,271 @@ lt.None%0A + // this type of notificaiton will be called only when you are in foreground.%0A // if it is a remote notification, don't do any app logic here. Another notification callback will be triggered with type NotificationType.Remote%0A
5de6c2b518a5189e79eaa7a359ff8e54a5738ce7
add back concurrency check, fix api urls
lib/plugins/output-filter/access-watch.js
lib/plugins/output-filter/access-watch.js
'use strict' var request = require('request') var LRU = require('lru-cache') var md5 = require('md5') var defaultConfig = { matchTypes: ['access_common', 'access_log_combined'], clientIpField: 'client_ip', userAgentField: 'user_agent', addressDestination: 'address', userAgentDestination: 'ua', robotDestination: 'robot', reputationDestination: 'reputation', addressProperties: ['value', 'hostname', 'country_code', 'flags'], robotProperties: ['id', 'name', 'url'], cacheSize: 10000, maxQueueLength: 1000, requestUserAgent: 'Access Watch Logagent Plugin', apiBaseUrl: 'https://api.access.watch', // apiBaseUrl: 'http://0.0.0.0:8008', } function init (config, context, eventEmitter) { if (config.initialized) { return } for (var key in defaultConfig) { if (defaultConfig.hasOwnProperty(key)) { if (typeof config[key] === 'undefined') { config[key] = defaultConfig[key] } } } if (!config.requestHeaders) { config.requestHeaders = { 'User-Agent': config.requestUserAgent, 'Api-Key': config.apiKey } } if (!config.cache) { config.cache = LRU({max: config.cacheSize}) } config.initialized = true } var queueHandler var queue = [] var currentRequests = {} function requestData(options, callback) { if (options.cache && options.id) { var object = options.cache.get(options.id) if (object) { callback(object) return } } if (currentRequests[options.id] !== undefined || Object.keys(currentRequests).length > 10) { if (options.queue.length > options.maxQueueLength) { console.log('Skipping request (queue too large, check maxQueueLength)') callback(null) return } options.queue.push([options, callback]) if (!queueHandler) { queueHandler = setTimeout(handleQueue, 1) } return } request(options, function (error, response, body) { if (body) { var object if (typeof body == 'object') { object = body } else if (typeof body == 'string') { object = JSON.parse(body) } if (object) { if (options.cache && options.id) { options.cache.set(options.id, object) } callback(object) return } } callback(null) }) } function fetchUserAgentData (userAgent, config, data, callback) { var hash = md5(userAgent) var options = { id: 'user_agent_' + hash, url: config.apiBaseUrl + '/1_1/user-agent/' + hash, headers: config.requestHeaders, cache: config.cache, queue: queue, maxQueueLength: config.maxQueueLength } requestData(options, function (result) { if (result && config.hasOwnProperty('userAgentDestination')) { data = augmentData(data, result, config['userAgentDestination']) } callback(null, data) }) } function fetchAddressData (address, config, data, callback) { var hash = md5(address) var options = { id: 'address_' + hash, url: config.apiBaseUrl + '/1_1/address/' + hash, headers: config.requestHeaders, cache: config.cache, queue: queue, maxQueueLength: config.maxQueueLength } requestData(options, function (result) { if (result && config.hasOwnProperty('addressDestination')) { data = augmentData(data, result, config['addressDestination'], config['addressProperties']) } callback(null, data) }) } function fetchIdentityData (address, userAgent, config, data, callback) { var options = { method: 'POST', json: {'address': address, 'user_agent': userAgent}, id: 'identity_' + md5(address) + '_' + md5(userAgent), url: config.apiBaseUrl + '/1_1/identity', headers: config.requestHeaders, cache: config.cache, queue: queue, maxQueueLength: config.maxQueueLength } requestData(options, function (result) { if (result) { if (result.hasOwnProperty('address') && config.hasOwnProperty('addressDestination')) { data = augmentData(data, result['address'], config['addressDestination'], config['addressProperties']) } if (result.hasOwnProperty('robot') && config.hasOwnProperty('robotDestination')) { data = augmentData(data, result['robot'], config['robotDestination'], config['robotProperties']) } if (result.hasOwnProperty('reputation') && config.hasOwnProperty('reputationDestination')) { data = augmentData(data, result['reputation'], config['reputationDestination']) } } callback(null, data) }) } function augmentData(data, object, destination, properties) { if (properties) { data[destination] = {} properties.forEach(function (key) { if (object.hasOwnProperty(key)) { data[destination][key] = object[key] } }) } else { data[destination] = object } return data } function handleQueue() { while (Object.keys(currentRequests).length < 10 && queue.length > 0) { var args = queue.shift() requestData.apply(null, args) } queueHandler = setTimeout(handleQueue, 100) } function accessWatch (context, config, eventEmitter, data, callback) { if (data == null) { return callback(new Error('data is null'), null) } init(config, context, eventEmitter) if (config.matchTypes && data._type && config.matchTypes.indexOf(data._type) > -1) { var address, userAgent if (config.clientIpField && data[config.clientIpField]) { address = data[config.clientIpField] } if (config.userAgentField && data[config.userAgentField]) { userAgent = data[config.userAgentField] if (userAgent === '-') { userAgent = null } } if (address && userAgent) { fetchIdentityData (address, userAgent, config, data, callback) } else if (address) { fetchAddressData (address, config, data, callback) } else if (userAgent) { fetchUserAgentData (userAgent, config, data, callback) } } else { callback(null, data) } } module.exports = accessWatch
JavaScript
0
@@ -629,50 +629,9 @@ tch' -,%0A // apiBaseUrl: 'http://0.0.0.0:8008', %0A + %7D%0A%0Af @@ -1825,24 +1825,59 @@ eturn%0A%0A %7D%0A%0A + currentRequests%5Boptions.id%5D = 1%0A%0A request(op @@ -1914,24 +1914,64 @@ se, body) %7B%0A + delete currentRequests%5Boptions.id%5D%0A%0A if (body @@ -2519,17 +2519,17 @@ rl + '/1 -_ +. 1/user-a @@ -3055,17 +3055,17 @@ rl + '/1 -_ +. 1/addres
9220e4ba58cd85c44ac4e04d8289ceec0275e843
add params
Algorithms/JS/arrays/maxNonNegativeSubArray.js
Algorithms/JS/arrays/maxNonNegativeSubArray.js
// Find out the maximum sub-array of non negative numbers from an array. // The sub-array should be continuous. That is, a sub-array created by choosing the second and fourth element // and skipping the third element is invalid. // Maximum sub-array is defined in terms of the sum of the elements in the sub-array. // Sub-array A is greater than sub-array B if sum(A) > sum(B). // Example: // A : [1, 2, 5, -7, 2, 3] // The two sub-arrays are [1, 2, 5] [2, 3]. // The answer is [1, 2, 5] as its sum is larger than [2, 3] // NOTE: If there is a tie, then compare with segment's length and return segment which has maximum length // NOTE 2: If there is still a tie, then return the segment with minimum starting index function maxset(A){ var allSub = [], // store all sub arrays temp = [], // build up array negCount = 0; for( var i = 0; i < A.length; i++ ){ if( A[i] >= 0 ){ temp.push(A[i]); } else { allSub.push( temp ); temp = []; negCount += 1; //increment everytime a negative numbers is encountered } } if( negCount === A.length ) return 0; // if all numbers are negative return 0 if( A[A.length -1] > 0 ) allSub.push(temp); // if last element was positive push build up into result arr var maxSum = 0, length = 0, sum, sub; for( var j =0, sum = allSub[j[0]]; j< allSub.length; j++ ){ sum = allSub[j].reduce(function(a, b) { return a + b; }, 0); if( sum >maxSum ){ maxSum = sum; length = allSub[j].length; sub = allSub[j]; } if( sum === maxSum){ if( allSub[j].length > length ){ maxSum = sum; length = allSub[j].length; sub = allSub[j]; } } } return sub; } console.log( maxset([ 0, 0, -1, 0 ]) )
JavaScript
0.000002
@@ -713,16 +713,69 @@ index%0A%0A +/**%0A * @param %7Barray %5B%5D%7D A%0A * @return %7Barray %5B%5D%7D%0A */%0A %0Afunctio
e67a504218d3de8ade640480acfc86135c174c00
fix linter
test/subscriberSpec.js
test/subscriberSpec.js
var expect = require('chai').expect, _ = require('underscore'), Subscriber = require('subscriber'), sinon = require('sinon'); describe('Subscriber', function () { beforeEach(function () { this.subscriber = new Subscriber(); this.sandbox = sinon.sandbox.create(); }); afterEach(function () { delete this.subscriber; this.sandbox.restore(); }); it('Should be able to listen for an event', function (done) { this.subscriber.on('foo', function (args) { expect(_.isObject(args)).to.be.true; expect(args.bar).to.equal('bar'); done(); }); this.subscriber.trigger('foo', {bar: 'bar'}); }); it('Should not be listening to an event when off', function () { var callback = this.sandbox.spy(); this.subscriber.on('foo', callback); this.subscriber.trigger('foo'); expect(callback.callCount).to.equal(1); this.subscriber.trigger('foo'); expect(callback.callCount).to.equal(2); this.subscriber.off('foo'); this.subscriber.trigger('foo'); expect(callback.callCount).to.equal(2); }); it('Should call multiple listeners', function () { var callback1 = this.sandbox.spy(); var callback2 = this.sandbox.spy(); this.subscriber.on('foo', callback1); this.subscriber.on('foo', callback2); this.subscriber.trigger('foo'); expect(callback1.calledOnce).to.be.true; expect(callback2.calledOnce).to.be.true; }); it('Should be able to listen to multiple namespaces with a single callback', function () { var callback = this.sandbox.spy(); this.subscriber.on('foo', callback); this.subscriber.on('bar', callback); this.subscriber.on('foobar', callback); this.subscriber.trigger('foo bar foobar'); expect(callback.callCount).to.equal(3); }); it('Should have "this" to be set to null', function (done) { this.subscriber.on('foo', function (args) { expect(this.listeners).to.be.undefined; done(); }); this.subscriber.trigger('foo'); }); });
JavaScript
0.000002
@@ -2056,36 +2056,32 @@ foo', function ( -args ) %7B%0A
b3e5a4d9db4bc6be378507c7c5875acdfab22326
add params
Algorithms/JS/arrays/sortTransformedArray.js
Algorithms/JS/arrays/sortTransformedArray.js
Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f(x) = ax2 + bx + c to each element x in the array. The returned array must be in sorted order. Expected time complexity: O(n) Example: nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5, Result: [3, 9, 15, 33] nums = [-4, -2, 2, 4], a = -1, b = 3, c = 5 Result: [-23, -5, 1, 7]
JavaScript
0.000002
@@ -1,8 +1,11 @@ +// Given a @@ -65,16 +65,19 @@ and c.%0A +// Apply a @@ -150,16 +150,19 @@ array.%0A%0A +// The retu @@ -198,16 +198,19 @@ order.%0A%0A +// Expected @@ -233,16 +233,19 @@ : O(n)%0A%0A +// Example: @@ -245,16 +245,19 @@ xample:%0A +// nums = %5B @@ -293,16 +293,19 @@ c = 5,%0A%0A +// Result: @@ -320,16 +320,19 @@ 5, 33%5D%0A%0A +// nums = %5B @@ -368,16 +368,19 @@ c = 5%0A%0A +// Result: @@ -395,8 +395,131 @@ , 1, 7%5D%0A +%0A%0A/**%0A * @param %7Bnumber%5B%5D%7D nums%0A * @param %7Bnumber%7D a%0A * @param %7Bnumber%7D b%0A * @param %7Bnumber%7D c%0A * @return %7Bnumber%5B%5D%7D%0A */%0A%0A%0A
9093a782421720bdd1100f90772aa63e7fdb4529
add motivation field
browserExtension/scripts/popup/popupAppender.js
browserExtension/scripts/popup/popupAppender.js
var globalInfo; function setDOMInfo(info) { console.log(info); globalInfo = info; var myData = info; var cardsList = document.getElementById('cards'); $('#cards').empty(); if(myData == undefined) { return; } for (var i = 0; i < myData.length; i++) { var dt = myData[i]; //add main card var newCard = document.createElement('div'); var cardAttr = document.createAttribute('class'); cardAttr.value = 'panel panel-default'; newCard.setAttributeNode(cardAttr); //add date var spanDate = document.createElement('span'); var date = new Date(dt.annotation.createdAt); var day = date.getDate(); var month = date.getMonth() +1; var year = date.getFullYear(); var convertedDate =day+'/'+month+'/'+year; spanDate.innerHTML = convertedDate; var spanAttr = document.createAttribute('class'); spanAttr.value = 'pull-right'; spanDate.setAttributeNode(spanAttr); newCard.appendChild(spanDate); //add panel body var divBody = document.createElement('div'); var bodyAttr = document.createAttribute('class'); bodyAttr.value = 'panel-body'; divBody.setAttributeNode(bodyAttr); newCard.appendChild(divBody); //add author tag var divAuthor = document.createElement('h5'); divAuthor.innerHTML = "<b>Author: </b>" + dt.user.firstName + " " + dt.user.lastName;//dt.authorName; divBody.appendChild(divAuthor); //add selected text tag var divSelectedText = document.createElement('p'); divSelectedText.innerHTML = "<b>Annotation:</b> "+dt.annotation.target.selector[2].exact; console.log("something"); console.log(dt.annotation.target.selector[2].exact); divBody.appendChild(divSelectedText); //add Comment var divComment = document.createElement('p'); divComment.innerHTML = "<b>Comment:</b> "+ dt.annotation.body.value; divBody.appendChild(divComment); cardsList.appendChild(newCard); } } function setGeekMode(info) { console.log(info); var myData = info; var cardsList = document.getElementById('cards'); $('#cards').empty(); if(myData == undefined) { return; } for (var i = 0; i < myData.length; i++) { var dt = myData[i]; //add main card var newCard = document.createElement('div'); var cardAttr = document.createAttribute('class'); cardAttr.value = 'panel panel-default'; newCard.setAttributeNode(cardAttr); //data var jsonSpan = document.createElement('span'); var data = dt.annotation; var geekString = data.replace('{','{"@context":"http://www.w3.org/ns/anno.jsonld",'); jsonSpan.innerHTML = JSON.stringify(geekString); newCard.appendChild(jsonSpan); cardsList.appendChild(newCard); } } function geekModeFun(el) { if ( el.value === "Geek Mode" ) { el.value = "User Mode"; setGeekMode(globalInfo); } else { el.value = "Geek Mode"; setDOMInfo(globalInfo); } } document.addEventListener("click", function (e) { if (e.target.id == "geekModeLink") { geekModeFun(e.target); } }); // Once the DOM is ready... window.addEventListener('DOMContentLoaded', function () { chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { chrome.tabs.sendMessage( tabs[0].id, {from: 'popup', subject: 'DOMInfo'}, // ...also specifying a callback to be called // from the receiving end (content script) setDOMInfo); }); });
JavaScript
0
@@ -2075,24 +2075,220 @@ vComment);%0A%0A + //add Comment%0A var divMotivation = document.createElement('p');%0A divMotivation.innerHTML = %22%3Cb%3EMotivation:%3C/b%3E %22+ dt.motivation;%0A divBody.appendChild(divMotivation);%0A%0A card
4b6c5631d5d9c28ab5403a5ec6d731d572cc0b70
Add concatenation of comma to addHeader function in tableCreator.js
sashimi-webapp/src/database/create/tableCreator.js
sashimi-webapp/src/database/create/tableCreator.js
const constants = require('../constants'); const sqlCommands = require('../sql-related/sqlCommands'); const exceptions = require('../exceptions'); let isTableInitializedForCreation = constants.CONST_TABLE_CREATION_CLOSED; let sqlCreateTableString = constants.STRING_INITIALIZE; const stringConcat = function stringConcat(...stringToConcat) { let fullString = ''; for (let index = 0; index < stringToConcat.length; index += 1) { fullString += stringToConcat[index]; } return fullString; }; class tableCreator { static constructor() { } static initCreateTable(tableName) { if (isTableInitializedForCreation) { throw new exceptions.TableCreationAlreadyInitiated('Table creation is already initiated. Please close the thread first.'); } else { try { sqlCommands.getFullTableData(tableName); throw new exceptions.TableAlreadyExists('Table already Exist. Not available for creation.'); } catch (exceptionTableDoesNotExists) { sqlCreateTableString = stringConcat('CREATE TABLE ', tableName, '('); isTableInitializedForCreation = constants.CONST_TABLE_CREATION_INITIALIZED; } } } static addHeader(headerName, dataType, ...extraConditions) { if (isTableInitializedForCreation) { sqlCreateTableString = stringConcat(sqlCreateTableString, headerName, ' '); sqlCreateTableString = stringConcat(sqlCreateTableString, dataType); for (let index = 0; index < extraConditions.length; index += 1) { sqlCreateTableString = stringConcat(sqlCreateTableString, ' ', extraConditions[index]); } } } } module.export = tableCreator;
JavaScript
0.000003
@@ -1587,32 +1587,103 @@ ndex%5D);%0A %7D%0A + sqlCreateTableString = stringConcat(sqlCreateTableString, ', ');%0A %7D%0A %7D%0A%7D%0A%0Amod
0c1d974de530332099cf5ae04389a99c362c067c
fix free space on pages
assets/js/index.js
assets/js/index.js
// reading time (function ($) { "use strict"; $(document).ready(function(){ $(".post-content").fitVids(); // Calculates Reading Time $('.post-content').readingTime({ readingTimeTarget: '.post-reading-time', wordCountTarget: '.post-word-count', }); // Creates Captions from Alt tags $(".post-content img").each(function() { // Let's put a caption if there is one if($(this).attr("alt")) $(this).wrap('<figure class="image"></figure>') .after('<figcaption>'+$(this).attr("alt")+'</figcaption>'); }); }); }(jQuery)); // transformation for article image (function ($) { "use strict"; $(document).ready(function(){ var $window = $(window), $image = $('.post-image-image'); $window.on('scroll', function() { var top = $window.scrollTop(); if (top < 0 || top > 1500) { return; } $image .css('transform', 'translate3d(0px, '+top/3+'px, 0px)') .css('opacity', 1-Math.max(top/700, 0)); }); $window.trigger('scroll'); $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 500); return false; } } }); }); }); }(jQuery)); // transformation for frontpage image (function ($) { "use strict"; $(document).ready(function(){ var $window = $(window), $image = $('.teaserimage-image'); $window.on('scroll', function() { var top = $window.scrollTop(); if (top < 0 || top > 1500) { return; } $image .css('transform', 'translate3d(0px, '+top/3+'px, 0px)') .css('opacity', 1-Math.max(top/700, 0)); }); $window.trigger('scroll'); }); }(jQuery)); // resize article image (function ($) { "use strict"; function arrangeItems(height) { var $teaserImage = $('.teaserimage'), $content = $('.post-content'), $articleImage = $('.post-image-image'), $articleImageContainer = $('.article-image'), $postReading = $('.post-reading'); $teaserImage.height(height - 200); $articleImage.height(height); $articleImageContainer.height(height); $content.css('padding-top', height + 'px'); $postReading.css('top', (height - 36) + 'px'); }; $(document).ready(function(){ arrangeItems($(window).height()); // initial orientation mode var $portraitMode = $(window).height() > $(window).width(); // listen to resize events $(window).resize(function() { if (isMobile.any) { // on mobile only resize when orientation change var $currentMode = $(window).height() > $(window).width(); if($portraitMode != $currentMode){ // toggle mode $portraitMode = $currentMode; arrangeItems($(window).height()); } } else { arrangeItems($(window).height()); } }); }); }(jQuery));
JavaScript
0.000012
@@ -2333,20 +2333,16 @@ ding');%0A - %0A $te @@ -2446,24 +2446,67 @@ ht(height);%0A + if ($articleImageContainer.length) %7B%0A $content @@ -2537,24 +2537,30 @@ ht + 'px');%0A + %7D%0A $postRea
11101470a59b3cc86d1c3407c802e7b9cef0c63f
Fix typo in test
test/test-date-plus.js
test/test-date-plus.js
/** * test-date-plus.js * copyright 2015-2020, Jürgen Leschner - github.com/jldec - MIT license * **/ var test = require('tape'); var date = require('../date-plus.js'); var dateformat = require('../dateformat.js'); test('date', function(t) { var nativeDate = new Date; var dd = date(nativeDate); t.true(dd.valid); t.equal(nativeDate.valueOf(), dd.valueOf()); t.end(); }); test('invalid', function(t) { t.false(date('booger').valid); t.false(date('NaN').valid); t.false(date('45 min'-1).valid); t.false(date([]).valid); t.false(date({}).valid); t.equal(date('booger').format(),'No Date'); t.equal(date('booger').format('isoDate'),'No Date'); t.end(); }); test('now', function(t) { t.true(date() - new Date() < 2); t.false(date(NaN) - date() < 2); t.true(isNaN(date(NaN) - date())); t.true(date(undefined) - date() < 2); t.true(date(null) - date() < 2); t.true(date(false) - date() < 2); t.true(date(0) - date() < 2); t.true(date('') - date() < 2); t.end(); }); test('shortcut', function(t) { var s = date().format('isoDateTime'); t.equal(date(s).format('longDate'), date(s,'longDate')); t.equal(date('booger', ''), 'No Date'); t.equal(date('booger', 'longDate'), 'No Date available'); t.equal(date('booger', 'fullDate'), 'No Date available'); t.end(); }); test('ES5 UTC gotcha avoidance', function(t) { var d3 = date('2014-04-02'); t.equal(d3.format('mmmm d, yyyy'), 'April 2, 2014'); var offset = dateformat('2014/04/02', 'o'); t.equal(date('2014-4-2' ).format('isoDateTime'), '2014-04-02T00:00:00'+offset); t.equal(date('2014/4/2' ).format('isoDateTime'), '2014-04-02T00:00:00'+offset); t.equal(date('2014-04-02').format('isoDateTime'), '2014-04-02T00:00:00'+offset); t.equal(date('2014/04/02').format('isoDateTime'), '2014-04-02T00:00:00'+offset); t.equal(date('4-2-2014' ).format('isoDateTime'), '2014-04-02T00:00:00'+offset); t.equal(date('4/2/2014' ).format('isoDateTime'), '2014-04-02T00:00:00'+offset); t.equal(date('04-02-2014').format('isoDateTime'), '2014-04-02T00:00:00'+offset); t.equal(date('04/02/2014').format('isoDateTime'), '2014-04-02T00:00:00'+offset); t.end(); }); test('addDays', function(t) { t.equal(date('4/2/2014').addDays(2).format('longDate'), 'April 4, 2014'); t.equal(date('4/2/2014').addDays(-2).format('longDate'), 'March 31, 2014'); t.equal(date('4/1/2015 01:00 pm').addDays(0.5).format('m/d/yyyy hh:MM tt'), '4/2/2015 01:00 am'); t.end(); }); test('lang de', function(t) { date.lang('de'); var strings = require('../lang/de'); var i, dfor; for (i=0; i<7; i++) { dfor = date(2015, 0, 11 + i); t.equal(dfor.format('ddd'), strings.dayNames[i]); t.equal(dfor.format('dddd'), strings.dayNames[i+7]); } for (i=0; i<12; i++) { dfor = date(2015, i, 1); t.equal(dfor.format('mmm'), strings.monthNames[i]); t.equal(dfor.format('mmmm'), strings.monthNames[i+12]); } t.equal(date('booger', ''), 'Kein Datum'); t.equal(date('booger', 'longDate'), 'Kein Datum vorhanden'); t.equal(date('booger', 'fullDate'), 'Kein Datum vorhanden'); t.end(); }); test('access dateformat masks', function(t) { date.dateformat.masks.shortDate = ('yyyy.mm.dd'); t.equal(date('1/1/2015').format('shortDate'), '2015.01.01'); t.end(); });
JavaScript
0.020738
@@ -464,13 +464,11 @@ ate( -' NaN -' ).va
5cbe1779a5ea3e741afa92a5ba36ffc4d9942d3f
add package.json to wallaby config
.wallaby.js
.wallaby.js
'use strict'; module.exports = function wallabyConfig() { return { files: [ 'lib/**/*.js' ], tests: [ 'test/**/*.spec.js' ], env: { type: 'node', runner: 'node' }, testFramework: 'mocha', bootstrap: function bootstrap(wallaby) { var path = require('path'); require(path.join(wallaby.localProjectDir, 'test', 'fixture')); } }; };
JavaScript
0.000001
@@ -91,24 +91,46 @@ lib/**/*.js' +,%0A 'package.json' %0A %5D,%0A
3abb95e9d752a3e08bdbea759a65535d7b9f9c1d
resolve linter issues
lib/mode.js
lib/mode.js
/** * Write a function that find the most repeated numbe * @param {Array} list */ function mode(list) { //Your code goes here var cnt = {}, mx = -1; if(!list.length) return "No elements in the Array"; var ans = []; Array.prototype.forEach.call(list, function(elem) { if(!cnt.hasOwnProperty(elem)) { cnt[elem] = 0; } cnt[elem]++; if(mx == cnt[elem]) { ans.push(elem); } if(mx < cnt[elem]) { mx = cnt[elem]; ans = []; ans.push(elem); } }); return ans.sort(); } module.exports = mode;
JavaScript
0
@@ -105,32 +105,8 @@ ) %7B%0A - //Your code goes here%0A va @@ -119,15 +119,15 @@ = %7B%7D -,%0A +;%0A var mx @@ -139,16 +139,17 @@ %0A %0A if + (!list.l @@ -154,16 +154,22 @@ .length) + %7B%0A return @@ -196,16 +196,20 @@ Array%22;%0A + %7D%0A %0A var @@ -264,16 +264,17 @@ function + (elem) %7B @@ -280,16 +280,17 @@ %7B%0A if + (!cnt.ha @@ -338,24 +338,26 @@ ;%0A %7D%0A +++ cnt%5Belem%5D++; @@ -353,18 +353,16 @@ nt%5Belem%5D -++ ;%0A%0A i @@ -366,14 +366,16 @@ if + (mx == += cnt @@ -419,16 +419,17 @@ %0A%0A if + (mx %3C cn
7db4e978f9d1e32914d3be0532cc9d1791d7ec36
enable button on set pages again
src/content_script/sc.js
src/content_script/sc.js
var MutationSummary = require('mutation-summary').MutationSummary; function addButton(soundActions) { var url; try { var wrap = soundActions.parentElement; // different containers: if (wrap.classList.contains('sound__soundActions')) { /* STREAM */ var soundEl = soundActions.parentElement.parentElement.parentElement; if (soundEl.parentElement.classList.contains('single')) { /* VISUAL PAGE */ url = location.href; } else { url = soundEl.querySelector('a.soundTitle__title').href; } } else if (wrap.classList.contains('listenEngagement__actions')) { /* PAGE */ url = location.href; } else if (wrap.classList.contains('soundBadge__actions')) { /* SIDEBAR */ var soundBadgeEl = soundActions.parentElement.parentElement.parentElement.parentElement; url = soundBadgeEl.querySelector('a.soundTitle__title').href; } else if (wrap.classList.contains('trackItem__actions')) { /* SET */ var trackItem = soundActions.parentElement.parentElement.parentElement; url = trackItem.querySelector('a.trackItem__trackTitle').href; } else { console.warn('add-to-sonos: cannot find container for soundActions:', soundActions); return; } } catch(e) { console.warn('add-to-sonos: cannot get url for soundActions:', soundActions, e); return; } if (soundActions.querySelector('.sc-button-addtoset') !== null) { addButtonToSound(soundActions, url); } else { addButtonToPlaylist(soundActions, url); } } function addButtonToPlaylist(soundActions, url) { var repostButton = soundActions.querySelector('.sc-button-repost'); if (typeof repostButton === 'undefined' || repostButton === null) { console.warn('repost playlist button not found', soundActions); return; } var addToSonosButton = createButton(repostButton, url); repostButton.parentElement.insertBefore(addToSonosButton, repostButton.nextSibling); } function addButtonToSound(soundActions, url) { var addToSetButton = soundActions.querySelector('.sc-button-addtoset'); addToSetButton.classList.add('ats-collapse'); var addToSonosButton = createButton(addToSetButton, url); addToSetButton.parentElement.insertBefore(addToSonosButton, addToSetButton.nextSibling); } function createButton(prevButton, url) { var prevClasses = prevButton.className.replace(/sc-button-(addtoset|repost)/g, ''); var addToSonosButton = document.createElement('button'); addToSonosButton.className = prevClasses + ' ats-button ats-collapse'; addToSonosButton.tabIndex = 0; addToSonosButton.title = 'Add to Sonos'; addToSonosButton.innerHTML = 'Add to Sonos'; addToSonosButton.addEventListener('click', function(ev) { ev.preventDefault(); ev.stopPropagation(); addToSonosButton.classList.remove('ats-success'); addToSonosButton.classList.remove('ats-failure'); addToSonosButton.classList.add('ats-loading'); chrome.runtime.sendMessage({action: 'addToPlaylist', url: url}, function(response) { addToSonosButton.classList.remove('ats-loading'); if (response.success) { addToSonosButton.classList.add('ats-success'); } else { addToSonosButton.classList.add('ats-failure'); if (response.setup) { chrome.runtime.sendMessage({action: 'openSettings'}); } } }); }, false); return addToSonosButton; } function handleSoundActionsChanges(summaries) { var soundActionsSummary = summaries[0]; soundActionsSummary.added.forEach(addButton); } // triggers on new soundActions var observer = new MutationSummary({ callback: handleSoundActionsChanges, queries: [{ element: 'div.soundActions' }] }); // handle already existing soundActions [].forEach.call(document.querySelectorAll('div.soundActions'), addButton);
JavaScript
0
@@ -596,24 +596,88 @@ t__actions') + %7C%7C soundActions.classList.contains('listenEngagement__actions') ) %7B /* PAGE
ae135c1c0582ec9ce637af9a8a411d62f8115429
Remove JS-code, adding to a branch instead
assets/js/index.js
assets/js/index.js
/** * Main JS file for Casper behaviours */ /* globals jQuery, document */ (function ($, undefined) { "use strict"; var $document = $(document); $document.ready(function () { var $postContent = $(".post-content"); $postContent.fitVids(); $(".scroll-down").arctic_scroll(); $(".menu-button, .nav-cover, .nav-close").on("click", function(e){ e.preventDefault(); $("body").toggleClass("nav-opened nav-closed"); }); }); $document.on("scroll",function(){ if($(document).scrollTop() > 100){ $(".navigation").removeClass("large").addClass("small"); } else { $(".navigation").removeClass("small").addClass("large"); } }); // Arctic Scroll by Paul Adam Davis // https://github.com/PaulAdamDavis/Arctic-Scroll $.fn.arctic_scroll = function (options) { var defaults = { elem: $(this), speed: 500 }, allOptions = $.extend(defaults, options); allOptions.elem.click(function (event) { event.preventDefault(); var $this = $(this), $htmlBody = $('html, body'), offset = ($this.attr('data-offset')) ? $this.attr('data-offset') : false, position = ($this.attr('data-position')) ? $this.attr('data-position') : false, toMove; if (offset) { toMove = parseInt(offset); $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top + toMove) }, allOptions.speed); } else if (position) { toMove = parseInt(position); $htmlBody.stop(true, false).animate({scrollTop: toMove }, allOptions.speed); } else { $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top) }, allOptions.speed); } }); }; })(jQuery);
JavaScript
0
@@ -503,249 +503,8 @@ );%0A%0A - $document.on(%22scroll%22,function()%7B%0A if($(document).scrollTop() %3E 100)%7B%0A $(%22.navigation%22).removeClass(%22large%22).addClass(%22small%22);%0A %7D else %7B%0A $(%22.navigation%22).removeClass(%22small%22).addClass(%22large%22);%0A %7D%0A %7D);%0A%0A
55b6313428cd0f60e77596a7cadc372e774d5d3b
Fix bug in Node's prune tree
lib/node.js
lib/node.js
'use strict'; var BehaviorConduit = require('./behavior-conduit'); var Bundle = require('./bundle'); var EventConduit = require('./event-conduit'); var EventManager = require('./event-manager'); var NodeStore = require('./node-store'); var StateManager = require('./state-manager'); var VirtualDOM = require('./virtual-dom'); var EMPTY_TREE = ''; var ALL_SELECTOR = '*'; var MESSAGES_ATTR_KEY = 'data-messages'; var TREE_SIG_ATTR_KEY = 'tree_sig'; var STATE_AUTOTRIGGER_RE = /^[a-zA-Z0-9].*/i; var ELEMENT_NODE_TYPE = 1; function Node(domNode) { this.domNode = domNode; this.name = this.domNode.tagName.toLowerCase(); this.definition = Bundle.getDefinition(this.name); this.isComponent = !!this.definition; // For e.g. <p> tags if (this.isComponent) { NodeStore.saveNode(this); this.statesObject = Bundle.getStates(this.name); this.eventsObject = Bundle.getEvents(this.name); this.publicEvents = Bundle.getPublicEvents(this.name); this.descendantEvents = Bundle.getDescendantEvents(this.name); this.handlerEvents = Bundle.getHandlerEvents(this.name); this.stateManager = StateManager.create(this.statesObject); this.eventManager = EventManager.create(this); this.behaviorConduit = new BehaviorConduit(this); this.eventConduit = new EventConduit(this); this.treeString = this.definition.tree || EMPTY_TREE; this.childrenRoot = VirtualDOM.parse(this.treeString); this.surrogateRoot = VirtualDOM.clone(this.domNode); VirtualDOM.attachAttributeToNodes( this.childrenRoot, TREE_SIG_ATTR_KEY, VirtualDOM.getUID(this.domNode) ); } } Node.prototype.prepare = function(famous) { this.famousNode = famous.addChild(); this.clearChildren(); this.behaviorConduit.prepareControlFlow(); this.behaviorConduit.prepareNormalBehaviors(); this.buildChildren(); this.buildTreeSignature(); this.eventConduit.prepare(); this.processMessages(); // Lock control flow behaviors since they have already been // triggered from BehaviorConduit.prepareControlFlow this.lockControlFlow = true; this.stateManager.triggerGlobalChange(STATE_AUTOTRIGGER_RE); this.lockControlFlow = false; }; Node.prototype.processMessages = function() { var messageStr = this.domNode.getAttribute(MESSAGES_ATTR_KEY); if (messageStr) { var messageHash = JSON.parse(messageStr); this.eventManager.sendMessages(messageHash); this.domNode.removeAttribute(MESSAGES_ATTR_KEY); } }; Node.prototype.buildChildren = function() { while (this.childrenRoot.childNodes[0]) { var child = this.childrenRoot.childNodes[0]; this.domNode.appendChild(child); if (child.nodeType === ELEMENT_NODE_TYPE) { var bestNode = new Node(child); bestNode.prepare(this.famousNode); } } }; Node.prototype.clearChildren = function() { var descendants = VirtualDOM.query(this.domNode, ALL_SELECTOR); for (var i = 0; i < descendants.length; i++) { var descendant = descendants[i]; if (descendant.nodeType === ELEMENT_NODE_TYPE) { var descendantUID = VirtualDOM.getUID(descendant); if (descendantUID) { var descendantNode = NodeStore.findNode(descendantUID); descendantNode.teardown(); } } } VirtualDOM.empty(this.domNode); if (this.treeSignature) { VirtualDOM.empty(this.treeSignature); } }; function isUIDMatch(node, UID) { return node.getAttribute(TREE_SIG_ATTR_KEY) === UID; } function pruneTree(node, matchUID) { var parent; var grandparent; // Process children first if (node.children.length > 0) { for (var i = 0; i < node.children.length; i++) { pruneTree(node.children[i], matchUID); } } parent = node.parentNode; // Remove node is UID doesn't match if (!isUIDMatch(node, matchUID)) { if (parent) { parent.removeChild(node); } node = null; } else { // Move child to grandparent if parent's UID doesn't match // since the parent will get pruned if (parent && !isUIDMatch(parent, matchUID)) { grandparent = parent.parentNode; if (grandparent) { grandparent.appendChild(node); } } } } Node.prototype.buildTreeSignature = function() { this.treeSignature = VirtualDOM.clone(this.domNode); pruneTree(this.treeSignature, VirtualDOM.getUID(this.domNode)); }; Node.prototype.teardown = function() { // // TODO // }; module.exports = Node;
JavaScript
0.000001
@@ -3738,17 +3738,24 @@ ;%0A%0A / -/ +*------- Process @@ -3768,118 +3768,179 @@ ren -first%0A if (node.children.length %3E 0) %7B%0A for (var i = 0; i %3C node.children.length; i++) %7B%0A +-------*/%0A var childrenCount = node.children.length;%0A var childIndex = 0;%0A var wasChildRemoved;%0A while (childIndex %3C childrenCount) %7B%0A wasChildRemoved = pru @@ -3960,17 +3960,26 @@ hildren%5B -i +childIndex %5D, match @@ -3992,23 +3992,175 @@ -%7D%0A %7D +if (wasChildRemoved) %7B%0A childrenCount--;%0A %7D%0A else %7B%0A childIndex++;%0A %7D%0A %7D%0A /*--------------------------------*/ %0A%0A pa @@ -4204,17 +4204,17 @@ e node i -s +f UID doe @@ -4354,16 +4354,37 @@ = null;%0A + return true;%0A %7D%0A @@ -4701,24 +4701,46 @@ %7D%0A %7D%0A + return false;%0A %7D%0A%7D%0A%0ANod
e71ab4bc47addf4a91cfa8aea93e14dc89d6f830
Add my page stack
app/alloy.js
app/alloy.js
// The contents of this file will be executed before any of // your view controllers are ever executed, including the index. // You have access to all functionality on the `Alloy` namespace. // // This is a great place to do any initialization for your app // or create any global variables/functions that you'd like to // make available throughout your app. You can easily make things // accessible globally by attaching them to the `Alloy.Globals` // object. For example: // // Alloy.Globals.someGlobalFunction = function(){};
JavaScript
0
@@ -1,529 +1,1387 @@ -// The contents of this file will be executed before any of%0A// your view controllers are ever executed, including the index.%0A// You have access to all functionality on the %60Alloy%60 namespace.%0A//%0A// This is a great place to do any initialization for your app%0A// or create any global variables/functions that you'd like to%0A// make available throughout your app. You can easily make things%0A// accessible globally by attaching them to the %60Alloy.Globals%60%0A// object. For example:%0A//%0A// Alloy.Globals.someGlobalFunction = function()%7B +Alloy.Globals.pageStack = %7B%0A navigationWindow: null,%0A pages: %5B%5D,%0A open: function(page) %7B%0A%0A Alloy.Globals.pageStack.pages.push(page);%0A%0A if (OS_IOS) %7B%0A%0A if (Alloy.Globals.pageStack.navigationWindow === null) %7B%0A%0A Alloy.Globals.pageStack.navigationWindow = Ti.UI.iOS.createNavigationWindow(%7B%0A window: page%0A %7D);%0A%0A Alloy.Globals.pageStack.navigationWindow.open();%0A %7D else %7B%0A Alloy.Globals.pageStack.navigationWindow.openWindow(page);%0A %7D%0A %7D else if (OS_MOBILEWEB) %7B%0A%0A Alloy.Globals.pageStack.navigationWindow.open(page);%0A %7D else %7B%0A page.open();%0A %7D%0A %7D,%0A close: function(page) %7B%0A%0A if (OS_IOS) %7B%0A Alloy.Globals.pageStack.navigationWindow.closeWindow(page);%0A %7D else if (OS_MOBILEWEB) %7B%0A Alloy.Globals.pageStack.navigationWindow.close(page);%0A %7D else %7B%0A page.close();%0A %7D%0A Alloy.Globals.pageStack.pages = _.without(Alloy.Globals.pageStack.pages, page);%0A %7D,%0A back: function() %7B%0A var page = _.last(Alloy.Globals.pageStack.pages);%0A Alloy.Globals.pageStack.close(page);%0A%0A if (Alloy.Globals.pageStack.pages.length == 0 && OS_IOS) %7B%0A Alloy.Globals.pageStack.navigationWindow.close();%0A Alloy.Globals.pageStack.navigationWindow = null;%0A %7D%0A %7D,%0A home: function() %7B%0A%0A while (Alloy.Globals.pageStack.pages.length %3E= 2) %7B%0A Alloy.Globals.pageStack.back();%0A %7D%0A %7D%0A %7D;%0A
e63949e34cef3f5482558d2abb744e051d7ddca4
Make mutator/perf-script runnable from node
packages/@sanity/mutator/perf/run.js
packages/@sanity/mutator/perf/run.js
import {BufferedDocument, Mutation} from '../src' import mutations from './fixtures/patches' import snapshot from './fixtures/snapshot' const bufferedDocument = new BufferedDocument(snapshot) const labelAll = `Adding ${mutations.length} mutations` console.time(labelAll) mutations.forEach((patches, i) => { const label = `${i}. bufferedDocument.add` console.time(label) bufferedDocument.add( new Mutation({mutations: patches.map(patch => ({patch: {...patch, id: snapshot._id}}))}) ) console.timeEnd(label) }) console.timeEnd(labelAll)
JavaScript
0
@@ -1,13 +1,12 @@ -impor +cons t %7BBuffe @@ -32,27 +32,32 @@ on%7D -from '../src'%0Aimpor += require('../lib')%0Acons t mu @@ -64,21 +64,26 @@ tations -from += require( './fixtu @@ -98,14 +98,14 @@ hes' -%0Aimpor +)%0Acons t sn @@ -115,13 +115,18 @@ hot -from += require( './f @@ -142,16 +142,17 @@ napshot' +) %0A%0Aconst
4963a5b30f676e928833dd8afba27d3678d208da
Fix language selection; Fix #4756
settings/js/personal.js
settings/js/personal.js
/** * Copyright (c) 2011, Robin Appelman <icewind1991@gmail.com> * This file is licensed under the Affero General Public License version 3 or later. * See the COPYING-README file. */ /** * Post the email address change to the server. */ function changeEmailAddress(){ var emailInfo = $('#email'); if (emailInfo.val() === emailInfo.defaultValue){ return; } emailInfo.defaultValue = emailInfo.val(); OC.msg.startSaving('#lostpassword .msg'); var post = $( "#lostpassword" ).serialize(); $.post( 'ajax/lostpassword.php', post, function(data){ OC.msg.finishedSaving('#lostpassword .msg', data); }); } /** * Post the display name change to the server. */ function changeDisplayName(){ if ($('#displayName').val() !== '' ) { OC.msg.startSaving('#displaynameform .msg'); // Serialize the data var post = $( "#displaynameform" ).serialize(); // Ajax foo $.post( 'ajax/changedisplayname.php', post, function(data){ if( data.status === "success" ){ $('#oldDisplayName').text($('#displayName').val()); // update displayName on the top right expand button $('#expandDisplayName').text($('#displayName').val()); } else{ $('#newdisplayname').val(data.data.displayName); } OC.msg.finishedSaving('#displaynameform .msg', data); }); return false; } } $(document).ready(function(){ $("#passwordbutton").click( function(){ if ($('#pass1').val() !== '' && $('#pass2').val() !== '') { // Serialize the data var post = $( "#passwordform" ).serialize(); $('#passwordchanged').hide(); $('#passworderror').hide(); // Ajax foo $.post( 'ajax/changepassword.php', post, function(data){ if( data.status === "success" ){ $('#pass1').val(''); $('#pass2').val(''); $('#passwordchanged').show(); } else{ $('#passworderror').html( data.data.message ); $('#passworderror').show(); } }); return false; } else { $('#passwordchanged').hide(); $('#passworderror').show(); return false; } }); $('#displayName').keyup(function(){ if ($('#displayName').val() !== '' ){ if(typeof timeout !== 'undefined'){ clearTimeout(timeout); } timeout = setTimeout('changeDisplayName()',1000); } }); $('#email').keyup(function(){ if ($('#email').val() !== '' ){ if(typeof timeout !== 'undefined'){ clearTimeout(timeout); } timeout = setTimeout('changeEmailAddress()',1000); } }); $("#languageinput").chosen(); // Show only the not selectable optgroup // Choosen only shows optgroup-labels if there are options in the optgroup $(".languagedivider").remove(); $("#languageinput").change( function(){ // Serialize the data var post = $( "#languageinput" ).serialize(); // Ajax foo $.post( 'ajax/setlanguage.php', post, function(data){ if( data.status === "success" ){ location.reload(); } else{ $('#passworderror').html( data.data.message ); } }); return false; }); $('button:button[name="submitDecryptAll"]').click(function() { var privateKeyPassword = $('#decryptAll input:password[id="privateKeyPassword"]').val(); OC.Encryption.decryptAll(privateKeyPassword); }); $('#decryptAll input:password[name="privateKeyPassword"]').keyup(function(event) { var privateKeyPassword = $('#decryptAll input:password[id="privateKeyPassword"]').val(); if (privateKeyPassword !== '' ) { $('#decryptAll button:button[name="submitDecryptAll"]').removeAttr("disabled"); if(event.which === 13) { OC.Encryption.decryptAll(privateKeyPassword); } } else { $('#decryptAll button:button[name="submitDecryptAll"]').attr("disabled", "true"); } }); } ); OC.Encryption = { decryptAll: function(password) { OC.Encryption.msg.startDecrypting('#decryptAll .msg'); $.post('ajax/decryptall.php', {password:password}, function(data) { if (data.status === "error") { OC.Encryption.msg.finishedDecrypting('#decryptAll .msg', data); } else { OC.Encryption.msg.finishedDecrypting('#decryptAll .msg', data); } } ); } } OC.Encryption.msg={ startDecrypting:function(selector){ $(selector) .html( t('files_encryption', 'Decrypting files... Please wait, this can take some time.') ) .removeClass('success') .removeClass('error') .stop(true, true) .show(); }, finishedDecrypting:function(selector, data){ if( data.status === "success" ){ $(selector).html( data.data.message ) .addClass('success') .stop(true, true) .delay(3000) .fadeOut(900); }else{ $(selector).html( data.data.message ).addClass('error'); } } }; OC.msg={ startSaving:function(selector){ $(selector) .html( t('settings', 'Saving...') ) .removeClass('success') .removeClass('error') .stop(true, true) .show(); }, finishedSaving:function(selector, data){ if( data.status === "success" ){ $(selector).html( data.data.message ) .addClass('success') .stop(true, true) .delay(3000) .fadeOut(900); }else{ $(selector).html( data.data.message ).addClass('error'); } } };
JavaScript
0
@@ -2875,21 +2875,19 @@ vider%22). -remov +hid e();%0A%0A%09$
e6222cf085b8d7eff41498d3461b14cf95ad9900
fix sign up bug
controllers/user.js
controllers/user.js
'use strict'; var path = require('path'); var fs = require('fs'); var page = fs.readFileSync(path.join(__dirname, '../views/index/index.ejs'), 'utf8'); var co = require('co'); var views = require('co-views'); var mysql = require('co-mysql'); var customer = require('../modles/customer.js'); var movie = require('../modles/movie.js'); var db = require('../modles/db.js'); var config = require('../config.js'); var result; var render = views(__dirname + '/../views', {ext: 'ejs' }); // render exports.show_login = function* (){ // this.body = yield render('login', {user : this.session.customer}); this.session.index_mode = "show_login"; this.response.redirect('/'); }; exports.show_signup = function* (){ // this.body = yield render('signup', {user : this.session.customer}); this.session.index_mode = "show_signup"; this.response.redirect('/'); }; exports.show_profile = function* (){ this.body = yield render('profile', {user : this.session.customer}); }; exports.show_profile_edit = function* (){ this.body = yield render('profile_edit', {user : this.session.customer}); }; exports.signup = function* (){ var result = yield customer.insert(this.request.body); if (result == false){ console.log('signup failed'); } else { this.session.customer = yield db.get_customer_by_email(this.request.body.email); if (config.admin_id.indexOf(current_customer.customer_id) !== -1) { current_customer.is_admin = true; } else { current_customer.is_admin = false; } this.response.redirect('/'); } }; exports.check_username = function* (){ var result = yield db.get_customer_by_username(this.request.body.username); this.body = result; }; exports.login = function* (){ var password = yield customer.get_password_by_email(this.request.body.email); if (password == null) { console.log('No such user'); } else if (password === this.request.body.password) { console.log('Login Successfully'); var current_customer = yield db.get_customer_by_email(this.request.body.email); if (current_customer !== undefined) { current_customer = current_customer[0]; if (config.admin_id.indexOf(current_customer.customer_id) !== -1) { current_customer.is_admin = true; } else { current_customer.is_admin = false; } } this.session.customer = current_customer; this.response.redirect('/'); } else { console.log('Password is incorrect'); } }; exports.profile = function* (){ this.response.redirect('/'); }; exports.profile_edit = function* (){ this.response.redirect('/'); } exports.logout = function* (){ this.session = null; this.response.redirect('/'); }; exports.movie_search = function* (){ console.log(this.request.body); var movie_result = yield movie.get_movie_by_title_keyword(this.request.body); };
JavaScript
0
@@ -1381,32 +1381,37 @@ _id.indexOf( -current_ +this.session. customer.cus @@ -1429,32 +1429,37 @@ == -1) %7B%0A%09%09%09 -current_ +this.session. customer.is_ @@ -1482,32 +1482,37 @@ %7D else %7B%0A%09%09%09 -current_ +this.session. customer.is_
80de1a0fbd63e5d6162ecd95c2147a73d7f74d8a
Remove a FlowFixMe
core/local/stater.js
core/local/stater.js
/* @flow */ const fse = require('fs-extra') let winfs if (process.platform === 'win32') { // $FlowFixMe winfs = require('@gyselroth/windows-fsstat') } /*:: import type { Metadata } from '../metadata' import type { Callback } from '../utils/func' import type fs from 'fs' export type WinStats = { fileid: string, ino: number, size: number, atime: Date, mtime: Date, ctime: Date, directory: bool, symbolicLink: bool } export type Stats = fs.Stats | WinStats */ module.exports = { stat: async function (filepath /*: string */) { if (!winfs) { return fse.stat(filepath) } return new Promise((resolve, reject) => { try { // XXX It would be better to avoid sync IO operations, but // before node 10.5.0, it's our only choice for reliable fileIDs. resolve(winfs.lstatSync(filepath)) } catch (err) { reject(err) } }) }, withStats: function (filepath /*: string */, callback /*: Callback */) { if (winfs) { try { const stats = winfs.lstatSync(filepath) callback(null, stats) } catch (err) { callback(err, {}) } } else { fse.stat(filepath, callback) } }, isDirectory (stats /*: Stats */) { if (stats.isDirectory) { // $FlowFixMe return stats.isDirectory() } else { // $FlowFixMe return stats.directory } }, kind (stats /*: Stats */) { return this.isDirectory(stats) ? 'directory' : 'file' }, assignInoAndFileId (doc /*: Metadata */, stats /*: Stats */) { doc.ino = stats.ino // $FlowFixMe if (stats.fileid) { doc.fileid = stats.fileid } } }
JavaScript
0.000001
@@ -296,16 +296,17 @@ tats = %7B +%7C %0A filei @@ -432,16 +432,17 @@ k: bool%0A +%7C %7D%0Aexport @@ -1273,36 +1273,16 @@ tory) %7B%0A - // $FlowFixMe%0A re
7d95b2a738098ee1d4a321ca1d0f2b5cd6509fa5
Fix referencing incorrect variable due to JS conversion
src/controllers/affix.js
src/controllers/affix.js
/** * @name MacAffixController * * @description * Controller for affix directive */ function MacAffixController ($element, $document, $window, defaults) { this.$document = $document; this.defaults = defaults; this.$element = $element; this.offset = { top: defaults.top, bottom: defaults.bottom }; this.windowEl = angular.element($window); this.disabled = defaults.disabled; this.lastAffix = null; this.unpin = null; this.pinnedOffset = null; } /** * @name updateOffset * @description * Update to or bottom offset. This function make sure the value is an integer * or use default values * @param {String} key Offset key * @param {String|Integer} value Update value * @param {Boolean} useDefault */ MacAffixController.prototype.updateOffset = function (key, value, useDefault) { // Don't do anything if changing invalid key if (key !== 'top' && key !== 'bottom') { return; } if (!!useDefault && value === null) { value = this.defaults[key]; } if (value !== null && !isNaN(+value)) { this.offset[key] = +value; } } MacAffixController.prototype.scrollEvent = function () { // Check if element is visible if (this.$element[0].offsetHeight <= 0 && this.$element[0].offsetWidth <= 0) { return; } var position = this.$element.offset(); var scrollTop = this.windowEl.scrollTop(); var scrollHeight = this.$document.height(); var elementHeight = this.$element.outerHeight(); var affix; if (this.unpin !== null && scrollTop <= this.unpin) { affix = false; } else if (this.offset.bottom !== null && scrollTop > scrollHeight - elementHeight - this.offset.bottom) { affix = 'bottom'; } else if (this.offset.top !== null && scrollTop <= this.offset.top) { affix = 'top'; } else { affix = false; } if (affix === this.lastAffix) return; if (this.unpin) { element.css('top', ''); } this.lastAffix = affix; if (affix === 'bottom') { if (this.pinnedOffset !== null) { this.unpin = pinnedOffset; } this.$element .removeClass(this.defaults.classes) .addClass('affix'); this.pinnedOffset = this.$document.height() - this.$element.outerHeight() - this.offset.bottom; this.unpin = this.pinnedOffset; } else { this.unpin = null; } this.$element .removeClass(this.defaults.classes) .addClass('affix' + (affix ? '-' + affix : '')); // Look into merging this with the move if block if (affix === 'bottom') { curOffset = element.offset(); element.css('top', this.unpin - curOffset.top); } return true; } MacAffixController.prototype.setDisabled = function (newValue) { this.disabled = newValue || this.defaults.disabled; if (this.disabled) { this.reset(); } else { this.scrollEvent(); } return this.disabled; } MacAffixController.prototype.reset = function () { // clear all styles and reset affix element this.lastAffix = null; this.unpin = null; this.$element .css('top', '') .removeClass(this.defaults.classes); } angular.module('Mac') .controller('MacAffixController', [ '$element', '$document', '$window', 'macAffixDefaults', MacAffixController ]);
JavaScript
0
@@ -1862,24 +1862,30 @@ npin) %7B%0A +this.$ element.css( @@ -2013,16 +2013,21 @@ unpin = +this. pinnedOf @@ -2507,16 +2507,22 @@ ffset = +this.$ element. @@ -2535,16 +2535,22 @@ ();%0A +this.$ element.